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.

279722 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. String welcome;
  974. welcome << "\r\n**********************************************************\r\n"
  975. << welcomeMessage
  976. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  977. << "\r\n";
  978. logMessage (welcome);
  979. }
  980. FileLogger::~FileLogger()
  981. {
  982. }
  983. void FileLogger::logMessage (const String& message)
  984. {
  985. DBG (message);
  986. const ScopedLock sl (logLock);
  987. FileOutputStream out (logFile, 256);
  988. out << message << "\r\n";
  989. }
  990. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  991. {
  992. if (maxFileSizeBytes <= 0)
  993. {
  994. logFile.deleteFile();
  995. }
  996. else
  997. {
  998. const int64 fileSize = logFile.getSize();
  999. if (fileSize > maxFileSizeBytes)
  1000. {
  1001. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1002. jassert (in != 0);
  1003. if (in != 0)
  1004. {
  1005. in->setPosition (fileSize - maxFileSizeBytes);
  1006. String content;
  1007. {
  1008. MemoryBlock contentToSave;
  1009. contentToSave.setSize (maxFileSizeBytes + 4);
  1010. contentToSave.fillWith (0);
  1011. in->read (contentToSave.getData(), maxFileSizeBytes);
  1012. in = 0;
  1013. content = contentToSave.toString();
  1014. }
  1015. int newStart = 0;
  1016. while (newStart < fileSize
  1017. && content[newStart] != '\n'
  1018. && content[newStart] != '\r')
  1019. ++newStart;
  1020. logFile.deleteFile();
  1021. logFile.appendText (content.substring (newStart), false, false);
  1022. }
  1023. }
  1024. }
  1025. }
  1026. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1027. const String& logFileName,
  1028. const String& welcomeMessage,
  1029. const int maxInitialFileSizeBytes)
  1030. {
  1031. #if JUCE_MAC
  1032. File logFile ("~/Library/Logs");
  1033. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1034. .getChildFile (logFileName);
  1035. #else
  1036. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1037. if (logFile.isDirectory())
  1038. {
  1039. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1040. .getChildFile (logFileName);
  1041. }
  1042. #endif
  1043. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1044. }
  1045. END_JUCE_NAMESPACE
  1046. /*** End of inlined file: juce_FileLogger.cpp ***/
  1047. /*** Start of inlined file: juce_Logger.cpp ***/
  1048. BEGIN_JUCE_NAMESPACE
  1049. Logger::Logger()
  1050. {
  1051. }
  1052. Logger::~Logger()
  1053. {
  1054. }
  1055. Logger* Logger::currentLogger = 0;
  1056. void Logger::setCurrentLogger (Logger* const newLogger,
  1057. const bool deleteOldLogger)
  1058. {
  1059. Logger* const oldLogger = currentLogger;
  1060. currentLogger = newLogger;
  1061. if (deleteOldLogger)
  1062. delete oldLogger;
  1063. }
  1064. void Logger::writeToLog (const String& message)
  1065. {
  1066. if (currentLogger != 0)
  1067. currentLogger->logMessage (message);
  1068. else
  1069. outputDebugString (message);
  1070. }
  1071. #if JUCE_LOG_ASSERTIONS
  1072. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1073. {
  1074. String m ("JUCE Assertion failure in ");
  1075. m << filename << ", line " << lineNum;
  1076. Logger::writeToLog (m);
  1077. }
  1078. #endif
  1079. END_JUCE_NAMESPACE
  1080. /*** End of inlined file: juce_Logger.cpp ***/
  1081. /*** Start of inlined file: juce_Random.cpp ***/
  1082. BEGIN_JUCE_NAMESPACE
  1083. Random::Random (const int64 seedValue) throw()
  1084. : seed (seedValue)
  1085. {
  1086. }
  1087. Random::~Random() throw()
  1088. {
  1089. }
  1090. void Random::setSeed (const int64 newSeed) throw()
  1091. {
  1092. seed = newSeed;
  1093. }
  1094. void Random::combineSeed (const int64 seedValue) throw()
  1095. {
  1096. seed ^= nextInt64() ^ seedValue;
  1097. }
  1098. void Random::setSeedRandomly()
  1099. {
  1100. combineSeed ((int64) (pointer_sized_int) this);
  1101. combineSeed (Time::getMillisecondCounter());
  1102. combineSeed (Time::getHighResolutionTicks());
  1103. combineSeed (Time::getHighResolutionTicksPerSecond());
  1104. combineSeed (Time::currentTimeMillis());
  1105. }
  1106. int Random::nextInt() throw()
  1107. {
  1108. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1109. return (int) (seed >> 16);
  1110. }
  1111. int Random::nextInt (const int maxValue) throw()
  1112. {
  1113. jassert (maxValue > 0);
  1114. return (nextInt() & 0x7fffffff) % maxValue;
  1115. }
  1116. int64 Random::nextInt64() throw()
  1117. {
  1118. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1119. }
  1120. bool Random::nextBool() throw()
  1121. {
  1122. return (nextInt() & 0x80000000) != 0;
  1123. }
  1124. float Random::nextFloat() throw()
  1125. {
  1126. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1127. }
  1128. double Random::nextDouble() throw()
  1129. {
  1130. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1131. }
  1132. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1133. {
  1134. BigInteger n;
  1135. do
  1136. {
  1137. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1138. }
  1139. while (n >= maximumValue);
  1140. return n;
  1141. }
  1142. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1143. {
  1144. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1145. while ((startBit & 31) != 0 && numBits > 0)
  1146. {
  1147. arrayToChange.setBit (startBit++, nextBool());
  1148. --numBits;
  1149. }
  1150. while (numBits >= 32)
  1151. {
  1152. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1153. startBit += 32;
  1154. numBits -= 32;
  1155. }
  1156. while (--numBits >= 0)
  1157. arrayToChange.setBit (startBit + numBits, nextBool());
  1158. }
  1159. Random& Random::getSystemRandom() throw()
  1160. {
  1161. static Random sysRand (1);
  1162. return sysRand;
  1163. }
  1164. END_JUCE_NAMESPACE
  1165. /*** End of inlined file: juce_Random.cpp ***/
  1166. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1167. BEGIN_JUCE_NAMESPACE
  1168. RelativeTime::RelativeTime (const double seconds_) throw()
  1169. : seconds (seconds_)
  1170. {
  1171. }
  1172. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1173. : seconds (other.seconds)
  1174. {
  1175. }
  1176. RelativeTime::~RelativeTime() throw()
  1177. {
  1178. }
  1179. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1180. {
  1181. return RelativeTime (milliseconds * 0.001);
  1182. }
  1183. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1184. {
  1185. return RelativeTime (milliseconds * 0.001);
  1186. }
  1187. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1188. {
  1189. return RelativeTime (numberOfMinutes * 60.0);
  1190. }
  1191. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1192. {
  1193. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1194. }
  1195. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1196. {
  1197. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1198. }
  1199. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1200. {
  1201. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1202. }
  1203. int64 RelativeTime::inMilliseconds() const throw()
  1204. {
  1205. return (int64) (seconds * 1000.0);
  1206. }
  1207. double RelativeTime::inMinutes() const throw()
  1208. {
  1209. return seconds / 60.0;
  1210. }
  1211. double RelativeTime::inHours() const throw()
  1212. {
  1213. return seconds / (60.0 * 60.0);
  1214. }
  1215. double RelativeTime::inDays() const throw()
  1216. {
  1217. return seconds / (60.0 * 60.0 * 24.0);
  1218. }
  1219. double RelativeTime::inWeeks() const throw()
  1220. {
  1221. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1222. }
  1223. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1224. {
  1225. if (seconds < 0.001 && seconds > -0.001)
  1226. return returnValueForZeroTime;
  1227. String result;
  1228. if (seconds < 0)
  1229. result = "-";
  1230. int fieldsShown = 0;
  1231. int n = abs ((int) inWeeks());
  1232. if (n > 0)
  1233. {
  1234. result << n << ((n == 1) ? TRANS(" week ")
  1235. : TRANS(" weeks "));
  1236. ++fieldsShown;
  1237. }
  1238. n = abs ((int) inDays()) % 7;
  1239. if (n > 0)
  1240. {
  1241. result << n << ((n == 1) ? TRANS(" day ")
  1242. : TRANS(" days "));
  1243. ++fieldsShown;
  1244. }
  1245. if (fieldsShown < 2)
  1246. {
  1247. n = abs ((int) inHours()) % 24;
  1248. if (n > 0)
  1249. {
  1250. result << n << ((n == 1) ? TRANS(" hr ")
  1251. : TRANS(" hrs "));
  1252. ++fieldsShown;
  1253. }
  1254. if (fieldsShown < 2)
  1255. {
  1256. n = abs ((int) inMinutes()) % 60;
  1257. if (n > 0)
  1258. {
  1259. result << n << ((n == 1) ? TRANS(" min ")
  1260. : TRANS(" mins "));
  1261. ++fieldsShown;
  1262. }
  1263. if (fieldsShown < 2)
  1264. {
  1265. n = abs ((int) inSeconds()) % 60;
  1266. if (n > 0)
  1267. {
  1268. result << n << ((n == 1) ? TRANS(" sec ")
  1269. : TRANS(" secs "));
  1270. ++fieldsShown;
  1271. }
  1272. if (fieldsShown < 1)
  1273. {
  1274. n = abs ((int) inMilliseconds()) % 1000;
  1275. if (n > 0)
  1276. {
  1277. result << n << TRANS(" ms");
  1278. ++fieldsShown;
  1279. }
  1280. }
  1281. }
  1282. }
  1283. }
  1284. return result.trimEnd();
  1285. }
  1286. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1287. {
  1288. seconds = other.seconds;
  1289. return *this;
  1290. }
  1291. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  1292. bool RelativeTime::operator!= (const RelativeTime& other) const throw() { return seconds != other.seconds; }
  1293. bool RelativeTime::operator> (const RelativeTime& other) const throw() { return seconds > other.seconds; }
  1294. bool RelativeTime::operator< (const RelativeTime& other) const throw() { return seconds < other.seconds; }
  1295. bool RelativeTime::operator>= (const RelativeTime& other) const throw() { return seconds >= other.seconds; }
  1296. bool RelativeTime::operator<= (const RelativeTime& other) const throw() { return seconds <= other.seconds; }
  1297. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1298. {
  1299. return RelativeTime (seconds + timeToAdd.seconds);
  1300. }
  1301. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1302. {
  1303. return RelativeTime (seconds - timeToSubtract.seconds);
  1304. }
  1305. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1306. {
  1307. return RelativeTime (seconds + secondsToAdd);
  1308. }
  1309. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1310. {
  1311. return RelativeTime (seconds - secondsToSubtract);
  1312. }
  1313. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1314. {
  1315. seconds += timeToAdd.seconds;
  1316. return *this;
  1317. }
  1318. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1319. {
  1320. seconds -= timeToSubtract.seconds;
  1321. return *this;
  1322. }
  1323. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1324. {
  1325. seconds += secondsToAdd;
  1326. return *this;
  1327. }
  1328. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1329. {
  1330. seconds -= secondsToSubtract;
  1331. return *this;
  1332. }
  1333. END_JUCE_NAMESPACE
  1334. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1335. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1336. BEGIN_JUCE_NAMESPACE
  1337. SystemStats::CPUFlags SystemStats::cpuFlags;
  1338. const String SystemStats::getJUCEVersion()
  1339. {
  1340. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1341. + "." + String (JUCE_MINOR_VERSION)
  1342. + "." + String (JUCE_BUILDNUMBER);
  1343. }
  1344. const StringArray SystemStats::getMACAddressStrings()
  1345. {
  1346. int64 macAddresses [16];
  1347. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1348. StringArray s;
  1349. for (int i = 0; i < numAddresses; ++i)
  1350. {
  1351. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1352. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1353. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1354. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1355. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1356. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1357. }
  1358. return s;
  1359. }
  1360. #ifdef JUCE_DLL
  1361. void* juce_Malloc (const int size)
  1362. {
  1363. return malloc (size);
  1364. }
  1365. void* juce_Calloc (const int size)
  1366. {
  1367. return calloc (1, size);
  1368. }
  1369. void* juce_Realloc (void* const block, const int size)
  1370. {
  1371. return realloc (block, size);
  1372. }
  1373. void juce_Free (void* const block)
  1374. {
  1375. free (block);
  1376. }
  1377. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1378. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1379. {
  1380. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1381. }
  1382. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1383. {
  1384. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1385. }
  1386. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1387. {
  1388. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1389. }
  1390. void juce_DebugFree (void* const block)
  1391. {
  1392. _free_dbg (block, _NORMAL_BLOCK);
  1393. }
  1394. #endif
  1395. #endif
  1396. END_JUCE_NAMESPACE
  1397. /*** End of inlined file: juce_SystemStats.cpp ***/
  1398. /*** Start of inlined file: juce_Time.cpp ***/
  1399. #if JUCE_MSVC
  1400. #pragma warning (push)
  1401. #pragma warning (disable: 4514)
  1402. #endif
  1403. #ifndef JUCE_WINDOWS
  1404. #include <sys/time.h>
  1405. #else
  1406. #include <ctime>
  1407. #endif
  1408. #include <sys/timeb.h>
  1409. #if JUCE_MSVC
  1410. #pragma warning (pop)
  1411. #ifdef _INC_TIME_INL
  1412. #define USE_NEW_SECURE_TIME_FNS
  1413. #endif
  1414. #endif
  1415. BEGIN_JUCE_NAMESPACE
  1416. namespace TimeHelpers
  1417. {
  1418. static struct tm millisToLocal (const int64 millis) throw()
  1419. {
  1420. struct tm result;
  1421. const int64 seconds = millis / 1000;
  1422. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1423. {
  1424. // use extended maths for dates beyond 1970 to 2037..
  1425. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1426. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1427. const int days = (int) (jdm / literal64bit (86400));
  1428. const int a = 32044 + days;
  1429. const int b = (4 * a + 3) / 146097;
  1430. const int c = a - (b * 146097) / 4;
  1431. const int d = (4 * c + 3) / 1461;
  1432. const int e = c - (d * 1461) / 4;
  1433. const int m = (5 * e + 2) / 153;
  1434. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1435. result.tm_mon = m + 2 - 12 * (m / 10);
  1436. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1437. result.tm_wday = (days + 1) % 7;
  1438. result.tm_yday = -1;
  1439. int t = (int) (jdm % literal64bit (86400));
  1440. result.tm_hour = t / 3600;
  1441. t %= 3600;
  1442. result.tm_min = t / 60;
  1443. result.tm_sec = t % 60;
  1444. result.tm_isdst = -1;
  1445. }
  1446. else
  1447. {
  1448. time_t now = static_cast <time_t> (seconds);
  1449. #if JUCE_WINDOWS
  1450. #ifdef USE_NEW_SECURE_TIME_FNS
  1451. if (now >= 0 && now <= 0x793406fff)
  1452. localtime_s (&result, &now);
  1453. else
  1454. zeromem (&result, sizeof (result));
  1455. #else
  1456. result = *localtime (&now);
  1457. #endif
  1458. #else
  1459. // more thread-safe
  1460. localtime_r (&now, &result);
  1461. #endif
  1462. }
  1463. return result;
  1464. }
  1465. static int extendedModulo (const int64 value, const int modulo) throw()
  1466. {
  1467. return (int) (value >= 0 ? (value % modulo)
  1468. : (value - ((value / modulo) + 1) * modulo));
  1469. }
  1470. static uint32 lastMSCounterValue = 0;
  1471. }
  1472. Time::Time() throw()
  1473. : millisSinceEpoch (0)
  1474. {
  1475. }
  1476. Time::Time (const Time& other) throw()
  1477. : millisSinceEpoch (other.millisSinceEpoch)
  1478. {
  1479. }
  1480. Time::Time (const int64 ms) throw()
  1481. : millisSinceEpoch (ms)
  1482. {
  1483. }
  1484. Time::Time (const int year,
  1485. const int month,
  1486. const int day,
  1487. const int hours,
  1488. const int minutes,
  1489. const int seconds,
  1490. const int milliseconds,
  1491. const bool useLocalTime) throw()
  1492. {
  1493. jassert (year > 100); // year must be a 4-digit version
  1494. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1495. {
  1496. // use extended maths for dates beyond 1970 to 2037..
  1497. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1498. : 0;
  1499. const int a = (13 - month) / 12;
  1500. const int y = year + 4800 - a;
  1501. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1502. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1503. - 32045;
  1504. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1505. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1506. + milliseconds;
  1507. }
  1508. else
  1509. {
  1510. struct tm t;
  1511. t.tm_year = year - 1900;
  1512. t.tm_mon = month;
  1513. t.tm_mday = day;
  1514. t.tm_hour = hours;
  1515. t.tm_min = minutes;
  1516. t.tm_sec = seconds;
  1517. t.tm_isdst = -1;
  1518. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1519. if (millisSinceEpoch < 0)
  1520. millisSinceEpoch = 0;
  1521. else
  1522. millisSinceEpoch += milliseconds;
  1523. }
  1524. }
  1525. Time::~Time() throw()
  1526. {
  1527. }
  1528. Time& Time::operator= (const Time& other) throw()
  1529. {
  1530. millisSinceEpoch = other.millisSinceEpoch;
  1531. return *this;
  1532. }
  1533. int64 Time::currentTimeMillis() throw()
  1534. {
  1535. static uint32 lastCounterResult = 0xffffffff;
  1536. static int64 correction = 0;
  1537. const uint32 now = getMillisecondCounter();
  1538. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1539. if (now < lastCounterResult)
  1540. {
  1541. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1542. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1543. {
  1544. // get the time once using normal library calls, and store the difference needed to
  1545. // turn the millisecond counter into a real time.
  1546. #if JUCE_WINDOWS
  1547. struct _timeb t;
  1548. #ifdef USE_NEW_SECURE_TIME_FNS
  1549. _ftime_s (&t);
  1550. #else
  1551. _ftime (&t);
  1552. #endif
  1553. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1554. #else
  1555. struct timeval tv;
  1556. struct timezone tz;
  1557. gettimeofday (&tv, &tz);
  1558. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1559. #endif
  1560. }
  1561. }
  1562. lastCounterResult = now;
  1563. return correction + now;
  1564. }
  1565. uint32 juce_millisecondsSinceStartup() throw();
  1566. uint32 Time::getMillisecondCounter() throw()
  1567. {
  1568. const uint32 now = juce_millisecondsSinceStartup();
  1569. if (now < TimeHelpers::lastMSCounterValue)
  1570. {
  1571. // in multi-threaded apps this might be called concurrently, so
  1572. // make sure that our last counter value only increases and doesn't
  1573. // go backwards..
  1574. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1575. TimeHelpers::lastMSCounterValue = now;
  1576. }
  1577. else
  1578. {
  1579. TimeHelpers::lastMSCounterValue = now;
  1580. }
  1581. return now;
  1582. }
  1583. uint32 Time::getApproximateMillisecondCounter() throw()
  1584. {
  1585. jassert (TimeHelpers::lastMSCounterValue != 0);
  1586. return TimeHelpers::lastMSCounterValue;
  1587. }
  1588. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1589. {
  1590. for (;;)
  1591. {
  1592. const uint32 now = getMillisecondCounter();
  1593. if (now >= targetTime)
  1594. break;
  1595. const int toWait = targetTime - now;
  1596. if (toWait > 2)
  1597. {
  1598. Thread::sleep (jmin (20, toWait >> 1));
  1599. }
  1600. else
  1601. {
  1602. // xxx should consider using mutex_pause on the mac as it apparently
  1603. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1604. for (int i = 10; --i >= 0;)
  1605. Thread::yield();
  1606. }
  1607. }
  1608. }
  1609. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1610. {
  1611. return ticks / (double) getHighResolutionTicksPerSecond();
  1612. }
  1613. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1614. {
  1615. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1616. }
  1617. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1618. {
  1619. return Time (currentTimeMillis());
  1620. }
  1621. const String Time::toString (const bool includeDate,
  1622. const bool includeTime,
  1623. const bool includeSeconds,
  1624. const bool use24HourClock) const throw()
  1625. {
  1626. String result;
  1627. if (includeDate)
  1628. {
  1629. result << getDayOfMonth() << ' '
  1630. << getMonthName (true) << ' '
  1631. << getYear();
  1632. if (includeTime)
  1633. result << ' ';
  1634. }
  1635. if (includeTime)
  1636. {
  1637. const int mins = getMinutes();
  1638. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1639. << (mins < 10 ? ":0" : ":") << mins;
  1640. if (includeSeconds)
  1641. {
  1642. const int secs = getSeconds();
  1643. result << (secs < 10 ? ":0" : ":") << secs;
  1644. }
  1645. if (! use24HourClock)
  1646. result << (isAfternoon() ? "pm" : "am");
  1647. }
  1648. return result.trimEnd();
  1649. }
  1650. const String Time::formatted (const String& format) const
  1651. {
  1652. String buffer;
  1653. int bufferSize = 128;
  1654. buffer.preallocateStorage (bufferSize);
  1655. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1656. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1657. {
  1658. bufferSize += 128;
  1659. buffer.preallocateStorage (bufferSize);
  1660. }
  1661. return buffer;
  1662. }
  1663. int Time::getYear() const throw()
  1664. {
  1665. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1666. }
  1667. int Time::getMonth() const throw()
  1668. {
  1669. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1670. }
  1671. int Time::getDayOfMonth() const throw()
  1672. {
  1673. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1674. }
  1675. int Time::getDayOfWeek() const throw()
  1676. {
  1677. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1678. }
  1679. int Time::getHours() const throw()
  1680. {
  1681. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1682. }
  1683. int Time::getHoursInAmPmFormat() const throw()
  1684. {
  1685. const int hours = getHours();
  1686. if (hours == 0)
  1687. return 12;
  1688. else if (hours <= 12)
  1689. return hours;
  1690. else
  1691. return hours - 12;
  1692. }
  1693. bool Time::isAfternoon() const throw()
  1694. {
  1695. return getHours() >= 12;
  1696. }
  1697. int Time::getMinutes() const throw()
  1698. {
  1699. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1700. }
  1701. int Time::getSeconds() const throw()
  1702. {
  1703. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1704. }
  1705. int Time::getMilliseconds() const throw()
  1706. {
  1707. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1708. }
  1709. bool Time::isDaylightSavingTime() const throw()
  1710. {
  1711. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1712. }
  1713. const String Time::getTimeZone() const throw()
  1714. {
  1715. String zone[2];
  1716. #if JUCE_WINDOWS
  1717. _tzset();
  1718. #ifdef USE_NEW_SECURE_TIME_FNS
  1719. {
  1720. char name [128];
  1721. size_t length;
  1722. for (int i = 0; i < 2; ++i)
  1723. {
  1724. zeromem (name, sizeof (name));
  1725. _get_tzname (&length, name, 127, i);
  1726. zone[i] = name;
  1727. }
  1728. }
  1729. #else
  1730. const char** const zonePtr = (const char**) _tzname;
  1731. zone[0] = zonePtr[0];
  1732. zone[1] = zonePtr[1];
  1733. #endif
  1734. #else
  1735. tzset();
  1736. const char** const zonePtr = (const char**) tzname;
  1737. zone[0] = zonePtr[0];
  1738. zone[1] = zonePtr[1];
  1739. #endif
  1740. if (isDaylightSavingTime())
  1741. {
  1742. zone[0] = zone[1];
  1743. if (zone[0].length() > 3
  1744. && zone[0].containsIgnoreCase ("daylight")
  1745. && zone[0].contains ("GMT"))
  1746. zone[0] = "BST";
  1747. }
  1748. return zone[0].substring (0, 3);
  1749. }
  1750. const String Time::getMonthName (const bool threeLetterVersion) const
  1751. {
  1752. return getMonthName (getMonth(), threeLetterVersion);
  1753. }
  1754. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1755. {
  1756. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1757. }
  1758. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1759. {
  1760. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1761. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1762. monthNumber %= 12;
  1763. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1764. : longMonthNames [monthNumber]);
  1765. }
  1766. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1767. {
  1768. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1769. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1770. day %= 7;
  1771. return TRANS (threeLetterVersion ? shortDayNames [day]
  1772. : longDayNames [day]);
  1773. }
  1774. END_JUCE_NAMESPACE
  1775. /*** End of inlined file: juce_Time.cpp ***/
  1776. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1777. BEGIN_JUCE_NAMESPACE
  1778. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1779. #endif
  1780. #if JUCE_WINDOWS
  1781. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1782. #endif
  1783. #if JUCE_DEBUG
  1784. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1785. #endif
  1786. static bool juceInitialisedNonGUI = false;
  1787. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1788. {
  1789. if (! juceInitialisedNonGUI)
  1790. {
  1791. juceInitialisedNonGUI = true;
  1792. JUCE_AUTORELEASEPOOL
  1793. DBG (SystemStats::getJUCEVersion());
  1794. SystemStats::initialiseStats();
  1795. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1796. }
  1797. // Some basic tests, to keep an eye on things and make sure these types work ok
  1798. // on all platforms. Let me know if any of these assertions fail on your system!
  1799. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1800. static_jassert (sizeof (int8) == 1);
  1801. static_jassert (sizeof (uint8) == 1);
  1802. static_jassert (sizeof (int16) == 2);
  1803. static_jassert (sizeof (uint16) == 2);
  1804. static_jassert (sizeof (int32) == 4);
  1805. static_jassert (sizeof (uint32) == 4);
  1806. static_jassert (sizeof (int64) == 8);
  1807. static_jassert (sizeof (uint64) == 8);
  1808. }
  1809. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1810. {
  1811. if (juceInitialisedNonGUI)
  1812. {
  1813. juceInitialisedNonGUI = false;
  1814. JUCE_AUTORELEASEPOOL
  1815. LocalisedStrings::setCurrentMappings (0);
  1816. Thread::stopAllThreads (3000);
  1817. #if JUCE_WINDOWS
  1818. juce_shutdownWin32Sockets();
  1819. #endif
  1820. #if JUCE_DEBUG
  1821. juce_CheckForDanglingStreams();
  1822. #endif
  1823. }
  1824. }
  1825. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1826. void juce_setCurrentThreadName (const String& name);
  1827. static bool juceInitialisedGUI = false;
  1828. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1829. {
  1830. if (! juceInitialisedGUI)
  1831. {
  1832. juceInitialisedGUI = true;
  1833. JUCE_AUTORELEASEPOOL
  1834. initialiseJuce_NonGUI();
  1835. MessageManager::getInstance();
  1836. LookAndFeel::setDefaultLookAndFeel (0);
  1837. juce_setCurrentThreadName ("Juce Message Thread");
  1838. #if JUCE_DEBUG
  1839. // This section is just for catching people who mess up their project settings and
  1840. // turn RTTI off..
  1841. try
  1842. {
  1843. TextButton tb (String::empty);
  1844. Component* c = &tb;
  1845. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1846. c = dynamic_cast <Button*> (c);
  1847. }
  1848. catch (...)
  1849. {
  1850. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1851. jassertfalse;
  1852. }
  1853. #endif
  1854. }
  1855. }
  1856. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1857. {
  1858. if (juceInitialisedGUI)
  1859. {
  1860. juceInitialisedGUI = false;
  1861. JUCE_AUTORELEASEPOOL
  1862. DeletedAtShutdown::deleteAll();
  1863. LookAndFeel::clearDefaultLookAndFeel();
  1864. delete MessageManager::getInstance();
  1865. shutdownJuce_NonGUI();
  1866. }
  1867. }
  1868. #endif
  1869. #if JUCE_UNIT_TESTS
  1870. class AtomicTests : public UnitTest
  1871. {
  1872. public:
  1873. AtomicTests() : UnitTest ("Atomics") {}
  1874. void runTest()
  1875. {
  1876. beginTest ("Misc");
  1877. char a1[7];
  1878. expect (numElementsInArray(a1) == 7);
  1879. int a2[3];
  1880. expect (numElementsInArray(a2) == 3);
  1881. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1882. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1883. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1884. beginTest ("Atomic types");
  1885. AtomicTester <int>::testInteger (*this);
  1886. AtomicTester <unsigned int>::testInteger (*this);
  1887. AtomicTester <int32>::testInteger (*this);
  1888. AtomicTester <uint32>::testInteger (*this);
  1889. AtomicTester <long>::testInteger (*this);
  1890. AtomicTester <void*>::testInteger (*this);
  1891. AtomicTester <int*>::testInteger (*this);
  1892. AtomicTester <float>::testFloat (*this);
  1893. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1894. AtomicTester <int64>::testInteger (*this);
  1895. AtomicTester <uint64>::testInteger (*this);
  1896. AtomicTester <double>::testFloat (*this);
  1897. #endif
  1898. }
  1899. template <typename Type>
  1900. class AtomicTester
  1901. {
  1902. public:
  1903. AtomicTester() {}
  1904. static void testInteger (UnitTest& test)
  1905. {
  1906. Atomic<Type> a, b;
  1907. a.set ((Type) 10);
  1908. a += (Type) 15;
  1909. a.memoryBarrier();
  1910. a -= (Type) 5;
  1911. ++a; ++a; --a;
  1912. a.memoryBarrier();
  1913. testFloat (test);
  1914. }
  1915. static void testFloat (UnitTest& test)
  1916. {
  1917. Atomic<Type> a, b;
  1918. a = (Type) 21;
  1919. a.memoryBarrier();
  1920. /* These are some simple test cases to check the atomics - let me know
  1921. if any of these assertions fail on your system!
  1922. */
  1923. test.expect (a.get() == (Type) 21);
  1924. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1925. test.expect (a.get() == (Type) 21);
  1926. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1927. test.expect (a.get() == (Type) 101);
  1928. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1929. test.expect (a.get() == (Type) 101);
  1930. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1931. test.expect (a.get() == (Type) 200);
  1932. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1933. test.expect (a.get() == (Type) 300);
  1934. b = a;
  1935. test.expect (b.get() == a.get());
  1936. }
  1937. };
  1938. };
  1939. static AtomicTests atomicUnitTests;
  1940. #endif
  1941. END_JUCE_NAMESPACE
  1942. /*** End of inlined file: juce_Initialisation.cpp ***/
  1943. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1944. BEGIN_JUCE_NAMESPACE
  1945. BigInteger::BigInteger()
  1946. : numValues (4),
  1947. highestBit (-1),
  1948. negative (false)
  1949. {
  1950. values.calloc (numValues + 1);
  1951. }
  1952. BigInteger::BigInteger (const int value)
  1953. : numValues (4),
  1954. highestBit (31),
  1955. negative (value < 0)
  1956. {
  1957. values.calloc (numValues + 1);
  1958. values[0] = abs (value);
  1959. highestBit = getHighestBit();
  1960. }
  1961. BigInteger::BigInteger (int64 value)
  1962. : numValues (4),
  1963. highestBit (63),
  1964. negative (value < 0)
  1965. {
  1966. values.calloc (numValues + 1);
  1967. if (value < 0)
  1968. value = -value;
  1969. values[0] = (unsigned int) value;
  1970. values[1] = (unsigned int) (value >> 32);
  1971. highestBit = getHighestBit();
  1972. }
  1973. BigInteger::BigInteger (const unsigned int value)
  1974. : numValues (4),
  1975. highestBit (31),
  1976. negative (false)
  1977. {
  1978. values.calloc (numValues + 1);
  1979. values[0] = value;
  1980. highestBit = getHighestBit();
  1981. }
  1982. BigInteger::BigInteger (const BigInteger& other)
  1983. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1984. highestBit (other.getHighestBit()),
  1985. negative (other.negative)
  1986. {
  1987. values.malloc (numValues + 1);
  1988. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1989. }
  1990. BigInteger::~BigInteger()
  1991. {
  1992. }
  1993. void BigInteger::swapWith (BigInteger& other) throw()
  1994. {
  1995. values.swapWith (other.values);
  1996. swapVariables (numValues, other.numValues);
  1997. swapVariables (highestBit, other.highestBit);
  1998. swapVariables (negative, other.negative);
  1999. }
  2000. BigInteger& BigInteger::operator= (const BigInteger& other)
  2001. {
  2002. if (this != &other)
  2003. {
  2004. highestBit = other.getHighestBit();
  2005. numValues = jmax (4, (highestBit >> 5) + 1);
  2006. negative = other.negative;
  2007. values.malloc (numValues + 1);
  2008. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2009. }
  2010. return *this;
  2011. }
  2012. void BigInteger::ensureSize (const int numVals)
  2013. {
  2014. if (numVals + 2 >= numValues)
  2015. {
  2016. int oldSize = numValues;
  2017. numValues = ((numVals + 2) * 3) / 2;
  2018. values.realloc (numValues + 1);
  2019. while (oldSize < numValues)
  2020. values [oldSize++] = 0;
  2021. }
  2022. }
  2023. bool BigInteger::operator[] (const int bit) const throw()
  2024. {
  2025. return bit <= highestBit && bit >= 0
  2026. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2027. }
  2028. int BigInteger::toInteger() const throw()
  2029. {
  2030. const int n = (int) (values[0] & 0x7fffffff);
  2031. return negative ? -n : n;
  2032. }
  2033. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2034. {
  2035. BigInteger r;
  2036. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2037. r.ensureSize (numBits >> 5);
  2038. r.highestBit = numBits;
  2039. int i = 0;
  2040. while (numBits > 0)
  2041. {
  2042. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2043. numBits -= 32;
  2044. startBit += 32;
  2045. }
  2046. r.highestBit = r.getHighestBit();
  2047. return r;
  2048. }
  2049. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2050. {
  2051. if (numBits > 32)
  2052. {
  2053. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2054. numBits = 32;
  2055. }
  2056. numBits = jmin (numBits, highestBit + 1 - startBit);
  2057. if (numBits <= 0)
  2058. return 0;
  2059. const int pos = startBit >> 5;
  2060. const int offset = startBit & 31;
  2061. const int endSpace = 32 - numBits;
  2062. uint32 n = ((uint32) values [pos]) >> offset;
  2063. if (offset > endSpace)
  2064. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2065. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2066. }
  2067. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2068. {
  2069. if (numBits > 32)
  2070. {
  2071. jassertfalse;
  2072. numBits = 32;
  2073. }
  2074. for (int i = 0; i < numBits; ++i)
  2075. {
  2076. setBit (startBit + i, (valueToSet & 1) != 0);
  2077. valueToSet >>= 1;
  2078. }
  2079. }
  2080. void BigInteger::clear()
  2081. {
  2082. if (numValues > 16)
  2083. {
  2084. numValues = 4;
  2085. values.calloc (numValues + 1);
  2086. }
  2087. else
  2088. {
  2089. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2090. }
  2091. highestBit = -1;
  2092. negative = false;
  2093. }
  2094. void BigInteger::setBit (const int bit)
  2095. {
  2096. if (bit >= 0)
  2097. {
  2098. if (bit > highestBit)
  2099. {
  2100. ensureSize (bit >> 5);
  2101. highestBit = bit;
  2102. }
  2103. values [bit >> 5] |= (1 << (bit & 31));
  2104. }
  2105. }
  2106. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2107. {
  2108. if (shouldBeSet)
  2109. setBit (bit);
  2110. else
  2111. clearBit (bit);
  2112. }
  2113. void BigInteger::clearBit (const int bit) throw()
  2114. {
  2115. if (bit >= 0 && bit <= highestBit)
  2116. values [bit >> 5] &= ~(1 << (bit & 31));
  2117. }
  2118. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2119. {
  2120. while (--numBits >= 0)
  2121. setBit (startBit++, shouldBeSet);
  2122. }
  2123. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2124. {
  2125. if (bit >= 0)
  2126. shiftBits (1, bit);
  2127. setBit (bit, shouldBeSet);
  2128. }
  2129. bool BigInteger::isZero() const throw()
  2130. {
  2131. return getHighestBit() < 0;
  2132. }
  2133. bool BigInteger::isOne() const throw()
  2134. {
  2135. return getHighestBit() == 0 && ! negative;
  2136. }
  2137. bool BigInteger::isNegative() const throw()
  2138. {
  2139. return negative && ! isZero();
  2140. }
  2141. void BigInteger::setNegative (const bool neg) throw()
  2142. {
  2143. negative = neg;
  2144. }
  2145. void BigInteger::negate() throw()
  2146. {
  2147. negative = (! negative) && ! isZero();
  2148. }
  2149. int BigInteger::countNumberOfSetBits() const throw()
  2150. {
  2151. int total = 0;
  2152. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2153. {
  2154. unsigned int n = values[i];
  2155. if (n == 0xffffffff)
  2156. {
  2157. total += 32;
  2158. }
  2159. else
  2160. {
  2161. while (n != 0)
  2162. {
  2163. total += (n & 1);
  2164. n >>= 1;
  2165. }
  2166. }
  2167. }
  2168. return total;
  2169. }
  2170. int BigInteger::getHighestBit() const throw()
  2171. {
  2172. for (int i = highestBit + 1; --i >= 0;)
  2173. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2174. return i;
  2175. return -1;
  2176. }
  2177. int BigInteger::findNextSetBit (int i) const throw()
  2178. {
  2179. for (; i <= highestBit; ++i)
  2180. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2181. return i;
  2182. return -1;
  2183. }
  2184. int BigInteger::findNextClearBit (int i) const throw()
  2185. {
  2186. for (; i <= highestBit; ++i)
  2187. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2188. break;
  2189. return i;
  2190. }
  2191. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2192. {
  2193. if (other.isNegative())
  2194. return operator-= (-other);
  2195. if (isNegative())
  2196. {
  2197. if (compareAbsolute (other) < 0)
  2198. {
  2199. BigInteger temp (*this);
  2200. temp.negate();
  2201. *this = other;
  2202. operator-= (temp);
  2203. }
  2204. else
  2205. {
  2206. negate();
  2207. operator-= (other);
  2208. negate();
  2209. }
  2210. }
  2211. else
  2212. {
  2213. if (other.highestBit > highestBit)
  2214. highestBit = other.highestBit;
  2215. ++highestBit;
  2216. const int numInts = (highestBit >> 5) + 1;
  2217. ensureSize (numInts);
  2218. int64 remainder = 0;
  2219. for (int i = 0; i <= numInts; ++i)
  2220. {
  2221. if (i < numValues)
  2222. remainder += values[i];
  2223. if (i < other.numValues)
  2224. remainder += other.values[i];
  2225. values[i] = (unsigned int) remainder;
  2226. remainder >>= 32;
  2227. }
  2228. jassert (remainder == 0);
  2229. highestBit = getHighestBit();
  2230. }
  2231. return *this;
  2232. }
  2233. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2234. {
  2235. if (other.isNegative())
  2236. return operator+= (-other);
  2237. if (! isNegative())
  2238. {
  2239. if (compareAbsolute (other) < 0)
  2240. {
  2241. BigInteger temp (other);
  2242. swapWith (temp);
  2243. operator-= (temp);
  2244. negate();
  2245. return *this;
  2246. }
  2247. }
  2248. else
  2249. {
  2250. negate();
  2251. operator+= (other);
  2252. negate();
  2253. return *this;
  2254. }
  2255. const int numInts = (highestBit >> 5) + 1;
  2256. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2257. int64 amountToSubtract = 0;
  2258. for (int i = 0; i <= numInts; ++i)
  2259. {
  2260. if (i <= maxOtherInts)
  2261. amountToSubtract += (int64) other.values[i];
  2262. if (values[i] >= amountToSubtract)
  2263. {
  2264. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2265. amountToSubtract = 0;
  2266. }
  2267. else
  2268. {
  2269. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2270. values[i] = (unsigned int) n;
  2271. amountToSubtract = 1;
  2272. }
  2273. }
  2274. return *this;
  2275. }
  2276. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2277. {
  2278. BigInteger total;
  2279. highestBit = getHighestBit();
  2280. const bool wasNegative = isNegative();
  2281. setNegative (false);
  2282. for (int i = 0; i <= highestBit; ++i)
  2283. {
  2284. if (operator[](i))
  2285. {
  2286. BigInteger n (other);
  2287. n.setNegative (false);
  2288. n <<= i;
  2289. total += n;
  2290. }
  2291. }
  2292. total.setNegative (wasNegative ^ other.isNegative());
  2293. swapWith (total);
  2294. return *this;
  2295. }
  2296. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2297. {
  2298. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2299. const int divHB = divisor.getHighestBit();
  2300. const int ourHB = getHighestBit();
  2301. if (divHB < 0 || ourHB < 0)
  2302. {
  2303. // division by zero
  2304. remainder.clear();
  2305. clear();
  2306. }
  2307. else
  2308. {
  2309. const bool wasNegative = isNegative();
  2310. swapWith (remainder);
  2311. remainder.setNegative (false);
  2312. clear();
  2313. BigInteger temp (divisor);
  2314. temp.setNegative (false);
  2315. int leftShift = ourHB - divHB;
  2316. temp <<= leftShift;
  2317. while (leftShift >= 0)
  2318. {
  2319. if (remainder.compareAbsolute (temp) >= 0)
  2320. {
  2321. remainder -= temp;
  2322. setBit (leftShift);
  2323. }
  2324. if (--leftShift >= 0)
  2325. temp >>= 1;
  2326. }
  2327. negative = wasNegative ^ divisor.isNegative();
  2328. remainder.setNegative (wasNegative);
  2329. }
  2330. }
  2331. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2332. {
  2333. BigInteger remainder;
  2334. divideBy (other, remainder);
  2335. return *this;
  2336. }
  2337. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2338. {
  2339. // this operation doesn't take into account negative values..
  2340. jassert (isNegative() == other.isNegative());
  2341. if (other.highestBit >= 0)
  2342. {
  2343. ensureSize (other.highestBit >> 5);
  2344. int n = (other.highestBit >> 5) + 1;
  2345. while (--n >= 0)
  2346. values[n] |= other.values[n];
  2347. if (other.highestBit > highestBit)
  2348. highestBit = other.highestBit;
  2349. highestBit = getHighestBit();
  2350. }
  2351. return *this;
  2352. }
  2353. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2354. {
  2355. // this operation doesn't take into account negative values..
  2356. jassert (isNegative() == other.isNegative());
  2357. int n = numValues;
  2358. while (n > other.numValues)
  2359. values[--n] = 0;
  2360. while (--n >= 0)
  2361. values[n] &= other.values[n];
  2362. if (other.highestBit < highestBit)
  2363. highestBit = other.highestBit;
  2364. highestBit = getHighestBit();
  2365. return *this;
  2366. }
  2367. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2368. {
  2369. // this operation will only work with the absolute values
  2370. jassert (isNegative() == other.isNegative());
  2371. if (other.highestBit >= 0)
  2372. {
  2373. ensureSize (other.highestBit >> 5);
  2374. int n = (other.highestBit >> 5) + 1;
  2375. while (--n >= 0)
  2376. values[n] ^= other.values[n];
  2377. if (other.highestBit > highestBit)
  2378. highestBit = other.highestBit;
  2379. highestBit = getHighestBit();
  2380. }
  2381. return *this;
  2382. }
  2383. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2384. {
  2385. BigInteger remainder;
  2386. divideBy (divisor, remainder);
  2387. swapWith (remainder);
  2388. return *this;
  2389. }
  2390. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2391. {
  2392. shiftBits (numBitsToShift, 0);
  2393. return *this;
  2394. }
  2395. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2396. {
  2397. return operator<<= (-numBitsToShift);
  2398. }
  2399. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2400. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2401. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2402. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2403. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2404. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2405. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2406. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2407. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2408. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2409. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2410. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2411. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2412. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2413. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2414. int BigInteger::compare (const BigInteger& other) const throw()
  2415. {
  2416. if (isNegative() == other.isNegative())
  2417. {
  2418. const int absComp = compareAbsolute (other);
  2419. return isNegative() ? -absComp : absComp;
  2420. }
  2421. else
  2422. {
  2423. return isNegative() ? -1 : 1;
  2424. }
  2425. }
  2426. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2427. {
  2428. const int h1 = getHighestBit();
  2429. const int h2 = other.getHighestBit();
  2430. if (h1 > h2)
  2431. return 1;
  2432. else if (h1 < h2)
  2433. return -1;
  2434. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2435. if (values[i] != other.values[i])
  2436. return (values[i] > other.values[i]) ? 1 : -1;
  2437. return 0;
  2438. }
  2439. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2440. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2441. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2442. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2443. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2444. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2445. void BigInteger::shiftBits (int bits, const int startBit)
  2446. {
  2447. if (highestBit < 0)
  2448. return;
  2449. if (startBit > 0)
  2450. {
  2451. if (bits < 0)
  2452. {
  2453. // right shift
  2454. for (int i = startBit; i <= highestBit; ++i)
  2455. setBit (i, operator[] (i - bits));
  2456. highestBit = getHighestBit();
  2457. }
  2458. else if (bits > 0)
  2459. {
  2460. // left shift
  2461. for (int i = highestBit + 1; --i >= startBit;)
  2462. setBit (i + bits, operator[] (i));
  2463. while (--bits >= 0)
  2464. clearBit (bits + startBit);
  2465. }
  2466. }
  2467. else
  2468. {
  2469. if (bits < 0)
  2470. {
  2471. // right shift
  2472. bits = -bits;
  2473. if (bits > highestBit)
  2474. {
  2475. clear();
  2476. }
  2477. else
  2478. {
  2479. const int wordsToMove = bits >> 5;
  2480. int top = 1 + (highestBit >> 5) - wordsToMove;
  2481. highestBit -= bits;
  2482. if (wordsToMove > 0)
  2483. {
  2484. int i;
  2485. for (i = 0; i < top; ++i)
  2486. values [i] = values [i + wordsToMove];
  2487. for (i = 0; i < wordsToMove; ++i)
  2488. values [top + i] = 0;
  2489. bits &= 31;
  2490. }
  2491. if (bits != 0)
  2492. {
  2493. const int invBits = 32 - bits;
  2494. --top;
  2495. for (int i = 0; i < top; ++i)
  2496. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2497. values[top] = (values[top] >> bits);
  2498. }
  2499. highestBit = getHighestBit();
  2500. }
  2501. }
  2502. else if (bits > 0)
  2503. {
  2504. // left shift
  2505. ensureSize (((highestBit + bits) >> 5) + 1);
  2506. const int wordsToMove = bits >> 5;
  2507. int top = 1 + (highestBit >> 5);
  2508. highestBit += bits;
  2509. if (wordsToMove > 0)
  2510. {
  2511. int i;
  2512. for (i = top; --i >= 0;)
  2513. values [i + wordsToMove] = values [i];
  2514. for (i = 0; i < wordsToMove; ++i)
  2515. values [i] = 0;
  2516. bits &= 31;
  2517. }
  2518. if (bits != 0)
  2519. {
  2520. const int invBits = 32 - bits;
  2521. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2522. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2523. values [wordsToMove] = values [wordsToMove] << bits;
  2524. }
  2525. highestBit = getHighestBit();
  2526. }
  2527. }
  2528. }
  2529. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2530. {
  2531. while (! m->isZero())
  2532. {
  2533. if (n->compareAbsolute (*m) > 0)
  2534. swapVariables (m, n);
  2535. *m -= *n;
  2536. }
  2537. return *n;
  2538. }
  2539. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2540. {
  2541. BigInteger m (*this);
  2542. while (! n.isZero())
  2543. {
  2544. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2545. return simpleGCD (&m, &n);
  2546. BigInteger temp1 (m), temp2;
  2547. temp1.divideBy (n, temp2);
  2548. m = n;
  2549. n = temp2;
  2550. }
  2551. return m;
  2552. }
  2553. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2554. {
  2555. BigInteger exp (exponent);
  2556. exp %= modulus;
  2557. BigInteger value (1);
  2558. swapWith (value);
  2559. value %= modulus;
  2560. while (! exp.isZero())
  2561. {
  2562. if (exp [0])
  2563. {
  2564. operator*= (value);
  2565. operator%= (modulus);
  2566. }
  2567. value *= value;
  2568. value %= modulus;
  2569. exp >>= 1;
  2570. }
  2571. }
  2572. void BigInteger::inverseModulo (const BigInteger& modulus)
  2573. {
  2574. if (modulus.isOne() || modulus.isNegative())
  2575. {
  2576. clear();
  2577. return;
  2578. }
  2579. if (isNegative() || compareAbsolute (modulus) >= 0)
  2580. operator%= (modulus);
  2581. if (isOne())
  2582. return;
  2583. if (! (*this)[0])
  2584. {
  2585. // not invertible
  2586. clear();
  2587. return;
  2588. }
  2589. BigInteger a1 (modulus);
  2590. BigInteger a2 (*this);
  2591. BigInteger b1 (modulus);
  2592. BigInteger b2 (1);
  2593. while (! a2.isOne())
  2594. {
  2595. BigInteger temp1, temp2, multiplier (a1);
  2596. multiplier.divideBy (a2, temp1);
  2597. temp1 = a2;
  2598. temp1 *= multiplier;
  2599. temp2 = a1;
  2600. temp2 -= temp1;
  2601. a1 = a2;
  2602. a2 = temp2;
  2603. temp1 = b2;
  2604. temp1 *= multiplier;
  2605. temp2 = b1;
  2606. temp2 -= temp1;
  2607. b1 = b2;
  2608. b2 = temp2;
  2609. }
  2610. while (b2.isNegative())
  2611. b2 += modulus;
  2612. b2 %= modulus;
  2613. swapWith (b2);
  2614. }
  2615. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2616. {
  2617. return stream << value.toString (10);
  2618. }
  2619. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2620. {
  2621. String s;
  2622. BigInteger v (*this);
  2623. if (base == 2 || base == 8 || base == 16)
  2624. {
  2625. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2626. static const char* const hexDigits = "0123456789abcdef";
  2627. for (;;)
  2628. {
  2629. const int remainder = v.getBitRangeAsInt (0, bits);
  2630. v >>= bits;
  2631. if (remainder == 0 && v.isZero())
  2632. break;
  2633. s = String::charToString (hexDigits [remainder]) + s;
  2634. }
  2635. }
  2636. else if (base == 10)
  2637. {
  2638. const BigInteger ten (10);
  2639. BigInteger remainder;
  2640. for (;;)
  2641. {
  2642. v.divideBy (ten, remainder);
  2643. if (remainder.isZero() && v.isZero())
  2644. break;
  2645. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2646. }
  2647. }
  2648. else
  2649. {
  2650. jassertfalse; // can't do the specified base!
  2651. return String::empty;
  2652. }
  2653. s = s.paddedLeft ('0', minimumNumCharacters);
  2654. return isNegative() ? "-" + s : s;
  2655. }
  2656. void BigInteger::parseString (const String& text, const int base)
  2657. {
  2658. clear();
  2659. const juce_wchar* t = text;
  2660. if (base == 2 || base == 8 || base == 16)
  2661. {
  2662. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2663. for (;;)
  2664. {
  2665. const juce_wchar c = *t++;
  2666. const int digit = CharacterFunctions::getHexDigitValue (c);
  2667. if (((unsigned int) digit) < (unsigned int) base)
  2668. {
  2669. operator<<= (bits);
  2670. operator+= (digit);
  2671. }
  2672. else if (c == 0)
  2673. {
  2674. break;
  2675. }
  2676. }
  2677. }
  2678. else if (base == 10)
  2679. {
  2680. const BigInteger ten ((unsigned int) 10);
  2681. for (;;)
  2682. {
  2683. const juce_wchar c = *t++;
  2684. if (c >= '0' && c <= '9')
  2685. {
  2686. operator*= (ten);
  2687. operator+= ((int) (c - '0'));
  2688. }
  2689. else if (c == 0)
  2690. {
  2691. break;
  2692. }
  2693. }
  2694. }
  2695. setNegative (text.trimStart().startsWithChar ('-'));
  2696. }
  2697. const MemoryBlock BigInteger::toMemoryBlock() const
  2698. {
  2699. const int numBytes = (getHighestBit() + 8) >> 3;
  2700. MemoryBlock mb ((size_t) numBytes);
  2701. for (int i = 0; i < numBytes; ++i)
  2702. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2703. return mb;
  2704. }
  2705. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2706. {
  2707. clear();
  2708. for (int i = (int) data.getSize(); --i >= 0;)
  2709. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2710. }
  2711. END_JUCE_NAMESPACE
  2712. /*** End of inlined file: juce_BigInteger.cpp ***/
  2713. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2714. BEGIN_JUCE_NAMESPACE
  2715. MemoryBlock::MemoryBlock() throw()
  2716. : size (0)
  2717. {
  2718. }
  2719. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2720. {
  2721. if (initialSize > 0)
  2722. {
  2723. size = initialSize;
  2724. data.allocate (initialSize, initialiseToZero);
  2725. }
  2726. else
  2727. {
  2728. size = 0;
  2729. }
  2730. }
  2731. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2732. : size (other.size)
  2733. {
  2734. if (size > 0)
  2735. {
  2736. jassert (other.data != 0);
  2737. data.malloc (size);
  2738. memcpy (data, other.data, size);
  2739. }
  2740. }
  2741. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2742. : size (jmax ((size_t) 0, sizeInBytes))
  2743. {
  2744. jassert (sizeInBytes >= 0);
  2745. if (size > 0)
  2746. {
  2747. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2748. data.malloc (size);
  2749. if (dataToInitialiseFrom != 0)
  2750. memcpy (data, dataToInitialiseFrom, size);
  2751. }
  2752. }
  2753. MemoryBlock::~MemoryBlock() throw()
  2754. {
  2755. jassert (size >= 0); // should never happen
  2756. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2757. }
  2758. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2759. {
  2760. if (this != &other)
  2761. {
  2762. setSize (other.size, false);
  2763. memcpy (data, other.data, size);
  2764. }
  2765. return *this;
  2766. }
  2767. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2768. {
  2769. return matches (other.data, other.size);
  2770. }
  2771. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2772. {
  2773. return ! operator== (other);
  2774. }
  2775. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2776. {
  2777. return size == dataSize
  2778. && memcmp (data, dataToCompare, size) == 0;
  2779. }
  2780. // this will resize the block to this size
  2781. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2782. {
  2783. if (size != newSize)
  2784. {
  2785. if (newSize <= 0)
  2786. {
  2787. data.free();
  2788. size = 0;
  2789. }
  2790. else
  2791. {
  2792. if (data != 0)
  2793. {
  2794. data.realloc (newSize);
  2795. if (initialiseToZero && (newSize > size))
  2796. zeromem (data + size, newSize - size);
  2797. }
  2798. else
  2799. {
  2800. data.allocate (newSize, initialiseToZero);
  2801. }
  2802. size = newSize;
  2803. }
  2804. }
  2805. }
  2806. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2807. {
  2808. if (size < minimumSize)
  2809. setSize (minimumSize, initialiseToZero);
  2810. }
  2811. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2812. {
  2813. swapVariables (size, other.size);
  2814. data.swapWith (other.data);
  2815. }
  2816. void MemoryBlock::fillWith (const uint8 value) throw()
  2817. {
  2818. memset (data, (int) value, size);
  2819. }
  2820. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2821. {
  2822. if (numBytes > 0)
  2823. {
  2824. const size_t oldSize = size;
  2825. setSize (size + numBytes);
  2826. memcpy (data + oldSize, srcData, numBytes);
  2827. }
  2828. }
  2829. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2830. {
  2831. const char* d = static_cast<const char*> (src);
  2832. if (offset < 0)
  2833. {
  2834. d -= offset;
  2835. num -= offset;
  2836. offset = 0;
  2837. }
  2838. if (offset + num > size)
  2839. num = size - offset;
  2840. if (num > 0)
  2841. memcpy (data + offset, d, num);
  2842. }
  2843. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2844. {
  2845. char* d = static_cast<char*> (dst);
  2846. if (offset < 0)
  2847. {
  2848. zeromem (d, -offset);
  2849. d -= offset;
  2850. num += offset;
  2851. offset = 0;
  2852. }
  2853. if (offset + num > size)
  2854. {
  2855. const size_t newNum = size - offset;
  2856. zeromem (d + newNum, num - newNum);
  2857. num = newNum;
  2858. }
  2859. if (num > 0)
  2860. memcpy (d, data + offset, num);
  2861. }
  2862. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2863. {
  2864. if (startByte < 0)
  2865. {
  2866. numBytesToRemove += startByte;
  2867. startByte = 0;
  2868. }
  2869. if (startByte + numBytesToRemove >= size)
  2870. {
  2871. setSize (startByte);
  2872. }
  2873. else if (numBytesToRemove > 0)
  2874. {
  2875. memmove (data + startByte,
  2876. data + startByte + numBytesToRemove,
  2877. size - (startByte + numBytesToRemove));
  2878. setSize (size - numBytesToRemove);
  2879. }
  2880. }
  2881. const String MemoryBlock::toString() const
  2882. {
  2883. return String (static_cast <const char*> (getData()), size);
  2884. }
  2885. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2886. {
  2887. int res = 0;
  2888. size_t byte = bitRangeStart >> 3;
  2889. int offsetInByte = (int) bitRangeStart & 7;
  2890. size_t bitsSoFar = 0;
  2891. while (numBits > 0 && (size_t) byte < size)
  2892. {
  2893. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2894. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2895. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2896. bitsSoFar += bitsThisTime;
  2897. numBits -= bitsThisTime;
  2898. ++byte;
  2899. offsetInByte = 0;
  2900. }
  2901. return res;
  2902. }
  2903. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2904. {
  2905. size_t byte = bitRangeStart >> 3;
  2906. int offsetInByte = (int) bitRangeStart & 7;
  2907. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2908. while (numBits > 0 && (size_t) byte < size)
  2909. {
  2910. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2911. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2912. const unsigned int tempBits = bitsToSet << offsetInByte;
  2913. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2914. ++byte;
  2915. numBits -= bitsThisTime;
  2916. bitsToSet >>= bitsThisTime;
  2917. mask >>= bitsThisTime;
  2918. offsetInByte = 0;
  2919. }
  2920. }
  2921. void MemoryBlock::loadFromHexString (const String& hex)
  2922. {
  2923. ensureSize (hex.length() >> 1);
  2924. char* dest = data;
  2925. int i = 0;
  2926. for (;;)
  2927. {
  2928. int byte = 0;
  2929. for (int loop = 2; --loop >= 0;)
  2930. {
  2931. byte <<= 4;
  2932. for (;;)
  2933. {
  2934. const juce_wchar c = hex [i++];
  2935. if (c >= '0' && c <= '9')
  2936. {
  2937. byte |= c - '0';
  2938. break;
  2939. }
  2940. else if (c >= 'a' && c <= 'z')
  2941. {
  2942. byte |= c - ('a' - 10);
  2943. break;
  2944. }
  2945. else if (c >= 'A' && c <= 'Z')
  2946. {
  2947. byte |= c - ('A' - 10);
  2948. break;
  2949. }
  2950. else if (c == 0)
  2951. {
  2952. setSize (static_cast <size_t> (dest - data));
  2953. return;
  2954. }
  2955. }
  2956. }
  2957. *dest++ = (char) byte;
  2958. }
  2959. }
  2960. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2961. const String MemoryBlock::toBase64Encoding() const
  2962. {
  2963. const size_t numChars = ((size << 3) + 5) / 6;
  2964. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2965. const int initialLen = destString.length();
  2966. destString.preallocateStorage (initialLen + 2 + numChars);
  2967. juce_wchar* d = destString;
  2968. d += initialLen;
  2969. *d++ = '.';
  2970. for (size_t i = 0; i < numChars; ++i)
  2971. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2972. *d++ = 0;
  2973. return destString;
  2974. }
  2975. bool MemoryBlock::fromBase64Encoding (const String& s)
  2976. {
  2977. const int startPos = s.indexOfChar ('.') + 1;
  2978. if (startPos <= 0)
  2979. return false;
  2980. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2981. setSize (numBytesNeeded, true);
  2982. const int numChars = s.length() - startPos;
  2983. const juce_wchar* srcChars = s;
  2984. srcChars += startPos;
  2985. int pos = 0;
  2986. for (int i = 0; i < numChars; ++i)
  2987. {
  2988. const char c = (char) srcChars[i];
  2989. for (int j = 0; j < 64; ++j)
  2990. {
  2991. if (encodingTable[j] == c)
  2992. {
  2993. setBitRange (pos, 6, j);
  2994. pos += 6;
  2995. break;
  2996. }
  2997. }
  2998. }
  2999. return true;
  3000. }
  3001. END_JUCE_NAMESPACE
  3002. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3003. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3004. BEGIN_JUCE_NAMESPACE
  3005. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3006. : properties (ignoreCaseOfKeyNames),
  3007. fallbackProperties (0),
  3008. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3009. {
  3010. }
  3011. PropertySet::PropertySet (const PropertySet& other)
  3012. : properties (other.properties),
  3013. fallbackProperties (other.fallbackProperties),
  3014. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3015. {
  3016. }
  3017. PropertySet& PropertySet::operator= (const PropertySet& other)
  3018. {
  3019. properties = other.properties;
  3020. fallbackProperties = other.fallbackProperties;
  3021. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3022. propertyChanged();
  3023. return *this;
  3024. }
  3025. PropertySet::~PropertySet()
  3026. {
  3027. }
  3028. void PropertySet::clear()
  3029. {
  3030. const ScopedLock sl (lock);
  3031. if (properties.size() > 0)
  3032. {
  3033. properties.clear();
  3034. propertyChanged();
  3035. }
  3036. }
  3037. const String PropertySet::getValue (const String& keyName,
  3038. const String& defaultValue) const throw()
  3039. {
  3040. const ScopedLock sl (lock);
  3041. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3042. if (index >= 0)
  3043. return properties.getAllValues() [index];
  3044. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3045. : defaultValue;
  3046. }
  3047. int PropertySet::getIntValue (const String& keyName,
  3048. const int defaultValue) const throw()
  3049. {
  3050. const ScopedLock sl (lock);
  3051. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3052. if (index >= 0)
  3053. return properties.getAllValues() [index].getIntValue();
  3054. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3055. : defaultValue;
  3056. }
  3057. double PropertySet::getDoubleValue (const String& keyName,
  3058. const double defaultValue) const throw()
  3059. {
  3060. const ScopedLock sl (lock);
  3061. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3062. if (index >= 0)
  3063. return properties.getAllValues()[index].getDoubleValue();
  3064. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3065. : defaultValue;
  3066. }
  3067. bool PropertySet::getBoolValue (const String& keyName,
  3068. const bool defaultValue) const throw()
  3069. {
  3070. const ScopedLock sl (lock);
  3071. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3072. if (index >= 0)
  3073. return properties.getAllValues() [index].getIntValue() != 0;
  3074. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3075. : defaultValue;
  3076. }
  3077. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3078. {
  3079. XmlDocument doc (getValue (keyName));
  3080. return doc.getDocumentElement();
  3081. }
  3082. void PropertySet::setValue (const String& keyName, const var& v)
  3083. {
  3084. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3085. if (keyName.isNotEmpty())
  3086. {
  3087. const String value (v.toString());
  3088. const ScopedLock sl (lock);
  3089. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3090. if (index < 0 || properties.getAllValues() [index] != value)
  3091. {
  3092. properties.set (keyName, value);
  3093. propertyChanged();
  3094. }
  3095. }
  3096. }
  3097. void PropertySet::removeValue (const String& keyName)
  3098. {
  3099. if (keyName.isNotEmpty())
  3100. {
  3101. const ScopedLock sl (lock);
  3102. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3103. if (index >= 0)
  3104. {
  3105. properties.remove (keyName);
  3106. propertyChanged();
  3107. }
  3108. }
  3109. }
  3110. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3111. {
  3112. setValue (keyName, xml == 0 ? var::null
  3113. : var (xml->createDocument (String::empty, true)));
  3114. }
  3115. bool PropertySet::containsKey (const String& keyName) const throw()
  3116. {
  3117. const ScopedLock sl (lock);
  3118. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3119. }
  3120. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3121. {
  3122. const ScopedLock sl (lock);
  3123. fallbackProperties = fallbackProperties_;
  3124. }
  3125. XmlElement* PropertySet::createXml (const String& nodeName) const
  3126. {
  3127. const ScopedLock sl (lock);
  3128. XmlElement* const xml = new XmlElement (nodeName);
  3129. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3130. {
  3131. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3132. e->setAttribute ("name", properties.getAllKeys()[i]);
  3133. e->setAttribute ("val", properties.getAllValues()[i]);
  3134. }
  3135. return xml;
  3136. }
  3137. void PropertySet::restoreFromXml (const XmlElement& xml)
  3138. {
  3139. const ScopedLock sl (lock);
  3140. clear();
  3141. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3142. {
  3143. if (e->hasAttribute ("name")
  3144. && e->hasAttribute ("val"))
  3145. {
  3146. properties.set (e->getStringAttribute ("name"),
  3147. e->getStringAttribute ("val"));
  3148. }
  3149. }
  3150. if (properties.size() > 0)
  3151. propertyChanged();
  3152. }
  3153. void PropertySet::propertyChanged()
  3154. {
  3155. }
  3156. END_JUCE_NAMESPACE
  3157. /*** End of inlined file: juce_PropertySet.cpp ***/
  3158. /*** Start of inlined file: juce_Identifier.cpp ***/
  3159. BEGIN_JUCE_NAMESPACE
  3160. StringPool& Identifier::getPool()
  3161. {
  3162. static StringPool pool;
  3163. return pool;
  3164. }
  3165. Identifier::Identifier() throw()
  3166. : name (0)
  3167. {
  3168. }
  3169. Identifier::Identifier (const Identifier& other) throw()
  3170. : name (other.name)
  3171. {
  3172. }
  3173. Identifier& Identifier::operator= (const Identifier& other) throw()
  3174. {
  3175. name = other.name;
  3176. return *this;
  3177. }
  3178. Identifier::Identifier (const String& name_)
  3179. : name (Identifier::getPool().getPooledString (name_))
  3180. {
  3181. /* An Identifier string must be suitable for use as a script variable or XML
  3182. attribute, so it can only contain this limited set of characters.. */
  3183. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3184. }
  3185. Identifier::Identifier (const char* const name_)
  3186. : name (Identifier::getPool().getPooledString (name_))
  3187. {
  3188. /* An Identifier string must be suitable for use as a script variable or XML
  3189. attribute, so it can only contain this limited set of characters.. */
  3190. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3191. }
  3192. Identifier::~Identifier()
  3193. {
  3194. }
  3195. END_JUCE_NAMESPACE
  3196. /*** End of inlined file: juce_Identifier.cpp ***/
  3197. /*** Start of inlined file: juce_Variant.cpp ***/
  3198. BEGIN_JUCE_NAMESPACE
  3199. class var::VariantType
  3200. {
  3201. public:
  3202. VariantType() {}
  3203. virtual ~VariantType() {}
  3204. virtual int toInt (const ValueUnion&) const { return 0; }
  3205. virtual double toDouble (const ValueUnion&) const { return 0; }
  3206. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3207. virtual bool toBool (const ValueUnion&) const { return false; }
  3208. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3209. virtual bool isVoid() const throw() { return false; }
  3210. virtual bool isInt() const throw() { return false; }
  3211. virtual bool isBool() const throw() { return false; }
  3212. virtual bool isDouble() const throw() { return false; }
  3213. virtual bool isString() const throw() { return false; }
  3214. virtual bool isObject() const throw() { return false; }
  3215. virtual bool isMethod() const throw() { return false; }
  3216. virtual void cleanUp (ValueUnion&) const throw() {}
  3217. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3218. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3219. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3220. };
  3221. class var::VariantType_Void : public var::VariantType
  3222. {
  3223. public:
  3224. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3225. bool isVoid() const throw() { return true; }
  3226. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3227. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3228. };
  3229. class var::VariantType_Int : public var::VariantType
  3230. {
  3231. public:
  3232. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3233. int toInt (const ValueUnion& data) const { return data.intValue; };
  3234. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3235. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3236. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3237. bool isInt() const throw() { return true; }
  3238. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3239. {
  3240. return otherType.toInt (otherData) == data.intValue;
  3241. }
  3242. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3243. {
  3244. output.writeCompressedInt (5);
  3245. output.writeByte (1);
  3246. output.writeInt (data.intValue);
  3247. }
  3248. };
  3249. class var::VariantType_Double : public var::VariantType
  3250. {
  3251. public:
  3252. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3253. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3254. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3255. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3256. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3257. bool isDouble() const throw() { return true; }
  3258. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3259. {
  3260. return otherType.toDouble (otherData) == data.doubleValue;
  3261. }
  3262. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3263. {
  3264. output.writeCompressedInt (9);
  3265. output.writeByte (4);
  3266. output.writeDouble (data.doubleValue);
  3267. }
  3268. };
  3269. class var::VariantType_Bool : public var::VariantType
  3270. {
  3271. public:
  3272. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3273. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3274. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3275. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3276. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3277. bool isBool() const throw() { return true; }
  3278. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3279. {
  3280. return otherType.toBool (otherData) == data.boolValue;
  3281. }
  3282. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3283. {
  3284. output.writeCompressedInt (1);
  3285. output.writeByte (data.boolValue ? 2 : 3);
  3286. }
  3287. };
  3288. class var::VariantType_String : public var::VariantType
  3289. {
  3290. public:
  3291. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3292. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3293. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3294. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3295. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3296. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3297. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3298. || data.stringValue->trim().equalsIgnoreCase ("true")
  3299. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3300. bool isString() const throw() { return true; }
  3301. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3302. {
  3303. return otherType.toString (otherData) == *data.stringValue;
  3304. }
  3305. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3306. {
  3307. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3308. output.writeCompressedInt (len + 1);
  3309. output.writeByte (5);
  3310. HeapBlock<char> temp (len);
  3311. data.stringValue->copyToUTF8 (temp, len);
  3312. output.write (temp, len);
  3313. }
  3314. };
  3315. class var::VariantType_Object : public var::VariantType
  3316. {
  3317. public:
  3318. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3319. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3320. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3321. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3322. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3323. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3324. bool isObject() const throw() { return true; }
  3325. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3326. {
  3327. return otherType.toObject (otherData) == data.objectValue;
  3328. }
  3329. void writeToStream (const ValueUnion&, OutputStream& output) const
  3330. {
  3331. jassertfalse; // Can't write an object to a stream!
  3332. output.writeCompressedInt (0);
  3333. }
  3334. };
  3335. class var::VariantType_Method : public var::VariantType
  3336. {
  3337. public:
  3338. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3339. const String toString (const ValueUnion&) const { return "Method"; }
  3340. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3341. bool isMethod() const throw() { return true; }
  3342. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3343. {
  3344. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3345. }
  3346. void writeToStream (const ValueUnion&, OutputStream& output) const
  3347. {
  3348. jassertfalse; // Can't write a method to a stream!
  3349. output.writeCompressedInt (0);
  3350. }
  3351. };
  3352. var::var() throw()
  3353. : type (VariantType_Void::getInstance())
  3354. {
  3355. }
  3356. var::~var() throw()
  3357. {
  3358. type->cleanUp (value);
  3359. }
  3360. const var var::null;
  3361. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3362. {
  3363. type->createCopy (value, valueToCopy.value);
  3364. }
  3365. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3366. {
  3367. value.intValue = value_;
  3368. }
  3369. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3370. {
  3371. value.boolValue = value_;
  3372. }
  3373. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3374. {
  3375. value.doubleValue = value_;
  3376. }
  3377. var::var (const String& value_) : type (VariantType_String::getInstance())
  3378. {
  3379. value.stringValue = new String (value_);
  3380. }
  3381. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3382. {
  3383. value.stringValue = new String (value_);
  3384. }
  3385. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3386. {
  3387. value.stringValue = new String (value_);
  3388. }
  3389. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3390. {
  3391. value.objectValue = object;
  3392. if (object != 0)
  3393. object->incReferenceCount();
  3394. }
  3395. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3396. {
  3397. value.methodValue = method_;
  3398. }
  3399. bool var::isVoid() const throw() { return type->isVoid(); }
  3400. bool var::isInt() const throw() { return type->isInt(); }
  3401. bool var::isBool() const throw() { return type->isBool(); }
  3402. bool var::isDouble() const throw() { return type->isDouble(); }
  3403. bool var::isString() const throw() { return type->isString(); }
  3404. bool var::isObject() const throw() { return type->isObject(); }
  3405. bool var::isMethod() const throw() { return type->isMethod(); }
  3406. var::operator int() const { return type->toInt (value); }
  3407. var::operator bool() const { return type->toBool (value); }
  3408. var::operator float() const { return (float) type->toDouble (value); }
  3409. var::operator double() const { return type->toDouble (value); }
  3410. const String var::toString() const { return type->toString (value); }
  3411. var::operator const String() const { return type->toString (value); }
  3412. DynamicObject* var::getObject() const { return type->toObject (value); }
  3413. void var::swapWith (var& other) throw()
  3414. {
  3415. swapVariables (type, other.type);
  3416. swapVariables (value, other.value);
  3417. }
  3418. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3419. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3420. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3421. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3422. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3423. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3424. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3425. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3426. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3427. bool var::equals (const var& other) const throw()
  3428. {
  3429. return type->equals (value, other.value, *other.type);
  3430. }
  3431. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3432. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3433. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3434. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3435. void var::writeToStream (OutputStream& output) const
  3436. {
  3437. type->writeToStream (value, output);
  3438. }
  3439. const var var::readFromStream (InputStream& input)
  3440. {
  3441. const int numBytes = input.readCompressedInt();
  3442. if (numBytes > 0)
  3443. {
  3444. switch (input.readByte())
  3445. {
  3446. case 1: return var (input.readInt());
  3447. case 2: return var (true);
  3448. case 3: return var (false);
  3449. case 4: return var (input.readDouble());
  3450. case 5:
  3451. {
  3452. MemoryOutputStream mo;
  3453. mo.writeFromInputStream (input, numBytes - 1);
  3454. return var (mo.toUTF8());
  3455. }
  3456. default: input.skipNextBytes (numBytes - 1); break;
  3457. }
  3458. }
  3459. return var::null;
  3460. }
  3461. const var var::operator[] (const Identifier& propertyName) const
  3462. {
  3463. DynamicObject* const o = getObject();
  3464. return o != 0 ? o->getProperty (propertyName) : var::null;
  3465. }
  3466. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3467. {
  3468. DynamicObject* const o = getObject();
  3469. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3470. }
  3471. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3472. {
  3473. if (isMethod())
  3474. {
  3475. DynamicObject* const target = targetObject.getObject();
  3476. if (target != 0)
  3477. return (target->*(value.methodValue)) (arguments, numArguments);
  3478. }
  3479. return var::null;
  3480. }
  3481. const var var::call (const Identifier& method) const
  3482. {
  3483. return invoke (method, 0, 0);
  3484. }
  3485. const var var::call (const Identifier& method, const var& arg1) const
  3486. {
  3487. return invoke (method, &arg1, 1);
  3488. }
  3489. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3490. {
  3491. var args[] = { arg1, arg2 };
  3492. return invoke (method, args, 2);
  3493. }
  3494. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3495. {
  3496. var args[] = { arg1, arg2, arg3 };
  3497. return invoke (method, args, 3);
  3498. }
  3499. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3500. {
  3501. var args[] = { arg1, arg2, arg3, arg4 };
  3502. return invoke (method, args, 4);
  3503. }
  3504. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3505. {
  3506. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3507. return invoke (method, args, 5);
  3508. }
  3509. END_JUCE_NAMESPACE
  3510. /*** End of inlined file: juce_Variant.cpp ***/
  3511. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3512. BEGIN_JUCE_NAMESPACE
  3513. NamedValueSet::NamedValue::NamedValue() throw()
  3514. {
  3515. }
  3516. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3517. : name (name_), value (value_)
  3518. {
  3519. }
  3520. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3521. {
  3522. return name == other.name && value == other.value;
  3523. }
  3524. NamedValueSet::NamedValueSet() throw()
  3525. {
  3526. }
  3527. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3528. : values (other.values)
  3529. {
  3530. }
  3531. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3532. {
  3533. values = other.values;
  3534. return *this;
  3535. }
  3536. NamedValueSet::~NamedValueSet()
  3537. {
  3538. }
  3539. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3540. {
  3541. return values == other.values;
  3542. }
  3543. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3544. {
  3545. return ! operator== (other);
  3546. }
  3547. int NamedValueSet::size() const throw()
  3548. {
  3549. return values.size();
  3550. }
  3551. const var& NamedValueSet::operator[] (const Identifier& name) const
  3552. {
  3553. for (int i = values.size(); --i >= 0;)
  3554. {
  3555. const NamedValue& v = values.getReference(i);
  3556. if (v.name == name)
  3557. return v.value;
  3558. }
  3559. return var::null;
  3560. }
  3561. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3562. {
  3563. const var* v = getItem (name);
  3564. return v != 0 ? *v : defaultReturnValue;
  3565. }
  3566. var* NamedValueSet::getItem (const Identifier& name) const
  3567. {
  3568. for (int i = values.size(); --i >= 0;)
  3569. {
  3570. NamedValue& v = values.getReference(i);
  3571. if (v.name == name)
  3572. return &(v.value);
  3573. }
  3574. return 0;
  3575. }
  3576. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3577. {
  3578. for (int i = values.size(); --i >= 0;)
  3579. {
  3580. NamedValue& v = values.getReference(i);
  3581. if (v.name == name)
  3582. {
  3583. if (v.value == newValue)
  3584. return false;
  3585. v.value = newValue;
  3586. return true;
  3587. }
  3588. }
  3589. values.add (NamedValue (name, newValue));
  3590. return true;
  3591. }
  3592. bool NamedValueSet::contains (const Identifier& name) const
  3593. {
  3594. return getItem (name) != 0;
  3595. }
  3596. bool NamedValueSet::remove (const Identifier& name)
  3597. {
  3598. for (int i = values.size(); --i >= 0;)
  3599. {
  3600. if (values.getReference(i).name == name)
  3601. {
  3602. values.remove (i);
  3603. return true;
  3604. }
  3605. }
  3606. return false;
  3607. }
  3608. const Identifier NamedValueSet::getName (const int index) const
  3609. {
  3610. jassert (((unsigned int) index) < (unsigned int) values.size());
  3611. return values [index].name;
  3612. }
  3613. const var NamedValueSet::getValueAt (const int index) const
  3614. {
  3615. jassert (((unsigned int) index) < (unsigned int) values.size());
  3616. return values [index].value;
  3617. }
  3618. void NamedValueSet::clear()
  3619. {
  3620. values.clear();
  3621. }
  3622. END_JUCE_NAMESPACE
  3623. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3624. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3625. BEGIN_JUCE_NAMESPACE
  3626. DynamicObject::DynamicObject()
  3627. {
  3628. }
  3629. DynamicObject::~DynamicObject()
  3630. {
  3631. }
  3632. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3633. {
  3634. var* const v = properties.getItem (propertyName);
  3635. return v != 0 && ! v->isMethod();
  3636. }
  3637. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3638. {
  3639. return properties [propertyName];
  3640. }
  3641. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3642. {
  3643. properties.set (propertyName, newValue);
  3644. }
  3645. void DynamicObject::removeProperty (const Identifier& propertyName)
  3646. {
  3647. properties.remove (propertyName);
  3648. }
  3649. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3650. {
  3651. return getProperty (methodName).isMethod();
  3652. }
  3653. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3654. const var* parameters,
  3655. int numParameters)
  3656. {
  3657. return properties [methodName].invoke (var (this), parameters, numParameters);
  3658. }
  3659. void DynamicObject::setMethod (const Identifier& name,
  3660. var::MethodFunction methodFunction)
  3661. {
  3662. properties.set (name, var (methodFunction));
  3663. }
  3664. void DynamicObject::clear()
  3665. {
  3666. properties.clear();
  3667. }
  3668. END_JUCE_NAMESPACE
  3669. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3670. /*** Start of inlined file: juce_Expression.cpp ***/
  3671. BEGIN_JUCE_NAMESPACE
  3672. class Expression::Helpers
  3673. {
  3674. public:
  3675. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3676. class Constant : public Term
  3677. {
  3678. public:
  3679. Constant (const double value_, bool isResolutionTarget_)
  3680. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3681. Type getType() const throw() { return constantType; }
  3682. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3683. double evaluate (const EvaluationContext&, int) const { return value; }
  3684. int getNumInputs() const { return 0; }
  3685. Term* getInput (int) const { return 0; }
  3686. const TermPtr negated()
  3687. {
  3688. return new Constant (-value, isResolutionTarget);
  3689. }
  3690. const String toString() const
  3691. {
  3692. if (isResolutionTarget)
  3693. return "@" + String (value);
  3694. return String (value);
  3695. }
  3696. double value;
  3697. bool isResolutionTarget;
  3698. };
  3699. class Symbol : public Term
  3700. {
  3701. public:
  3702. explicit Symbol (const String& symbol_)
  3703. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3704. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3705. {}
  3706. Symbol (const String& symbol_, const String& member_)
  3707. : mainSymbol (symbol_),
  3708. member (member_)
  3709. {}
  3710. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3711. {
  3712. if (++recursionDepth > 256)
  3713. throw EvaluationError ("Recursive symbol references");
  3714. try
  3715. {
  3716. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3717. }
  3718. catch (...)
  3719. {}
  3720. return 0;
  3721. }
  3722. Type getType() const throw() { return symbolType; }
  3723. Term* clone() const { return new Symbol (mainSymbol, member); }
  3724. int getNumInputs() const { return 0; }
  3725. Term* getInput (int) const { return 0; }
  3726. const String getFunctionName() const { return toString(); }
  3727. const String toString() const
  3728. {
  3729. return member.isEmpty() ? mainSymbol
  3730. : mainSymbol + "." + member;
  3731. }
  3732. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3733. {
  3734. if (s == mainSymbol)
  3735. return true;
  3736. if (++recursionDepth > 256)
  3737. throw EvaluationError ("Recursive symbol references");
  3738. try
  3739. {
  3740. return c.getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3741. }
  3742. catch (EvaluationError&)
  3743. {
  3744. return false;
  3745. }
  3746. }
  3747. String mainSymbol, member;
  3748. };
  3749. class Function : public Term
  3750. {
  3751. public:
  3752. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3753. : functionName (functionName_), parameters (parameters_)
  3754. {}
  3755. Term* clone() const { return new Function (functionName, parameters); }
  3756. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3757. {
  3758. HeapBlock <double> params (parameters.size());
  3759. for (int i = 0; i < parameters.size(); ++i)
  3760. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3761. return c.evaluateFunction (functionName, params, parameters.size());
  3762. }
  3763. Type getType() const throw() { return functionType; }
  3764. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3765. int getNumInputs() const { return parameters.size(); }
  3766. Term* getInput (int i) const { return parameters [i]; }
  3767. const String getFunctionName() const { return functionName; }
  3768. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3769. {
  3770. for (int i = 0; i < parameters.size(); ++i)
  3771. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3772. return true;
  3773. return false;
  3774. }
  3775. const String toString() const
  3776. {
  3777. if (parameters.size() == 0)
  3778. return functionName + "()";
  3779. String s (functionName + " (");
  3780. for (int i = 0; i < parameters.size(); ++i)
  3781. {
  3782. s << parameters.getUnchecked(i)->toString();
  3783. if (i < parameters.size() - 1)
  3784. s << ", ";
  3785. }
  3786. s << ')';
  3787. return s;
  3788. }
  3789. const String functionName;
  3790. ReferenceCountedArray<Term> parameters;
  3791. };
  3792. class Negate : public Term
  3793. {
  3794. public:
  3795. Negate (const TermPtr& input_) : input (input_)
  3796. {
  3797. jassert (input_ != 0);
  3798. }
  3799. Type getType() const throw() { return operatorType; }
  3800. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3801. int getNumInputs() const { return 1; }
  3802. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3803. Term* clone() const { return new Negate (input->clone()); }
  3804. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3805. const String getFunctionName() const { return "-"; }
  3806. const TermPtr negated()
  3807. {
  3808. return input;
  3809. }
  3810. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3811. {
  3812. jassert (input_ == input);
  3813. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3814. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3815. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3816. }
  3817. const String toString() const
  3818. {
  3819. if (input->getOperatorPrecedence() > 0)
  3820. return "-(" + input->toString() + ")";
  3821. else
  3822. return "-" + input->toString();
  3823. }
  3824. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3825. {
  3826. return input->referencesSymbol (s, c, recursionDepth);
  3827. }
  3828. private:
  3829. const TermPtr input;
  3830. };
  3831. class BinaryTerm : public Term
  3832. {
  3833. public:
  3834. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3835. {
  3836. jassert (left_ != 0 && right_ != 0);
  3837. }
  3838. int getInputIndexFor (const Term* possibleInput) const
  3839. {
  3840. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3841. }
  3842. Type getType() const throw() { return operatorType; }
  3843. int getNumInputs() const { return 2; }
  3844. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3845. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3846. {
  3847. return left->referencesSymbol (s, c, recursionDepth)
  3848. || right->referencesSymbol (s, c, recursionDepth);
  3849. }
  3850. const String toString() const
  3851. {
  3852. String s;
  3853. const int ourPrecendence = getOperatorPrecedence();
  3854. if (left->getOperatorPrecedence() > ourPrecendence)
  3855. s << '(' << left->toString() << ')';
  3856. else
  3857. s = left->toString();
  3858. s << ' ' << getFunctionName() << ' ';
  3859. if (right->getOperatorPrecedence() >= ourPrecendence)
  3860. s << '(' << right->toString() << ')';
  3861. else
  3862. s << right->toString();
  3863. return s;
  3864. }
  3865. protected:
  3866. const TermPtr left, right;
  3867. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3868. {
  3869. jassert (input == left || input == right);
  3870. if (input != left && input != right)
  3871. return 0;
  3872. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3873. if (dest == 0)
  3874. return new Constant (overallTarget, false);
  3875. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3876. }
  3877. };
  3878. class Add : public BinaryTerm
  3879. {
  3880. public:
  3881. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3882. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3883. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3884. int getOperatorPrecedence() const { return 2; }
  3885. const String getFunctionName() const { return "+"; }
  3886. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3887. {
  3888. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3889. if (newDest == 0)
  3890. return 0;
  3891. return new Subtract (newDest, (input == left ? right : left)->clone());
  3892. }
  3893. };
  3894. class Subtract : public BinaryTerm
  3895. {
  3896. public:
  3897. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3898. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3899. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3900. int getOperatorPrecedence() const { return 2; }
  3901. const String getFunctionName() const { return "-"; }
  3902. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3903. {
  3904. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3905. if (newDest == 0)
  3906. return 0;
  3907. if (input == left)
  3908. return new Add (newDest, right->clone());
  3909. else
  3910. return new Subtract (left->clone(), newDest);
  3911. }
  3912. };
  3913. class Multiply : public BinaryTerm
  3914. {
  3915. public:
  3916. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3917. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  3918. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  3919. const String getFunctionName() const { return "*"; }
  3920. int getOperatorPrecedence() const { return 1; }
  3921. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3922. {
  3923. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3924. if (newDest == 0)
  3925. return 0;
  3926. return new Divide (newDest, (input == left ? right : left)->clone());
  3927. }
  3928. };
  3929. class Divide : public BinaryTerm
  3930. {
  3931. public:
  3932. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3933. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  3934. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  3935. const String getFunctionName() const { return "/"; }
  3936. int getOperatorPrecedence() const { return 1; }
  3937. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3938. {
  3939. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3940. if (newDest == 0)
  3941. return 0;
  3942. if (input == left)
  3943. return new Multiply (newDest, right->clone());
  3944. else
  3945. return new Divide (left->clone(), newDest);
  3946. }
  3947. };
  3948. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  3949. {
  3950. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  3951. if (inputIndex >= 0)
  3952. return topLevel;
  3953. for (int i = topLevel->getNumInputs(); --i >= 0;)
  3954. {
  3955. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  3956. if (t != 0)
  3957. return t;
  3958. }
  3959. return 0;
  3960. }
  3961. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  3962. {
  3963. Constant* c = dynamic_cast<Constant*> (term);
  3964. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  3965. return c;
  3966. if (dynamic_cast<Function*> (term) != 0)
  3967. return 0;
  3968. int i;
  3969. const int numIns = term->getNumInputs();
  3970. for (i = 0; i < numIns; ++i)
  3971. {
  3972. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  3973. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  3974. return c;
  3975. }
  3976. for (i = 0; i < numIns; ++i)
  3977. {
  3978. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  3979. if (c != 0)
  3980. return c;
  3981. }
  3982. return 0;
  3983. }
  3984. static bool containsAnySymbols (const Term* const t)
  3985. {
  3986. if (dynamic_cast <const Symbol*> (t) != 0)
  3987. return true;
  3988. for (int i = t->getNumInputs(); --i >= 0;)
  3989. if (containsAnySymbols (t->getInput (i)))
  3990. return true;
  3991. return false;
  3992. }
  3993. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  3994. {
  3995. Symbol* const sym = dynamic_cast <Symbol*> (t);
  3996. if (sym != 0 && sym->mainSymbol == oldName)
  3997. {
  3998. sym->mainSymbol = newName;
  3999. return true;
  4000. }
  4001. bool anyChanged = false;
  4002. for (int i = t->getNumInputs(); --i >= 0;)
  4003. if (renameSymbol (t->getInput (i), oldName, newName))
  4004. anyChanged = true;
  4005. return anyChanged;
  4006. }
  4007. class Parser
  4008. {
  4009. public:
  4010. Parser (const String& stringToParse, int& textIndex_)
  4011. : textString (stringToParse), textIndex (textIndex_)
  4012. {
  4013. text = textString;
  4014. }
  4015. const TermPtr readExpression()
  4016. {
  4017. TermPtr lhs (readMultiplyOrDivideExpression());
  4018. char opType;
  4019. while (lhs != 0 && readOperator ("+-", &opType))
  4020. {
  4021. TermPtr rhs (readMultiplyOrDivideExpression());
  4022. if (rhs == 0)
  4023. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4024. if (opType == '+')
  4025. lhs = new Add (lhs, rhs);
  4026. else
  4027. lhs = new Subtract (lhs, rhs);
  4028. }
  4029. return lhs;
  4030. }
  4031. private:
  4032. const String textString;
  4033. const juce_wchar* text;
  4034. int& textIndex;
  4035. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4036. {
  4037. return c >= '0' && c <= '9';
  4038. }
  4039. void skipWhitespace (int& i)
  4040. {
  4041. while (CharacterFunctions::isWhitespace (text [i]))
  4042. ++i;
  4043. }
  4044. bool readChar (const juce_wchar required)
  4045. {
  4046. if (text[textIndex] == required)
  4047. {
  4048. ++textIndex;
  4049. return true;
  4050. }
  4051. return false;
  4052. }
  4053. bool readOperator (const char* ops, char* const opType = 0)
  4054. {
  4055. skipWhitespace (textIndex);
  4056. while (*ops != 0)
  4057. {
  4058. if (readChar (*ops))
  4059. {
  4060. if (opType != 0)
  4061. *opType = *ops;
  4062. return true;
  4063. }
  4064. ++ops;
  4065. }
  4066. return false;
  4067. }
  4068. bool readIdentifier (String& identifier)
  4069. {
  4070. skipWhitespace (textIndex);
  4071. int i = textIndex;
  4072. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4073. {
  4074. ++i;
  4075. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4076. ++i;
  4077. }
  4078. if (i > textIndex)
  4079. {
  4080. identifier = String (text + textIndex, i - textIndex);
  4081. textIndex = i;
  4082. return true;
  4083. }
  4084. return false;
  4085. }
  4086. Term* readNumber()
  4087. {
  4088. skipWhitespace (textIndex);
  4089. int i = textIndex;
  4090. const bool isResolutionTarget = (text[i] == '@');
  4091. if (isResolutionTarget)
  4092. {
  4093. ++i;
  4094. skipWhitespace (i);
  4095. textIndex = i;
  4096. }
  4097. if (text[i] == '-')
  4098. {
  4099. ++i;
  4100. skipWhitespace (i);
  4101. }
  4102. int numDigits = 0;
  4103. while (isDecimalDigit (text[i]))
  4104. {
  4105. ++i;
  4106. ++numDigits;
  4107. }
  4108. const bool hasPoint = (text[i] == '.');
  4109. if (hasPoint)
  4110. {
  4111. ++i;
  4112. while (isDecimalDigit (text[i]))
  4113. {
  4114. ++i;
  4115. ++numDigits;
  4116. }
  4117. }
  4118. if (numDigits == 0)
  4119. return 0;
  4120. juce_wchar c = text[i];
  4121. const bool hasExponent = (c == 'e' || c == 'E');
  4122. if (hasExponent)
  4123. {
  4124. ++i;
  4125. c = text[i];
  4126. if (c == '+' || c == '-')
  4127. ++i;
  4128. int numExpDigits = 0;
  4129. while (isDecimalDigit (text[i]))
  4130. {
  4131. ++i;
  4132. ++numExpDigits;
  4133. }
  4134. if (numExpDigits == 0)
  4135. return 0;
  4136. }
  4137. const int start = textIndex;
  4138. textIndex = i;
  4139. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4140. }
  4141. const TermPtr readMultiplyOrDivideExpression()
  4142. {
  4143. TermPtr lhs (readUnaryExpression());
  4144. char opType;
  4145. while (lhs != 0 && readOperator ("*/", &opType))
  4146. {
  4147. TermPtr rhs (readUnaryExpression());
  4148. if (rhs == 0)
  4149. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4150. if (opType == '*')
  4151. lhs = new Multiply (lhs, rhs);
  4152. else
  4153. lhs = new Divide (lhs, rhs);
  4154. }
  4155. return lhs;
  4156. }
  4157. const TermPtr readUnaryExpression()
  4158. {
  4159. char opType;
  4160. if (readOperator ("+-", &opType))
  4161. {
  4162. TermPtr term (readUnaryExpression());
  4163. if (term == 0)
  4164. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4165. if (opType == '-')
  4166. term = term->negated();
  4167. return term;
  4168. }
  4169. return readPrimaryExpression();
  4170. }
  4171. const TermPtr readPrimaryExpression()
  4172. {
  4173. TermPtr e (readParenthesisedExpression());
  4174. if (e != 0)
  4175. return e;
  4176. e = readNumber();
  4177. if (e != 0)
  4178. return e;
  4179. String identifier;
  4180. if (readIdentifier (identifier))
  4181. {
  4182. if (readOperator ("(")) // method call...
  4183. {
  4184. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4185. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4186. TermPtr param (readExpression());
  4187. if (param == 0)
  4188. {
  4189. if (readOperator (")"))
  4190. return func.release();
  4191. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4192. }
  4193. f->parameters.add (param);
  4194. while (readOperator (","))
  4195. {
  4196. param = readExpression();
  4197. if (param == 0)
  4198. throw ParseError ("Expected expression after \",\"");
  4199. f->parameters.add (param);
  4200. }
  4201. if (readOperator (")"))
  4202. return func.release();
  4203. throw ParseError ("Expected \")\"");
  4204. }
  4205. else // just a symbol..
  4206. {
  4207. return new Symbol (identifier);
  4208. }
  4209. }
  4210. return 0;
  4211. }
  4212. const TermPtr readParenthesisedExpression()
  4213. {
  4214. if (! readOperator ("("))
  4215. return 0;
  4216. const TermPtr e (readExpression());
  4217. if (e == 0 || ! readOperator (")"))
  4218. return 0;
  4219. return e;
  4220. }
  4221. Parser (const Parser&);
  4222. Parser& operator= (const Parser&);
  4223. };
  4224. };
  4225. Expression::Expression()
  4226. : term (new Expression::Helpers::Constant (0, false))
  4227. {
  4228. }
  4229. Expression::~Expression()
  4230. {
  4231. }
  4232. Expression::Expression (Term* const term_)
  4233. : term (term_)
  4234. {
  4235. jassert (term != 0);
  4236. }
  4237. Expression::Expression (const double constant)
  4238. : term (new Expression::Helpers::Constant (constant, false))
  4239. {
  4240. }
  4241. Expression::Expression (const Expression& other)
  4242. : term (other.term)
  4243. {
  4244. }
  4245. Expression& Expression::operator= (const Expression& other)
  4246. {
  4247. term = other.term;
  4248. return *this;
  4249. }
  4250. Expression::Expression (const String& stringToParse)
  4251. {
  4252. int i = 0;
  4253. Helpers::Parser parser (stringToParse, i);
  4254. term = parser.readExpression();
  4255. if (term == 0)
  4256. term = new Helpers::Constant (0, false);
  4257. }
  4258. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4259. {
  4260. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4261. const Helpers::TermPtr term (parser.readExpression());
  4262. if (term != 0)
  4263. return Expression (term);
  4264. return Expression();
  4265. }
  4266. double Expression::evaluate() const
  4267. {
  4268. return evaluate (Expression::EvaluationContext());
  4269. }
  4270. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4271. {
  4272. return term->evaluate (context, 0);
  4273. }
  4274. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4275. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4276. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4277. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4278. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4279. const String Expression::toString() const
  4280. {
  4281. return term->toString();
  4282. }
  4283. const Expression Expression::symbol (const String& symbol)
  4284. {
  4285. return Expression (new Helpers::Symbol (symbol));
  4286. }
  4287. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4288. {
  4289. ReferenceCountedArray<Term> params;
  4290. for (int i = 0; i < parameters.size(); ++i)
  4291. params.add (parameters.getReference(i).term);
  4292. return Expression (new Helpers::Function (functionName, params));
  4293. }
  4294. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4295. const Expression::EvaluationContext& context) const
  4296. {
  4297. ScopedPointer<Term> newTerm (term->clone());
  4298. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4299. if (termToAdjust == 0)
  4300. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4301. if (termToAdjust == 0)
  4302. {
  4303. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4304. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4305. }
  4306. jassert (termToAdjust != 0);
  4307. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4308. if (parent == 0)
  4309. {
  4310. termToAdjust->value = targetValue;
  4311. }
  4312. else
  4313. {
  4314. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4315. if (reverseTerm == 0)
  4316. return Expression (targetValue);
  4317. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4318. }
  4319. return Expression (newTerm.release());
  4320. }
  4321. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4322. {
  4323. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4324. Expression newExpression (term->clone());
  4325. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4326. return newExpression;
  4327. }
  4328. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext& context) const
  4329. {
  4330. return term->referencesSymbol (symbol, context, 0);
  4331. }
  4332. bool Expression::usesAnySymbols() const
  4333. {
  4334. return Helpers::containsAnySymbols (term);
  4335. }
  4336. Expression::Type Expression::getType() const throw()
  4337. {
  4338. return term->getType();
  4339. }
  4340. const String Expression::getSymbol() const
  4341. {
  4342. return term->getSymbolName();
  4343. }
  4344. const String Expression::getFunction() const
  4345. {
  4346. return term->getFunctionName();
  4347. }
  4348. const String Expression::getOperator() const
  4349. {
  4350. return term->getFunctionName();
  4351. }
  4352. int Expression::getNumInputs() const
  4353. {
  4354. return term->getNumInputs();
  4355. }
  4356. const Expression Expression::getInput (int index) const
  4357. {
  4358. return Expression (term->getInput (index));
  4359. }
  4360. int Expression::Term::getOperatorPrecedence() const
  4361. {
  4362. return 0;
  4363. }
  4364. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext&, int) const
  4365. {
  4366. return false;
  4367. }
  4368. int Expression::Term::getInputIndexFor (const Term*) const
  4369. {
  4370. return -1;
  4371. }
  4372. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4373. {
  4374. jassertfalse;
  4375. return 0;
  4376. }
  4377. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4378. {
  4379. return new Helpers::Negate (this);
  4380. }
  4381. const String Expression::Term::getSymbolName() const
  4382. {
  4383. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4384. return String::empty;
  4385. }
  4386. const String Expression::Term::getFunctionName() const
  4387. {
  4388. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4389. return String::empty;
  4390. }
  4391. Expression::ParseError::ParseError (const String& message)
  4392. : description (message)
  4393. {
  4394. DBG ("Expression::ParseError: " + message);
  4395. }
  4396. Expression::EvaluationError::EvaluationError (const String& message)
  4397. : description (message)
  4398. {
  4399. DBG ("Expression::EvaluationError: " + message);
  4400. }
  4401. Expression::EvaluationContext::EvaluationContext() {}
  4402. Expression::EvaluationContext::~EvaluationContext() {}
  4403. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4404. {
  4405. throw EvaluationError ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")));
  4406. }
  4407. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4408. {
  4409. if (numParams > 0)
  4410. {
  4411. if (functionName == "min")
  4412. {
  4413. double v = parameters[0];
  4414. for (int i = 1; i < numParams; ++i)
  4415. v = jmin (v, parameters[i]);
  4416. return v;
  4417. }
  4418. else if (functionName == "max")
  4419. {
  4420. double v = parameters[0];
  4421. for (int i = 1; i < numParams; ++i)
  4422. v = jmax (v, parameters[i]);
  4423. return v;
  4424. }
  4425. else if (numParams == 1)
  4426. {
  4427. if (functionName == "sin")
  4428. return sin (parameters[0]);
  4429. else if (functionName == "cos")
  4430. return cos (parameters[0]);
  4431. else if (functionName == "tan")
  4432. return tan (parameters[0]);
  4433. else if (functionName == "abs")
  4434. return std::abs (parameters[0]);
  4435. }
  4436. }
  4437. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4438. }
  4439. END_JUCE_NAMESPACE
  4440. /*** End of inlined file: juce_Expression.cpp ***/
  4441. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4442. BEGIN_JUCE_NAMESPACE
  4443. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4444. {
  4445. jassert (keyData != 0);
  4446. jassert (keyBytes > 0);
  4447. static const uint32 initialPValues [18] =
  4448. {
  4449. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4450. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4451. 0x9216d5d9, 0x8979fb1b
  4452. };
  4453. static const uint32 initialSValues [4 * 256] =
  4454. {
  4455. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4456. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4457. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4458. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4459. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4460. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4461. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4462. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4463. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4464. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4465. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4466. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4467. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4468. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4469. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4470. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4471. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4472. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4473. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4474. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4475. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4476. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4477. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4478. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4479. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4480. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4481. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4482. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4483. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4484. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4485. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4486. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4487. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4488. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4489. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4490. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4491. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4492. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4493. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4494. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4495. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4496. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4497. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4498. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4499. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4500. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4501. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4502. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4503. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4504. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4505. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4506. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4507. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4508. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4509. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4510. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4511. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4512. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4513. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4514. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4515. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4516. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4517. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4518. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4519. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4520. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4521. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4522. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4523. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4524. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4525. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4526. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4527. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4528. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4529. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4530. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4531. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4532. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4533. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4534. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4535. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4536. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4537. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4538. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4539. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4540. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4541. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4542. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4543. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4544. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4545. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4546. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4547. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4548. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4549. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4550. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4551. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4552. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4553. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4554. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4555. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4556. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4557. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4558. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4559. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4560. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4561. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4562. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4563. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4564. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4565. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4566. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4567. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4568. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4569. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4570. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4571. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4572. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4573. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4574. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4575. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4576. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4577. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4578. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4579. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4580. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4581. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4582. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4583. };
  4584. memcpy (p, initialPValues, sizeof (p));
  4585. int i, j = 0;
  4586. for (i = 4; --i >= 0;)
  4587. {
  4588. s[i].malloc (256);
  4589. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4590. }
  4591. for (i = 0; i < 18; ++i)
  4592. {
  4593. uint32 d = 0;
  4594. for (int k = 0; k < 4; ++k)
  4595. {
  4596. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4597. if (++j >= keyBytes)
  4598. j = 0;
  4599. }
  4600. p[i] = initialPValues[i] ^ d;
  4601. }
  4602. uint32 l = 0, r = 0;
  4603. for (i = 0; i < 18; i += 2)
  4604. {
  4605. encrypt (l, r);
  4606. p[i] = l;
  4607. p[i + 1] = r;
  4608. }
  4609. for (i = 0; i < 4; ++i)
  4610. {
  4611. for (j = 0; j < 256; j += 2)
  4612. {
  4613. encrypt (l, r);
  4614. s[i][j] = l;
  4615. s[i][j + 1] = r;
  4616. }
  4617. }
  4618. }
  4619. BlowFish::BlowFish (const BlowFish& other)
  4620. {
  4621. for (int i = 4; --i >= 0;)
  4622. s[i].malloc (256);
  4623. operator= (other);
  4624. }
  4625. BlowFish& BlowFish::operator= (const BlowFish& other)
  4626. {
  4627. memcpy (p, other.p, sizeof (p));
  4628. for (int i = 4; --i >= 0;)
  4629. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4630. return *this;
  4631. }
  4632. BlowFish::~BlowFish()
  4633. {
  4634. }
  4635. uint32 BlowFish::F (const uint32 x) const throw()
  4636. {
  4637. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4638. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4639. }
  4640. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4641. {
  4642. uint32 l = data1;
  4643. uint32 r = data2;
  4644. for (int i = 0; i < 16; ++i)
  4645. {
  4646. l ^= p[i];
  4647. r ^= F(l);
  4648. swapVariables (l, r);
  4649. }
  4650. data1 = r ^ p[17];
  4651. data2 = l ^ p[16];
  4652. }
  4653. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4654. {
  4655. uint32 l = data1;
  4656. uint32 r = data2;
  4657. for (int i = 17; i > 1; --i)
  4658. {
  4659. l ^= p[i];
  4660. r ^= F(l);
  4661. swapVariables (l, r);
  4662. }
  4663. data1 = r ^ p[0];
  4664. data2 = l ^ p[1];
  4665. }
  4666. END_JUCE_NAMESPACE
  4667. /*** End of inlined file: juce_BlowFish.cpp ***/
  4668. /*** Start of inlined file: juce_MD5.cpp ***/
  4669. BEGIN_JUCE_NAMESPACE
  4670. MD5::MD5()
  4671. {
  4672. zerostruct (result);
  4673. }
  4674. MD5::MD5 (const MD5& other)
  4675. {
  4676. memcpy (result, other.result, sizeof (result));
  4677. }
  4678. MD5& MD5::operator= (const MD5& other)
  4679. {
  4680. memcpy (result, other.result, sizeof (result));
  4681. return *this;
  4682. }
  4683. MD5::MD5 (const MemoryBlock& data)
  4684. {
  4685. ProcessContext context;
  4686. context.processBlock (data.getData(), data.getSize());
  4687. context.finish (result);
  4688. }
  4689. MD5::MD5 (const void* data, const size_t numBytes)
  4690. {
  4691. ProcessContext context;
  4692. context.processBlock (data, numBytes);
  4693. context.finish (result);
  4694. }
  4695. MD5::MD5 (const String& text)
  4696. {
  4697. ProcessContext context;
  4698. const int len = text.length();
  4699. const juce_wchar* const t = text;
  4700. for (int i = 0; i < len; ++i)
  4701. {
  4702. // force the string into integer-sized unicode characters, to try to make it
  4703. // get the same results on all platforms + compilers.
  4704. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4705. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4706. }
  4707. context.finish (result);
  4708. }
  4709. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4710. {
  4711. ProcessContext context;
  4712. if (numBytesToRead < 0)
  4713. numBytesToRead = std::numeric_limits<int64>::max();
  4714. while (numBytesToRead > 0)
  4715. {
  4716. uint8 tempBuffer [512];
  4717. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4718. if (bytesRead <= 0)
  4719. break;
  4720. numBytesToRead -= bytesRead;
  4721. context.processBlock (tempBuffer, bytesRead);
  4722. }
  4723. context.finish (result);
  4724. }
  4725. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4726. {
  4727. processStream (input, numBytesToRead);
  4728. }
  4729. MD5::MD5 (const File& file)
  4730. {
  4731. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4732. if (fin != 0)
  4733. processStream (*fin, -1);
  4734. else
  4735. zerostruct (result);
  4736. }
  4737. MD5::~MD5()
  4738. {
  4739. }
  4740. namespace MD5Functions
  4741. {
  4742. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4743. {
  4744. for (int i = 0; i < (numBytes >> 2); ++i)
  4745. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4746. }
  4747. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4748. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4749. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4750. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4751. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4752. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4753. {
  4754. a += F (b, c, d) + x + ac;
  4755. a = rotateLeft (a, s) + b;
  4756. }
  4757. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4758. {
  4759. a += G (b, c, d) + x + ac;
  4760. a = rotateLeft (a, s) + b;
  4761. }
  4762. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4763. {
  4764. a += H (b, c, d) + x + ac;
  4765. a = rotateLeft (a, s) + b;
  4766. }
  4767. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4768. {
  4769. a += I (b, c, d) + x + ac;
  4770. a = rotateLeft (a, s) + b;
  4771. }
  4772. }
  4773. MD5::ProcessContext::ProcessContext()
  4774. {
  4775. state[0] = 0x67452301;
  4776. state[1] = 0xefcdab89;
  4777. state[2] = 0x98badcfe;
  4778. state[3] = 0x10325476;
  4779. count[0] = 0;
  4780. count[1] = 0;
  4781. }
  4782. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4783. {
  4784. int bufferPos = ((count[0] >> 3) & 0x3F);
  4785. count[0] += (uint32) (dataSize << 3);
  4786. if (count[0] < ((uint32) dataSize << 3))
  4787. count[1]++;
  4788. count[1] += (uint32) (dataSize >> 29);
  4789. const size_t spaceLeft = 64 - bufferPos;
  4790. size_t i = 0;
  4791. if (dataSize >= spaceLeft)
  4792. {
  4793. memcpy (buffer + bufferPos, data, spaceLeft);
  4794. transform (buffer);
  4795. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4796. transform (static_cast <const char*> (data) + i);
  4797. bufferPos = 0;
  4798. }
  4799. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4800. }
  4801. void MD5::ProcessContext::finish (void* const result)
  4802. {
  4803. unsigned char encodedLength[8];
  4804. MD5Functions::encode (encodedLength, count, 8);
  4805. // Pad out to 56 mod 64.
  4806. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4807. const int paddingLength = (index < 56) ? (56 - index)
  4808. : (120 - index);
  4809. uint8 paddingBuffer [64];
  4810. zeromem (paddingBuffer, paddingLength);
  4811. paddingBuffer [0] = 0x80;
  4812. processBlock (paddingBuffer, paddingLength);
  4813. processBlock (encodedLength, 8);
  4814. MD5Functions::encode (result, state, 16);
  4815. zerostruct (buffer);
  4816. }
  4817. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4818. {
  4819. using namespace MD5Functions;
  4820. uint32 a = state[0];
  4821. uint32 b = state[1];
  4822. uint32 c = state[2];
  4823. uint32 d = state[3];
  4824. uint32 x[16];
  4825. encode (x, bufferToTransform, 64);
  4826. enum Constants
  4827. {
  4828. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4829. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4830. };
  4831. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4832. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4833. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4834. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4835. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4836. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4837. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4838. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4839. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4840. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4841. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4842. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4843. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4844. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4845. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4846. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4847. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4848. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4849. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4850. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4851. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4852. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4853. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4854. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4855. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4856. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4857. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4858. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4859. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4860. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4861. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4862. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4863. state[0] += a;
  4864. state[1] += b;
  4865. state[2] += c;
  4866. state[3] += d;
  4867. zerostruct (x);
  4868. }
  4869. const MemoryBlock MD5::getRawChecksumData() const
  4870. {
  4871. return MemoryBlock (result, sizeof (result));
  4872. }
  4873. const String MD5::toHexString() const
  4874. {
  4875. return String::toHexString (result, sizeof (result), 0);
  4876. }
  4877. bool MD5::operator== (const MD5& other) const
  4878. {
  4879. return memcmp (result, other.result, sizeof (result)) == 0;
  4880. }
  4881. bool MD5::operator!= (const MD5& other) const
  4882. {
  4883. return ! operator== (other);
  4884. }
  4885. END_JUCE_NAMESPACE
  4886. /*** End of inlined file: juce_MD5.cpp ***/
  4887. /*** Start of inlined file: juce_Primes.cpp ***/
  4888. BEGIN_JUCE_NAMESPACE
  4889. namespace PrimesHelpers
  4890. {
  4891. static void createSmallSieve (const int numBits, BigInteger& result)
  4892. {
  4893. result.setBit (numBits);
  4894. result.clearBit (numBits); // to enlarge the array
  4895. result.setBit (0);
  4896. int n = 2;
  4897. do
  4898. {
  4899. for (int i = n + n; i < numBits; i += n)
  4900. result.setBit (i);
  4901. n = result.findNextClearBit (n + 1);
  4902. }
  4903. while (n <= (numBits >> 1));
  4904. }
  4905. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4906. const BigInteger& smallSieve, const int smallSieveSize)
  4907. {
  4908. jassert (! base[0]); // must be even!
  4909. result.setBit (numBits);
  4910. result.clearBit (numBits); // to enlarge the array
  4911. int index = smallSieve.findNextClearBit (0);
  4912. do
  4913. {
  4914. const int prime = (index << 1) + 1;
  4915. BigInteger r (base), remainder;
  4916. r.divideBy (prime, remainder);
  4917. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4918. if (r.isZero())
  4919. i += prime;
  4920. if ((i & 1) == 0)
  4921. i += prime;
  4922. i = (i - 1) >> 1;
  4923. while (i < numBits)
  4924. {
  4925. result.setBit (i);
  4926. i += prime;
  4927. }
  4928. index = smallSieve.findNextClearBit (index + 1);
  4929. }
  4930. while (index < smallSieveSize);
  4931. }
  4932. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4933. const int numBits, BigInteger& result, const int certainty)
  4934. {
  4935. for (int i = 0; i < numBits; ++i)
  4936. {
  4937. if (! sieve[i])
  4938. {
  4939. result = base + (unsigned int) ((i << 1) + 1);
  4940. if (Primes::isProbablyPrime (result, certainty))
  4941. return true;
  4942. }
  4943. }
  4944. return false;
  4945. }
  4946. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4947. {
  4948. const BigInteger one (1), two (2);
  4949. const BigInteger nMinusOne (n - one);
  4950. BigInteger d (nMinusOne);
  4951. const int s = d.findNextSetBit (0);
  4952. d >>= s;
  4953. BigInteger smallPrimes;
  4954. int numBitsInSmallPrimes = 0;
  4955. for (;;)
  4956. {
  4957. numBitsInSmallPrimes += 256;
  4958. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4959. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4960. if (numPrimesFound > iterations + 1)
  4961. break;
  4962. }
  4963. int smallPrime = 2;
  4964. while (--iterations >= 0)
  4965. {
  4966. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4967. BigInteger r (smallPrime);
  4968. r.exponentModulo (d, n);
  4969. if (r != one && r != nMinusOne)
  4970. {
  4971. for (int j = 0; j < s; ++j)
  4972. {
  4973. r.exponentModulo (two, n);
  4974. if (r == nMinusOne)
  4975. break;
  4976. }
  4977. if (r != nMinusOne)
  4978. return false;
  4979. }
  4980. }
  4981. return true;
  4982. }
  4983. }
  4984. const BigInteger Primes::createProbablePrime (const int bitLength,
  4985. const int certainty,
  4986. const int* randomSeeds,
  4987. int numRandomSeeds)
  4988. {
  4989. using namespace PrimesHelpers;
  4990. int defaultSeeds [16];
  4991. if (numRandomSeeds <= 0)
  4992. {
  4993. randomSeeds = defaultSeeds;
  4994. numRandomSeeds = numElementsInArray (defaultSeeds);
  4995. Random r (0);
  4996. for (int j = 10; --j >= 0;)
  4997. {
  4998. r.setSeedRandomly();
  4999. for (int i = numRandomSeeds; --i >= 0;)
  5000. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5001. }
  5002. }
  5003. BigInteger smallSieve;
  5004. const int smallSieveSize = 15000;
  5005. createSmallSieve (smallSieveSize, smallSieve);
  5006. BigInteger p;
  5007. for (int i = numRandomSeeds; --i >= 0;)
  5008. {
  5009. BigInteger p2;
  5010. Random r (randomSeeds[i]);
  5011. r.fillBitsRandomly (p2, 0, bitLength);
  5012. p ^= p2;
  5013. }
  5014. p.setBit (bitLength - 1);
  5015. p.clearBit (0);
  5016. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5017. while (p.getHighestBit() < bitLength)
  5018. {
  5019. p += 2 * searchLen;
  5020. BigInteger sieve;
  5021. bigSieve (p, searchLen, sieve,
  5022. smallSieve, smallSieveSize);
  5023. BigInteger candidate;
  5024. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5025. return candidate;
  5026. }
  5027. jassertfalse;
  5028. return BigInteger();
  5029. }
  5030. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5031. {
  5032. using namespace PrimesHelpers;
  5033. if (! number[0])
  5034. return false;
  5035. if (number.getHighestBit() <= 10)
  5036. {
  5037. const int num = number.getBitRangeAsInt (0, 10);
  5038. for (int i = num / 2; --i > 1;)
  5039. if (num % i == 0)
  5040. return false;
  5041. return true;
  5042. }
  5043. else
  5044. {
  5045. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5046. return false;
  5047. return passesMillerRabin (number, certainty);
  5048. }
  5049. }
  5050. END_JUCE_NAMESPACE
  5051. /*** End of inlined file: juce_Primes.cpp ***/
  5052. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5053. BEGIN_JUCE_NAMESPACE
  5054. RSAKey::RSAKey()
  5055. {
  5056. }
  5057. RSAKey::RSAKey (const String& s)
  5058. {
  5059. if (s.containsChar (','))
  5060. {
  5061. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5062. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5063. }
  5064. else
  5065. {
  5066. // the string needs to be two hex numbers, comma-separated..
  5067. jassertfalse;
  5068. }
  5069. }
  5070. RSAKey::~RSAKey()
  5071. {
  5072. }
  5073. bool RSAKey::operator== (const RSAKey& other) const throw()
  5074. {
  5075. return part1 == other.part1 && part2 == other.part2;
  5076. }
  5077. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5078. {
  5079. return ! operator== (other);
  5080. }
  5081. const String RSAKey::toString() const
  5082. {
  5083. return part1.toString (16) + "," + part2.toString (16);
  5084. }
  5085. bool RSAKey::applyToValue (BigInteger& value) const
  5086. {
  5087. if (part1.isZero() || part2.isZero() || value <= 0)
  5088. {
  5089. jassertfalse; // using an uninitialised key
  5090. value.clear();
  5091. return false;
  5092. }
  5093. BigInteger result;
  5094. while (! value.isZero())
  5095. {
  5096. result *= part2;
  5097. BigInteger remainder;
  5098. value.divideBy (part2, remainder);
  5099. remainder.exponentModulo (part1, part2);
  5100. result += remainder;
  5101. }
  5102. value.swapWith (result);
  5103. return true;
  5104. }
  5105. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5106. {
  5107. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5108. // are fast to divide + multiply
  5109. for (int i = 2; i <= 65536; i *= 2)
  5110. {
  5111. const BigInteger e (1 + i);
  5112. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5113. return e;
  5114. }
  5115. BigInteger e (4);
  5116. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5117. ++e;
  5118. return e;
  5119. }
  5120. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5121. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5122. {
  5123. jassert (numBits > 16); // not much point using less than this..
  5124. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5125. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5126. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5127. const BigInteger n (p * q);
  5128. const BigInteger m (--p * --q);
  5129. const BigInteger e (findBestCommonDivisor (p, q));
  5130. BigInteger d (e);
  5131. d.inverseModulo (m);
  5132. publicKey.part1 = e;
  5133. publicKey.part2 = n;
  5134. privateKey.part1 = d;
  5135. privateKey.part2 = n;
  5136. }
  5137. END_JUCE_NAMESPACE
  5138. /*** End of inlined file: juce_RSAKey.cpp ***/
  5139. /*** Start of inlined file: juce_InputStream.cpp ***/
  5140. BEGIN_JUCE_NAMESPACE
  5141. char InputStream::readByte()
  5142. {
  5143. char temp = 0;
  5144. read (&temp, 1);
  5145. return temp;
  5146. }
  5147. bool InputStream::readBool()
  5148. {
  5149. return readByte() != 0;
  5150. }
  5151. short InputStream::readShort()
  5152. {
  5153. char temp[2];
  5154. if (read (temp, 2) == 2)
  5155. return (short) ByteOrder::littleEndianShort (temp);
  5156. return 0;
  5157. }
  5158. short InputStream::readShortBigEndian()
  5159. {
  5160. char temp[2];
  5161. if (read (temp, 2) == 2)
  5162. return (short) ByteOrder::bigEndianShort (temp);
  5163. return 0;
  5164. }
  5165. int InputStream::readInt()
  5166. {
  5167. char temp[4];
  5168. if (read (temp, 4) == 4)
  5169. return (int) ByteOrder::littleEndianInt (temp);
  5170. return 0;
  5171. }
  5172. int InputStream::readIntBigEndian()
  5173. {
  5174. char temp[4];
  5175. if (read (temp, 4) == 4)
  5176. return (int) ByteOrder::bigEndianInt (temp);
  5177. return 0;
  5178. }
  5179. int InputStream::readCompressedInt()
  5180. {
  5181. const unsigned char sizeByte = readByte();
  5182. if (sizeByte == 0)
  5183. return 0;
  5184. const int numBytes = (sizeByte & 0x7f);
  5185. if (numBytes > 4)
  5186. {
  5187. jassertfalse; // trying to read corrupt data - this method must only be used
  5188. // to read data that was written by OutputStream::writeCompressedInt()
  5189. return 0;
  5190. }
  5191. char bytes[4] = { 0, 0, 0, 0 };
  5192. if (read (bytes, numBytes) != numBytes)
  5193. return 0;
  5194. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5195. return (sizeByte >> 7) ? -num : num;
  5196. }
  5197. int64 InputStream::readInt64()
  5198. {
  5199. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5200. if (read (n.asBytes, 8) == 8)
  5201. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5202. return 0;
  5203. }
  5204. int64 InputStream::readInt64BigEndian()
  5205. {
  5206. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5207. if (read (n.asBytes, 8) == 8)
  5208. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5209. return 0;
  5210. }
  5211. float InputStream::readFloat()
  5212. {
  5213. // the union below relies on these types being the same size...
  5214. static_jassert (sizeof (int32) == sizeof (float));
  5215. union { int32 asInt; float asFloat; } n;
  5216. n.asInt = (int32) readInt();
  5217. return n.asFloat;
  5218. }
  5219. float InputStream::readFloatBigEndian()
  5220. {
  5221. union { int32 asInt; float asFloat; } n;
  5222. n.asInt = (int32) readIntBigEndian();
  5223. return n.asFloat;
  5224. }
  5225. double InputStream::readDouble()
  5226. {
  5227. union { int64 asInt; double asDouble; } n;
  5228. n.asInt = readInt64();
  5229. return n.asDouble;
  5230. }
  5231. double InputStream::readDoubleBigEndian()
  5232. {
  5233. union { int64 asInt; double asDouble; } n;
  5234. n.asInt = readInt64BigEndian();
  5235. return n.asDouble;
  5236. }
  5237. const String InputStream::readString()
  5238. {
  5239. MemoryBlock buffer (256);
  5240. char* data = static_cast<char*> (buffer.getData());
  5241. size_t i = 0;
  5242. while ((data[i] = readByte()) != 0)
  5243. {
  5244. if (++i >= buffer.getSize())
  5245. {
  5246. buffer.setSize (buffer.getSize() + 512);
  5247. data = static_cast<char*> (buffer.getData());
  5248. }
  5249. }
  5250. return String::fromUTF8 (data, (int) i);
  5251. }
  5252. const String InputStream::readNextLine()
  5253. {
  5254. MemoryBlock buffer (256);
  5255. char* data = static_cast<char*> (buffer.getData());
  5256. size_t i = 0;
  5257. while ((data[i] = readByte()) != 0)
  5258. {
  5259. if (data[i] == '\n')
  5260. break;
  5261. if (data[i] == '\r')
  5262. {
  5263. const int64 lastPos = getPosition();
  5264. if (readByte() != '\n')
  5265. setPosition (lastPos);
  5266. break;
  5267. }
  5268. if (++i >= buffer.getSize())
  5269. {
  5270. buffer.setSize (buffer.getSize() + 512);
  5271. data = static_cast<char*> (buffer.getData());
  5272. }
  5273. }
  5274. return String::fromUTF8 (data, (int) i);
  5275. }
  5276. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5277. {
  5278. MemoryOutputStream mo (block, true);
  5279. return mo.writeFromInputStream (*this, numBytes);
  5280. }
  5281. const String InputStream::readEntireStreamAsString()
  5282. {
  5283. MemoryOutputStream mo;
  5284. mo.writeFromInputStream (*this, -1);
  5285. return mo.toString();
  5286. }
  5287. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5288. {
  5289. if (numBytesToSkip > 0)
  5290. {
  5291. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5292. HeapBlock<char> temp (skipBufferSize);
  5293. while (numBytesToSkip > 0 && ! isExhausted())
  5294. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5295. }
  5296. }
  5297. END_JUCE_NAMESPACE
  5298. /*** End of inlined file: juce_InputStream.cpp ***/
  5299. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5300. BEGIN_JUCE_NAMESPACE
  5301. #if JUCE_DEBUG
  5302. static Array<void*, CriticalSection> activeStreams;
  5303. void juce_CheckForDanglingStreams()
  5304. {
  5305. /*
  5306. It's always a bad idea to leak any object, but if you're leaking output
  5307. streams, then there's a good chance that you're failing to flush a file
  5308. to disk properly, which could result in corrupted data and other similar
  5309. nastiness..
  5310. */
  5311. jassert (activeStreams.size() == 0);
  5312. };
  5313. #endif
  5314. OutputStream::OutputStream()
  5315. {
  5316. #if JUCE_DEBUG
  5317. activeStreams.add (this);
  5318. #endif
  5319. }
  5320. OutputStream::~OutputStream()
  5321. {
  5322. #if JUCE_DEBUG
  5323. activeStreams.removeValue (this);
  5324. #endif
  5325. }
  5326. void OutputStream::writeBool (const bool b)
  5327. {
  5328. writeByte (b ? (char) 1
  5329. : (char) 0);
  5330. }
  5331. void OutputStream::writeByte (char byte)
  5332. {
  5333. write (&byte, 1);
  5334. }
  5335. void OutputStream::writeShort (short value)
  5336. {
  5337. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5338. write (&v, 2);
  5339. }
  5340. void OutputStream::writeShortBigEndian (short value)
  5341. {
  5342. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5343. write (&v, 2);
  5344. }
  5345. void OutputStream::writeInt (int value)
  5346. {
  5347. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5348. write (&v, 4);
  5349. }
  5350. void OutputStream::writeIntBigEndian (int value)
  5351. {
  5352. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5353. write (&v, 4);
  5354. }
  5355. void OutputStream::writeCompressedInt (int value)
  5356. {
  5357. unsigned int un = (value < 0) ? (unsigned int) -value
  5358. : (unsigned int) value;
  5359. uint8 data[5];
  5360. int num = 0;
  5361. while (un > 0)
  5362. {
  5363. data[++num] = (uint8) un;
  5364. un >>= 8;
  5365. }
  5366. data[0] = (uint8) num;
  5367. if (value < 0)
  5368. data[0] |= 0x80;
  5369. write (data, num + 1);
  5370. }
  5371. void OutputStream::writeInt64 (int64 value)
  5372. {
  5373. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5374. write (&v, 8);
  5375. }
  5376. void OutputStream::writeInt64BigEndian (int64 value)
  5377. {
  5378. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5379. write (&v, 8);
  5380. }
  5381. void OutputStream::writeFloat (float value)
  5382. {
  5383. union { int asInt; float asFloat; } n;
  5384. n.asFloat = value;
  5385. writeInt (n.asInt);
  5386. }
  5387. void OutputStream::writeFloatBigEndian (float value)
  5388. {
  5389. union { int asInt; float asFloat; } n;
  5390. n.asFloat = value;
  5391. writeIntBigEndian (n.asInt);
  5392. }
  5393. void OutputStream::writeDouble (double value)
  5394. {
  5395. union { int64 asInt; double asDouble; } n;
  5396. n.asDouble = value;
  5397. writeInt64 (n.asInt);
  5398. }
  5399. void OutputStream::writeDoubleBigEndian (double value)
  5400. {
  5401. union { int64 asInt; double asDouble; } n;
  5402. n.asDouble = value;
  5403. writeInt64BigEndian (n.asInt);
  5404. }
  5405. void OutputStream::writeString (const String& text)
  5406. {
  5407. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5408. // if lots of large, persistent strings were to be written to streams).
  5409. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5410. HeapBlock<char> temp (numBytes);
  5411. text.copyToUTF8 (temp, numBytes);
  5412. write (temp, numBytes);
  5413. }
  5414. void OutputStream::writeText (const String& text, const bool asUnicode,
  5415. const bool writeUnicodeHeaderBytes)
  5416. {
  5417. if (asUnicode)
  5418. {
  5419. if (writeUnicodeHeaderBytes)
  5420. write ("\x0ff\x0fe", 2);
  5421. const juce_wchar* src = text;
  5422. bool lastCharWasReturn = false;
  5423. while (*src != 0)
  5424. {
  5425. if (*src == L'\n' && ! lastCharWasReturn)
  5426. writeShort ((short) L'\r');
  5427. lastCharWasReturn = (*src == L'\r');
  5428. writeShort ((short) *src++);
  5429. }
  5430. }
  5431. else
  5432. {
  5433. const char* src = text.toUTF8();
  5434. const char* t = src;
  5435. for (;;)
  5436. {
  5437. if (*t == '\n')
  5438. {
  5439. if (t > src)
  5440. write (src, (int) (t - src));
  5441. write ("\r\n", 2);
  5442. src = t + 1;
  5443. }
  5444. else if (*t == '\r')
  5445. {
  5446. if (t[1] == '\n')
  5447. ++t;
  5448. }
  5449. else if (*t == 0)
  5450. {
  5451. if (t > src)
  5452. write (src, (int) (t - src));
  5453. break;
  5454. }
  5455. ++t;
  5456. }
  5457. }
  5458. }
  5459. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5460. {
  5461. if (numBytesToWrite < 0)
  5462. numBytesToWrite = std::numeric_limits<int64>::max();
  5463. int numWritten = 0;
  5464. while (numBytesToWrite > 0 && ! source.isExhausted())
  5465. {
  5466. char buffer [8192];
  5467. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5468. if (num <= 0)
  5469. break;
  5470. write (buffer, num);
  5471. numBytesToWrite -= num;
  5472. numWritten += num;
  5473. }
  5474. return numWritten;
  5475. }
  5476. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5477. {
  5478. return stream << String (number);
  5479. }
  5480. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5481. {
  5482. return stream << String (number);
  5483. }
  5484. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5485. {
  5486. stream.writeByte (character);
  5487. return stream;
  5488. }
  5489. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5490. {
  5491. stream.write (text, (int) strlen (text));
  5492. return stream;
  5493. }
  5494. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5495. {
  5496. stream.write (data.getData(), (int) data.getSize());
  5497. return stream;
  5498. }
  5499. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5500. {
  5501. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5502. if (in != 0)
  5503. stream.writeFromInputStream (*in, -1);
  5504. return stream;
  5505. }
  5506. END_JUCE_NAMESPACE
  5507. /*** End of inlined file: juce_OutputStream.cpp ***/
  5508. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5509. BEGIN_JUCE_NAMESPACE
  5510. DirectoryIterator::DirectoryIterator (const File& directory,
  5511. bool isRecursive_,
  5512. const String& wildCard_,
  5513. const int whatToLookFor_)
  5514. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5515. wildCard (wildCard_),
  5516. path (File::addTrailingSeparator (directory.getFullPathName())),
  5517. index (-1),
  5518. totalNumFiles (-1),
  5519. whatToLookFor (whatToLookFor_),
  5520. isRecursive (isRecursive_)
  5521. {
  5522. // you have to specify the type of files you're looking for!
  5523. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5524. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5525. }
  5526. DirectoryIterator::~DirectoryIterator()
  5527. {
  5528. }
  5529. bool DirectoryIterator::next()
  5530. {
  5531. return next (0, 0, 0, 0, 0, 0);
  5532. }
  5533. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5534. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5535. {
  5536. if (subIterator != 0)
  5537. {
  5538. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5539. return true;
  5540. subIterator = 0;
  5541. }
  5542. String filename;
  5543. bool isDirectory, isHidden;
  5544. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5545. {
  5546. ++index;
  5547. if (! filename.containsOnly ("."))
  5548. {
  5549. const File fileFound (path + filename, 0);
  5550. bool matches = false;
  5551. if (isDirectory)
  5552. {
  5553. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5554. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5555. matches = (whatToLookFor & File::findDirectories) != 0;
  5556. }
  5557. else
  5558. {
  5559. matches = (whatToLookFor & File::findFiles) != 0;
  5560. }
  5561. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5562. if (matches && isRecursive)
  5563. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5564. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5565. matches = ! isHidden;
  5566. if (matches)
  5567. {
  5568. currentFile = fileFound;
  5569. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5570. if (isDirResult != 0) *isDirResult = isDirectory;
  5571. return true;
  5572. }
  5573. else if (subIterator != 0)
  5574. {
  5575. return next();
  5576. }
  5577. }
  5578. }
  5579. return false;
  5580. }
  5581. const File DirectoryIterator::getFile() const
  5582. {
  5583. if (subIterator != 0)
  5584. return subIterator->getFile();
  5585. return currentFile;
  5586. }
  5587. float DirectoryIterator::getEstimatedProgress() const
  5588. {
  5589. if (totalNumFiles < 0)
  5590. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5591. if (totalNumFiles <= 0)
  5592. return 0.0f;
  5593. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5594. : (float) index;
  5595. return detailedIndex / totalNumFiles;
  5596. }
  5597. END_JUCE_NAMESPACE
  5598. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5599. /*** Start of inlined file: juce_File.cpp ***/
  5600. #if ! JUCE_WINDOWS
  5601. #include <pwd.h>
  5602. #endif
  5603. BEGIN_JUCE_NAMESPACE
  5604. File::File (const String& fullPathName)
  5605. : fullPath (parseAbsolutePath (fullPathName))
  5606. {
  5607. }
  5608. File::File (const String& path, int)
  5609. : fullPath (path)
  5610. {
  5611. }
  5612. const File File::createFileWithoutCheckingPath (const String& path)
  5613. {
  5614. return File (path, 0);
  5615. }
  5616. File::File (const File& other)
  5617. : fullPath (other.fullPath)
  5618. {
  5619. }
  5620. File& File::operator= (const String& newPath)
  5621. {
  5622. fullPath = parseAbsolutePath (newPath);
  5623. return *this;
  5624. }
  5625. File& File::operator= (const File& other)
  5626. {
  5627. fullPath = other.fullPath;
  5628. return *this;
  5629. }
  5630. const File File::nonexistent;
  5631. const String File::parseAbsolutePath (const String& p)
  5632. {
  5633. if (p.isEmpty())
  5634. return String::empty;
  5635. #if JUCE_WINDOWS
  5636. // Windows..
  5637. String path (p.replaceCharacter ('/', '\\'));
  5638. if (path.startsWithChar (File::separator))
  5639. {
  5640. if (path[1] != File::separator)
  5641. {
  5642. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5643. If you're trying to parse a string that may be either a relative path or an absolute path,
  5644. you MUST provide a context against which the partial path can be evaluated - you can do
  5645. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5646. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5647. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5648. */
  5649. jassertfalse;
  5650. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5651. }
  5652. }
  5653. else if (! path.containsChar (':'))
  5654. {
  5655. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5656. If you're trying to parse a string that may be either a relative path or an absolute path,
  5657. you MUST provide a context against which the partial path can be evaluated - you can do
  5658. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5659. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5660. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5661. */
  5662. jassertfalse;
  5663. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5664. }
  5665. #else
  5666. // Mac or Linux..
  5667. String path (p.replaceCharacter ('\\', '/'));
  5668. if (path.startsWithChar ('~'))
  5669. {
  5670. if (path[1] == File::separator || path[1] == 0)
  5671. {
  5672. // expand a name of the form "~/abc"
  5673. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5674. + path.substring (1);
  5675. }
  5676. else
  5677. {
  5678. // expand a name of type "~dave/abc"
  5679. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5680. struct passwd* const pw = getpwnam (userName.toUTF8());
  5681. if (pw != 0)
  5682. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5683. }
  5684. }
  5685. else if (! path.startsWithChar (File::separator))
  5686. {
  5687. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5688. If you're trying to parse a string that may be either a relative path or an absolute path,
  5689. you MUST provide a context against which the partial path can be evaluated - you can do
  5690. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5691. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5692. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5693. */
  5694. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5695. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5696. }
  5697. #endif
  5698. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5699. path = path.dropLastCharacters (1);
  5700. return path;
  5701. }
  5702. const String File::addTrailingSeparator (const String& path)
  5703. {
  5704. return path.endsWithChar (File::separator) ? path
  5705. : path + File::separator;
  5706. }
  5707. #if JUCE_LINUX
  5708. #define NAMES_ARE_CASE_SENSITIVE 1
  5709. #endif
  5710. bool File::areFileNamesCaseSensitive()
  5711. {
  5712. #if NAMES_ARE_CASE_SENSITIVE
  5713. return true;
  5714. #else
  5715. return false;
  5716. #endif
  5717. }
  5718. bool File::operator== (const File& other) const
  5719. {
  5720. #if NAMES_ARE_CASE_SENSITIVE
  5721. return fullPath == other.fullPath;
  5722. #else
  5723. return fullPath.equalsIgnoreCase (other.fullPath);
  5724. #endif
  5725. }
  5726. bool File::operator!= (const File& other) const
  5727. {
  5728. return ! operator== (other);
  5729. }
  5730. bool File::operator< (const File& other) const
  5731. {
  5732. #if NAMES_ARE_CASE_SENSITIVE
  5733. return fullPath < other.fullPath;
  5734. #else
  5735. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5736. #endif
  5737. }
  5738. bool File::operator> (const File& other) const
  5739. {
  5740. #if NAMES_ARE_CASE_SENSITIVE
  5741. return fullPath > other.fullPath;
  5742. #else
  5743. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5744. #endif
  5745. }
  5746. bool File::setReadOnly (const bool shouldBeReadOnly,
  5747. const bool applyRecursively) const
  5748. {
  5749. bool worked = true;
  5750. if (applyRecursively && isDirectory())
  5751. {
  5752. Array <File> subFiles;
  5753. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5754. for (int i = subFiles.size(); --i >= 0;)
  5755. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5756. }
  5757. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5758. }
  5759. bool File::deleteRecursively() const
  5760. {
  5761. bool worked = true;
  5762. if (isDirectory())
  5763. {
  5764. Array<File> subFiles;
  5765. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5766. for (int i = subFiles.size(); --i >= 0;)
  5767. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5768. }
  5769. return deleteFile() && worked;
  5770. }
  5771. bool File::moveFileTo (const File& newFile) const
  5772. {
  5773. if (newFile.fullPath == fullPath)
  5774. return true;
  5775. #if ! NAMES_ARE_CASE_SENSITIVE
  5776. if (*this != newFile)
  5777. #endif
  5778. if (! newFile.deleteFile())
  5779. return false;
  5780. return moveInternal (newFile);
  5781. }
  5782. bool File::copyFileTo (const File& newFile) const
  5783. {
  5784. return (*this == newFile)
  5785. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5786. }
  5787. bool File::copyDirectoryTo (const File& newDirectory) const
  5788. {
  5789. if (isDirectory() && newDirectory.createDirectory())
  5790. {
  5791. Array<File> subFiles;
  5792. findChildFiles (subFiles, File::findFiles, false);
  5793. int i;
  5794. for (i = 0; i < subFiles.size(); ++i)
  5795. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5796. return false;
  5797. subFiles.clear();
  5798. findChildFiles (subFiles, File::findDirectories, false);
  5799. for (i = 0; i < subFiles.size(); ++i)
  5800. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5801. return false;
  5802. return true;
  5803. }
  5804. return false;
  5805. }
  5806. const String File::getPathUpToLastSlash() const
  5807. {
  5808. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5809. if (lastSlash > 0)
  5810. return fullPath.substring (0, lastSlash);
  5811. else if (lastSlash == 0)
  5812. return separatorString;
  5813. else
  5814. return fullPath;
  5815. }
  5816. const File File::getParentDirectory() const
  5817. {
  5818. return File (getPathUpToLastSlash(), (int) 0);
  5819. }
  5820. const String File::getFileName() const
  5821. {
  5822. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5823. }
  5824. int File::hashCode() const
  5825. {
  5826. return fullPath.hashCode();
  5827. }
  5828. int64 File::hashCode64() const
  5829. {
  5830. return fullPath.hashCode64();
  5831. }
  5832. const String File::getFileNameWithoutExtension() const
  5833. {
  5834. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5835. const int lastDot = fullPath.lastIndexOfChar ('.');
  5836. if (lastDot > lastSlash)
  5837. return fullPath.substring (lastSlash, lastDot);
  5838. else
  5839. return fullPath.substring (lastSlash);
  5840. }
  5841. bool File::isAChildOf (const File& potentialParent) const
  5842. {
  5843. if (potentialParent == File::nonexistent)
  5844. return false;
  5845. const String ourPath (getPathUpToLastSlash());
  5846. #if NAMES_ARE_CASE_SENSITIVE
  5847. if (potentialParent.fullPath == ourPath)
  5848. #else
  5849. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5850. #endif
  5851. {
  5852. return true;
  5853. }
  5854. else if (potentialParent.fullPath.length() >= ourPath.length())
  5855. {
  5856. return false;
  5857. }
  5858. else
  5859. {
  5860. return getParentDirectory().isAChildOf (potentialParent);
  5861. }
  5862. }
  5863. bool File::isAbsolutePath (const String& path)
  5864. {
  5865. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5866. #if JUCE_WINDOWS
  5867. || (path.isNotEmpty() && path[1] == ':');
  5868. #else
  5869. || path.startsWithChar ('~');
  5870. #endif
  5871. }
  5872. const File File::getChildFile (String relativePath) const
  5873. {
  5874. if (isAbsolutePath (relativePath))
  5875. {
  5876. // the path is really absolute..
  5877. return File (relativePath);
  5878. }
  5879. else
  5880. {
  5881. // it's relative, so remove any ../ or ./ bits at the start.
  5882. String path (fullPath);
  5883. if (relativePath[0] == '.')
  5884. {
  5885. #if JUCE_WINDOWS
  5886. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5887. #else
  5888. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5889. #endif
  5890. while (relativePath[0] == '.')
  5891. {
  5892. if (relativePath[1] == '.')
  5893. {
  5894. if (relativePath [2] == 0 || relativePath[2] == separator)
  5895. {
  5896. const int lastSlash = path.lastIndexOfChar (separator);
  5897. if (lastSlash >= 0)
  5898. path = path.substring (0, lastSlash);
  5899. relativePath = relativePath.substring (3);
  5900. }
  5901. else
  5902. {
  5903. break;
  5904. }
  5905. }
  5906. else if (relativePath[1] == separator)
  5907. {
  5908. relativePath = relativePath.substring (2);
  5909. }
  5910. else
  5911. {
  5912. break;
  5913. }
  5914. }
  5915. }
  5916. return File (addTrailingSeparator (path) + relativePath);
  5917. }
  5918. }
  5919. const File File::getSiblingFile (const String& fileName) const
  5920. {
  5921. return getParentDirectory().getChildFile (fileName);
  5922. }
  5923. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5924. {
  5925. if (bytes == 1)
  5926. {
  5927. return "1 byte";
  5928. }
  5929. else if (bytes < 1024)
  5930. {
  5931. return String ((int) bytes) + " bytes";
  5932. }
  5933. else if (bytes < 1024 * 1024)
  5934. {
  5935. return String (bytes / 1024.0, 1) + " KB";
  5936. }
  5937. else if (bytes < 1024 * 1024 * 1024)
  5938. {
  5939. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5940. }
  5941. else
  5942. {
  5943. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5944. }
  5945. }
  5946. bool File::create() const
  5947. {
  5948. if (exists())
  5949. return true;
  5950. {
  5951. const File parentDir (getParentDirectory());
  5952. if (parentDir == *this || ! parentDir.createDirectory())
  5953. return false;
  5954. FileOutputStream fo (*this, 8);
  5955. }
  5956. return exists();
  5957. }
  5958. bool File::createDirectory() const
  5959. {
  5960. if (! isDirectory())
  5961. {
  5962. const File parentDir (getParentDirectory());
  5963. if (parentDir == *this || ! parentDir.createDirectory())
  5964. return false;
  5965. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5966. return isDirectory();
  5967. }
  5968. return true;
  5969. }
  5970. const Time File::getCreationTime() const
  5971. {
  5972. int64 m, a, c;
  5973. getFileTimesInternal (m, a, c);
  5974. return Time (c);
  5975. }
  5976. const Time File::getLastModificationTime() const
  5977. {
  5978. int64 m, a, c;
  5979. getFileTimesInternal (m, a, c);
  5980. return Time (m);
  5981. }
  5982. const Time File::getLastAccessTime() const
  5983. {
  5984. int64 m, a, c;
  5985. getFileTimesInternal (m, a, c);
  5986. return Time (a);
  5987. }
  5988. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5989. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5990. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5991. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5992. {
  5993. if (! existsAsFile())
  5994. return false;
  5995. FileInputStream in (*this);
  5996. return getSize() == in.readIntoMemoryBlock (destBlock);
  5997. }
  5998. const String File::loadFileAsString() const
  5999. {
  6000. if (! existsAsFile())
  6001. return String::empty;
  6002. FileInputStream in (*this);
  6003. return in.readEntireStreamAsString();
  6004. }
  6005. int File::findChildFiles (Array<File>& results,
  6006. const int whatToLookFor,
  6007. const bool searchRecursively,
  6008. const String& wildCardPattern) const
  6009. {
  6010. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6011. int total = 0;
  6012. while (di.next())
  6013. {
  6014. results.add (di.getFile());
  6015. ++total;
  6016. }
  6017. return total;
  6018. }
  6019. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6020. {
  6021. DirectoryIterator di (*this, false, "*", whatToLookFor);
  6022. int total = 0;
  6023. while (di.next())
  6024. ++total;
  6025. return total;
  6026. }
  6027. bool File::containsSubDirectories() const
  6028. {
  6029. if (isDirectory())
  6030. {
  6031. DirectoryIterator di (*this, false, "*", findDirectories);
  6032. return di.next();
  6033. }
  6034. return false;
  6035. }
  6036. const File File::getNonexistentChildFile (const String& prefix_,
  6037. const String& suffix,
  6038. bool putNumbersInBrackets) const
  6039. {
  6040. File f (getChildFile (prefix_ + suffix));
  6041. if (f.exists())
  6042. {
  6043. int num = 2;
  6044. String prefix (prefix_);
  6045. // remove any bracketed numbers that may already be on the end..
  6046. if (prefix.trim().endsWithChar (')'))
  6047. {
  6048. putNumbersInBrackets = true;
  6049. const int openBracks = prefix.lastIndexOfChar ('(');
  6050. const int closeBracks = prefix.lastIndexOfChar (')');
  6051. if (openBracks > 0
  6052. && closeBracks > openBracks
  6053. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6054. {
  6055. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6056. prefix = prefix.substring (0, openBracks);
  6057. }
  6058. }
  6059. // also use brackets if it ends in a digit.
  6060. putNumbersInBrackets = putNumbersInBrackets
  6061. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6062. do
  6063. {
  6064. if (putNumbersInBrackets)
  6065. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6066. else
  6067. f = getChildFile (prefix + String (num++) + suffix);
  6068. } while (f.exists());
  6069. }
  6070. return f;
  6071. }
  6072. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6073. {
  6074. if (exists())
  6075. {
  6076. return getParentDirectory()
  6077. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6078. getFileExtension(),
  6079. putNumbersInBrackets);
  6080. }
  6081. else
  6082. {
  6083. return *this;
  6084. }
  6085. }
  6086. const String File::getFileExtension() const
  6087. {
  6088. String ext;
  6089. if (! isDirectory())
  6090. {
  6091. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6092. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6093. ext = fullPath.substring (indexOfDot);
  6094. }
  6095. return ext;
  6096. }
  6097. bool File::hasFileExtension (const String& possibleSuffix) const
  6098. {
  6099. if (possibleSuffix.isEmpty())
  6100. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6101. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6102. if (semicolon >= 0)
  6103. {
  6104. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6105. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6106. }
  6107. else
  6108. {
  6109. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6110. {
  6111. if (possibleSuffix.startsWithChar ('.'))
  6112. return true;
  6113. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6114. if (dotPos >= 0)
  6115. return fullPath [dotPos] == '.';
  6116. }
  6117. }
  6118. return false;
  6119. }
  6120. const File File::withFileExtension (const String& newExtension) const
  6121. {
  6122. if (fullPath.isEmpty())
  6123. return File::nonexistent;
  6124. String filePart (getFileName());
  6125. int i = filePart.lastIndexOfChar ('.');
  6126. if (i >= 0)
  6127. filePart = filePart.substring (0, i);
  6128. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6129. filePart << '.';
  6130. return getSiblingFile (filePart + newExtension);
  6131. }
  6132. bool File::startAsProcess (const String& parameters) const
  6133. {
  6134. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6135. }
  6136. FileInputStream* File::createInputStream() const
  6137. {
  6138. if (existsAsFile())
  6139. return new FileInputStream (*this);
  6140. return 0;
  6141. }
  6142. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6143. {
  6144. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6145. if (out->failedToOpen())
  6146. return 0;
  6147. return out.release();
  6148. }
  6149. bool File::appendData (const void* const dataToAppend,
  6150. const int numberOfBytes) const
  6151. {
  6152. if (numberOfBytes > 0)
  6153. {
  6154. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6155. if (out == 0)
  6156. return false;
  6157. out->write (dataToAppend, numberOfBytes);
  6158. }
  6159. return true;
  6160. }
  6161. bool File::replaceWithData (const void* const dataToWrite,
  6162. const int numberOfBytes) const
  6163. {
  6164. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6165. if (numberOfBytes <= 0)
  6166. return deleteFile();
  6167. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6168. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6169. return tempFile.overwriteTargetFileWithTemporary();
  6170. }
  6171. bool File::appendText (const String& text,
  6172. const bool asUnicode,
  6173. const bool writeUnicodeHeaderBytes) const
  6174. {
  6175. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6176. if (out != 0)
  6177. {
  6178. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6179. return true;
  6180. }
  6181. return false;
  6182. }
  6183. bool File::replaceWithText (const String& textToWrite,
  6184. const bool asUnicode,
  6185. const bool writeUnicodeHeaderBytes) const
  6186. {
  6187. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6188. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6189. return tempFile.overwriteTargetFileWithTemporary();
  6190. }
  6191. bool File::hasIdenticalContentTo (const File& other) const
  6192. {
  6193. if (other == *this)
  6194. return true;
  6195. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6196. {
  6197. FileInputStream in1 (*this), in2 (other);
  6198. const int bufferSize = 4096;
  6199. HeapBlock <char> buffer1, buffer2;
  6200. buffer1.malloc (bufferSize);
  6201. buffer2.malloc (bufferSize);
  6202. for (;;)
  6203. {
  6204. const int num1 = in1.read (buffer1, bufferSize);
  6205. const int num2 = in2.read (buffer2, bufferSize);
  6206. if (num1 != num2)
  6207. break;
  6208. if (num1 <= 0)
  6209. return true;
  6210. if (memcmp (buffer1, buffer2, num1) != 0)
  6211. break;
  6212. }
  6213. }
  6214. return false;
  6215. }
  6216. const String File::createLegalPathName (const String& original)
  6217. {
  6218. String s (original);
  6219. String start;
  6220. if (s[1] == ':')
  6221. {
  6222. start = s.substring (0, 2);
  6223. s = s.substring (2);
  6224. }
  6225. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6226. .substring (0, 1024);
  6227. }
  6228. const String File::createLegalFileName (const String& original)
  6229. {
  6230. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6231. const int maxLength = 128; // only the length of the filename, not the whole path
  6232. const int len = s.length();
  6233. if (len > maxLength)
  6234. {
  6235. const int lastDot = s.lastIndexOfChar ('.');
  6236. if (lastDot > jmax (0, len - 12))
  6237. {
  6238. s = s.substring (0, maxLength - (len - lastDot))
  6239. + s.substring (lastDot);
  6240. }
  6241. else
  6242. {
  6243. s = s.substring (0, maxLength);
  6244. }
  6245. }
  6246. return s;
  6247. }
  6248. const String File::getRelativePathFrom (const File& dir) const
  6249. {
  6250. String thisPath (fullPath);
  6251. {
  6252. int len = thisPath.length();
  6253. while (--len >= 0 && thisPath [len] == File::separator)
  6254. thisPath [len] = 0;
  6255. }
  6256. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6257. : dir.fullPath));
  6258. const int len = jmin (thisPath.length(), dirPath.length());
  6259. int commonBitLength = 0;
  6260. for (int i = 0; i < len; ++i)
  6261. {
  6262. #if NAMES_ARE_CASE_SENSITIVE
  6263. if (thisPath[i] != dirPath[i])
  6264. #else
  6265. if (CharacterFunctions::toLowerCase (thisPath[i])
  6266. != CharacterFunctions::toLowerCase (dirPath[i]))
  6267. #endif
  6268. {
  6269. break;
  6270. }
  6271. ++commonBitLength;
  6272. }
  6273. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6274. --commonBitLength;
  6275. // if the only common bit is the root, then just return the full path..
  6276. if (commonBitLength <= 0
  6277. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6278. return fullPath;
  6279. thisPath = thisPath.substring (commonBitLength);
  6280. dirPath = dirPath.substring (commonBitLength);
  6281. while (dirPath.isNotEmpty())
  6282. {
  6283. #if JUCE_WINDOWS
  6284. thisPath = "..\\" + thisPath;
  6285. #else
  6286. thisPath = "../" + thisPath;
  6287. #endif
  6288. const int sep = dirPath.indexOfChar (separator);
  6289. if (sep >= 0)
  6290. dirPath = dirPath.substring (sep + 1);
  6291. else
  6292. dirPath = String::empty;
  6293. }
  6294. return thisPath;
  6295. }
  6296. const File File::createTempFile (const String& fileNameEnding)
  6297. {
  6298. const File tempFile (getSpecialLocation (tempDirectory)
  6299. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6300. .withFileExtension (fileNameEnding));
  6301. if (tempFile.exists())
  6302. return createTempFile (fileNameEnding);
  6303. else
  6304. return tempFile;
  6305. }
  6306. END_JUCE_NAMESPACE
  6307. /*** End of inlined file: juce_File.cpp ***/
  6308. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6309. BEGIN_JUCE_NAMESPACE
  6310. int64 juce_fileSetPosition (void* handle, int64 pos);
  6311. FileInputStream::FileInputStream (const File& f)
  6312. : file (f),
  6313. fileHandle (0),
  6314. currentPosition (0),
  6315. totalSize (0),
  6316. needToSeek (true)
  6317. {
  6318. openHandle();
  6319. }
  6320. FileInputStream::~FileInputStream()
  6321. {
  6322. closeHandle();
  6323. }
  6324. int64 FileInputStream::getTotalLength()
  6325. {
  6326. return totalSize;
  6327. }
  6328. int FileInputStream::read (void* buffer, int bytesToRead)
  6329. {
  6330. int num = 0;
  6331. if (needToSeek)
  6332. {
  6333. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6334. return 0;
  6335. needToSeek = false;
  6336. }
  6337. num = readInternal (buffer, bytesToRead);
  6338. currentPosition += num;
  6339. return num;
  6340. }
  6341. bool FileInputStream::isExhausted()
  6342. {
  6343. return currentPosition >= totalSize;
  6344. }
  6345. int64 FileInputStream::getPosition()
  6346. {
  6347. return currentPosition;
  6348. }
  6349. bool FileInputStream::setPosition (int64 pos)
  6350. {
  6351. pos = jlimit ((int64) 0, totalSize, pos);
  6352. needToSeek |= (currentPosition != pos);
  6353. currentPosition = pos;
  6354. return true;
  6355. }
  6356. END_JUCE_NAMESPACE
  6357. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6358. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6359. BEGIN_JUCE_NAMESPACE
  6360. int64 juce_fileSetPosition (void* handle, int64 pos);
  6361. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6362. : file (f),
  6363. fileHandle (0),
  6364. currentPosition (0),
  6365. bufferSize (bufferSize_),
  6366. bytesInBuffer (0),
  6367. buffer (jmax (bufferSize_, 16))
  6368. {
  6369. openHandle();
  6370. }
  6371. FileOutputStream::~FileOutputStream()
  6372. {
  6373. flush();
  6374. closeHandle();
  6375. }
  6376. int64 FileOutputStream::getPosition()
  6377. {
  6378. return currentPosition;
  6379. }
  6380. bool FileOutputStream::setPosition (int64 newPosition)
  6381. {
  6382. if (newPosition != currentPosition)
  6383. {
  6384. flush();
  6385. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6386. }
  6387. return newPosition == currentPosition;
  6388. }
  6389. void FileOutputStream::flush()
  6390. {
  6391. if (bytesInBuffer > 0)
  6392. {
  6393. writeInternal (buffer, bytesInBuffer);
  6394. bytesInBuffer = 0;
  6395. }
  6396. flushInternal();
  6397. }
  6398. bool FileOutputStream::write (const void* const src, const int numBytes)
  6399. {
  6400. if (bytesInBuffer + numBytes < bufferSize)
  6401. {
  6402. memcpy (buffer + bytesInBuffer, src, numBytes);
  6403. bytesInBuffer += numBytes;
  6404. currentPosition += numBytes;
  6405. }
  6406. else
  6407. {
  6408. if (bytesInBuffer > 0)
  6409. {
  6410. // flush the reservoir
  6411. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6412. bytesInBuffer = 0;
  6413. if (! wroteOk)
  6414. return false;
  6415. }
  6416. if (numBytes < bufferSize)
  6417. {
  6418. memcpy (buffer + bytesInBuffer, src, numBytes);
  6419. bytesInBuffer += numBytes;
  6420. currentPosition += numBytes;
  6421. }
  6422. else
  6423. {
  6424. const int bytesWritten = writeInternal (src, numBytes);
  6425. if (bytesWritten < 0)
  6426. return false;
  6427. currentPosition += bytesWritten;
  6428. return bytesWritten == numBytes;
  6429. }
  6430. }
  6431. return true;
  6432. }
  6433. END_JUCE_NAMESPACE
  6434. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6435. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6436. BEGIN_JUCE_NAMESPACE
  6437. FileSearchPath::FileSearchPath()
  6438. {
  6439. }
  6440. FileSearchPath::FileSearchPath (const String& path)
  6441. {
  6442. init (path);
  6443. }
  6444. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6445. : directories (other.directories)
  6446. {
  6447. }
  6448. FileSearchPath::~FileSearchPath()
  6449. {
  6450. }
  6451. FileSearchPath& FileSearchPath::operator= (const String& path)
  6452. {
  6453. init (path);
  6454. return *this;
  6455. }
  6456. void FileSearchPath::init (const String& path)
  6457. {
  6458. directories.clear();
  6459. directories.addTokens (path, ";", "\"");
  6460. directories.trim();
  6461. directories.removeEmptyStrings();
  6462. for (int i = directories.size(); --i >= 0;)
  6463. directories.set (i, directories[i].unquoted());
  6464. }
  6465. int FileSearchPath::getNumPaths() const
  6466. {
  6467. return directories.size();
  6468. }
  6469. const File FileSearchPath::operator[] (const int index) const
  6470. {
  6471. return File (directories [index]);
  6472. }
  6473. const String FileSearchPath::toString() const
  6474. {
  6475. StringArray directories2 (directories);
  6476. for (int i = directories2.size(); --i >= 0;)
  6477. if (directories2[i].containsChar (';'))
  6478. directories2.set (i, directories2[i].quoted());
  6479. return directories2.joinIntoString (";");
  6480. }
  6481. void FileSearchPath::add (const File& dir, const int insertIndex)
  6482. {
  6483. directories.insert (insertIndex, dir.getFullPathName());
  6484. }
  6485. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6486. {
  6487. for (int i = 0; i < directories.size(); ++i)
  6488. if (File (directories[i]) == dir)
  6489. return;
  6490. add (dir);
  6491. }
  6492. void FileSearchPath::remove (const int index)
  6493. {
  6494. directories.remove (index);
  6495. }
  6496. void FileSearchPath::addPath (const FileSearchPath& other)
  6497. {
  6498. for (int i = 0; i < other.getNumPaths(); ++i)
  6499. addIfNotAlreadyThere (other[i]);
  6500. }
  6501. void FileSearchPath::removeRedundantPaths()
  6502. {
  6503. for (int i = directories.size(); --i >= 0;)
  6504. {
  6505. const File d1 (directories[i]);
  6506. for (int j = directories.size(); --j >= 0;)
  6507. {
  6508. const File d2 (directories[j]);
  6509. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6510. {
  6511. directories.remove (i);
  6512. break;
  6513. }
  6514. }
  6515. }
  6516. }
  6517. void FileSearchPath::removeNonExistentPaths()
  6518. {
  6519. for (int i = directories.size(); --i >= 0;)
  6520. if (! File (directories[i]).isDirectory())
  6521. directories.remove (i);
  6522. }
  6523. int FileSearchPath::findChildFiles (Array<File>& results,
  6524. const int whatToLookFor,
  6525. const bool searchRecursively,
  6526. const String& wildCardPattern) const
  6527. {
  6528. int total = 0;
  6529. for (int i = 0; i < directories.size(); ++i)
  6530. total += operator[] (i).findChildFiles (results,
  6531. whatToLookFor,
  6532. searchRecursively,
  6533. wildCardPattern);
  6534. return total;
  6535. }
  6536. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6537. const bool checkRecursively) const
  6538. {
  6539. for (int i = directories.size(); --i >= 0;)
  6540. {
  6541. const File d (directories[i]);
  6542. if (checkRecursively)
  6543. {
  6544. if (fileToCheck.isAChildOf (d))
  6545. return true;
  6546. }
  6547. else
  6548. {
  6549. if (fileToCheck.getParentDirectory() == d)
  6550. return true;
  6551. }
  6552. }
  6553. return false;
  6554. }
  6555. END_JUCE_NAMESPACE
  6556. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6557. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6558. BEGIN_JUCE_NAMESPACE
  6559. NamedPipe::NamedPipe()
  6560. : internal (0)
  6561. {
  6562. }
  6563. NamedPipe::~NamedPipe()
  6564. {
  6565. close();
  6566. }
  6567. bool NamedPipe::openExisting (const String& pipeName)
  6568. {
  6569. currentPipeName = pipeName;
  6570. return openInternal (pipeName, false);
  6571. }
  6572. bool NamedPipe::createNewPipe (const String& pipeName)
  6573. {
  6574. currentPipeName = pipeName;
  6575. return openInternal (pipeName, true);
  6576. }
  6577. bool NamedPipe::isOpen() const
  6578. {
  6579. return internal != 0;
  6580. }
  6581. const String NamedPipe::getName() const
  6582. {
  6583. return currentPipeName;
  6584. }
  6585. // other methods for this class are implemented in the platform-specific files
  6586. END_JUCE_NAMESPACE
  6587. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6588. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6589. BEGIN_JUCE_NAMESPACE
  6590. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6591. {
  6592. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6593. "temp_" + String (Random::getSystemRandom().nextInt()),
  6594. suffix,
  6595. optionFlags);
  6596. }
  6597. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6598. : targetFile (targetFile_)
  6599. {
  6600. // If you use this constructor, you need to give it a valid target file!
  6601. jassert (targetFile != File::nonexistent);
  6602. createTempFile (targetFile.getParentDirectory(),
  6603. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6604. targetFile.getFileExtension(),
  6605. optionFlags);
  6606. }
  6607. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6608. const String& suffix, const int optionFlags)
  6609. {
  6610. if ((optionFlags & useHiddenFile) != 0)
  6611. name = "." + name;
  6612. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6613. }
  6614. TemporaryFile::~TemporaryFile()
  6615. {
  6616. if (! deleteTemporaryFile())
  6617. {
  6618. /* Failed to delete our temporary file! The most likely reason for this would be
  6619. that you've not closed an output stream that was being used to write to file.
  6620. If you find that something beyond your control is changing permissions on
  6621. your temporary files and preventing them from being deleted, you may want to
  6622. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6623. handle them appropriately.
  6624. */
  6625. jassertfalse;
  6626. }
  6627. }
  6628. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6629. {
  6630. // This method only works if you created this object with the constructor
  6631. // that takes a target file!
  6632. jassert (targetFile != File::nonexistent);
  6633. if (temporaryFile.exists())
  6634. {
  6635. // Have a few attempts at overwriting the file before giving up..
  6636. for (int i = 5; --i >= 0;)
  6637. {
  6638. if (temporaryFile.moveFileTo (targetFile))
  6639. return true;
  6640. Thread::sleep (100);
  6641. }
  6642. }
  6643. else
  6644. {
  6645. // There's no temporary file to use. If your write failed, you should
  6646. // probably check, and not bother calling this method.
  6647. jassertfalse;
  6648. }
  6649. return false;
  6650. }
  6651. bool TemporaryFile::deleteTemporaryFile() const
  6652. {
  6653. // Have a few attempts at deleting the file before giving up..
  6654. for (int i = 5; --i >= 0;)
  6655. {
  6656. if (temporaryFile.deleteFile())
  6657. return true;
  6658. Thread::sleep (50);
  6659. }
  6660. return false;
  6661. }
  6662. END_JUCE_NAMESPACE
  6663. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6664. /*** Start of inlined file: juce_Socket.cpp ***/
  6665. #if JUCE_WINDOWS
  6666. #include <winsock2.h>
  6667. #if JUCE_MSVC
  6668. #pragma warning (push)
  6669. #pragma warning (disable : 4127 4389 4018)
  6670. #endif
  6671. #else
  6672. #if JUCE_LINUX
  6673. #include <sys/types.h>
  6674. #include <sys/socket.h>
  6675. #include <sys/errno.h>
  6676. #include <unistd.h>
  6677. #include <netinet/in.h>
  6678. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6679. #include <CoreServices/CoreServices.h>
  6680. #endif
  6681. #include <fcntl.h>
  6682. #include <netdb.h>
  6683. #include <arpa/inet.h>
  6684. #include <netinet/tcp.h>
  6685. #endif
  6686. BEGIN_JUCE_NAMESPACE
  6687. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6688. typedef socklen_t juce_socklen_t;
  6689. #else
  6690. typedef int juce_socklen_t;
  6691. #endif
  6692. #if JUCE_WINDOWS
  6693. namespace SocketHelpers
  6694. {
  6695. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6696. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6697. }
  6698. static void initWin32Sockets()
  6699. {
  6700. static CriticalSection lock;
  6701. const ScopedLock sl (lock);
  6702. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6703. {
  6704. WSADATA wsaData;
  6705. const WORD wVersionRequested = MAKEWORD (1, 1);
  6706. WSAStartup (wVersionRequested, &wsaData);
  6707. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6708. }
  6709. }
  6710. void juce_shutdownWin32Sockets()
  6711. {
  6712. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6713. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6714. }
  6715. #endif
  6716. namespace SocketHelpers
  6717. {
  6718. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6719. {
  6720. const int sndBufSize = 65536;
  6721. const int rcvBufSize = 65536;
  6722. const int one = 1;
  6723. return handle > 0
  6724. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6725. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6726. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6727. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6728. }
  6729. static bool bindSocketToPort (const int handle, const int port) throw()
  6730. {
  6731. if (handle <= 0 || port <= 0)
  6732. return false;
  6733. struct sockaddr_in servTmpAddr;
  6734. zerostruct (servTmpAddr);
  6735. servTmpAddr.sin_family = PF_INET;
  6736. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6737. servTmpAddr.sin_port = htons ((uint16) port);
  6738. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6739. }
  6740. static int readSocket (const int handle,
  6741. void* const destBuffer, const int maxBytesToRead,
  6742. bool volatile& connected,
  6743. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6744. {
  6745. int bytesRead = 0;
  6746. while (bytesRead < maxBytesToRead)
  6747. {
  6748. int bytesThisTime;
  6749. #if JUCE_WINDOWS
  6750. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6751. #else
  6752. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6753. && errno == EINTR
  6754. && connected)
  6755. {
  6756. }
  6757. #endif
  6758. if (bytesThisTime <= 0 || ! connected)
  6759. {
  6760. if (bytesRead == 0)
  6761. bytesRead = -1;
  6762. break;
  6763. }
  6764. bytesRead += bytesThisTime;
  6765. if (! blockUntilSpecifiedAmountHasArrived)
  6766. break;
  6767. }
  6768. return bytesRead;
  6769. }
  6770. static int waitForReadiness (const int handle, const bool forReading,
  6771. const int timeoutMsecs) throw()
  6772. {
  6773. struct timeval timeout;
  6774. struct timeval* timeoutp;
  6775. if (timeoutMsecs >= 0)
  6776. {
  6777. timeout.tv_sec = timeoutMsecs / 1000;
  6778. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6779. timeoutp = &timeout;
  6780. }
  6781. else
  6782. {
  6783. timeoutp = 0;
  6784. }
  6785. fd_set rset, wset;
  6786. FD_ZERO (&rset);
  6787. FD_SET (handle, &rset);
  6788. FD_ZERO (&wset);
  6789. FD_SET (handle, &wset);
  6790. fd_set* const prset = forReading ? &rset : 0;
  6791. fd_set* const pwset = forReading ? 0 : &wset;
  6792. #if JUCE_WINDOWS
  6793. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6794. return -1;
  6795. #else
  6796. {
  6797. int result;
  6798. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6799. && errno == EINTR)
  6800. {
  6801. }
  6802. if (result < 0)
  6803. return -1;
  6804. }
  6805. #endif
  6806. {
  6807. int opt;
  6808. juce_socklen_t len = sizeof (opt);
  6809. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6810. || opt != 0)
  6811. return -1;
  6812. }
  6813. if ((forReading && FD_ISSET (handle, &rset))
  6814. || ((! forReading) && FD_ISSET (handle, &wset)))
  6815. return 1;
  6816. return 0;
  6817. }
  6818. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6819. {
  6820. #if JUCE_WINDOWS
  6821. u_long nonBlocking = shouldBlock ? 0 : 1;
  6822. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6823. return false;
  6824. #else
  6825. int socketFlags = fcntl (handle, F_GETFL, 0);
  6826. if (socketFlags == -1)
  6827. return false;
  6828. if (shouldBlock)
  6829. socketFlags &= ~O_NONBLOCK;
  6830. else
  6831. socketFlags |= O_NONBLOCK;
  6832. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6833. return false;
  6834. #endif
  6835. return true;
  6836. }
  6837. static bool connectSocket (int volatile& handle,
  6838. const bool isDatagram,
  6839. void** serverAddress,
  6840. const String& hostName,
  6841. const int portNumber,
  6842. const int timeOutMillisecs) throw()
  6843. {
  6844. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6845. if (hostEnt == 0)
  6846. return false;
  6847. struct in_addr targetAddress;
  6848. memcpy (&targetAddress.s_addr,
  6849. *(hostEnt->h_addr_list),
  6850. sizeof (targetAddress.s_addr));
  6851. struct sockaddr_in servTmpAddr;
  6852. zerostruct (servTmpAddr);
  6853. servTmpAddr.sin_family = PF_INET;
  6854. servTmpAddr.sin_addr = targetAddress;
  6855. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6856. if (handle < 0)
  6857. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6858. if (handle < 0)
  6859. return false;
  6860. if (isDatagram)
  6861. {
  6862. *serverAddress = new struct sockaddr_in();
  6863. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6864. return true;
  6865. }
  6866. setSocketBlockingState (handle, false);
  6867. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6868. if (result < 0)
  6869. {
  6870. #if JUCE_WINDOWS
  6871. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6872. #else
  6873. if (errno == EINPROGRESS)
  6874. #endif
  6875. {
  6876. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6877. {
  6878. setSocketBlockingState (handle, true);
  6879. return false;
  6880. }
  6881. }
  6882. }
  6883. setSocketBlockingState (handle, true);
  6884. resetSocketOptions (handle, false, false);
  6885. return true;
  6886. }
  6887. }
  6888. StreamingSocket::StreamingSocket()
  6889. : portNumber (0),
  6890. handle (-1),
  6891. connected (false),
  6892. isListener (false)
  6893. {
  6894. #if JUCE_WINDOWS
  6895. initWin32Sockets();
  6896. #endif
  6897. }
  6898. StreamingSocket::StreamingSocket (const String& hostName_,
  6899. const int portNumber_,
  6900. const int handle_)
  6901. : hostName (hostName_),
  6902. portNumber (portNumber_),
  6903. handle (handle_),
  6904. connected (true),
  6905. isListener (false)
  6906. {
  6907. #if JUCE_WINDOWS
  6908. initWin32Sockets();
  6909. #endif
  6910. SocketHelpers::resetSocketOptions (handle_, false, false);
  6911. }
  6912. StreamingSocket::~StreamingSocket()
  6913. {
  6914. close();
  6915. }
  6916. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6917. {
  6918. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6919. : -1;
  6920. }
  6921. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6922. {
  6923. if (isListener || ! connected)
  6924. return -1;
  6925. #if JUCE_WINDOWS
  6926. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6927. #else
  6928. int result;
  6929. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6930. && errno == EINTR)
  6931. {
  6932. }
  6933. return result;
  6934. #endif
  6935. }
  6936. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6937. const int timeoutMsecs) const
  6938. {
  6939. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6940. : -1;
  6941. }
  6942. bool StreamingSocket::bindToPort (const int port)
  6943. {
  6944. return SocketHelpers::bindSocketToPort (handle, port);
  6945. }
  6946. bool StreamingSocket::connect (const String& remoteHostName,
  6947. const int remotePortNumber,
  6948. const int timeOutMillisecs)
  6949. {
  6950. if (isListener)
  6951. {
  6952. jassertfalse; // a listener socket can't connect to another one!
  6953. return false;
  6954. }
  6955. if (connected)
  6956. close();
  6957. hostName = remoteHostName;
  6958. portNumber = remotePortNumber;
  6959. isListener = false;
  6960. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  6961. remotePortNumber, timeOutMillisecs);
  6962. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  6963. {
  6964. close();
  6965. return false;
  6966. }
  6967. return true;
  6968. }
  6969. void StreamingSocket::close()
  6970. {
  6971. #if JUCE_WINDOWS
  6972. if (handle != SOCKET_ERROR || connected)
  6973. closesocket (handle);
  6974. connected = false;
  6975. #else
  6976. if (connected)
  6977. {
  6978. connected = false;
  6979. if (isListener)
  6980. {
  6981. // need to do this to interrupt the accept() function..
  6982. StreamingSocket temp;
  6983. temp.connect ("localhost", portNumber, 1000);
  6984. }
  6985. }
  6986. if (handle != -1)
  6987. ::close (handle);
  6988. #endif
  6989. hostName = String::empty;
  6990. portNumber = 0;
  6991. handle = -1;
  6992. isListener = false;
  6993. }
  6994. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6995. {
  6996. if (connected)
  6997. close();
  6998. hostName = "listener";
  6999. portNumber = newPortNumber;
  7000. isListener = true;
  7001. struct sockaddr_in servTmpAddr;
  7002. zerostruct (servTmpAddr);
  7003. servTmpAddr.sin_family = PF_INET;
  7004. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7005. if (localHostName.isNotEmpty())
  7006. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7007. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7008. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7009. if (handle < 0)
  7010. return false;
  7011. const int reuse = 1;
  7012. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7013. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7014. || listen (handle, SOMAXCONN) < 0)
  7015. {
  7016. close();
  7017. return false;
  7018. }
  7019. connected = true;
  7020. return true;
  7021. }
  7022. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7023. {
  7024. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7025. // prepare this socket as a listener.
  7026. if (connected && isListener)
  7027. {
  7028. struct sockaddr address;
  7029. juce_socklen_t len = sizeof (sockaddr);
  7030. const int newSocket = (int) accept (handle, &address, &len);
  7031. if (newSocket >= 0 && connected)
  7032. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7033. portNumber, newSocket);
  7034. }
  7035. return 0;
  7036. }
  7037. bool StreamingSocket::isLocal() const throw()
  7038. {
  7039. return hostName == "127.0.0.1";
  7040. }
  7041. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7042. : portNumber (0),
  7043. handle (-1),
  7044. connected (true),
  7045. allowBroadcast (allowBroadcast_),
  7046. serverAddress (0)
  7047. {
  7048. #if JUCE_WINDOWS
  7049. initWin32Sockets();
  7050. #endif
  7051. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7052. bindToPort (localPortNumber);
  7053. }
  7054. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7055. const int handle_, const int localPortNumber)
  7056. : hostName (hostName_),
  7057. portNumber (portNumber_),
  7058. handle (handle_),
  7059. connected (true),
  7060. allowBroadcast (false),
  7061. serverAddress (0)
  7062. {
  7063. #if JUCE_WINDOWS
  7064. initWin32Sockets();
  7065. #endif
  7066. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7067. bindToPort (localPortNumber);
  7068. }
  7069. DatagramSocket::~DatagramSocket()
  7070. {
  7071. close();
  7072. delete static_cast <struct sockaddr_in*> (serverAddress);
  7073. serverAddress = 0;
  7074. }
  7075. void DatagramSocket::close()
  7076. {
  7077. #if JUCE_WINDOWS
  7078. closesocket (handle);
  7079. connected = false;
  7080. #else
  7081. connected = false;
  7082. ::close (handle);
  7083. #endif
  7084. hostName = String::empty;
  7085. portNumber = 0;
  7086. handle = -1;
  7087. }
  7088. bool DatagramSocket::bindToPort (const int port)
  7089. {
  7090. return SocketHelpers::bindSocketToPort (handle, port);
  7091. }
  7092. bool DatagramSocket::connect (const String& remoteHostName,
  7093. const int remotePortNumber,
  7094. const int timeOutMillisecs)
  7095. {
  7096. if (connected)
  7097. close();
  7098. hostName = remoteHostName;
  7099. portNumber = remotePortNumber;
  7100. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7101. remoteHostName, remotePortNumber,
  7102. timeOutMillisecs);
  7103. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7104. {
  7105. close();
  7106. return false;
  7107. }
  7108. return true;
  7109. }
  7110. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7111. {
  7112. struct sockaddr address;
  7113. juce_socklen_t len = sizeof (sockaddr);
  7114. while (waitUntilReady (true, -1) == 1)
  7115. {
  7116. char buf[1];
  7117. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7118. {
  7119. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7120. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7121. -1, -1);
  7122. }
  7123. }
  7124. return 0;
  7125. }
  7126. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7127. const int timeoutMsecs) const
  7128. {
  7129. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7130. : -1;
  7131. }
  7132. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7133. {
  7134. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7135. : -1;
  7136. }
  7137. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7138. {
  7139. // You need to call connect() first to set the server address..
  7140. jassert (serverAddress != 0 && connected);
  7141. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7142. numBytesToWrite, 0,
  7143. (const struct sockaddr*) serverAddress,
  7144. sizeof (struct sockaddr_in))
  7145. : -1;
  7146. }
  7147. bool DatagramSocket::isLocal() const throw()
  7148. {
  7149. return hostName == "127.0.0.1";
  7150. }
  7151. #if JUCE_MSVC
  7152. #pragma warning (pop)
  7153. #endif
  7154. END_JUCE_NAMESPACE
  7155. /*** End of inlined file: juce_Socket.cpp ***/
  7156. /*** Start of inlined file: juce_URL.cpp ***/
  7157. BEGIN_JUCE_NAMESPACE
  7158. URL::URL()
  7159. {
  7160. }
  7161. URL::URL (const String& url_)
  7162. : url (url_)
  7163. {
  7164. int i = url.indexOfChar ('?');
  7165. if (i >= 0)
  7166. {
  7167. do
  7168. {
  7169. const int nextAmp = url.indexOfChar (i + 1, '&');
  7170. const int equalsPos = url.indexOfChar (i + 1, '=');
  7171. if (equalsPos > i + 1)
  7172. {
  7173. if (nextAmp < 0)
  7174. {
  7175. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7176. removeEscapeChars (url.substring (equalsPos + 1)));
  7177. }
  7178. else if (nextAmp > 0 && equalsPos < nextAmp)
  7179. {
  7180. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7181. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7182. }
  7183. }
  7184. i = nextAmp;
  7185. }
  7186. while (i >= 0);
  7187. url = url.upToFirstOccurrenceOf ("?", false, false);
  7188. }
  7189. }
  7190. URL::URL (const URL& other)
  7191. : url (other.url),
  7192. postData (other.postData),
  7193. parameters (other.parameters),
  7194. filesToUpload (other.filesToUpload),
  7195. mimeTypes (other.mimeTypes)
  7196. {
  7197. }
  7198. URL& URL::operator= (const URL& other)
  7199. {
  7200. url = other.url;
  7201. postData = other.postData;
  7202. parameters = other.parameters;
  7203. filesToUpload = other.filesToUpload;
  7204. mimeTypes = other.mimeTypes;
  7205. return *this;
  7206. }
  7207. URL::~URL()
  7208. {
  7209. }
  7210. static const String getMangledParameters (const StringPairArray& parameters)
  7211. {
  7212. String p;
  7213. for (int i = 0; i < parameters.size(); ++i)
  7214. {
  7215. if (i > 0)
  7216. p << '&';
  7217. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7218. << '='
  7219. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7220. }
  7221. return p;
  7222. }
  7223. const String URL::toString (const bool includeGetParameters) const
  7224. {
  7225. if (includeGetParameters && parameters.size() > 0)
  7226. return url + "?" + getMangledParameters (parameters);
  7227. else
  7228. return url;
  7229. }
  7230. bool URL::isWellFormed() const
  7231. {
  7232. //xxx TODO
  7233. return url.isNotEmpty();
  7234. }
  7235. static int findStartOfDomain (const String& url)
  7236. {
  7237. int i = 0;
  7238. while (CharacterFunctions::isLetterOrDigit (url[i])
  7239. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7240. ++i;
  7241. return url[i] == ':' ? i + 1 : 0;
  7242. }
  7243. const String URL::getDomain() const
  7244. {
  7245. int start = findStartOfDomain (url);
  7246. while (url[start] == '/')
  7247. ++start;
  7248. const int end1 = url.indexOfChar (start, '/');
  7249. const int end2 = url.indexOfChar (start, ':');
  7250. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7251. : jmin (end1, end2);
  7252. return url.substring (start, end);
  7253. }
  7254. const String URL::getSubPath() const
  7255. {
  7256. int start = findStartOfDomain (url);
  7257. while (url[start] == '/')
  7258. ++start;
  7259. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7260. return startOfPath <= 0 ? String::empty
  7261. : url.substring (startOfPath);
  7262. }
  7263. const String URL::getScheme() const
  7264. {
  7265. return url.substring (0, findStartOfDomain (url) - 1);
  7266. }
  7267. const URL URL::withNewSubPath (const String& newPath) const
  7268. {
  7269. int start = findStartOfDomain (url);
  7270. while (url[start] == '/')
  7271. ++start;
  7272. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7273. URL u (*this);
  7274. if (startOfPath > 0)
  7275. u.url = url.substring (0, startOfPath);
  7276. if (! u.url.endsWithChar ('/'))
  7277. u.url << '/';
  7278. if (newPath.startsWithChar ('/'))
  7279. u.url << newPath.substring (1);
  7280. else
  7281. u.url << newPath;
  7282. return u;
  7283. }
  7284. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7285. {
  7286. if (possibleURL.startsWithIgnoreCase ("http:")
  7287. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7288. return true;
  7289. if (possibleURL.startsWithIgnoreCase ("file:")
  7290. || possibleURL.containsChar ('@')
  7291. || possibleURL.endsWithChar ('.')
  7292. || (! possibleURL.containsChar ('.')))
  7293. return false;
  7294. if (possibleURL.startsWithIgnoreCase ("www.")
  7295. && possibleURL.substring (5).containsChar ('.'))
  7296. return true;
  7297. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7298. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7299. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7300. return true;
  7301. return false;
  7302. }
  7303. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7304. {
  7305. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7306. return atSign > 0
  7307. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7308. && (! possibleEmailAddress.endsWithChar ('.'));
  7309. }
  7310. void* juce_openInternetFile (const String& url,
  7311. const String& headers,
  7312. const MemoryBlock& optionalPostData,
  7313. const bool isPost,
  7314. URL::OpenStreamProgressCallback* callback,
  7315. void* callbackContext,
  7316. int timeOutMs);
  7317. void juce_closeInternetFile (void* handle);
  7318. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7319. int juce_seekInInternetFile (void* handle, int newPosition);
  7320. int64 juce_getInternetFileContentLength (void* handle);
  7321. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7322. class WebInputStream : public InputStream
  7323. {
  7324. public:
  7325. WebInputStream (const URL& url,
  7326. const bool isPost_,
  7327. URL::OpenStreamProgressCallback* const progressCallback_,
  7328. void* const progressCallbackContext_,
  7329. const String& extraHeaders,
  7330. const int timeOutMs_,
  7331. StringPairArray* const responseHeaders)
  7332. : position (0),
  7333. finished (false),
  7334. isPost (isPost_),
  7335. progressCallback (progressCallback_),
  7336. progressCallbackContext (progressCallbackContext_),
  7337. timeOutMs (timeOutMs_)
  7338. {
  7339. server = url.toString (! isPost);
  7340. if (isPost_)
  7341. createHeadersAndPostData (url);
  7342. headers += extraHeaders;
  7343. if (! headers.endsWithChar ('\n'))
  7344. headers << "\r\n";
  7345. handle = juce_openInternetFile (server, headers, postData, isPost,
  7346. progressCallback_, progressCallbackContext_,
  7347. timeOutMs);
  7348. if (responseHeaders != 0)
  7349. juce_getInternetFileHeaders (handle, *responseHeaders);
  7350. }
  7351. ~WebInputStream()
  7352. {
  7353. juce_closeInternetFile (handle);
  7354. }
  7355. bool isError() const { return handle == 0; }
  7356. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7357. bool isExhausted() { return finished; }
  7358. int64 getPosition() { return position; }
  7359. int read (void* dest, int bytes)
  7360. {
  7361. if (finished || isError())
  7362. {
  7363. return 0;
  7364. }
  7365. else
  7366. {
  7367. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7368. position += bytesRead;
  7369. if (bytesRead == 0)
  7370. finished = true;
  7371. return bytesRead;
  7372. }
  7373. }
  7374. bool setPosition (int64 wantedPos)
  7375. {
  7376. if (wantedPos != position)
  7377. {
  7378. finished = false;
  7379. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7380. if (actualPos == wantedPos)
  7381. {
  7382. position = wantedPos;
  7383. }
  7384. else
  7385. {
  7386. if (wantedPos < position)
  7387. {
  7388. juce_closeInternetFile (handle);
  7389. position = 0;
  7390. finished = false;
  7391. handle = juce_openInternetFile (server, headers, postData, isPost,
  7392. progressCallback, progressCallbackContext,
  7393. timeOutMs);
  7394. }
  7395. skipNextBytes (wantedPos - position);
  7396. }
  7397. }
  7398. return true;
  7399. }
  7400. juce_UseDebuggingNewOperator
  7401. private:
  7402. String server, headers;
  7403. MemoryBlock postData;
  7404. int64 position;
  7405. bool finished;
  7406. const bool isPost;
  7407. void* handle;
  7408. URL::OpenStreamProgressCallback* const progressCallback;
  7409. void* const progressCallbackContext;
  7410. const int timeOutMs;
  7411. void createHeadersAndPostData (const URL& url)
  7412. {
  7413. MemoryOutputStream data (postData, false);
  7414. if (url.getFilesToUpload().size() > 0)
  7415. {
  7416. // need to upload some files, so do it as multi-part...
  7417. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7418. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7419. data << "--" << boundary;
  7420. int i;
  7421. for (i = 0; i < url.getParameters().size(); ++i)
  7422. {
  7423. data << "\r\nContent-Disposition: form-data; name=\""
  7424. << url.getParameters().getAllKeys() [i]
  7425. << "\"\r\n\r\n"
  7426. << url.getParameters().getAllValues() [i]
  7427. << "\r\n--"
  7428. << boundary;
  7429. }
  7430. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7431. {
  7432. const File file (url.getFilesToUpload().getAllValues() [i]);
  7433. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7434. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7435. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7436. const String mimeType (url.getMimeTypesOfUploadFiles()
  7437. .getValue (paramName, String::empty));
  7438. if (mimeType.isNotEmpty())
  7439. data << "Content-Type: " << mimeType << "\r\n";
  7440. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7441. << file << "\r\n--" << boundary;
  7442. }
  7443. data << "--\r\n";
  7444. data.flush();
  7445. }
  7446. else
  7447. {
  7448. data << getMangledParameters (url.getParameters())
  7449. << url.getPostData();
  7450. data.flush();
  7451. // just a short text attachment, so use simple url encoding..
  7452. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7453. + String ((unsigned int) postData.getSize())
  7454. + "\r\n";
  7455. }
  7456. }
  7457. WebInputStream (const WebInputStream&);
  7458. WebInputStream& operator= (const WebInputStream&);
  7459. };
  7460. InputStream* URL::createInputStream (const bool usePostCommand,
  7461. OpenStreamProgressCallback* const progressCallback,
  7462. void* const progressCallbackContext,
  7463. const String& extraHeaders,
  7464. const int timeOutMs,
  7465. StringPairArray* const responseHeaders) const
  7466. {
  7467. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7468. progressCallback, progressCallbackContext,
  7469. extraHeaders, timeOutMs, responseHeaders));
  7470. return wi->isError() ? 0 : wi.release();
  7471. }
  7472. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7473. const bool usePostCommand) const
  7474. {
  7475. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7476. if (in != 0)
  7477. {
  7478. in->readIntoMemoryBlock (destData);
  7479. return true;
  7480. }
  7481. return false;
  7482. }
  7483. const String URL::readEntireTextStream (const bool usePostCommand) const
  7484. {
  7485. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7486. if (in != 0)
  7487. return in->readEntireStreamAsString();
  7488. return String::empty;
  7489. }
  7490. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7491. {
  7492. XmlDocument doc (readEntireTextStream (usePostCommand));
  7493. return doc.getDocumentElement();
  7494. }
  7495. const URL URL::withParameter (const String& parameterName,
  7496. const String& parameterValue) const
  7497. {
  7498. URL u (*this);
  7499. u.parameters.set (parameterName, parameterValue);
  7500. return u;
  7501. }
  7502. const URL URL::withFileToUpload (const String& parameterName,
  7503. const File& fileToUpload,
  7504. const String& mimeType) const
  7505. {
  7506. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7507. URL u (*this);
  7508. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7509. u.mimeTypes.set (parameterName, mimeType);
  7510. return u;
  7511. }
  7512. const URL URL::withPOSTData (const String& postData_) const
  7513. {
  7514. URL u (*this);
  7515. u.postData = postData_;
  7516. return u;
  7517. }
  7518. const StringPairArray& URL::getParameters() const
  7519. {
  7520. return parameters;
  7521. }
  7522. const StringPairArray& URL::getFilesToUpload() const
  7523. {
  7524. return filesToUpload;
  7525. }
  7526. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7527. {
  7528. return mimeTypes;
  7529. }
  7530. const String URL::removeEscapeChars (const String& s)
  7531. {
  7532. String result (s.replaceCharacter ('+', ' '));
  7533. int nextPercent = 0;
  7534. for (;;)
  7535. {
  7536. nextPercent = result.indexOfChar (nextPercent, '%');
  7537. if (nextPercent < 0)
  7538. break;
  7539. int hexDigit1 = 0, hexDigit2 = 0;
  7540. if ((hexDigit1 = CharacterFunctions::getHexDigitValue (result [nextPercent + 1])) >= 0
  7541. && (hexDigit2 = CharacterFunctions::getHexDigitValue (result [nextPercent + 2])) >= 0)
  7542. {
  7543. const juce_wchar replacementChar = (juce_wchar) ((hexDigit1 << 4) + hexDigit2);
  7544. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  7545. }
  7546. ++nextPercent;
  7547. }
  7548. return result;
  7549. }
  7550. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7551. {
  7552. String result;
  7553. result.preallocateStorage (s.length() + 8);
  7554. const char* utf8 = s.toUTF8();
  7555. const char* legalChars = isParameter ? "_-.*!'()"
  7556. : "_-$.*!'(),";
  7557. while (*utf8 != 0)
  7558. {
  7559. const char c = *utf8++;
  7560. if (CharacterFunctions::isLetterOrDigit (c)
  7561. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  7562. {
  7563. result << c;
  7564. }
  7565. else
  7566. {
  7567. const int v = (int) (uint8) c;
  7568. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  7569. }
  7570. }
  7571. return result;
  7572. }
  7573. bool URL::launchInDefaultBrowser() const
  7574. {
  7575. String u (toString (true));
  7576. if (u.containsChar ('@') && ! u.containsChar (':'))
  7577. u = "mailto:" + u;
  7578. return PlatformUtilities::openDocument (u, String::empty);
  7579. }
  7580. END_JUCE_NAMESPACE
  7581. /*** End of inlined file: juce_URL.cpp ***/
  7582. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7583. BEGIN_JUCE_NAMESPACE
  7584. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  7585. const int bufferSize_,
  7586. const bool deleteSourceWhenDestroyed)
  7587. : source (source_),
  7588. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  7589. bufferSize (jmax (256, bufferSize_)),
  7590. position (source_->getPosition()),
  7591. lastReadPos (0),
  7592. bufferOverlap (128)
  7593. {
  7594. const int sourceSize = (int) source_->getTotalLength();
  7595. if (sourceSize >= 0)
  7596. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  7597. bufferStart = position;
  7598. buffer.malloc (bufferSize);
  7599. }
  7600. BufferedInputStream::~BufferedInputStream()
  7601. {
  7602. }
  7603. int64 BufferedInputStream::getTotalLength()
  7604. {
  7605. return source->getTotalLength();
  7606. }
  7607. int64 BufferedInputStream::getPosition()
  7608. {
  7609. return position;
  7610. }
  7611. bool BufferedInputStream::setPosition (int64 newPosition)
  7612. {
  7613. position = jmax ((int64) 0, newPosition);
  7614. return true;
  7615. }
  7616. bool BufferedInputStream::isExhausted()
  7617. {
  7618. return (position >= lastReadPos)
  7619. && source->isExhausted();
  7620. }
  7621. void BufferedInputStream::ensureBuffered()
  7622. {
  7623. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7624. if (position < bufferStart || position >= bufferEndOverlap)
  7625. {
  7626. int bytesRead;
  7627. if (position < lastReadPos
  7628. && position >= bufferEndOverlap
  7629. && position >= bufferStart)
  7630. {
  7631. const int bytesToKeep = (int) (lastReadPos - position);
  7632. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7633. bufferStart = position;
  7634. bytesRead = source->read (buffer + bytesToKeep,
  7635. bufferSize - bytesToKeep);
  7636. lastReadPos += bytesRead;
  7637. bytesRead += bytesToKeep;
  7638. }
  7639. else
  7640. {
  7641. bufferStart = position;
  7642. source->setPosition (bufferStart);
  7643. bytesRead = source->read (buffer, bufferSize);
  7644. lastReadPos = bufferStart + bytesRead;
  7645. }
  7646. while (bytesRead < bufferSize)
  7647. buffer [bytesRead++] = 0;
  7648. }
  7649. }
  7650. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7651. {
  7652. if (position >= bufferStart
  7653. && position + maxBytesToRead <= lastReadPos)
  7654. {
  7655. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7656. position += maxBytesToRead;
  7657. return maxBytesToRead;
  7658. }
  7659. else
  7660. {
  7661. if (position < bufferStart || position >= lastReadPos)
  7662. ensureBuffered();
  7663. int bytesRead = 0;
  7664. while (maxBytesToRead > 0)
  7665. {
  7666. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7667. if (bytesAvailable > 0)
  7668. {
  7669. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7670. maxBytesToRead -= bytesAvailable;
  7671. bytesRead += bytesAvailable;
  7672. position += bytesAvailable;
  7673. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7674. }
  7675. const int64 oldLastReadPos = lastReadPos;
  7676. ensureBuffered();
  7677. if (oldLastReadPos == lastReadPos)
  7678. break; // if ensureBuffered() failed to read any more data, bail out
  7679. if (isExhausted())
  7680. break;
  7681. }
  7682. return bytesRead;
  7683. }
  7684. }
  7685. const String BufferedInputStream::readString()
  7686. {
  7687. if (position >= bufferStart
  7688. && position < lastReadPos)
  7689. {
  7690. const int maxChars = (int) (lastReadPos - position);
  7691. const char* const src = buffer + (int) (position - bufferStart);
  7692. for (int i = 0; i < maxChars; ++i)
  7693. {
  7694. if (src[i] == 0)
  7695. {
  7696. position += i + 1;
  7697. return String::fromUTF8 (src, i);
  7698. }
  7699. }
  7700. }
  7701. return InputStream::readString();
  7702. }
  7703. END_JUCE_NAMESPACE
  7704. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7705. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7706. BEGIN_JUCE_NAMESPACE
  7707. FileInputSource::FileInputSource (const File& file_)
  7708. : file (file_)
  7709. {
  7710. }
  7711. FileInputSource::~FileInputSource()
  7712. {
  7713. }
  7714. InputStream* FileInputSource::createInputStream()
  7715. {
  7716. return file.createInputStream();
  7717. }
  7718. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7719. {
  7720. return file.getSiblingFile (relatedItemPath).createInputStream();
  7721. }
  7722. int64 FileInputSource::hashCode() const
  7723. {
  7724. return file.hashCode();
  7725. }
  7726. END_JUCE_NAMESPACE
  7727. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7728. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7729. BEGIN_JUCE_NAMESPACE
  7730. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7731. const size_t sourceDataSize,
  7732. const bool keepInternalCopy)
  7733. : data (static_cast <const char*> (sourceData)),
  7734. dataSize (sourceDataSize),
  7735. position (0)
  7736. {
  7737. if (keepInternalCopy)
  7738. {
  7739. internalCopy.append (data, sourceDataSize);
  7740. data = static_cast <const char*> (internalCopy.getData());
  7741. }
  7742. }
  7743. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7744. const bool keepInternalCopy)
  7745. : data (static_cast <const char*> (sourceData.getData())),
  7746. dataSize (sourceData.getSize()),
  7747. position (0)
  7748. {
  7749. if (keepInternalCopy)
  7750. {
  7751. internalCopy = sourceData;
  7752. data = static_cast <const char*> (internalCopy.getData());
  7753. }
  7754. }
  7755. MemoryInputStream::~MemoryInputStream()
  7756. {
  7757. }
  7758. int64 MemoryInputStream::getTotalLength()
  7759. {
  7760. return dataSize;
  7761. }
  7762. int MemoryInputStream::read (void* const buffer, const int howMany)
  7763. {
  7764. jassert (howMany >= 0);
  7765. const int num = jmin (howMany, (int) (dataSize - position));
  7766. memcpy (buffer, data + position, num);
  7767. position += num;
  7768. return (int) num;
  7769. }
  7770. bool MemoryInputStream::isExhausted()
  7771. {
  7772. return (position >= dataSize);
  7773. }
  7774. bool MemoryInputStream::setPosition (const int64 pos)
  7775. {
  7776. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7777. return true;
  7778. }
  7779. int64 MemoryInputStream::getPosition()
  7780. {
  7781. return position;
  7782. }
  7783. #if JUCE_UNIT_TESTS
  7784. class MemoryStreamTests : public UnitTest
  7785. {
  7786. public:
  7787. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  7788. void runTest()
  7789. {
  7790. beginTest ("Basics");
  7791. int randomInt = Random::getSystemRandom().nextInt();
  7792. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  7793. double randomDouble = Random::getSystemRandom().nextDouble();
  7794. String randomString;
  7795. for (int i = 50; --i >= 0;)
  7796. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  7797. MemoryOutputStream mo;
  7798. mo.writeInt (randomInt);
  7799. mo.writeIntBigEndian (randomInt);
  7800. mo.writeCompressedInt (randomInt);
  7801. mo.writeString (randomString);
  7802. mo.writeInt64 (randomInt64);
  7803. mo.writeInt64BigEndian (randomInt64);
  7804. mo.writeDouble (randomDouble);
  7805. mo.writeDoubleBigEndian (randomDouble);
  7806. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  7807. expect (mi.readInt() == randomInt);
  7808. expect (mi.readIntBigEndian() == randomInt);
  7809. expect (mi.readCompressedInt() == randomInt);
  7810. expect (mi.readString() == randomString);
  7811. expect (mi.readInt64() == randomInt64);
  7812. expect (mi.readInt64BigEndian() == randomInt64);
  7813. expect (mi.readDouble() == randomDouble);
  7814. expect (mi.readDoubleBigEndian() == randomDouble);
  7815. }
  7816. };
  7817. static MemoryStreamTests memoryInputStreamUnitTests;
  7818. #endif
  7819. END_JUCE_NAMESPACE
  7820. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7821. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7822. BEGIN_JUCE_NAMESPACE
  7823. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  7824. : data (internalBlock),
  7825. position (0),
  7826. size (0)
  7827. {
  7828. internalBlock.setSize (initialSize, false);
  7829. }
  7830. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  7831. const bool appendToExistingBlockContent)
  7832. : data (memoryBlockToWriteTo),
  7833. position (0),
  7834. size (0)
  7835. {
  7836. if (appendToExistingBlockContent)
  7837. position = size = memoryBlockToWriteTo.getSize();
  7838. }
  7839. MemoryOutputStream::~MemoryOutputStream()
  7840. {
  7841. flush();
  7842. }
  7843. void MemoryOutputStream::flush()
  7844. {
  7845. if (&data != &internalBlock)
  7846. data.setSize (size, false);
  7847. }
  7848. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  7849. {
  7850. data.ensureSize (bytesToPreallocate + 1);
  7851. }
  7852. void MemoryOutputStream::reset() throw()
  7853. {
  7854. position = 0;
  7855. size = 0;
  7856. }
  7857. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7858. {
  7859. if (howMany > 0)
  7860. {
  7861. const size_t storageNeeded = position + howMany;
  7862. if (storageNeeded >= data.getSize())
  7863. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  7864. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  7865. position += howMany;
  7866. size = jmax (size, position);
  7867. }
  7868. return true;
  7869. }
  7870. const void* MemoryOutputStream::getData() const throw()
  7871. {
  7872. void* const d = data.getData();
  7873. if (data.getSize() > size)
  7874. static_cast <char*> (d) [size] = 0;
  7875. return d;
  7876. }
  7877. bool MemoryOutputStream::setPosition (int64 newPosition)
  7878. {
  7879. if (newPosition <= (int64) size)
  7880. {
  7881. // ok to seek backwards
  7882. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7883. return true;
  7884. }
  7885. else
  7886. {
  7887. // trying to make it bigger isn't a good thing to do..
  7888. return false;
  7889. }
  7890. }
  7891. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  7892. {
  7893. // before writing from an input, see if we can preallocate to make it more efficient..
  7894. int64 availableData = source.getTotalLength() - source.getPosition();
  7895. if (availableData > 0)
  7896. {
  7897. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  7898. availableData = maxNumBytesToWrite;
  7899. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  7900. }
  7901. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  7902. }
  7903. const String MemoryOutputStream::toUTF8() const
  7904. {
  7905. return String (static_cast <const char*> (getData()), getDataSize());
  7906. }
  7907. const String MemoryOutputStream::toString() const
  7908. {
  7909. return String::createStringFromData (getData(), getDataSize());
  7910. }
  7911. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  7912. {
  7913. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  7914. return stream;
  7915. }
  7916. END_JUCE_NAMESPACE
  7917. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7918. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7919. BEGIN_JUCE_NAMESPACE
  7920. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7921. const int64 startPositionInSourceStream_,
  7922. const int64 lengthOfSourceStream_,
  7923. const bool deleteSourceWhenDestroyed)
  7924. : source (sourceStream),
  7925. startPositionInSourceStream (startPositionInSourceStream_),
  7926. lengthOfSourceStream (lengthOfSourceStream_)
  7927. {
  7928. if (deleteSourceWhenDestroyed)
  7929. sourceToDelete = source;
  7930. setPosition (0);
  7931. }
  7932. SubregionStream::~SubregionStream()
  7933. {
  7934. }
  7935. int64 SubregionStream::getTotalLength()
  7936. {
  7937. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7938. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7939. : srcLen;
  7940. }
  7941. int64 SubregionStream::getPosition()
  7942. {
  7943. return source->getPosition() - startPositionInSourceStream;
  7944. }
  7945. bool SubregionStream::setPosition (int64 newPosition)
  7946. {
  7947. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7948. }
  7949. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7950. {
  7951. if (lengthOfSourceStream < 0)
  7952. {
  7953. return source->read (destBuffer, maxBytesToRead);
  7954. }
  7955. else
  7956. {
  7957. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7958. if (maxBytesToRead <= 0)
  7959. return 0;
  7960. return source->read (destBuffer, maxBytesToRead);
  7961. }
  7962. }
  7963. bool SubregionStream::isExhausted()
  7964. {
  7965. if (lengthOfSourceStream >= 0)
  7966. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7967. else
  7968. return source->isExhausted();
  7969. }
  7970. END_JUCE_NAMESPACE
  7971. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7972. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7973. BEGIN_JUCE_NAMESPACE
  7974. PerformanceCounter::PerformanceCounter (const String& name_,
  7975. int runsPerPrintout,
  7976. const File& loggingFile)
  7977. : name (name_),
  7978. numRuns (0),
  7979. runsPerPrint (runsPerPrintout),
  7980. totalTime (0),
  7981. outputFile (loggingFile)
  7982. {
  7983. if (outputFile != File::nonexistent)
  7984. {
  7985. String s ("**** Counter for \"");
  7986. s << name_ << "\" started at: "
  7987. << Time::getCurrentTime().toString (true, true)
  7988. << "\r\n";
  7989. outputFile.appendText (s, false, false);
  7990. }
  7991. }
  7992. PerformanceCounter::~PerformanceCounter()
  7993. {
  7994. printStatistics();
  7995. }
  7996. void PerformanceCounter::start()
  7997. {
  7998. started = Time::getHighResolutionTicks();
  7999. }
  8000. void PerformanceCounter::stop()
  8001. {
  8002. const int64 now = Time::getHighResolutionTicks();
  8003. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8004. if (++numRuns == runsPerPrint)
  8005. printStatistics();
  8006. }
  8007. void PerformanceCounter::printStatistics()
  8008. {
  8009. if (numRuns > 0)
  8010. {
  8011. String s ("Performance count for \"");
  8012. s << name << "\" - average over " << numRuns << " run(s) = ";
  8013. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8014. if (micros > 10000)
  8015. s << (micros/1000) << " millisecs";
  8016. else
  8017. s << micros << " microsecs";
  8018. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8019. Logger::outputDebugString (s);
  8020. s << "\r\n";
  8021. if (outputFile != File::nonexistent)
  8022. outputFile.appendText (s, false, false);
  8023. numRuns = 0;
  8024. totalTime = 0;
  8025. }
  8026. }
  8027. END_JUCE_NAMESPACE
  8028. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8029. /*** Start of inlined file: juce_Uuid.cpp ***/
  8030. BEGIN_JUCE_NAMESPACE
  8031. Uuid::Uuid()
  8032. {
  8033. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8034. // to make it very very unlikely that two UUIDs will ever be the same..
  8035. static int64 macAddresses[2];
  8036. static bool hasCheckedMacAddresses = false;
  8037. if (! hasCheckedMacAddresses)
  8038. {
  8039. hasCheckedMacAddresses = true;
  8040. SystemStats::getMACAddresses (macAddresses, 2);
  8041. }
  8042. value.asInt64[0] = macAddresses[0];
  8043. value.asInt64[1] = macAddresses[1];
  8044. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8045. // whose seed will carry over between calls to this method.
  8046. Random r (macAddresses[0] ^ macAddresses[1]
  8047. ^ Random::getSystemRandom().nextInt64());
  8048. for (int i = 4; --i >= 0;)
  8049. {
  8050. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8051. value.asInt[i] ^= r.nextInt();
  8052. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8053. }
  8054. }
  8055. Uuid::~Uuid() throw()
  8056. {
  8057. }
  8058. Uuid::Uuid (const Uuid& other)
  8059. : value (other.value)
  8060. {
  8061. }
  8062. Uuid& Uuid::operator= (const Uuid& other)
  8063. {
  8064. value = other.value;
  8065. return *this;
  8066. }
  8067. bool Uuid::operator== (const Uuid& other) const
  8068. {
  8069. return value.asInt64[0] == other.value.asInt64[0]
  8070. && value.asInt64[1] == other.value.asInt64[1];
  8071. }
  8072. bool Uuid::operator!= (const Uuid& other) const
  8073. {
  8074. return ! operator== (other);
  8075. }
  8076. bool Uuid::isNull() const throw()
  8077. {
  8078. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8079. }
  8080. const String Uuid::toString() const
  8081. {
  8082. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8083. }
  8084. Uuid::Uuid (const String& uuidString)
  8085. {
  8086. operator= (uuidString);
  8087. }
  8088. Uuid& Uuid::operator= (const String& uuidString)
  8089. {
  8090. MemoryBlock mb;
  8091. mb.loadFromHexString (uuidString);
  8092. mb.ensureSize (sizeof (value.asBytes), true);
  8093. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8094. return *this;
  8095. }
  8096. Uuid::Uuid (const uint8* const rawData)
  8097. {
  8098. operator= (rawData);
  8099. }
  8100. Uuid& Uuid::operator= (const uint8* const rawData)
  8101. {
  8102. if (rawData != 0)
  8103. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8104. else
  8105. zeromem (value.asBytes, sizeof (value.asBytes));
  8106. return *this;
  8107. }
  8108. END_JUCE_NAMESPACE
  8109. /*** End of inlined file: juce_Uuid.cpp ***/
  8110. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8111. BEGIN_JUCE_NAMESPACE
  8112. class ZipFile::ZipEntryInfo
  8113. {
  8114. public:
  8115. ZipFile::ZipEntry entry;
  8116. int streamOffset;
  8117. int compressedSize;
  8118. bool compressed;
  8119. };
  8120. class ZipFile::ZipInputStream : public InputStream
  8121. {
  8122. public:
  8123. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8124. : file (file_),
  8125. zipEntryInfo (zei),
  8126. pos (0),
  8127. headerSize (0),
  8128. inputStream (0)
  8129. {
  8130. inputStream = file_.inputStream;
  8131. if (file_.inputSource != 0)
  8132. {
  8133. inputStream = file.inputSource->createInputStream();
  8134. }
  8135. else
  8136. {
  8137. #if JUCE_DEBUG
  8138. file_.numOpenStreams++;
  8139. #endif
  8140. }
  8141. char buffer [30];
  8142. if (inputStream != 0
  8143. && inputStream->setPosition (zei.streamOffset)
  8144. && inputStream->read (buffer, 30) == 30
  8145. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8146. {
  8147. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8148. + ByteOrder::littleEndianShort (buffer + 28);
  8149. }
  8150. }
  8151. ~ZipInputStream()
  8152. {
  8153. #if JUCE_DEBUG
  8154. if (inputStream != 0 && inputStream == file.inputStream)
  8155. file.numOpenStreams--;
  8156. #endif
  8157. if (inputStream != file.inputStream)
  8158. delete inputStream;
  8159. }
  8160. int64 getTotalLength()
  8161. {
  8162. return zipEntryInfo.compressedSize;
  8163. }
  8164. int read (void* buffer, int howMany)
  8165. {
  8166. if (headerSize <= 0)
  8167. return 0;
  8168. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8169. if (inputStream == 0)
  8170. return 0;
  8171. int num;
  8172. if (inputStream == file.inputStream)
  8173. {
  8174. const ScopedLock sl (file.lock);
  8175. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8176. num = inputStream->read (buffer, howMany);
  8177. }
  8178. else
  8179. {
  8180. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8181. num = inputStream->read (buffer, howMany);
  8182. }
  8183. pos += num;
  8184. return num;
  8185. }
  8186. bool isExhausted()
  8187. {
  8188. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8189. }
  8190. int64 getPosition()
  8191. {
  8192. return pos;
  8193. }
  8194. bool setPosition (int64 newPos)
  8195. {
  8196. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8197. return true;
  8198. }
  8199. private:
  8200. ZipFile& file;
  8201. ZipEntryInfo zipEntryInfo;
  8202. int64 pos;
  8203. int headerSize;
  8204. InputStream* inputStream;
  8205. ZipInputStream (const ZipInputStream&);
  8206. ZipInputStream& operator= (const ZipInputStream&);
  8207. };
  8208. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8209. : inputStream (source_)
  8210. #if JUCE_DEBUG
  8211. , numOpenStreams (0)
  8212. #endif
  8213. {
  8214. if (deleteStreamWhenDestroyed)
  8215. streamToDelete = inputStream;
  8216. init();
  8217. }
  8218. ZipFile::ZipFile (const File& file)
  8219. : inputStream (0)
  8220. #if JUCE_DEBUG
  8221. , numOpenStreams (0)
  8222. #endif
  8223. {
  8224. inputSource = new FileInputSource (file);
  8225. init();
  8226. }
  8227. ZipFile::ZipFile (InputSource* const inputSource_)
  8228. : inputStream (0),
  8229. inputSource (inputSource_)
  8230. #if JUCE_DEBUG
  8231. , numOpenStreams (0)
  8232. #endif
  8233. {
  8234. init();
  8235. }
  8236. ZipFile::~ZipFile()
  8237. {
  8238. #if JUCE_DEBUG
  8239. entries.clear();
  8240. // If you hit this assertion, it means you've created a stream to read
  8241. // one of the items in the zipfile, but you've forgotten to delete that
  8242. // stream object before deleting the file.. Streams can't be kept open
  8243. // after the file is deleted because they need to share the input
  8244. // stream that the file uses to read itself.
  8245. jassert (numOpenStreams == 0);
  8246. #endif
  8247. }
  8248. int ZipFile::getNumEntries() const throw()
  8249. {
  8250. return entries.size();
  8251. }
  8252. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8253. {
  8254. ZipEntryInfo* const zei = entries [index];
  8255. return zei != 0 ? &(zei->entry) : 0;
  8256. }
  8257. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8258. {
  8259. for (int i = 0; i < entries.size(); ++i)
  8260. if (entries.getUnchecked (i)->entry.filename == fileName)
  8261. return i;
  8262. return -1;
  8263. }
  8264. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8265. {
  8266. return getEntry (getIndexOfFileName (fileName));
  8267. }
  8268. InputStream* ZipFile::createStreamForEntry (const int index)
  8269. {
  8270. ZipEntryInfo* const zei = entries[index];
  8271. InputStream* stream = 0;
  8272. if (zei != 0)
  8273. {
  8274. stream = new ZipInputStream (*this, *zei);
  8275. if (zei->compressed)
  8276. {
  8277. stream = new GZIPDecompressorInputStream (stream, true, true,
  8278. zei->entry.uncompressedSize);
  8279. // (much faster to unzip in big blocks using a buffer..)
  8280. stream = new BufferedInputStream (stream, 32768, true);
  8281. }
  8282. }
  8283. return stream;
  8284. }
  8285. class ZipFile::ZipFilenameComparator
  8286. {
  8287. public:
  8288. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8289. {
  8290. return first->entry.filename.compare (second->entry.filename);
  8291. }
  8292. };
  8293. void ZipFile::sortEntriesByFilename()
  8294. {
  8295. ZipFilenameComparator sorter;
  8296. entries.sort (sorter);
  8297. }
  8298. void ZipFile::init()
  8299. {
  8300. ScopedPointer <InputStream> toDelete;
  8301. InputStream* in = inputStream;
  8302. if (inputSource != 0)
  8303. {
  8304. in = inputSource->createInputStream();
  8305. toDelete = in;
  8306. }
  8307. if (in != 0)
  8308. {
  8309. int numEntries = 0;
  8310. int pos = findEndOfZipEntryTable (in, numEntries);
  8311. if (pos >= 0 && pos < in->getTotalLength())
  8312. {
  8313. const int size = (int) (in->getTotalLength() - pos);
  8314. in->setPosition (pos);
  8315. MemoryBlock headerData;
  8316. if (in->readIntoMemoryBlock (headerData, size) == size)
  8317. {
  8318. pos = 0;
  8319. for (int i = 0; i < numEntries; ++i)
  8320. {
  8321. if (pos + 46 > size)
  8322. break;
  8323. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8324. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8325. if (pos + 46 + fileNameLen > size)
  8326. break;
  8327. ZipEntryInfo* const zei = new ZipEntryInfo();
  8328. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8329. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8330. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8331. const int year = 1980 + (date >> 9);
  8332. const int month = ((date >> 5) & 15) - 1;
  8333. const int day = date & 31;
  8334. const int hours = time >> 11;
  8335. const int minutes = (time >> 5) & 63;
  8336. const int seconds = (time & 31) << 1;
  8337. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8338. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8339. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8340. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8341. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8342. entries.add (zei);
  8343. pos += 46 + fileNameLen
  8344. + ByteOrder::littleEndianShort (buffer + 30)
  8345. + ByteOrder::littleEndianShort (buffer + 32);
  8346. }
  8347. }
  8348. }
  8349. }
  8350. }
  8351. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  8352. {
  8353. BufferedInputStream in (input, 8192, false);
  8354. in.setPosition (in.getTotalLength());
  8355. int64 pos = in.getPosition();
  8356. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8357. char buffer [32];
  8358. zeromem (buffer, sizeof (buffer));
  8359. while (pos > lowestPos)
  8360. {
  8361. in.setPosition (pos - 22);
  8362. pos = in.getPosition();
  8363. memcpy (buffer + 22, buffer, 4);
  8364. if (in.read (buffer, 22) != 22)
  8365. return 0;
  8366. for (int i = 0; i < 22; ++i)
  8367. {
  8368. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8369. {
  8370. in.setPosition (pos + i);
  8371. in.read (buffer, 22);
  8372. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8373. return ByteOrder::littleEndianInt (buffer + 16);
  8374. }
  8375. }
  8376. }
  8377. return 0;
  8378. }
  8379. bool ZipFile::uncompressTo (const File& targetDirectory,
  8380. const bool shouldOverwriteFiles)
  8381. {
  8382. for (int i = 0; i < entries.size(); ++i)
  8383. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8384. return false;
  8385. return true;
  8386. }
  8387. bool ZipFile::uncompressEntry (const int index,
  8388. const File& targetDirectory,
  8389. bool shouldOverwriteFiles)
  8390. {
  8391. const ZipEntryInfo* zei = entries [index];
  8392. if (zei != 0)
  8393. {
  8394. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8395. if (zei->entry.filename.endsWithChar ('/'))
  8396. {
  8397. targetFile.createDirectory(); // (entry is a directory, not a file)
  8398. }
  8399. else
  8400. {
  8401. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8402. if (in != 0)
  8403. {
  8404. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8405. return false;
  8406. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8407. {
  8408. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8409. if (out != 0)
  8410. {
  8411. out->writeFromInputStream (*in, -1);
  8412. out = 0;
  8413. targetFile.setCreationTime (zei->entry.fileTime);
  8414. targetFile.setLastModificationTime (zei->entry.fileTime);
  8415. targetFile.setLastAccessTime (zei->entry.fileTime);
  8416. return true;
  8417. }
  8418. }
  8419. }
  8420. }
  8421. }
  8422. return false;
  8423. }
  8424. END_JUCE_NAMESPACE
  8425. /*** End of inlined file: juce_ZipFile.cpp ***/
  8426. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8427. #if JUCE_MSVC
  8428. #pragma warning (push)
  8429. #pragma warning (disable: 4514 4996)
  8430. #endif
  8431. #include <cwctype>
  8432. #include <cctype>
  8433. #include <ctime>
  8434. BEGIN_JUCE_NAMESPACE
  8435. int CharacterFunctions::length (const char* const s) throw()
  8436. {
  8437. return (int) strlen (s);
  8438. }
  8439. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8440. {
  8441. return (int) wcslen (s);
  8442. }
  8443. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8444. {
  8445. strncpy (dest, src, maxChars);
  8446. }
  8447. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8448. {
  8449. wcsncpy (dest, src, maxChars);
  8450. }
  8451. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8452. {
  8453. mbstowcs (dest, src, maxChars);
  8454. }
  8455. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8456. {
  8457. wcstombs (dest, src, maxChars);
  8458. }
  8459. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8460. {
  8461. return (int) wcstombs (0, src, 0);
  8462. }
  8463. void CharacterFunctions::append (char* dest, const char* src) throw()
  8464. {
  8465. strcat (dest, src);
  8466. }
  8467. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8468. {
  8469. wcscat (dest, src);
  8470. }
  8471. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8472. {
  8473. return strcmp (s1, s2);
  8474. }
  8475. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8476. {
  8477. jassert (s1 != 0 && s2 != 0);
  8478. return wcscmp (s1, s2);
  8479. }
  8480. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8481. {
  8482. jassert (s1 != 0 && s2 != 0);
  8483. return strncmp (s1, s2, maxChars);
  8484. }
  8485. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8486. {
  8487. jassert (s1 != 0 && s2 != 0);
  8488. return wcsncmp (s1, s2, maxChars);
  8489. }
  8490. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8491. {
  8492. jassert (s1 != 0 && s2 != 0);
  8493. for (;;)
  8494. {
  8495. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8496. if (diff != 0)
  8497. return diff;
  8498. else if (*s1 == 0)
  8499. break;
  8500. ++s1;
  8501. ++s2;
  8502. }
  8503. return 0;
  8504. }
  8505. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8506. {
  8507. return -compare (s2, s1);
  8508. }
  8509. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8510. {
  8511. jassert (s1 != 0 && s2 != 0);
  8512. #if JUCE_WINDOWS
  8513. return stricmp (s1, s2);
  8514. #else
  8515. return strcasecmp (s1, s2);
  8516. #endif
  8517. }
  8518. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8519. {
  8520. jassert (s1 != 0 && s2 != 0);
  8521. #if JUCE_WINDOWS
  8522. return _wcsicmp (s1, s2);
  8523. #else
  8524. for (;;)
  8525. {
  8526. if (*s1 != *s2)
  8527. {
  8528. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8529. if (diff != 0)
  8530. return diff < 0 ? -1 : 1;
  8531. }
  8532. else if (*s1 == 0)
  8533. break;
  8534. ++s1;
  8535. ++s2;
  8536. }
  8537. return 0;
  8538. #endif
  8539. }
  8540. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8541. {
  8542. jassert (s1 != 0 && s2 != 0);
  8543. for (;;)
  8544. {
  8545. if (*s1 != *s2)
  8546. {
  8547. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8548. if (diff != 0)
  8549. return diff < 0 ? -1 : 1;
  8550. }
  8551. else if (*s1 == 0)
  8552. break;
  8553. ++s1;
  8554. ++s2;
  8555. }
  8556. return 0;
  8557. }
  8558. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8559. {
  8560. jassert (s1 != 0 && s2 != 0);
  8561. #if JUCE_WINDOWS
  8562. return strnicmp (s1, s2, maxChars);
  8563. #else
  8564. return strncasecmp (s1, s2, maxChars);
  8565. #endif
  8566. }
  8567. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8568. {
  8569. jassert (s1 != 0 && s2 != 0);
  8570. #if JUCE_WINDOWS
  8571. return _wcsnicmp (s1, s2, maxChars);
  8572. #else
  8573. while (--maxChars >= 0)
  8574. {
  8575. if (*s1 != *s2)
  8576. {
  8577. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8578. if (diff != 0)
  8579. return diff < 0 ? -1 : 1;
  8580. }
  8581. else if (*s1 == 0)
  8582. break;
  8583. ++s1;
  8584. ++s2;
  8585. }
  8586. return 0;
  8587. #endif
  8588. }
  8589. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8590. {
  8591. return strstr (haystack, needle);
  8592. }
  8593. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8594. {
  8595. return wcsstr (haystack, needle);
  8596. }
  8597. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8598. {
  8599. if (haystack != 0)
  8600. {
  8601. int i = 0;
  8602. if (ignoreCase)
  8603. {
  8604. const char n1 = toLowerCase (needle);
  8605. const char n2 = toUpperCase (needle);
  8606. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8607. {
  8608. while (haystack[i] != 0)
  8609. {
  8610. if (haystack[i] == n1 || haystack[i] == n2)
  8611. return i;
  8612. ++i;
  8613. }
  8614. return -1;
  8615. }
  8616. jassert (n1 == needle);
  8617. }
  8618. while (haystack[i] != 0)
  8619. {
  8620. if (haystack[i] == needle)
  8621. return i;
  8622. ++i;
  8623. }
  8624. }
  8625. return -1;
  8626. }
  8627. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8628. {
  8629. if (haystack != 0)
  8630. {
  8631. int i = 0;
  8632. if (ignoreCase)
  8633. {
  8634. const juce_wchar n1 = toLowerCase (needle);
  8635. const juce_wchar n2 = toUpperCase (needle);
  8636. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8637. {
  8638. while (haystack[i] != 0)
  8639. {
  8640. if (haystack[i] == n1 || haystack[i] == n2)
  8641. return i;
  8642. ++i;
  8643. }
  8644. return -1;
  8645. }
  8646. jassert (n1 == needle);
  8647. }
  8648. while (haystack[i] != 0)
  8649. {
  8650. if (haystack[i] == needle)
  8651. return i;
  8652. ++i;
  8653. }
  8654. }
  8655. return -1;
  8656. }
  8657. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8658. {
  8659. jassert (haystack != 0);
  8660. int i = 0;
  8661. while (haystack[i] != 0)
  8662. {
  8663. if (haystack[i] == needle)
  8664. return i;
  8665. ++i;
  8666. }
  8667. return -1;
  8668. }
  8669. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8670. {
  8671. jassert (haystack != 0);
  8672. int i = 0;
  8673. while (haystack[i] != 0)
  8674. {
  8675. if (haystack[i] == needle)
  8676. return i;
  8677. ++i;
  8678. }
  8679. return -1;
  8680. }
  8681. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8682. {
  8683. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8684. }
  8685. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8686. {
  8687. if (allowedChars == 0)
  8688. return 0;
  8689. int i = 0;
  8690. for (;;)
  8691. {
  8692. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8693. break;
  8694. ++i;
  8695. }
  8696. return i;
  8697. }
  8698. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8699. {
  8700. return (int) strftime (dest, maxChars, format, tm);
  8701. }
  8702. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8703. {
  8704. return (int) wcsftime (dest, maxChars, format, tm);
  8705. }
  8706. int CharacterFunctions::getIntValue (const char* const s) throw()
  8707. {
  8708. return atoi (s);
  8709. }
  8710. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8711. {
  8712. #if JUCE_WINDOWS
  8713. return _wtoi (s);
  8714. #else
  8715. int v = 0;
  8716. while (isWhitespace (*s))
  8717. ++s;
  8718. const bool isNeg = *s == '-';
  8719. if (isNeg)
  8720. ++s;
  8721. for (;;)
  8722. {
  8723. const wchar_t c = *s++;
  8724. if (c >= '0' && c <= '9')
  8725. v = v * 10 + (int) (c - '0');
  8726. else
  8727. break;
  8728. }
  8729. return isNeg ? -v : v;
  8730. #endif
  8731. }
  8732. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8733. {
  8734. #if JUCE_LINUX
  8735. return atoll (s);
  8736. #elif JUCE_WINDOWS
  8737. return _atoi64 (s);
  8738. #else
  8739. int64 v = 0;
  8740. while (isWhitespace (*s))
  8741. ++s;
  8742. const bool isNeg = *s == '-';
  8743. if (isNeg)
  8744. ++s;
  8745. for (;;)
  8746. {
  8747. const char c = *s++;
  8748. if (c >= '0' && c <= '9')
  8749. v = v * 10 + (int64) (c - '0');
  8750. else
  8751. break;
  8752. }
  8753. return isNeg ? -v : v;
  8754. #endif
  8755. }
  8756. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8757. {
  8758. #if JUCE_WINDOWS
  8759. return _wtoi64 (s);
  8760. #else
  8761. int64 v = 0;
  8762. while (isWhitespace (*s))
  8763. ++s;
  8764. const bool isNeg = *s == '-';
  8765. if (isNeg)
  8766. ++s;
  8767. for (;;)
  8768. {
  8769. const juce_wchar c = *s++;
  8770. if (c >= '0' && c <= '9')
  8771. v = v * 10 + (int64) (c - '0');
  8772. else
  8773. break;
  8774. }
  8775. return isNeg ? -v : v;
  8776. #endif
  8777. }
  8778. static double juce_mulexp10 (const double value, int exponent) throw()
  8779. {
  8780. if (exponent == 0)
  8781. return value;
  8782. if (value == 0)
  8783. return 0;
  8784. const bool negative = (exponent < 0);
  8785. if (negative)
  8786. exponent = -exponent;
  8787. double result = 1.0, power = 10.0;
  8788. for (int bit = 1; exponent != 0; bit <<= 1)
  8789. {
  8790. if ((exponent & bit) != 0)
  8791. {
  8792. exponent ^= bit;
  8793. result *= power;
  8794. if (exponent == 0)
  8795. break;
  8796. }
  8797. power *= power;
  8798. }
  8799. return negative ? (value / result) : (value * result);
  8800. }
  8801. template <class CharType>
  8802. double juce_atof (const CharType* const original) throw()
  8803. {
  8804. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8805. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8806. int exponent = 0, decPointIndex = 0, digit = 0;
  8807. int lastDigit = 0, numSignificantDigits = 0;
  8808. bool isNegative = false, digitsFound = false;
  8809. const int maxSignificantDigits = 15 + 2;
  8810. const CharType* s = original;
  8811. while (CharacterFunctions::isWhitespace (*s))
  8812. ++s;
  8813. switch (*s)
  8814. {
  8815. case '-': isNegative = true; // fall-through..
  8816. case '+': ++s;
  8817. }
  8818. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8819. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8820. for (;;)
  8821. {
  8822. if (CharacterFunctions::isDigit (*s))
  8823. {
  8824. lastDigit = digit;
  8825. digit = *s++ - '0';
  8826. digitsFound = true;
  8827. if (decPointIndex != 0)
  8828. exponentAdjustment[1]++;
  8829. if (numSignificantDigits == 0 && digit == 0)
  8830. continue;
  8831. if (++numSignificantDigits > maxSignificantDigits)
  8832. {
  8833. if (digit > 5)
  8834. ++accumulator [decPointIndex];
  8835. else if (digit == 5 && (lastDigit & 1) != 0)
  8836. ++accumulator [decPointIndex];
  8837. if (decPointIndex > 0)
  8838. exponentAdjustment[1]--;
  8839. else
  8840. exponentAdjustment[0]++;
  8841. while (CharacterFunctions::isDigit (*s))
  8842. {
  8843. ++s;
  8844. if (decPointIndex == 0)
  8845. exponentAdjustment[0]++;
  8846. }
  8847. }
  8848. else
  8849. {
  8850. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8851. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8852. {
  8853. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8854. + accumulator [decPointIndex];
  8855. accumulator [decPointIndex] = 0;
  8856. exponentAccumulator [decPointIndex] = 0;
  8857. }
  8858. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8859. exponentAccumulator [decPointIndex]++;
  8860. }
  8861. }
  8862. else if (decPointIndex == 0 && *s == '.')
  8863. {
  8864. ++s;
  8865. decPointIndex = 1;
  8866. if (numSignificantDigits > maxSignificantDigits)
  8867. {
  8868. while (CharacterFunctions::isDigit (*s))
  8869. ++s;
  8870. break;
  8871. }
  8872. }
  8873. else
  8874. {
  8875. break;
  8876. }
  8877. }
  8878. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8879. if (decPointIndex != 0)
  8880. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8881. if ((*s == 'e' || *s == 'E') && digitsFound)
  8882. {
  8883. bool negativeExponent = false;
  8884. switch (*++s)
  8885. {
  8886. case '-': negativeExponent = true; // fall-through..
  8887. case '+': ++s;
  8888. }
  8889. while (CharacterFunctions::isDigit (*s))
  8890. exponent = (exponent * 10) + (*s++ - '0');
  8891. if (negativeExponent)
  8892. exponent = -exponent;
  8893. }
  8894. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8895. if (decPointIndex != 0)
  8896. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8897. return isNegative ? -r : r;
  8898. }
  8899. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8900. {
  8901. return juce_atof <char> (s);
  8902. }
  8903. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8904. {
  8905. return juce_atof <juce_wchar> (s);
  8906. }
  8907. char CharacterFunctions::toUpperCase (const char character) throw()
  8908. {
  8909. return (char) toupper (character);
  8910. }
  8911. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8912. {
  8913. return towupper (character);
  8914. }
  8915. void CharacterFunctions::toUpperCase (char* s) throw()
  8916. {
  8917. #if JUCE_WINDOWS
  8918. strupr (s);
  8919. #else
  8920. while (*s != 0)
  8921. {
  8922. *s = toUpperCase (*s);
  8923. ++s;
  8924. }
  8925. #endif
  8926. }
  8927. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8928. {
  8929. #if JUCE_WINDOWS
  8930. _wcsupr (s);
  8931. #else
  8932. while (*s != 0)
  8933. {
  8934. *s = toUpperCase (*s);
  8935. ++s;
  8936. }
  8937. #endif
  8938. }
  8939. bool CharacterFunctions::isUpperCase (const char character) throw()
  8940. {
  8941. return isupper (character) != 0;
  8942. }
  8943. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8944. {
  8945. #if JUCE_WINDOWS
  8946. return iswupper (character) != 0;
  8947. #else
  8948. return toLowerCase (character) != character;
  8949. #endif
  8950. }
  8951. char CharacterFunctions::toLowerCase (const char character) throw()
  8952. {
  8953. return (char) tolower (character);
  8954. }
  8955. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8956. {
  8957. return towlower (character);
  8958. }
  8959. void CharacterFunctions::toLowerCase (char* s) throw()
  8960. {
  8961. #if JUCE_WINDOWS
  8962. strlwr (s);
  8963. #else
  8964. while (*s != 0)
  8965. {
  8966. *s = toLowerCase (*s);
  8967. ++s;
  8968. }
  8969. #endif
  8970. }
  8971. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8972. {
  8973. #if JUCE_WINDOWS
  8974. _wcslwr (s);
  8975. #else
  8976. while (*s != 0)
  8977. {
  8978. *s = toLowerCase (*s);
  8979. ++s;
  8980. }
  8981. #endif
  8982. }
  8983. bool CharacterFunctions::isLowerCase (const char character) throw()
  8984. {
  8985. return islower (character) != 0;
  8986. }
  8987. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8988. {
  8989. #if JUCE_WINDOWS
  8990. return iswlower (character) != 0;
  8991. #else
  8992. return toUpperCase (character) != character;
  8993. #endif
  8994. }
  8995. bool CharacterFunctions::isWhitespace (const char character) throw()
  8996. {
  8997. return character == ' ' || (character <= 13 && character >= 9);
  8998. }
  8999. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9000. {
  9001. return iswspace (character) != 0;
  9002. }
  9003. bool CharacterFunctions::isDigit (const char character) throw()
  9004. {
  9005. return (character >= '0' && character <= '9');
  9006. }
  9007. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9008. {
  9009. return iswdigit (character) != 0;
  9010. }
  9011. bool CharacterFunctions::isLetter (const char character) throw()
  9012. {
  9013. return (character >= 'a' && character <= 'z')
  9014. || (character >= 'A' && character <= 'Z');
  9015. }
  9016. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9017. {
  9018. return iswalpha (character) != 0;
  9019. }
  9020. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9021. {
  9022. return (character >= 'a' && character <= 'z')
  9023. || (character >= 'A' && character <= 'Z')
  9024. || (character >= '0' && character <= '9');
  9025. }
  9026. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9027. {
  9028. return iswalnum (character) != 0;
  9029. }
  9030. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9031. {
  9032. unsigned int d = digit - '0';
  9033. if (d < (unsigned int) 10)
  9034. return (int) d;
  9035. d += (unsigned int) ('0' - 'a');
  9036. if (d < (unsigned int) 6)
  9037. return (int) d + 10;
  9038. d += (unsigned int) ('a' - 'A');
  9039. if (d < (unsigned int) 6)
  9040. return (int) d + 10;
  9041. return -1;
  9042. }
  9043. #if JUCE_MSVC
  9044. #pragma warning (pop)
  9045. #endif
  9046. END_JUCE_NAMESPACE
  9047. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9048. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9049. BEGIN_JUCE_NAMESPACE
  9050. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9051. {
  9052. loadFromText (fileContents);
  9053. }
  9054. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9055. {
  9056. loadFromText (fileToLoad.loadFileAsString());
  9057. }
  9058. LocalisedStrings::~LocalisedStrings()
  9059. {
  9060. }
  9061. const String LocalisedStrings::translate (const String& text) const
  9062. {
  9063. return translations.getValue (text, text);
  9064. }
  9065. static int findCloseQuote (const String& text, int startPos)
  9066. {
  9067. juce_wchar lastChar = 0;
  9068. for (;;)
  9069. {
  9070. const juce_wchar c = text [startPos];
  9071. if (c == 0 || (c == '"' && lastChar != '\\'))
  9072. break;
  9073. lastChar = c;
  9074. ++startPos;
  9075. }
  9076. return startPos;
  9077. }
  9078. static const String unescapeString (const String& s)
  9079. {
  9080. return s.replace ("\\\"", "\"")
  9081. .replace ("\\\'", "\'")
  9082. .replace ("\\t", "\t")
  9083. .replace ("\\r", "\r")
  9084. .replace ("\\n", "\n");
  9085. }
  9086. void LocalisedStrings::loadFromText (const String& fileContents)
  9087. {
  9088. StringArray lines;
  9089. lines.addLines (fileContents);
  9090. for (int i = 0; i < lines.size(); ++i)
  9091. {
  9092. String line (lines[i].trim());
  9093. if (line.startsWithChar ('"'))
  9094. {
  9095. int closeQuote = findCloseQuote (line, 1);
  9096. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9097. if (originalText.isNotEmpty())
  9098. {
  9099. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9100. closeQuote = findCloseQuote (line, openingQuote + 1);
  9101. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9102. if (newText.isNotEmpty())
  9103. translations.set (originalText, newText);
  9104. }
  9105. }
  9106. else if (line.startsWithIgnoreCase ("language:"))
  9107. {
  9108. languageName = line.substring (9).trim();
  9109. }
  9110. else if (line.startsWithIgnoreCase ("countries:"))
  9111. {
  9112. countryCodes.addTokens (line.substring (10).trim(), true);
  9113. countryCodes.trim();
  9114. countryCodes.removeEmptyStrings();
  9115. }
  9116. }
  9117. }
  9118. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9119. {
  9120. translations.setIgnoresCase (shouldIgnoreCase);
  9121. }
  9122. static CriticalSection currentMappingsLock;
  9123. static LocalisedStrings* currentMappings = 0;
  9124. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9125. {
  9126. const ScopedLock sl (currentMappingsLock);
  9127. delete currentMappings;
  9128. currentMappings = newTranslations;
  9129. }
  9130. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9131. {
  9132. return currentMappings;
  9133. }
  9134. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9135. {
  9136. const ScopedLock sl (currentMappingsLock);
  9137. if (currentMappings != 0)
  9138. return currentMappings->translate (text);
  9139. return text;
  9140. }
  9141. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9142. {
  9143. return translateWithCurrentMappings (String (text));
  9144. }
  9145. END_JUCE_NAMESPACE
  9146. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9147. /*** Start of inlined file: juce_String.cpp ***/
  9148. #if JUCE_MSVC
  9149. #pragma warning (push)
  9150. #pragma warning (disable: 4514)
  9151. #endif
  9152. #include <locale>
  9153. BEGIN_JUCE_NAMESPACE
  9154. #if JUCE_MSVC
  9155. #pragma warning (pop)
  9156. #endif
  9157. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9158. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9159. #endif
  9160. class StringHolder
  9161. {
  9162. public:
  9163. StringHolder()
  9164. : refCount (0x3fffffff), allocatedNumChars (0)
  9165. {
  9166. text[0] = 0;
  9167. }
  9168. static juce_wchar* createUninitialised (const size_t numChars)
  9169. {
  9170. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9171. s->refCount.value = 0;
  9172. s->allocatedNumChars = numChars;
  9173. return &(s->text[0]);
  9174. }
  9175. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9176. {
  9177. juce_wchar* const dest = createUninitialised (numChars);
  9178. copyChars (dest, src, numChars);
  9179. return dest;
  9180. }
  9181. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9182. {
  9183. juce_wchar* const dest = createUninitialised (numChars);
  9184. CharacterFunctions::copy (dest, src, (int) numChars);
  9185. dest [numChars] = 0;
  9186. return dest;
  9187. }
  9188. static inline juce_wchar* getEmpty() throw()
  9189. {
  9190. return &(empty.text[0]);
  9191. }
  9192. static void retain (juce_wchar* const text) throw()
  9193. {
  9194. ++(bufferFromText (text)->refCount);
  9195. }
  9196. static inline void release (StringHolder* const b) throw()
  9197. {
  9198. if (--(b->refCount) == -1 && b != &empty)
  9199. delete[] reinterpret_cast <char*> (b);
  9200. }
  9201. static void release (juce_wchar* const text) throw()
  9202. {
  9203. release (bufferFromText (text));
  9204. }
  9205. static juce_wchar* makeUnique (juce_wchar* const text)
  9206. {
  9207. StringHolder* const b = bufferFromText (text);
  9208. if (b->refCount.get() <= 0)
  9209. return text;
  9210. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9211. release (b);
  9212. return newText;
  9213. }
  9214. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9215. {
  9216. StringHolder* const b = bufferFromText (text);
  9217. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9218. return text;
  9219. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9220. copyChars (newText, text, b->allocatedNumChars);
  9221. release (b);
  9222. return newText;
  9223. }
  9224. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9225. {
  9226. return bufferFromText (text)->allocatedNumChars;
  9227. }
  9228. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9229. {
  9230. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9231. dest [numChars] = 0;
  9232. }
  9233. Atomic<int> refCount;
  9234. size_t allocatedNumChars;
  9235. juce_wchar text[1];
  9236. static StringHolder empty;
  9237. private:
  9238. static inline StringHolder* bufferFromText (void* const text) throw()
  9239. {
  9240. // (Can't use offsetof() here because of warnings about this not being a POD)
  9241. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9242. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9243. }
  9244. };
  9245. StringHolder StringHolder::empty;
  9246. const String String::empty;
  9247. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9248. {
  9249. jassert (t[numChars] == 0); // must have a null terminator
  9250. text = StringHolder::createCopy (t, numChars);
  9251. }
  9252. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9253. {
  9254. if (numExtraChars > 0)
  9255. {
  9256. const int oldLen = length();
  9257. const int newTotalLen = oldLen + numExtraChars;
  9258. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9259. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9260. }
  9261. }
  9262. void String::preallocateStorage (const size_t numChars)
  9263. {
  9264. text = StringHolder::makeUniqueWithSize (text, numChars);
  9265. }
  9266. String::String() throw()
  9267. : text (StringHolder::getEmpty())
  9268. {
  9269. }
  9270. String::~String() throw()
  9271. {
  9272. StringHolder::release (text);
  9273. }
  9274. String::String (const String& other) throw()
  9275. : text (other.text)
  9276. {
  9277. StringHolder::retain (text);
  9278. }
  9279. void String::swapWith (String& other) throw()
  9280. {
  9281. swapVariables (text, other.text);
  9282. }
  9283. String& String::operator= (const String& other) throw()
  9284. {
  9285. juce_wchar* const newText = other.text;
  9286. StringHolder::retain (newText);
  9287. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9288. return *this;
  9289. }
  9290. String::String (const size_t numChars, const int /*dummyVariable*/)
  9291. : text (StringHolder::createUninitialised (numChars))
  9292. {
  9293. }
  9294. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9295. {
  9296. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9297. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9298. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9299. }
  9300. String::String (const char* const t)
  9301. {
  9302. if (t != 0 && *t != 0)
  9303. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9304. else
  9305. text = StringHolder::getEmpty();
  9306. }
  9307. String::String (const juce_wchar* const t)
  9308. {
  9309. if (t != 0 && *t != 0)
  9310. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9311. else
  9312. text = StringHolder::getEmpty();
  9313. }
  9314. String::String (const char* const t, const size_t maxChars)
  9315. {
  9316. int i;
  9317. for (i = 0; (size_t) i < maxChars; ++i)
  9318. if (t[i] == 0)
  9319. break;
  9320. if (i > 0)
  9321. text = StringHolder::createCopy (t, i);
  9322. else
  9323. text = StringHolder::getEmpty();
  9324. }
  9325. String::String (const juce_wchar* const t, const size_t maxChars)
  9326. {
  9327. int i;
  9328. for (i = 0; (size_t) i < maxChars; ++i)
  9329. if (t[i] == 0)
  9330. break;
  9331. if (i > 0)
  9332. text = StringHolder::createCopy (t, i);
  9333. else
  9334. text = StringHolder::getEmpty();
  9335. }
  9336. const String String::charToString (const juce_wchar character)
  9337. {
  9338. String result ((size_t) 1, (int) 0);
  9339. result.text[0] = character;
  9340. result.text[1] = 0;
  9341. return result;
  9342. }
  9343. namespace NumberToStringConverters
  9344. {
  9345. // pass in a pointer to the END of a buffer..
  9346. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9347. {
  9348. *--t = 0;
  9349. int64 v = (n >= 0) ? n : -n;
  9350. do
  9351. {
  9352. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9353. v /= 10;
  9354. } while (v > 0);
  9355. if (n < 0)
  9356. *--t = '-';
  9357. return t;
  9358. }
  9359. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9360. {
  9361. *--t = 0;
  9362. do
  9363. {
  9364. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9365. v /= 10;
  9366. } while (v > 0);
  9367. return t;
  9368. }
  9369. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9370. {
  9371. if (n == (int) 0x80000000) // (would cause an overflow)
  9372. return int64ToString (t, n);
  9373. *--t = 0;
  9374. int v = abs (n);
  9375. do
  9376. {
  9377. *--t = (juce_wchar) ('0' + (v % 10));
  9378. v /= 10;
  9379. } while (v > 0);
  9380. if (n < 0)
  9381. *--t = '-';
  9382. return t;
  9383. }
  9384. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9385. {
  9386. *--t = 0;
  9387. do
  9388. {
  9389. *--t = (juce_wchar) ('0' + (v % 10));
  9390. v /= 10;
  9391. } while (v > 0);
  9392. return t;
  9393. }
  9394. static juce_wchar getDecimalPoint()
  9395. {
  9396. #if JUCE_WINDOWS && _MSC_VER < 1400
  9397. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9398. #else
  9399. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9400. #endif
  9401. return dp;
  9402. }
  9403. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9404. {
  9405. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9406. {
  9407. juce_wchar* const end = buffer + numChars;
  9408. juce_wchar* t = end;
  9409. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9410. *--t = (juce_wchar) 0;
  9411. while (numDecPlaces >= 0 || v > 0)
  9412. {
  9413. if (numDecPlaces == 0)
  9414. *--t = getDecimalPoint();
  9415. *--t = (juce_wchar) ('0' + (v % 10));
  9416. v /= 10;
  9417. --numDecPlaces;
  9418. }
  9419. if (n < 0)
  9420. *--t = '-';
  9421. len = end - t - 1;
  9422. return t;
  9423. }
  9424. else
  9425. {
  9426. #if JUCE_WINDOWS
  9427. #if _MSC_VER <= 1400
  9428. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9429. #else
  9430. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9431. #endif
  9432. #else
  9433. len = swprintf (buffer, numChars, L"%.9g", n);
  9434. #endif
  9435. return buffer;
  9436. }
  9437. }
  9438. }
  9439. String::String (const int number)
  9440. {
  9441. juce_wchar buffer [16];
  9442. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9443. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9444. createInternal (start, end - start - 1);
  9445. }
  9446. String::String (const unsigned int number)
  9447. {
  9448. juce_wchar buffer [16];
  9449. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9450. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9451. createInternal (start, end - start - 1);
  9452. }
  9453. String::String (const short number)
  9454. {
  9455. juce_wchar buffer [16];
  9456. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9457. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9458. createInternal (start, end - start - 1);
  9459. }
  9460. String::String (const unsigned short number)
  9461. {
  9462. juce_wchar buffer [16];
  9463. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9464. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9465. createInternal (start, end - start - 1);
  9466. }
  9467. String::String (const int64 number)
  9468. {
  9469. juce_wchar buffer [32];
  9470. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9471. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9472. createInternal (start, end - start - 1);
  9473. }
  9474. String::String (const uint64 number)
  9475. {
  9476. juce_wchar buffer [32];
  9477. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9478. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9479. createInternal (start, end - start - 1);
  9480. }
  9481. String::String (const float number, const int numberOfDecimalPlaces)
  9482. {
  9483. juce_wchar buffer [48];
  9484. size_t len;
  9485. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9486. createInternal (start, len);
  9487. }
  9488. String::String (const double number, const int numberOfDecimalPlaces)
  9489. {
  9490. juce_wchar buffer [48];
  9491. size_t len;
  9492. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9493. createInternal (start, len);
  9494. }
  9495. int String::length() const throw()
  9496. {
  9497. return CharacterFunctions::length (text);
  9498. }
  9499. int String::hashCode() const throw()
  9500. {
  9501. const juce_wchar* t = text;
  9502. int result = 0;
  9503. while (*t != (juce_wchar) 0)
  9504. result = 31 * result + *t++;
  9505. return result;
  9506. }
  9507. int64 String::hashCode64() const throw()
  9508. {
  9509. const juce_wchar* t = text;
  9510. int64 result = 0;
  9511. while (*t != (juce_wchar) 0)
  9512. result = 101 * result + *t++;
  9513. return result;
  9514. }
  9515. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  9516. {
  9517. return string1.compare (string2) == 0;
  9518. }
  9519. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  9520. {
  9521. return string1.compare (string2) == 0;
  9522. }
  9523. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  9524. {
  9525. return string1.compare (string2) == 0;
  9526. }
  9527. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  9528. {
  9529. return string1.compare (string2) != 0;
  9530. }
  9531. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  9532. {
  9533. return string1.compare (string2) != 0;
  9534. }
  9535. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  9536. {
  9537. return string1.compare (string2) != 0;
  9538. }
  9539. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  9540. {
  9541. return string1.compare (string2) > 0;
  9542. }
  9543. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  9544. {
  9545. return string1.compare (string2) < 0;
  9546. }
  9547. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  9548. {
  9549. return string1.compare (string2) >= 0;
  9550. }
  9551. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  9552. {
  9553. return string1.compare (string2) <= 0;
  9554. }
  9555. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9556. {
  9557. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9558. : isEmpty();
  9559. }
  9560. bool String::equalsIgnoreCase (const char* t) const throw()
  9561. {
  9562. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9563. : isEmpty();
  9564. }
  9565. bool String::equalsIgnoreCase (const String& other) const throw()
  9566. {
  9567. return text == other.text
  9568. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9569. }
  9570. int String::compare (const String& other) const throw()
  9571. {
  9572. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9573. }
  9574. int String::compare (const char* other) const throw()
  9575. {
  9576. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9577. }
  9578. int String::compare (const juce_wchar* other) const throw()
  9579. {
  9580. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9581. }
  9582. int String::compareIgnoreCase (const String& other) const throw()
  9583. {
  9584. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9585. }
  9586. int String::compareLexicographically (const String& other) const throw()
  9587. {
  9588. const juce_wchar* s1 = text;
  9589. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9590. ++s1;
  9591. const juce_wchar* s2 = other.text;
  9592. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9593. ++s2;
  9594. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9595. }
  9596. String& String::operator+= (const juce_wchar* const t)
  9597. {
  9598. if (t != 0)
  9599. appendInternal (t, CharacterFunctions::length (t));
  9600. return *this;
  9601. }
  9602. String& String::operator+= (const String& other)
  9603. {
  9604. if (isEmpty())
  9605. operator= (other);
  9606. else
  9607. appendInternal (other.text, other.length());
  9608. return *this;
  9609. }
  9610. String& String::operator+= (const char ch)
  9611. {
  9612. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9613. return operator+= (static_cast <const juce_wchar*> (asString));
  9614. }
  9615. String& String::operator+= (const juce_wchar ch)
  9616. {
  9617. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9618. return operator+= (static_cast <const juce_wchar*> (asString));
  9619. }
  9620. String& String::operator+= (const int number)
  9621. {
  9622. juce_wchar buffer [16];
  9623. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9624. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9625. appendInternal (start, (int) (end - start));
  9626. return *this;
  9627. }
  9628. String& String::operator+= (const unsigned int number)
  9629. {
  9630. juce_wchar buffer [16];
  9631. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9632. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9633. appendInternal (start, (int) (end - start));
  9634. return *this;
  9635. }
  9636. void String::append (const juce_wchar* const other, const int howMany)
  9637. {
  9638. if (howMany > 0)
  9639. {
  9640. int i;
  9641. for (i = 0; i < howMany; ++i)
  9642. if (other[i] == 0)
  9643. break;
  9644. appendInternal (other, i);
  9645. }
  9646. }
  9647. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  9648. {
  9649. String s (string1);
  9650. return s += string2;
  9651. }
  9652. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  9653. {
  9654. String s (string1);
  9655. return s += string2;
  9656. }
  9657. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  9658. {
  9659. return String::charToString (string1) + string2;
  9660. }
  9661. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  9662. {
  9663. return String::charToString (string1) + string2;
  9664. }
  9665. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  9666. {
  9667. return string1 += string2;
  9668. }
  9669. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  9670. {
  9671. return string1 += string2;
  9672. }
  9673. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  9674. {
  9675. return string1 += string2;
  9676. }
  9677. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  9678. {
  9679. return string1 += string2;
  9680. }
  9681. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  9682. {
  9683. return string1 += string2;
  9684. }
  9685. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  9686. {
  9687. return string1 += characterToAppend;
  9688. }
  9689. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  9690. {
  9691. return string1 += characterToAppend;
  9692. }
  9693. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  9694. {
  9695. return string1 += string2;
  9696. }
  9697. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  9698. {
  9699. return string1 += string2;
  9700. }
  9701. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  9702. {
  9703. return string1 += string2;
  9704. }
  9705. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  9706. {
  9707. return string1 += (int) number;
  9708. }
  9709. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  9710. {
  9711. return string1 += number;
  9712. }
  9713. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  9714. {
  9715. return string1 += number;
  9716. }
  9717. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  9718. {
  9719. return string1 += (int) number;
  9720. }
  9721. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  9722. {
  9723. return string1 += (unsigned int) number;
  9724. }
  9725. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9726. {
  9727. return string1 += String (number);
  9728. }
  9729. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9730. {
  9731. return string1 += String (number);
  9732. }
  9733. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9734. {
  9735. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9736. // if lots of large, persistent strings were to be written to streams).
  9737. const int numBytes = text.getNumBytesAsUTF8();
  9738. HeapBlock<char> temp (numBytes + 1);
  9739. text.copyToUTF8 (temp, numBytes + 1);
  9740. stream.write (temp, numBytes);
  9741. return stream;
  9742. }
  9743. int String::indexOfChar (const juce_wchar character) const throw()
  9744. {
  9745. const juce_wchar* t = text;
  9746. for (;;)
  9747. {
  9748. if (*t == character)
  9749. return (int) (t - text);
  9750. if (*t++ == 0)
  9751. return -1;
  9752. }
  9753. }
  9754. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9755. {
  9756. for (int i = length(); --i >= 0;)
  9757. if (text[i] == character)
  9758. return i;
  9759. return -1;
  9760. }
  9761. int String::indexOf (const String& t) const throw()
  9762. {
  9763. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9764. return r == 0 ? -1 : (int) (r - text);
  9765. }
  9766. int String::indexOfChar (const int startIndex,
  9767. const juce_wchar character) const throw()
  9768. {
  9769. if (startIndex > 0 && startIndex >= length())
  9770. return -1;
  9771. const juce_wchar* t = text + jmax (0, startIndex);
  9772. for (;;)
  9773. {
  9774. if (*t == character)
  9775. return (int) (t - text);
  9776. if (*t == 0)
  9777. return -1;
  9778. ++t;
  9779. }
  9780. }
  9781. int String::indexOfAnyOf (const String& charactersToLookFor,
  9782. const int startIndex,
  9783. const bool ignoreCase) const throw()
  9784. {
  9785. if (startIndex > 0 && startIndex >= length())
  9786. return -1;
  9787. const juce_wchar* t = text + jmax (0, startIndex);
  9788. while (*t != 0)
  9789. {
  9790. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  9791. return (int) (t - text);
  9792. ++t;
  9793. }
  9794. return -1;
  9795. }
  9796. int String::indexOf (const int startIndex, const String& other) const throw()
  9797. {
  9798. if (startIndex > 0 && startIndex >= length())
  9799. return -1;
  9800. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  9801. return found == 0 ? -1 : (int) (found - text);
  9802. }
  9803. int String::indexOfIgnoreCase (const String& other) const throw()
  9804. {
  9805. if (other.isNotEmpty())
  9806. {
  9807. const int len = other.length();
  9808. const int end = length() - len;
  9809. for (int i = 0; i <= end; ++i)
  9810. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9811. return i;
  9812. }
  9813. return -1;
  9814. }
  9815. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9816. {
  9817. if (other.isNotEmpty())
  9818. {
  9819. const int len = other.length();
  9820. const int end = length() - len;
  9821. for (int i = jmax (0, startIndex); i <= end; ++i)
  9822. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9823. return i;
  9824. }
  9825. return -1;
  9826. }
  9827. int String::lastIndexOf (const String& other) const throw()
  9828. {
  9829. if (other.isNotEmpty())
  9830. {
  9831. const int len = other.length();
  9832. int i = length() - len;
  9833. if (i >= 0)
  9834. {
  9835. const juce_wchar* n = text + i;
  9836. while (i >= 0)
  9837. {
  9838. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9839. return i;
  9840. --i;
  9841. }
  9842. }
  9843. }
  9844. return -1;
  9845. }
  9846. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9847. {
  9848. if (other.isNotEmpty())
  9849. {
  9850. const int len = other.length();
  9851. int i = length() - len;
  9852. if (i >= 0)
  9853. {
  9854. const juce_wchar* n = text + i;
  9855. while (i >= 0)
  9856. {
  9857. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9858. return i;
  9859. --i;
  9860. }
  9861. }
  9862. }
  9863. return -1;
  9864. }
  9865. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9866. {
  9867. for (int i = length(); --i >= 0;)
  9868. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9869. return i;
  9870. return -1;
  9871. }
  9872. bool String::contains (const String& other) const throw()
  9873. {
  9874. return indexOf (other) >= 0;
  9875. }
  9876. bool String::containsChar (const juce_wchar character) const throw()
  9877. {
  9878. const juce_wchar* t = text;
  9879. for (;;)
  9880. {
  9881. if (*t == 0)
  9882. return false;
  9883. if (*t == character)
  9884. return true;
  9885. ++t;
  9886. }
  9887. }
  9888. bool String::containsIgnoreCase (const String& t) const throw()
  9889. {
  9890. return indexOfIgnoreCase (t) >= 0;
  9891. }
  9892. int String::indexOfWholeWord (const String& word) const throw()
  9893. {
  9894. if (word.isNotEmpty())
  9895. {
  9896. const int wordLen = word.length();
  9897. const int end = length() - wordLen;
  9898. const juce_wchar* t = text;
  9899. for (int i = 0; i <= end; ++i)
  9900. {
  9901. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9902. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9903. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9904. {
  9905. return i;
  9906. }
  9907. ++t;
  9908. }
  9909. }
  9910. return -1;
  9911. }
  9912. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9913. {
  9914. if (word.isNotEmpty())
  9915. {
  9916. const int wordLen = word.length();
  9917. const int end = length() - wordLen;
  9918. const juce_wchar* t = text;
  9919. for (int i = 0; i <= end; ++i)
  9920. {
  9921. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9922. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9923. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9924. {
  9925. return i;
  9926. }
  9927. ++t;
  9928. }
  9929. }
  9930. return -1;
  9931. }
  9932. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9933. {
  9934. return indexOfWholeWord (wordToLookFor) >= 0;
  9935. }
  9936. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9937. {
  9938. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9939. }
  9940. static int indexOfMatch (const juce_wchar* const wildcard,
  9941. const juce_wchar* const test,
  9942. const bool ignoreCase) throw()
  9943. {
  9944. int start = 0;
  9945. while (test [start] != 0)
  9946. {
  9947. int i = 0;
  9948. for (;;)
  9949. {
  9950. const juce_wchar wc = wildcard [i];
  9951. const juce_wchar c = test [i + start];
  9952. if (wc == c
  9953. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9954. || (wc == '?' && c != 0))
  9955. {
  9956. if (wc == 0)
  9957. return start;
  9958. ++i;
  9959. }
  9960. else
  9961. {
  9962. if (wc == '*' && (wildcard [i + 1] == 0
  9963. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9964. {
  9965. return start;
  9966. }
  9967. break;
  9968. }
  9969. }
  9970. ++start;
  9971. }
  9972. return -1;
  9973. }
  9974. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9975. {
  9976. int i = 0;
  9977. for (;;)
  9978. {
  9979. const juce_wchar wc = wildcard.text [i];
  9980. const juce_wchar c = text [i];
  9981. if (wc == c
  9982. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9983. || (wc == '?' && c != 0))
  9984. {
  9985. if (wc == 0)
  9986. return true;
  9987. ++i;
  9988. }
  9989. else
  9990. {
  9991. return wc == '*' && (wildcard [i + 1] == 0
  9992. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  9993. }
  9994. }
  9995. }
  9996. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9997. {
  9998. const int len = stringToRepeat.length();
  9999. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10000. juce_wchar* n = result.text;
  10001. *n = 0;
  10002. while (--numberOfTimesToRepeat >= 0)
  10003. {
  10004. StringHolder::copyChars (n, stringToRepeat.text, len);
  10005. n += len;
  10006. }
  10007. return result;
  10008. }
  10009. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10010. {
  10011. jassert (padCharacter != 0);
  10012. const int len = length();
  10013. if (len >= minimumLength || padCharacter == 0)
  10014. return *this;
  10015. String result ((size_t) minimumLength + 1, (int) 0);
  10016. juce_wchar* n = result.text;
  10017. minimumLength -= len;
  10018. while (--minimumLength >= 0)
  10019. *n++ = padCharacter;
  10020. StringHolder::copyChars (n, text, len);
  10021. return result;
  10022. }
  10023. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10024. {
  10025. jassert (padCharacter != 0);
  10026. const int len = length();
  10027. if (len >= minimumLength || padCharacter == 0)
  10028. return *this;
  10029. String result (*this, (size_t) minimumLength);
  10030. juce_wchar* n = result.text + len;
  10031. minimumLength -= len;
  10032. while (--minimumLength >= 0)
  10033. *n++ = padCharacter;
  10034. *n = 0;
  10035. return result;
  10036. }
  10037. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10038. {
  10039. if (index < 0)
  10040. {
  10041. // a negative index to replace from?
  10042. jassertfalse;
  10043. index = 0;
  10044. }
  10045. if (numCharsToReplace < 0)
  10046. {
  10047. // replacing a negative number of characters?
  10048. numCharsToReplace = 0;
  10049. jassertfalse;
  10050. }
  10051. const int len = length();
  10052. if (index + numCharsToReplace > len)
  10053. {
  10054. if (index > len)
  10055. {
  10056. // replacing beyond the end of the string?
  10057. index = len;
  10058. jassertfalse;
  10059. }
  10060. numCharsToReplace = len - index;
  10061. }
  10062. const int newStringLen = stringToInsert.length();
  10063. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10064. if (newTotalLen <= 0)
  10065. return String::empty;
  10066. String result ((size_t) newTotalLen, (int) 0);
  10067. StringHolder::copyChars (result.text, text, index);
  10068. if (newStringLen > 0)
  10069. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10070. const int endStringLen = newTotalLen - (index + newStringLen);
  10071. if (endStringLen > 0)
  10072. StringHolder::copyChars (result.text + (index + newStringLen),
  10073. text + (index + numCharsToReplace),
  10074. endStringLen);
  10075. return result;
  10076. }
  10077. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10078. {
  10079. const int stringToReplaceLen = stringToReplace.length();
  10080. const int stringToInsertLen = stringToInsert.length();
  10081. int i = 0;
  10082. String result (*this);
  10083. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10084. : result.indexOf (i, stringToReplace))) >= 0)
  10085. {
  10086. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10087. i += stringToInsertLen;
  10088. }
  10089. return result;
  10090. }
  10091. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10092. {
  10093. const int index = indexOfChar (charToReplace);
  10094. if (index < 0)
  10095. return *this;
  10096. String result (*this, size_t());
  10097. juce_wchar* t = result.text + index;
  10098. while (*t != 0)
  10099. {
  10100. if (*t == charToReplace)
  10101. *t = charToInsert;
  10102. ++t;
  10103. }
  10104. return result;
  10105. }
  10106. const String String::replaceCharacters (const String& charactersToReplace,
  10107. const String& charactersToInsertInstead) const
  10108. {
  10109. String result (*this, size_t());
  10110. juce_wchar* t = result.text;
  10111. const int len2 = charactersToInsertInstead.length();
  10112. // the two strings passed in are supposed to be the same length!
  10113. jassert (len2 == charactersToReplace.length());
  10114. while (*t != 0)
  10115. {
  10116. const int index = charactersToReplace.indexOfChar (*t);
  10117. if (((unsigned int) index) < (unsigned int) len2)
  10118. *t = charactersToInsertInstead [index];
  10119. ++t;
  10120. }
  10121. return result;
  10122. }
  10123. bool String::startsWith (const String& other) const throw()
  10124. {
  10125. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10126. }
  10127. bool String::startsWithIgnoreCase (const String& other) const throw()
  10128. {
  10129. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10130. }
  10131. bool String::startsWithChar (const juce_wchar character) const throw()
  10132. {
  10133. jassert (character != 0); // strings can't contain a null character!
  10134. return text[0] == character;
  10135. }
  10136. bool String::endsWithChar (const juce_wchar character) const throw()
  10137. {
  10138. jassert (character != 0); // strings can't contain a null character!
  10139. return text[0] != 0
  10140. && text [length() - 1] == character;
  10141. }
  10142. bool String::endsWith (const String& other) const throw()
  10143. {
  10144. const int thisLen = length();
  10145. const int otherLen = other.length();
  10146. return thisLen >= otherLen
  10147. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10148. }
  10149. bool String::endsWithIgnoreCase (const String& other) const throw()
  10150. {
  10151. const int thisLen = length();
  10152. const int otherLen = other.length();
  10153. return thisLen >= otherLen
  10154. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10155. }
  10156. const String String::toUpperCase() const
  10157. {
  10158. String result (*this, size_t());
  10159. CharacterFunctions::toUpperCase (result.text);
  10160. return result;
  10161. }
  10162. const String String::toLowerCase() const
  10163. {
  10164. String result (*this, size_t());
  10165. CharacterFunctions::toLowerCase (result.text);
  10166. return result;
  10167. }
  10168. juce_wchar& String::operator[] (const int index)
  10169. {
  10170. jassert (((unsigned int) index) <= (unsigned int) length());
  10171. text = StringHolder::makeUnique (text);
  10172. return text [index];
  10173. }
  10174. juce_wchar String::getLastCharacter() const throw()
  10175. {
  10176. return isEmpty() ? juce_wchar() : text [length() - 1];
  10177. }
  10178. const String String::substring (int start, int end) const
  10179. {
  10180. if (start < 0)
  10181. start = 0;
  10182. else if (end <= start)
  10183. return empty;
  10184. int len = 0;
  10185. while (len <= end && text [len] != 0)
  10186. ++len;
  10187. if (end >= len)
  10188. {
  10189. if (start == 0)
  10190. return *this;
  10191. end = len;
  10192. }
  10193. return String (text + start, end - start);
  10194. }
  10195. const String String::substring (const int start) const
  10196. {
  10197. if (start <= 0)
  10198. return *this;
  10199. const int len = length();
  10200. if (start >= len)
  10201. return empty;
  10202. return String (text + start, len - start);
  10203. }
  10204. const String String::dropLastCharacters (const int numberToDrop) const
  10205. {
  10206. return String (text, jmax (0, length() - numberToDrop));
  10207. }
  10208. const String String::getLastCharacters (const int numCharacters) const
  10209. {
  10210. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10211. }
  10212. const String String::fromFirstOccurrenceOf (const String& sub,
  10213. const bool includeSubString,
  10214. const bool ignoreCase) const
  10215. {
  10216. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10217. : indexOf (sub);
  10218. if (i < 0)
  10219. return empty;
  10220. return substring (includeSubString ? i : i + sub.length());
  10221. }
  10222. const String String::fromLastOccurrenceOf (const String& sub,
  10223. const bool includeSubString,
  10224. const bool ignoreCase) const
  10225. {
  10226. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10227. : lastIndexOf (sub);
  10228. if (i < 0)
  10229. return *this;
  10230. return substring (includeSubString ? i : i + sub.length());
  10231. }
  10232. const String String::upToFirstOccurrenceOf (const String& sub,
  10233. const bool includeSubString,
  10234. const bool ignoreCase) const
  10235. {
  10236. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10237. : indexOf (sub);
  10238. if (i < 0)
  10239. return *this;
  10240. return substring (0, includeSubString ? i + sub.length() : i);
  10241. }
  10242. const String String::upToLastOccurrenceOf (const String& sub,
  10243. const bool includeSubString,
  10244. const bool ignoreCase) const
  10245. {
  10246. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10247. : lastIndexOf (sub);
  10248. if (i < 0)
  10249. return *this;
  10250. return substring (0, includeSubString ? i + sub.length() : i);
  10251. }
  10252. bool String::isQuotedString() const
  10253. {
  10254. const String trimmed (trimStart());
  10255. return trimmed[0] == '"'
  10256. || trimmed[0] == '\'';
  10257. }
  10258. const String String::unquoted() const
  10259. {
  10260. String s (*this);
  10261. if (s.text[0] == '"' || s.text[0] == '\'')
  10262. s = s.substring (1);
  10263. const int lastCharIndex = s.length() - 1;
  10264. if (lastCharIndex >= 0
  10265. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10266. s [lastCharIndex] = 0;
  10267. return s;
  10268. }
  10269. const String String::quoted (const juce_wchar quoteCharacter) const
  10270. {
  10271. if (isEmpty())
  10272. return charToString (quoteCharacter) + quoteCharacter;
  10273. String t (*this);
  10274. if (! t.startsWithChar (quoteCharacter))
  10275. t = charToString (quoteCharacter) + t;
  10276. if (! t.endsWithChar (quoteCharacter))
  10277. t += quoteCharacter;
  10278. return t;
  10279. }
  10280. const String String::trim() const
  10281. {
  10282. if (isEmpty())
  10283. return empty;
  10284. int start = 0;
  10285. while (CharacterFunctions::isWhitespace (text [start]))
  10286. ++start;
  10287. const int len = length();
  10288. int end = len - 1;
  10289. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10290. --end;
  10291. ++end;
  10292. if (end <= start)
  10293. return empty;
  10294. else if (start > 0 || end < len)
  10295. return String (text + start, end - start);
  10296. return *this;
  10297. }
  10298. const String String::trimStart() const
  10299. {
  10300. if (isEmpty())
  10301. return empty;
  10302. const juce_wchar* t = text;
  10303. while (CharacterFunctions::isWhitespace (*t))
  10304. ++t;
  10305. if (t == text)
  10306. return *this;
  10307. return String (t);
  10308. }
  10309. const String String::trimEnd() const
  10310. {
  10311. if (isEmpty())
  10312. return empty;
  10313. const juce_wchar* endT = text + (length() - 1);
  10314. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10315. --endT;
  10316. return String (text, (int) (++endT - text));
  10317. }
  10318. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10319. {
  10320. const juce_wchar* t = text;
  10321. while (charactersToTrim.containsChar (*t))
  10322. ++t;
  10323. return t == text ? *this : String (t);
  10324. }
  10325. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10326. {
  10327. if (isEmpty())
  10328. return empty;
  10329. const int len = length();
  10330. const juce_wchar* endT = text + (len - 1);
  10331. int numToRemove = 0;
  10332. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10333. {
  10334. ++numToRemove;
  10335. --endT;
  10336. }
  10337. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10338. }
  10339. const String String::retainCharacters (const String& charactersToRetain) const
  10340. {
  10341. if (isEmpty())
  10342. return empty;
  10343. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10344. juce_wchar* dst = result.text;
  10345. const juce_wchar* src = text;
  10346. while (*src != 0)
  10347. {
  10348. if (charactersToRetain.containsChar (*src))
  10349. *dst++ = *src;
  10350. ++src;
  10351. }
  10352. *dst = 0;
  10353. return result;
  10354. }
  10355. const String String::removeCharacters (const String& charactersToRemove) const
  10356. {
  10357. if (isEmpty())
  10358. return empty;
  10359. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10360. juce_wchar* dst = result.text;
  10361. const juce_wchar* src = text;
  10362. while (*src != 0)
  10363. {
  10364. if (! charactersToRemove.containsChar (*src))
  10365. *dst++ = *src;
  10366. ++src;
  10367. }
  10368. *dst = 0;
  10369. return result;
  10370. }
  10371. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10372. {
  10373. int i = 0;
  10374. for (;;)
  10375. {
  10376. if (! permittedCharacters.containsChar (text[i]))
  10377. break;
  10378. ++i;
  10379. }
  10380. return substring (0, i);
  10381. }
  10382. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10383. {
  10384. const juce_wchar* const t = text;
  10385. int i = 0;
  10386. while (t[i] != 0)
  10387. {
  10388. if (charactersToStopAt.containsChar (t[i]))
  10389. return String (text, i);
  10390. ++i;
  10391. }
  10392. return empty;
  10393. }
  10394. bool String::containsOnly (const String& chars) const throw()
  10395. {
  10396. const juce_wchar* t = text;
  10397. while (*t != 0)
  10398. if (! chars.containsChar (*t++))
  10399. return false;
  10400. return true;
  10401. }
  10402. bool String::containsAnyOf (const String& chars) const throw()
  10403. {
  10404. const juce_wchar* t = text;
  10405. while (*t != 0)
  10406. if (chars.containsChar (*t++))
  10407. return true;
  10408. return false;
  10409. }
  10410. bool String::containsNonWhitespaceChars() const throw()
  10411. {
  10412. const juce_wchar* t = text;
  10413. while (*t != 0)
  10414. if (! CharacterFunctions::isWhitespace (*t++))
  10415. return true;
  10416. return false;
  10417. }
  10418. const String String::formatted (const juce_wchar* const pf, ... )
  10419. {
  10420. jassert (pf != 0);
  10421. va_list args;
  10422. va_start (args, pf);
  10423. size_t bufferSize = 256;
  10424. String result (bufferSize, (int) 0);
  10425. result.text[0] = 0;
  10426. for (;;)
  10427. {
  10428. #if JUCE_LINUX && JUCE_64BIT
  10429. va_list tempArgs;
  10430. va_copy (tempArgs, args);
  10431. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10432. va_end (tempArgs);
  10433. #elif JUCE_WINDOWS
  10434. #if JUCE_MSVC
  10435. #pragma warning (push)
  10436. #pragma warning (disable: 4996)
  10437. #endif
  10438. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10439. #if JUCE_MSVC
  10440. #pragma warning (pop)
  10441. #endif
  10442. #else
  10443. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10444. #endif
  10445. if (num > 0)
  10446. return result;
  10447. bufferSize += 256;
  10448. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10449. break; // returns -1 because of an error rather than because it needs more space.
  10450. result.preallocateStorage (bufferSize);
  10451. }
  10452. return empty;
  10453. }
  10454. int String::getIntValue() const throw()
  10455. {
  10456. return CharacterFunctions::getIntValue (text);
  10457. }
  10458. int String::getTrailingIntValue() const throw()
  10459. {
  10460. int n = 0;
  10461. int mult = 1;
  10462. const juce_wchar* t = text + length();
  10463. while (--t >= text)
  10464. {
  10465. const juce_wchar c = *t;
  10466. if (! CharacterFunctions::isDigit (c))
  10467. {
  10468. if (c == '-')
  10469. n = -n;
  10470. break;
  10471. }
  10472. n += mult * (c - '0');
  10473. mult *= 10;
  10474. }
  10475. return n;
  10476. }
  10477. int64 String::getLargeIntValue() const throw()
  10478. {
  10479. return CharacterFunctions::getInt64Value (text);
  10480. }
  10481. float String::getFloatValue() const throw()
  10482. {
  10483. return (float) CharacterFunctions::getDoubleValue (text);
  10484. }
  10485. double String::getDoubleValue() const throw()
  10486. {
  10487. return CharacterFunctions::getDoubleValue (text);
  10488. }
  10489. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10490. const String String::toHexString (const int number)
  10491. {
  10492. juce_wchar buffer[32];
  10493. juce_wchar* const end = buffer + 32;
  10494. juce_wchar* t = end;
  10495. *--t = 0;
  10496. unsigned int v = (unsigned int) number;
  10497. do
  10498. {
  10499. *--t = hexDigits [v & 15];
  10500. v >>= 4;
  10501. } while (v != 0);
  10502. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10503. }
  10504. const String String::toHexString (const int64 number)
  10505. {
  10506. juce_wchar buffer[32];
  10507. juce_wchar* const end = buffer + 32;
  10508. juce_wchar* t = end;
  10509. *--t = 0;
  10510. uint64 v = (uint64) number;
  10511. do
  10512. {
  10513. *--t = hexDigits [(int) (v & 15)];
  10514. v >>= 4;
  10515. } while (v != 0);
  10516. return String (t, (int) (((char*) end) - (char*) t));
  10517. }
  10518. const String String::toHexString (const short number)
  10519. {
  10520. return toHexString ((int) (unsigned short) number);
  10521. }
  10522. const String String::toHexString (const unsigned char* data,
  10523. const int size,
  10524. const int groupSize)
  10525. {
  10526. if (size <= 0)
  10527. return empty;
  10528. int numChars = (size * 2) + 2;
  10529. if (groupSize > 0)
  10530. numChars += size / groupSize;
  10531. String s ((size_t) numChars, (int) 0);
  10532. juce_wchar* d = s.text;
  10533. for (int i = 0; i < size; ++i)
  10534. {
  10535. *d++ = hexDigits [(*data) >> 4];
  10536. *d++ = hexDigits [(*data) & 0xf];
  10537. ++data;
  10538. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10539. *d++ = ' ';
  10540. }
  10541. *d = 0;
  10542. return s;
  10543. }
  10544. int String::getHexValue32() const throw()
  10545. {
  10546. int result = 0;
  10547. const juce_wchar* c = text;
  10548. for (;;)
  10549. {
  10550. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10551. if (hexValue >= 0)
  10552. result = (result << 4) | hexValue;
  10553. else if (*c == 0)
  10554. break;
  10555. ++c;
  10556. }
  10557. return result;
  10558. }
  10559. int64 String::getHexValue64() const throw()
  10560. {
  10561. int64 result = 0;
  10562. const juce_wchar* c = text;
  10563. for (;;)
  10564. {
  10565. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10566. if (hexValue >= 0)
  10567. result = (result << 4) | hexValue;
  10568. else if (*c == 0)
  10569. break;
  10570. ++c;
  10571. }
  10572. return result;
  10573. }
  10574. const String String::createStringFromData (const void* const data_, const int size)
  10575. {
  10576. const char* const data = static_cast <const char*> (data_);
  10577. if (size <= 0 || data == 0)
  10578. {
  10579. return empty;
  10580. }
  10581. else if (size < 2)
  10582. {
  10583. return charToString (data[0]);
  10584. }
  10585. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10586. || (data[0] == (char)-1 && data[1] == (char)-2))
  10587. {
  10588. // assume it's 16-bit unicode
  10589. const bool bigEndian = (data[0] == (char)-2);
  10590. const int numChars = size / 2 - 1;
  10591. String result;
  10592. result.preallocateStorage (numChars + 2);
  10593. const uint16* const src = (const uint16*) (data + 2);
  10594. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10595. if (bigEndian)
  10596. {
  10597. for (int i = 0; i < numChars; ++i)
  10598. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10599. }
  10600. else
  10601. {
  10602. for (int i = 0; i < numChars; ++i)
  10603. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10604. }
  10605. dst [numChars] = 0;
  10606. return result;
  10607. }
  10608. else
  10609. {
  10610. return String::fromUTF8 (data, size);
  10611. }
  10612. }
  10613. const char* String::toUTF8() const
  10614. {
  10615. if (isEmpty())
  10616. {
  10617. return reinterpret_cast <const char*> (text);
  10618. }
  10619. else
  10620. {
  10621. const int currentLen = length() + 1;
  10622. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10623. String* const mutableThis = const_cast <String*> (this);
  10624. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10625. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10626. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10627. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10628. #endif
  10629. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10630. return otherCopy;
  10631. }
  10632. }
  10633. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10634. {
  10635. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10636. int num = 0, index = 0;
  10637. for (;;)
  10638. {
  10639. const uint32 c = (uint32) text [index++];
  10640. if (c >= 0x80)
  10641. {
  10642. int numExtraBytes = 1;
  10643. if (c >= 0x800)
  10644. {
  10645. ++numExtraBytes;
  10646. if (c >= 0x10000)
  10647. {
  10648. ++numExtraBytes;
  10649. if (c >= 0x200000)
  10650. {
  10651. ++numExtraBytes;
  10652. if (c >= 0x4000000)
  10653. ++numExtraBytes;
  10654. }
  10655. }
  10656. }
  10657. if (buffer != 0)
  10658. {
  10659. if (num + numExtraBytes >= maxBufferSizeBytes)
  10660. {
  10661. buffer [num++] = 0;
  10662. break;
  10663. }
  10664. else
  10665. {
  10666. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10667. while (--numExtraBytes >= 0)
  10668. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10669. }
  10670. }
  10671. else
  10672. {
  10673. num += numExtraBytes + 1;
  10674. }
  10675. }
  10676. else
  10677. {
  10678. if (buffer != 0)
  10679. {
  10680. if (num + 1 >= maxBufferSizeBytes)
  10681. {
  10682. buffer [num++] = 0;
  10683. break;
  10684. }
  10685. buffer [num] = (uint8) c;
  10686. }
  10687. ++num;
  10688. }
  10689. if (c == 0)
  10690. break;
  10691. }
  10692. return num;
  10693. }
  10694. int String::getNumBytesAsUTF8() const throw()
  10695. {
  10696. int num = 0;
  10697. const juce_wchar* t = text;
  10698. for (;;)
  10699. {
  10700. const uint32 c = (uint32) *t;
  10701. if (c >= 0x80)
  10702. {
  10703. ++num;
  10704. if (c >= 0x800)
  10705. {
  10706. ++num;
  10707. if (c >= 0x10000)
  10708. {
  10709. ++num;
  10710. if (c >= 0x200000)
  10711. {
  10712. ++num;
  10713. if (c >= 0x4000000)
  10714. ++num;
  10715. }
  10716. }
  10717. }
  10718. }
  10719. else if (c == 0)
  10720. break;
  10721. ++num;
  10722. ++t;
  10723. }
  10724. return num;
  10725. }
  10726. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10727. {
  10728. if (buffer == 0)
  10729. return empty;
  10730. if (bufferSizeBytes < 0)
  10731. bufferSizeBytes = std::numeric_limits<int>::max();
  10732. size_t numBytes;
  10733. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10734. if (buffer [numBytes] == 0)
  10735. break;
  10736. String result ((size_t) numBytes + 1, (int) 0);
  10737. juce_wchar* dest = result.text;
  10738. size_t i = 0;
  10739. while (i < numBytes)
  10740. {
  10741. const char c = buffer [i++];
  10742. if (c < 0)
  10743. {
  10744. unsigned int mask = 0x7f;
  10745. int bit = 0x40;
  10746. int numExtraValues = 0;
  10747. while (bit != 0 && (c & bit) != 0)
  10748. {
  10749. bit >>= 1;
  10750. mask >>= 1;
  10751. ++numExtraValues;
  10752. }
  10753. int n = (mask & (unsigned char) c);
  10754. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10755. {
  10756. const char nextByte = buffer[i];
  10757. if ((nextByte & 0xc0) != 0x80)
  10758. break;
  10759. n <<= 6;
  10760. n |= (nextByte & 0x3f);
  10761. ++i;
  10762. }
  10763. *dest++ = (juce_wchar) n;
  10764. }
  10765. else
  10766. {
  10767. *dest++ = (juce_wchar) c;
  10768. }
  10769. }
  10770. *dest = 0;
  10771. return result;
  10772. }
  10773. const char* String::toCString() const
  10774. {
  10775. if (isEmpty())
  10776. {
  10777. return reinterpret_cast <const char*> (text);
  10778. }
  10779. else
  10780. {
  10781. const int len = length();
  10782. String* const mutableThis = const_cast <String*> (this);
  10783. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  10784. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  10785. CharacterFunctions::copy (otherCopy, text, len);
  10786. otherCopy [len] = 0;
  10787. return otherCopy;
  10788. }
  10789. }
  10790. #if JUCE_MSVC
  10791. #pragma warning (push)
  10792. #pragma warning (disable: 4514 4996)
  10793. #endif
  10794. int String::getNumBytesAsCString() const throw()
  10795. {
  10796. return (int) wcstombs (0, text, 0);
  10797. }
  10798. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10799. {
  10800. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10801. if (destBuffer != 0 && numBytes >= 0)
  10802. destBuffer [numBytes] = 0;
  10803. return numBytes;
  10804. }
  10805. #if JUCE_MSVC
  10806. #pragma warning (pop)
  10807. #endif
  10808. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  10809. {
  10810. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  10811. }
  10812. String::Concatenator::Concatenator (String& stringToAppendTo)
  10813. : result (stringToAppendTo),
  10814. nextIndex (stringToAppendTo.length())
  10815. {
  10816. }
  10817. String::Concatenator::~Concatenator()
  10818. {
  10819. }
  10820. void String::Concatenator::append (const String& s)
  10821. {
  10822. const int len = s.length();
  10823. if (len > 0)
  10824. {
  10825. result.preallocateStorage (nextIndex + len);
  10826. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  10827. nextIndex += len;
  10828. }
  10829. }
  10830. #if JUCE_UNIT_TESTS
  10831. class StringTests : public UnitTest
  10832. {
  10833. public:
  10834. StringTests() : UnitTest ("String class") {}
  10835. void runTest()
  10836. {
  10837. {
  10838. beginTest ("Basics");
  10839. expect (String().length() == 0);
  10840. expect (String() == String::empty);
  10841. String s1, s2 ("abcd");
  10842. expect (s1.isEmpty() && ! s1.isNotEmpty());
  10843. expect (s2.isNotEmpty() && ! s2.isEmpty());
  10844. expect (s2.length() == 4);
  10845. s1 = "abcd";
  10846. expect (s2 == s1 && s1 == s2);
  10847. expect (s1 == "abcd" && s1 == L"abcd");
  10848. expect (String ("abcd") == String (L"abcd"));
  10849. expect (String ("abcdefg", 4) == L"abcd");
  10850. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  10851. expect (String::charToString ('x') == "x");
  10852. expect (String::charToString (0) == String::empty);
  10853. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  10854. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  10855. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  10856. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  10857. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  10858. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  10859. expect (s1.indexOf (String::empty) == 0);
  10860. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  10861. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  10862. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  10863. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  10864. }
  10865. {
  10866. beginTest ("Operations");
  10867. String s ("012345678");
  10868. expect (s.hashCode() != 0);
  10869. expect (s.hashCode64() != 0);
  10870. expect (s.hashCode() != (s + s).hashCode());
  10871. expect (s.hashCode64() != (s + s).hashCode64());
  10872. expect (s.compare (String ("012345678")) == 0);
  10873. expect (s.compare (String ("012345679")) < 0);
  10874. expect (s.compare (String ("012345676")) > 0);
  10875. expect (s.substring (2, 3) == String::charToString (s[2]));
  10876. expect (s.substring (0, 1) == String::charToString (s[0]));
  10877. expect (s.getLastCharacter() == s [s.length() - 1]);
  10878. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  10879. expect (s.substring (0, 3) == L"012");
  10880. expect (s.substring (0, 100) == s);
  10881. expect (s.substring (-1, 100) == s);
  10882. expect (s.substring (3) == "345678");
  10883. expect (s.indexOf (L"45") == 4);
  10884. expect (String ("444445").indexOf ("45") == 4);
  10885. expect (String ("444445").lastIndexOfChar ('4') == 4);
  10886. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  10887. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  10888. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  10889. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  10890. expect (s.indexOfChar (L'4') == 4);
  10891. expect (s + s == "012345678012345678");
  10892. expect (s.startsWith (s));
  10893. expect (s.startsWith (s.substring (0, 4)));
  10894. expect (s.startsWith (s.dropLastCharacters (4)));
  10895. expect (s.endsWith (s.substring (5)));
  10896. expect (s.endsWith (s));
  10897. expect (s.contains (s.substring (3, 6)));
  10898. expect (s.contains (s.substring (3)));
  10899. expect (s.startsWithChar (s[0]));
  10900. expect (s.endsWithChar (s.getLastCharacter()));
  10901. expect (s [s.length()] == 0);
  10902. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  10903. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  10904. String s2 ("123");
  10905. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  10906. s2 += "xyz";
  10907. expect (s2 == "1234567890xyz");
  10908. beginTest ("Numeric conversions");
  10909. expect (String::empty.getIntValue() == 0);
  10910. expect (String::empty.getDoubleValue() == 0.0);
  10911. expect (String::empty.getFloatValue() == 0.0f);
  10912. expect (s.getIntValue() == 12345678);
  10913. expect (s.getLargeIntValue() == (int64) 12345678);
  10914. expect (s.getDoubleValue() == 12345678.0);
  10915. expect (s.getFloatValue() == 12345678.0f);
  10916. expect (String (-1234).getIntValue() == -1234);
  10917. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  10918. expect (String (-1234.56).getDoubleValue() == -1234.56);
  10919. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  10920. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  10921. expect (s.getHexValue32() == 0x12345678);
  10922. expect (s.getHexValue64() == (int64) 0x12345678);
  10923. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10924. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10925. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  10926. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  10927. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  10928. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  10929. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  10930. beginTest ("Subsections");
  10931. String s3;
  10932. s3 = "abcdeFGHIJ";
  10933. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  10934. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  10935. expect (s3.containsIgnoreCase (s3.substring (3)));
  10936. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  10937. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  10938. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  10939. expect (s3.containsAnyOf (L"zzzFs"));
  10940. expect (s3.startsWith ("abcd"));
  10941. expect (s3.startsWithIgnoreCase (L"abCD"));
  10942. expect (s3.startsWith (String::empty));
  10943. expect (s3.startsWithChar ('a'));
  10944. expect (s3.endsWith (String ("HIJ")));
  10945. expect (s3.endsWithIgnoreCase (L"Hij"));
  10946. expect (s3.endsWith (String::empty));
  10947. expect (s3.endsWithChar (L'J'));
  10948. expect (s3.indexOf ("HIJ") == 7);
  10949. expect (s3.indexOf (L"HIJK") == -1);
  10950. expect (s3.indexOfIgnoreCase ("hij") == 7);
  10951. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  10952. String s4 (s3);
  10953. s4.append (String ("xyz123"), 3);
  10954. expect (s4 == s3 + "xyz");
  10955. expect (String (1234) < String (1235));
  10956. expect (String (1235) > String (1234));
  10957. expect (String (1234) >= String (1234));
  10958. expect (String (1234) <= String (1234));
  10959. expect (String (1235) >= String (1234));
  10960. expect (String (1234) <= String (1235));
  10961. String s5 ("word word2 word3");
  10962. expect (s5.containsWholeWord (String ("word2")));
  10963. expect (s5.indexOfWholeWord ("word2") == 5);
  10964. expect (s5.containsWholeWord (L"word"));
  10965. expect (s5.containsWholeWord ("word3"));
  10966. expect (s5.containsWholeWord (s5));
  10967. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  10968. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  10969. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  10970. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  10971. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  10972. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  10973. expect (s5.containsNonWhitespaceChars());
  10974. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  10975. expect (s5.matchesWildcard (L"wor*", false));
  10976. expect (s5.matchesWildcard ("wOr*", true));
  10977. expect (s5.matchesWildcard (L"*word3", true));
  10978. expect (s5.matchesWildcard ("*word?", true));
  10979. expect (s5.matchesWildcard (L"Word*3", true));
  10980. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  10981. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  10982. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  10983. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  10984. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  10985. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  10986. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  10987. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  10988. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  10989. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  10990. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  10991. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  10992. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  10993. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  10994. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  10995. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  10996. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  10997. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  10998. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  10999. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11000. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11001. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11002. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11003. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11004. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11005. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11006. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11007. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11008. expect (s5.replace ("Word", "", true) == " 2 3");
  11009. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11010. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11011. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11012. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11013. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11014. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11015. expect (s5.retainCharacters (String::empty).isEmpty());
  11016. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11017. expect (s5.removeCharacters (String::empty) == s5);
  11018. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11019. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11020. expect (! s5.isQuotedString());
  11021. expect (s5.quoted().isQuotedString());
  11022. expect (! s5.quoted().unquoted().isQuotedString());
  11023. expect (! String ("x'").isQuotedString());
  11024. expect (String ("'x").isQuotedString());
  11025. String s6 (" \t xyz \t\r\n");
  11026. expect (s6.trim() == String ("xyz"));
  11027. expect (s6.trim().trim() == "xyz");
  11028. expect (s5.trim() == s5);
  11029. expect (s6.trimStart().trimEnd() == s6.trim());
  11030. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11031. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11032. expect (s6.trimStart() != s6.trimEnd());
  11033. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11034. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11035. }
  11036. {
  11037. beginTest ("UTF8");
  11038. String s ("word word2 word3");
  11039. {
  11040. char buffer [100];
  11041. memset (buffer, 0xff, sizeof (buffer));
  11042. s.copyToUTF8 (buffer, 100);
  11043. expect (String::fromUTF8 (buffer, 100) == s);
  11044. juce_wchar bufferUnicode [100];
  11045. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11046. s.copyToUnicode (bufferUnicode, 100);
  11047. expect (String (bufferUnicode, 100) == s);
  11048. }
  11049. {
  11050. juce_wchar wideBuffer [50];
  11051. zerostruct (wideBuffer);
  11052. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11053. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11054. String wide (wideBuffer);
  11055. expect (wide == (const juce_wchar*) wideBuffer);
  11056. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11057. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11058. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11059. }
  11060. }
  11061. }
  11062. };
  11063. static StringTests stringUnitTests;
  11064. #endif
  11065. END_JUCE_NAMESPACE
  11066. /*** End of inlined file: juce_String.cpp ***/
  11067. /*** Start of inlined file: juce_StringArray.cpp ***/
  11068. BEGIN_JUCE_NAMESPACE
  11069. StringArray::StringArray() throw()
  11070. {
  11071. }
  11072. StringArray::StringArray (const StringArray& other)
  11073. : strings (other.strings)
  11074. {
  11075. }
  11076. StringArray::StringArray (const String& firstValue)
  11077. {
  11078. strings.add (firstValue);
  11079. }
  11080. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11081. const int numberOfStrings)
  11082. {
  11083. for (int i = 0; i < numberOfStrings; ++i)
  11084. strings.add (initialStrings [i]);
  11085. }
  11086. StringArray::StringArray (const char* const* const initialStrings,
  11087. const int numberOfStrings)
  11088. {
  11089. for (int i = 0; i < numberOfStrings; ++i)
  11090. strings.add (initialStrings [i]);
  11091. }
  11092. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11093. {
  11094. int i = 0;
  11095. while (initialStrings[i] != 0)
  11096. strings.add (initialStrings [i++]);
  11097. }
  11098. StringArray::StringArray (const char* const* const initialStrings)
  11099. {
  11100. int i = 0;
  11101. while (initialStrings[i] != 0)
  11102. strings.add (initialStrings [i++]);
  11103. }
  11104. StringArray& StringArray::operator= (const StringArray& other)
  11105. {
  11106. strings = other.strings;
  11107. return *this;
  11108. }
  11109. StringArray::~StringArray()
  11110. {
  11111. }
  11112. bool StringArray::operator== (const StringArray& other) const throw()
  11113. {
  11114. if (other.size() != size())
  11115. return false;
  11116. for (int i = size(); --i >= 0;)
  11117. if (other.strings.getReference(i) != strings.getReference(i))
  11118. return false;
  11119. return true;
  11120. }
  11121. bool StringArray::operator!= (const StringArray& other) const throw()
  11122. {
  11123. return ! operator== (other);
  11124. }
  11125. void StringArray::clear()
  11126. {
  11127. strings.clear();
  11128. }
  11129. const String& StringArray::operator[] (const int index) const throw()
  11130. {
  11131. if (((unsigned int) index) < (unsigned int) strings.size())
  11132. return strings.getReference (index);
  11133. return String::empty;
  11134. }
  11135. String& StringArray::getReference (const int index) throw()
  11136. {
  11137. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11138. return strings.getReference (index);
  11139. }
  11140. void StringArray::add (const String& newString)
  11141. {
  11142. strings.add (newString);
  11143. }
  11144. void StringArray::insert (const int index, const String& newString)
  11145. {
  11146. strings.insert (index, newString);
  11147. }
  11148. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11149. {
  11150. if (! contains (newString, ignoreCase))
  11151. add (newString);
  11152. }
  11153. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11154. {
  11155. if (startIndex < 0)
  11156. {
  11157. jassertfalse;
  11158. startIndex = 0;
  11159. }
  11160. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11161. numElementsToAdd = otherArray.size() - startIndex;
  11162. while (--numElementsToAdd >= 0)
  11163. strings.add (otherArray.strings.getReference (startIndex++));
  11164. }
  11165. void StringArray::set (const int index, const String& newString)
  11166. {
  11167. strings.set (index, newString);
  11168. }
  11169. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11170. {
  11171. if (ignoreCase)
  11172. {
  11173. for (int i = size(); --i >= 0;)
  11174. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11175. return true;
  11176. }
  11177. else
  11178. {
  11179. for (int i = size(); --i >= 0;)
  11180. if (stringToLookFor == strings.getReference(i))
  11181. return true;
  11182. }
  11183. return false;
  11184. }
  11185. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11186. {
  11187. if (i < 0)
  11188. i = 0;
  11189. const int numElements = size();
  11190. if (ignoreCase)
  11191. {
  11192. while (i < numElements)
  11193. {
  11194. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11195. return i;
  11196. ++i;
  11197. }
  11198. }
  11199. else
  11200. {
  11201. while (i < numElements)
  11202. {
  11203. if (stringToLookFor == strings.getReference (i))
  11204. return i;
  11205. ++i;
  11206. }
  11207. }
  11208. return -1;
  11209. }
  11210. void StringArray::remove (const int index)
  11211. {
  11212. strings.remove (index);
  11213. }
  11214. void StringArray::removeString (const String& stringToRemove,
  11215. const bool ignoreCase)
  11216. {
  11217. if (ignoreCase)
  11218. {
  11219. for (int i = size(); --i >= 0;)
  11220. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11221. strings.remove (i);
  11222. }
  11223. else
  11224. {
  11225. for (int i = size(); --i >= 0;)
  11226. if (stringToRemove == strings.getReference (i))
  11227. strings.remove (i);
  11228. }
  11229. }
  11230. void StringArray::removeRange (int startIndex, int numberToRemove)
  11231. {
  11232. strings.removeRange (startIndex, numberToRemove);
  11233. }
  11234. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11235. {
  11236. if (removeWhitespaceStrings)
  11237. {
  11238. for (int i = size(); --i >= 0;)
  11239. if (! strings.getReference(i).containsNonWhitespaceChars())
  11240. strings.remove (i);
  11241. }
  11242. else
  11243. {
  11244. for (int i = size(); --i >= 0;)
  11245. if (strings.getReference(i).isEmpty())
  11246. strings.remove (i);
  11247. }
  11248. }
  11249. void StringArray::trim()
  11250. {
  11251. for (int i = size(); --i >= 0;)
  11252. {
  11253. String& s = strings.getReference(i);
  11254. s = s.trim();
  11255. }
  11256. }
  11257. class InternalStringArrayComparator_CaseSensitive
  11258. {
  11259. public:
  11260. static int compareElements (String& first, String& second) { return first.compare (second); }
  11261. };
  11262. class InternalStringArrayComparator_CaseInsensitive
  11263. {
  11264. public:
  11265. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11266. };
  11267. void StringArray::sort (const bool ignoreCase)
  11268. {
  11269. if (ignoreCase)
  11270. {
  11271. InternalStringArrayComparator_CaseInsensitive comp;
  11272. strings.sort (comp);
  11273. }
  11274. else
  11275. {
  11276. InternalStringArrayComparator_CaseSensitive comp;
  11277. strings.sort (comp);
  11278. }
  11279. }
  11280. void StringArray::move (const int currentIndex, int newIndex) throw()
  11281. {
  11282. strings.move (currentIndex, newIndex);
  11283. }
  11284. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11285. {
  11286. const int last = (numberToJoin < 0) ? size()
  11287. : jmin (size(), start + numberToJoin);
  11288. if (start < 0)
  11289. start = 0;
  11290. if (start >= last)
  11291. return String::empty;
  11292. if (start == last - 1)
  11293. return strings.getReference (start);
  11294. const int separatorLen = separator.length();
  11295. int charsNeeded = separatorLen * (last - start - 1);
  11296. for (int i = start; i < last; ++i)
  11297. charsNeeded += strings.getReference(i).length();
  11298. String result;
  11299. result.preallocateStorage (charsNeeded);
  11300. juce_wchar* dest = result;
  11301. while (start < last)
  11302. {
  11303. const String& s = strings.getReference (start);
  11304. const int len = s.length();
  11305. if (len > 0)
  11306. {
  11307. s.copyToUnicode (dest, len);
  11308. dest += len;
  11309. }
  11310. if (++start < last && separatorLen > 0)
  11311. {
  11312. separator.copyToUnicode (dest, separatorLen);
  11313. dest += separatorLen;
  11314. }
  11315. }
  11316. *dest = 0;
  11317. return result;
  11318. }
  11319. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11320. {
  11321. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11322. }
  11323. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11324. {
  11325. int num = 0;
  11326. if (text.isNotEmpty())
  11327. {
  11328. bool insideQuotes = false;
  11329. juce_wchar currentQuoteChar = 0;
  11330. int i = 0;
  11331. int tokenStart = 0;
  11332. for (;;)
  11333. {
  11334. const juce_wchar c = text[i];
  11335. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11336. if (! isBreak)
  11337. {
  11338. if (quoteCharacters.containsChar (c))
  11339. {
  11340. if (insideQuotes)
  11341. {
  11342. // only break out of quotes-mode if we find a matching quote to the
  11343. // one that we opened with..
  11344. if (currentQuoteChar == c)
  11345. insideQuotes = false;
  11346. }
  11347. else
  11348. {
  11349. insideQuotes = true;
  11350. currentQuoteChar = c;
  11351. }
  11352. }
  11353. }
  11354. else
  11355. {
  11356. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11357. ++num;
  11358. tokenStart = i + 1;
  11359. }
  11360. if (c == 0)
  11361. break;
  11362. ++i;
  11363. }
  11364. }
  11365. return num;
  11366. }
  11367. int StringArray::addLines (const String& sourceText)
  11368. {
  11369. int numLines = 0;
  11370. const juce_wchar* text = sourceText;
  11371. while (*text != 0)
  11372. {
  11373. const juce_wchar* const startOfLine = text;
  11374. while (*text != 0)
  11375. {
  11376. if (*text == '\r')
  11377. {
  11378. ++text;
  11379. if (*text == '\n')
  11380. ++text;
  11381. break;
  11382. }
  11383. if (*text == '\n')
  11384. {
  11385. ++text;
  11386. break;
  11387. }
  11388. ++text;
  11389. }
  11390. const juce_wchar* endOfLine = text;
  11391. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11392. --endOfLine;
  11393. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11394. --endOfLine;
  11395. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11396. ++numLines;
  11397. }
  11398. return numLines;
  11399. }
  11400. void StringArray::removeDuplicates (const bool ignoreCase)
  11401. {
  11402. for (int i = 0; i < size() - 1; ++i)
  11403. {
  11404. const String s (strings.getReference(i));
  11405. int nextIndex = i + 1;
  11406. for (;;)
  11407. {
  11408. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11409. if (nextIndex < 0)
  11410. break;
  11411. strings.remove (nextIndex);
  11412. }
  11413. }
  11414. }
  11415. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11416. const bool appendNumberToFirstInstance,
  11417. const juce_wchar* preNumberString,
  11418. const juce_wchar* postNumberString)
  11419. {
  11420. if (preNumberString == 0)
  11421. preNumberString = L" (";
  11422. if (postNumberString == 0)
  11423. postNumberString = L")";
  11424. for (int i = 0; i < size() - 1; ++i)
  11425. {
  11426. String& s = strings.getReference(i);
  11427. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11428. if (nextIndex >= 0)
  11429. {
  11430. const String original (s);
  11431. int number = 0;
  11432. if (appendNumberToFirstInstance)
  11433. s = original + preNumberString + String (++number) + postNumberString;
  11434. else
  11435. ++number;
  11436. while (nextIndex >= 0)
  11437. {
  11438. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11439. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11440. }
  11441. }
  11442. }
  11443. }
  11444. void StringArray::minimiseStorageOverheads()
  11445. {
  11446. strings.minimiseStorageOverheads();
  11447. }
  11448. END_JUCE_NAMESPACE
  11449. /*** End of inlined file: juce_StringArray.cpp ***/
  11450. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11451. BEGIN_JUCE_NAMESPACE
  11452. StringPairArray::StringPairArray (const bool ignoreCase_)
  11453. : ignoreCase (ignoreCase_)
  11454. {
  11455. }
  11456. StringPairArray::StringPairArray (const StringPairArray& other)
  11457. : keys (other.keys),
  11458. values (other.values),
  11459. ignoreCase (other.ignoreCase)
  11460. {
  11461. }
  11462. StringPairArray::~StringPairArray()
  11463. {
  11464. }
  11465. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11466. {
  11467. keys = other.keys;
  11468. values = other.values;
  11469. return *this;
  11470. }
  11471. bool StringPairArray::operator== (const StringPairArray& other) const
  11472. {
  11473. for (int i = keys.size(); --i >= 0;)
  11474. if (other [keys[i]] != values[i])
  11475. return false;
  11476. return true;
  11477. }
  11478. bool StringPairArray::operator!= (const StringPairArray& other) const
  11479. {
  11480. return ! operator== (other);
  11481. }
  11482. const String& StringPairArray::operator[] (const String& key) const
  11483. {
  11484. return values [keys.indexOf (key, ignoreCase)];
  11485. }
  11486. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11487. {
  11488. const int i = keys.indexOf (key, ignoreCase);
  11489. if (i >= 0)
  11490. return values[i];
  11491. return defaultReturnValue;
  11492. }
  11493. void StringPairArray::set (const String& key, const String& value)
  11494. {
  11495. const int i = keys.indexOf (key, ignoreCase);
  11496. if (i >= 0)
  11497. {
  11498. values.set (i, value);
  11499. }
  11500. else
  11501. {
  11502. keys.add (key);
  11503. values.add (value);
  11504. }
  11505. }
  11506. void StringPairArray::addArray (const StringPairArray& other)
  11507. {
  11508. for (int i = 0; i < other.size(); ++i)
  11509. set (other.keys[i], other.values[i]);
  11510. }
  11511. void StringPairArray::clear()
  11512. {
  11513. keys.clear();
  11514. values.clear();
  11515. }
  11516. void StringPairArray::remove (const String& key)
  11517. {
  11518. remove (keys.indexOf (key, ignoreCase));
  11519. }
  11520. void StringPairArray::remove (const int index)
  11521. {
  11522. keys.remove (index);
  11523. values.remove (index);
  11524. }
  11525. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11526. {
  11527. ignoreCase = shouldIgnoreCase;
  11528. }
  11529. const String StringPairArray::getDescription() const
  11530. {
  11531. String s;
  11532. for (int i = 0; i < keys.size(); ++i)
  11533. {
  11534. s << keys[i] << " = " << values[i];
  11535. if (i < keys.size())
  11536. s << ", ";
  11537. }
  11538. return s;
  11539. }
  11540. void StringPairArray::minimiseStorageOverheads()
  11541. {
  11542. keys.minimiseStorageOverheads();
  11543. values.minimiseStorageOverheads();
  11544. }
  11545. END_JUCE_NAMESPACE
  11546. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11547. /*** Start of inlined file: juce_StringPool.cpp ***/
  11548. BEGIN_JUCE_NAMESPACE
  11549. StringPool::StringPool() throw() {}
  11550. StringPool::~StringPool() {}
  11551. template <class StringType>
  11552. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11553. {
  11554. int start = 0;
  11555. int end = strings.size();
  11556. for (;;)
  11557. {
  11558. if (start >= end)
  11559. {
  11560. jassert (start <= end);
  11561. strings.insert (start, newString);
  11562. return strings.getReference (start);
  11563. }
  11564. else
  11565. {
  11566. const String& startString = strings.getReference (start);
  11567. if (startString == newString)
  11568. return startString;
  11569. const int halfway = (start + end) >> 1;
  11570. if (halfway == start)
  11571. {
  11572. if (startString.compare (newString) < 0)
  11573. ++start;
  11574. strings.insert (start, newString);
  11575. return strings.getReference (start);
  11576. }
  11577. const int comp = strings.getReference (halfway).compare (newString);
  11578. if (comp == 0)
  11579. return strings.getReference (halfway);
  11580. else if (comp < 0)
  11581. start = halfway;
  11582. else
  11583. end = halfway;
  11584. }
  11585. }
  11586. }
  11587. const juce_wchar* StringPool::getPooledString (const String& s)
  11588. {
  11589. if (s.isEmpty())
  11590. return String::empty;
  11591. return getPooledStringFromArray (strings, s);
  11592. }
  11593. const juce_wchar* StringPool::getPooledString (const char* const s)
  11594. {
  11595. if (s == 0 || *s == 0)
  11596. return String::empty;
  11597. return getPooledStringFromArray (strings, s);
  11598. }
  11599. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11600. {
  11601. if (s == 0 || *s == 0)
  11602. return String::empty;
  11603. return getPooledStringFromArray (strings, s);
  11604. }
  11605. int StringPool::size() const throw()
  11606. {
  11607. return strings.size();
  11608. }
  11609. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11610. {
  11611. return strings [index];
  11612. }
  11613. END_JUCE_NAMESPACE
  11614. /*** End of inlined file: juce_StringPool.cpp ***/
  11615. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11616. BEGIN_JUCE_NAMESPACE
  11617. XmlDocument::XmlDocument (const String& documentText)
  11618. : originalText (documentText),
  11619. ignoreEmptyTextElements (true)
  11620. {
  11621. }
  11622. XmlDocument::XmlDocument (const File& file)
  11623. : ignoreEmptyTextElements (true)
  11624. {
  11625. inputSource = new FileInputSource (file);
  11626. }
  11627. XmlDocument::~XmlDocument()
  11628. {
  11629. }
  11630. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11631. {
  11632. inputSource = newSource;
  11633. }
  11634. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11635. {
  11636. ignoreEmptyTextElements = shouldBeIgnored;
  11637. }
  11638. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11639. {
  11640. return CharacterFunctions::isLetterOrDigit (c)
  11641. || c == '_' || c == '-' || c == ':' || c == '.';
  11642. }
  11643. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11644. {
  11645. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11646. : isXmlIdentifierCharSlow (c);
  11647. }
  11648. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11649. {
  11650. String textToParse (originalText);
  11651. if (textToParse.isEmpty() && inputSource != 0)
  11652. {
  11653. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11654. if (in != 0)
  11655. {
  11656. MemoryOutputStream data;
  11657. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11658. textToParse = data.toString();
  11659. if (! onlyReadOuterDocumentElement)
  11660. originalText = textToParse;
  11661. }
  11662. }
  11663. input = textToParse;
  11664. lastError = String::empty;
  11665. errorOccurred = false;
  11666. outOfData = false;
  11667. needToLoadDTD = true;
  11668. for (int i = 0; i < 128; ++i)
  11669. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11670. if (textToParse.isEmpty())
  11671. {
  11672. lastError = "not enough input";
  11673. }
  11674. else
  11675. {
  11676. skipHeader();
  11677. if (input != 0)
  11678. {
  11679. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11680. if (! errorOccurred)
  11681. return result.release();
  11682. }
  11683. else
  11684. {
  11685. lastError = "incorrect xml header";
  11686. }
  11687. }
  11688. return 0;
  11689. }
  11690. const String& XmlDocument::getLastParseError() const throw()
  11691. {
  11692. return lastError;
  11693. }
  11694. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11695. {
  11696. lastError = desc;
  11697. errorOccurred = ! carryOn;
  11698. }
  11699. const String XmlDocument::getFileContents (const String& filename) const
  11700. {
  11701. if (inputSource != 0)
  11702. {
  11703. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11704. if (in != 0)
  11705. return in->readEntireStreamAsString();
  11706. }
  11707. return String::empty;
  11708. }
  11709. juce_wchar XmlDocument::readNextChar() throw()
  11710. {
  11711. if (*input != 0)
  11712. {
  11713. return *input++;
  11714. }
  11715. else
  11716. {
  11717. outOfData = true;
  11718. return 0;
  11719. }
  11720. }
  11721. int XmlDocument::findNextTokenLength() throw()
  11722. {
  11723. int len = 0;
  11724. juce_wchar c = *input;
  11725. while (isXmlIdentifierChar (c))
  11726. c = input [++len];
  11727. return len;
  11728. }
  11729. void XmlDocument::skipHeader()
  11730. {
  11731. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11732. if (found != 0)
  11733. {
  11734. input = found;
  11735. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11736. if (input == 0)
  11737. return;
  11738. input += 2;
  11739. }
  11740. skipNextWhiteSpace();
  11741. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11742. if (docType == 0)
  11743. return;
  11744. input = docType + 9;
  11745. int n = 1;
  11746. while (n > 0)
  11747. {
  11748. const juce_wchar c = readNextChar();
  11749. if (outOfData)
  11750. return;
  11751. if (c == '<')
  11752. ++n;
  11753. else if (c == '>')
  11754. --n;
  11755. }
  11756. docType += 9;
  11757. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11758. }
  11759. void XmlDocument::skipNextWhiteSpace()
  11760. {
  11761. for (;;)
  11762. {
  11763. juce_wchar c = *input;
  11764. while (CharacterFunctions::isWhitespace (c))
  11765. c = *++input;
  11766. if (c == 0)
  11767. {
  11768. outOfData = true;
  11769. break;
  11770. }
  11771. else if (c == '<')
  11772. {
  11773. if (input[1] == '!'
  11774. && input[2] == '-'
  11775. && input[3] == '-')
  11776. {
  11777. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  11778. if (closeComment == 0)
  11779. {
  11780. outOfData = true;
  11781. break;
  11782. }
  11783. input = closeComment + 3;
  11784. continue;
  11785. }
  11786. else if (input[1] == '?')
  11787. {
  11788. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  11789. if (closeBracket == 0)
  11790. {
  11791. outOfData = true;
  11792. break;
  11793. }
  11794. input = closeBracket + 2;
  11795. continue;
  11796. }
  11797. }
  11798. break;
  11799. }
  11800. }
  11801. void XmlDocument::readQuotedString (String& result)
  11802. {
  11803. const juce_wchar quote = readNextChar();
  11804. while (! outOfData)
  11805. {
  11806. const juce_wchar c = readNextChar();
  11807. if (c == quote)
  11808. break;
  11809. if (c == '&')
  11810. {
  11811. --input;
  11812. readEntity (result);
  11813. }
  11814. else
  11815. {
  11816. --input;
  11817. const juce_wchar* const start = input;
  11818. for (;;)
  11819. {
  11820. const juce_wchar character = *input;
  11821. if (character == quote)
  11822. {
  11823. result.append (start, (int) (input - start));
  11824. ++input;
  11825. return;
  11826. }
  11827. else if (character == '&')
  11828. {
  11829. result.append (start, (int) (input - start));
  11830. break;
  11831. }
  11832. else if (character == 0)
  11833. {
  11834. outOfData = true;
  11835. setLastError ("unmatched quotes", false);
  11836. break;
  11837. }
  11838. ++input;
  11839. }
  11840. }
  11841. }
  11842. }
  11843. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11844. {
  11845. XmlElement* node = 0;
  11846. skipNextWhiteSpace();
  11847. if (outOfData)
  11848. return 0;
  11849. input = CharacterFunctions::find (input, JUCE_T("<"));
  11850. if (input != 0)
  11851. {
  11852. ++input;
  11853. int tagLen = findNextTokenLength();
  11854. if (tagLen == 0)
  11855. {
  11856. // no tag name - but allow for a gap after the '<' before giving an error
  11857. skipNextWhiteSpace();
  11858. tagLen = findNextTokenLength();
  11859. if (tagLen == 0)
  11860. {
  11861. setLastError ("tag name missing", false);
  11862. return node;
  11863. }
  11864. }
  11865. node = new XmlElement (String (input, tagLen));
  11866. input += tagLen;
  11867. XmlElement::XmlAttributeNode* lastAttribute = 0;
  11868. // look for attributes
  11869. for (;;)
  11870. {
  11871. skipNextWhiteSpace();
  11872. const juce_wchar c = *input;
  11873. // empty tag..
  11874. if (c == '/' && input[1] == '>')
  11875. {
  11876. input += 2;
  11877. break;
  11878. }
  11879. // parse the guts of the element..
  11880. if (c == '>')
  11881. {
  11882. ++input;
  11883. skipNextWhiteSpace();
  11884. if (alsoParseSubElements)
  11885. readChildElements (node);
  11886. break;
  11887. }
  11888. // get an attribute..
  11889. if (isXmlIdentifierChar (c))
  11890. {
  11891. const int attNameLen = findNextTokenLength();
  11892. if (attNameLen > 0)
  11893. {
  11894. const juce_wchar* attNameStart = input;
  11895. input += attNameLen;
  11896. skipNextWhiteSpace();
  11897. if (readNextChar() == '=')
  11898. {
  11899. skipNextWhiteSpace();
  11900. const juce_wchar nextChar = *input;
  11901. if (nextChar == '"' || nextChar == '\'')
  11902. {
  11903. XmlElement::XmlAttributeNode* const newAtt
  11904. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  11905. String::empty);
  11906. readQuotedString (newAtt->value);
  11907. if (lastAttribute == 0)
  11908. node->attributes = newAtt;
  11909. else
  11910. lastAttribute->next = newAtt;
  11911. lastAttribute = newAtt;
  11912. continue;
  11913. }
  11914. }
  11915. }
  11916. }
  11917. else
  11918. {
  11919. if (! outOfData)
  11920. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11921. }
  11922. break;
  11923. }
  11924. }
  11925. return node;
  11926. }
  11927. void XmlDocument::readChildElements (XmlElement* parent)
  11928. {
  11929. XmlElement* lastChildNode = 0;
  11930. for (;;)
  11931. {
  11932. skipNextWhiteSpace();
  11933. if (outOfData)
  11934. {
  11935. setLastError ("unmatched tags", false);
  11936. break;
  11937. }
  11938. if (*input == '<')
  11939. {
  11940. if (input[1] == '/')
  11941. {
  11942. // our close tag..
  11943. input = CharacterFunctions::find (input, JUCE_T(">"));
  11944. ++input;
  11945. break;
  11946. }
  11947. else if (input[1] == '!'
  11948. && input[2] == '['
  11949. && input[3] == 'C'
  11950. && input[4] == 'D'
  11951. && input[5] == 'A'
  11952. && input[6] == 'T'
  11953. && input[7] == 'A'
  11954. && input[8] == '[')
  11955. {
  11956. input += 9;
  11957. const juce_wchar* const inputStart = input;
  11958. int len = 0;
  11959. for (;;)
  11960. {
  11961. if (*input == 0)
  11962. {
  11963. setLastError ("unterminated CDATA section", false);
  11964. outOfData = true;
  11965. break;
  11966. }
  11967. else if (input[0] == ']'
  11968. && input[1] == ']'
  11969. && input[2] == '>')
  11970. {
  11971. input += 3;
  11972. break;
  11973. }
  11974. ++input;
  11975. ++len;
  11976. }
  11977. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  11978. if (lastChildNode != 0)
  11979. lastChildNode->nextElement = e;
  11980. else
  11981. parent->addChildElement (e);
  11982. lastChildNode = e;
  11983. }
  11984. else
  11985. {
  11986. // this is some other element, so parse and add it..
  11987. XmlElement* const n = readNextElement (true);
  11988. if (n != 0)
  11989. {
  11990. if (lastChildNode == 0)
  11991. parent->addChildElement (n);
  11992. else
  11993. lastChildNode->nextElement = n;
  11994. lastChildNode = n;
  11995. }
  11996. else
  11997. {
  11998. return;
  11999. }
  12000. }
  12001. }
  12002. else
  12003. {
  12004. // read character block..
  12005. XmlElement* const e = new XmlElement ((int)0);
  12006. if (lastChildNode != 0)
  12007. lastChildNode->nextElement = e;
  12008. else
  12009. parent->addChildElement (e);
  12010. lastChildNode = e;
  12011. String textElementContent;
  12012. for (;;)
  12013. {
  12014. const juce_wchar c = *input;
  12015. if (c == '<')
  12016. break;
  12017. if (c == 0)
  12018. {
  12019. setLastError ("unmatched tags", false);
  12020. outOfData = true;
  12021. return;
  12022. }
  12023. if (c == '&')
  12024. {
  12025. String entity;
  12026. readEntity (entity);
  12027. if (entity.startsWithChar ('<') && entity [1] != 0)
  12028. {
  12029. const juce_wchar* const oldInput = input;
  12030. const bool oldOutOfData = outOfData;
  12031. input = entity;
  12032. outOfData = false;
  12033. for (;;)
  12034. {
  12035. XmlElement* const n = readNextElement (true);
  12036. if (n == 0)
  12037. break;
  12038. if (lastChildNode == 0)
  12039. parent->addChildElement (n);
  12040. else
  12041. lastChildNode->nextElement = n;
  12042. lastChildNode = n;
  12043. }
  12044. input = oldInput;
  12045. outOfData = oldOutOfData;
  12046. }
  12047. else
  12048. {
  12049. textElementContent += entity;
  12050. }
  12051. }
  12052. else
  12053. {
  12054. const juce_wchar* start = input;
  12055. int len = 0;
  12056. for (;;)
  12057. {
  12058. const juce_wchar nextChar = *input;
  12059. if (nextChar == '<' || nextChar == '&')
  12060. {
  12061. break;
  12062. }
  12063. else if (nextChar == 0)
  12064. {
  12065. setLastError ("unmatched tags", false);
  12066. outOfData = true;
  12067. return;
  12068. }
  12069. ++input;
  12070. ++len;
  12071. }
  12072. textElementContent.append (start, len);
  12073. }
  12074. }
  12075. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  12076. : textElementContent.isNotEmpty())
  12077. e->setText (textElementContent);
  12078. }
  12079. }
  12080. }
  12081. void XmlDocument::readEntity (String& result)
  12082. {
  12083. // skip over the ampersand
  12084. ++input;
  12085. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12086. {
  12087. input += 4;
  12088. result += '&';
  12089. }
  12090. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12091. {
  12092. input += 5;
  12093. result += '"';
  12094. }
  12095. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12096. {
  12097. input += 5;
  12098. result += '\'';
  12099. }
  12100. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12101. {
  12102. input += 3;
  12103. result += '<';
  12104. }
  12105. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12106. {
  12107. input += 3;
  12108. result += '>';
  12109. }
  12110. else if (*input == '#')
  12111. {
  12112. int charCode = 0;
  12113. ++input;
  12114. if (*input == 'x' || *input == 'X')
  12115. {
  12116. ++input;
  12117. int numChars = 0;
  12118. while (input[0] != ';')
  12119. {
  12120. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12121. if (hexValue < 0 || ++numChars > 8)
  12122. {
  12123. setLastError ("illegal escape sequence", true);
  12124. break;
  12125. }
  12126. charCode = (charCode << 4) | hexValue;
  12127. ++input;
  12128. }
  12129. ++input;
  12130. }
  12131. else if (input[0] >= '0' && input[0] <= '9')
  12132. {
  12133. int numChars = 0;
  12134. while (input[0] != ';')
  12135. {
  12136. if (++numChars > 12)
  12137. {
  12138. setLastError ("illegal escape sequence", true);
  12139. break;
  12140. }
  12141. charCode = charCode * 10 + (input[0] - '0');
  12142. ++input;
  12143. }
  12144. ++input;
  12145. }
  12146. else
  12147. {
  12148. setLastError ("illegal escape sequence", true);
  12149. result += '&';
  12150. return;
  12151. }
  12152. result << (juce_wchar) charCode;
  12153. }
  12154. else
  12155. {
  12156. const juce_wchar* const entityNameStart = input;
  12157. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12158. if (closingSemiColon == 0)
  12159. {
  12160. outOfData = true;
  12161. result += '&';
  12162. }
  12163. else
  12164. {
  12165. input = closingSemiColon + 1;
  12166. result += expandExternalEntity (String (entityNameStart,
  12167. (int) (closingSemiColon - entityNameStart)));
  12168. }
  12169. }
  12170. }
  12171. const String XmlDocument::expandEntity (const String& ent)
  12172. {
  12173. if (ent.equalsIgnoreCase ("amp"))
  12174. return String::charToString ('&');
  12175. if (ent.equalsIgnoreCase ("quot"))
  12176. return String::charToString ('"');
  12177. if (ent.equalsIgnoreCase ("apos"))
  12178. return String::charToString ('\'');
  12179. if (ent.equalsIgnoreCase ("lt"))
  12180. return String::charToString ('<');
  12181. if (ent.equalsIgnoreCase ("gt"))
  12182. return String::charToString ('>');
  12183. if (ent[0] == '#')
  12184. {
  12185. if (ent[1] == 'x' || ent[1] == 'X')
  12186. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12187. if (ent[1] >= '0' && ent[1] <= '9')
  12188. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12189. setLastError ("illegal escape sequence", false);
  12190. return String::charToString ('&');
  12191. }
  12192. return expandExternalEntity (ent);
  12193. }
  12194. const String XmlDocument::expandExternalEntity (const String& entity)
  12195. {
  12196. if (needToLoadDTD)
  12197. {
  12198. if (dtdText.isNotEmpty())
  12199. {
  12200. dtdText = dtdText.trimCharactersAtEnd (">");
  12201. tokenisedDTD.addTokens (dtdText, true);
  12202. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12203. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12204. {
  12205. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12206. tokenisedDTD.clear();
  12207. tokenisedDTD.addTokens (getFileContents (fn), true);
  12208. }
  12209. else
  12210. {
  12211. tokenisedDTD.clear();
  12212. const int openBracket = dtdText.indexOfChar ('[');
  12213. if (openBracket > 0)
  12214. {
  12215. const int closeBracket = dtdText.lastIndexOfChar (']');
  12216. if (closeBracket > openBracket)
  12217. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12218. closeBracket), true);
  12219. }
  12220. }
  12221. for (int i = tokenisedDTD.size(); --i >= 0;)
  12222. {
  12223. if (tokenisedDTD[i].startsWithChar ('%')
  12224. && tokenisedDTD[i].endsWithChar (';'))
  12225. {
  12226. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12227. StringArray newToks;
  12228. newToks.addTokens (parsed, true);
  12229. tokenisedDTD.remove (i);
  12230. for (int j = newToks.size(); --j >= 0;)
  12231. tokenisedDTD.insert (i, newToks[j]);
  12232. }
  12233. }
  12234. }
  12235. needToLoadDTD = false;
  12236. }
  12237. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12238. {
  12239. if (tokenisedDTD[i] == entity)
  12240. {
  12241. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12242. {
  12243. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12244. // check for sub-entities..
  12245. int ampersand = ent.indexOfChar ('&');
  12246. while (ampersand >= 0)
  12247. {
  12248. const int semiColon = ent.indexOf (i + 1, ";");
  12249. if (semiColon < 0)
  12250. {
  12251. setLastError ("entity without terminating semi-colon", false);
  12252. break;
  12253. }
  12254. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12255. ent = ent.substring (0, ampersand)
  12256. + resolved
  12257. + ent.substring (semiColon + 1);
  12258. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12259. }
  12260. return ent;
  12261. }
  12262. }
  12263. }
  12264. setLastError ("unknown entity", true);
  12265. return entity;
  12266. }
  12267. const String XmlDocument::getParameterEntity (const String& entity)
  12268. {
  12269. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12270. {
  12271. if (tokenisedDTD[i] == entity)
  12272. {
  12273. if (tokenisedDTD [i - 1] == "%"
  12274. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12275. {
  12276. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12277. if (ent.equalsIgnoreCase ("system"))
  12278. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12279. else
  12280. return ent.trim().unquoted();
  12281. }
  12282. }
  12283. }
  12284. return entity;
  12285. }
  12286. END_JUCE_NAMESPACE
  12287. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12288. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12289. BEGIN_JUCE_NAMESPACE
  12290. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12291. : name (other.name),
  12292. value (other.value),
  12293. next (0)
  12294. {
  12295. }
  12296. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12297. : name (name_),
  12298. value (value_),
  12299. next (0)
  12300. {
  12301. }
  12302. XmlElement::XmlElement (const String& tagName_) throw()
  12303. : tagName (tagName_),
  12304. firstChildElement (0),
  12305. nextElement (0),
  12306. attributes (0)
  12307. {
  12308. // the tag name mustn't be empty, or it'll look like a text element!
  12309. jassert (tagName_.containsNonWhitespaceChars())
  12310. // The tag can't contain spaces or other characters that would create invalid XML!
  12311. jassert (! tagName_.containsAnyOf (" <>/&"));
  12312. }
  12313. XmlElement::XmlElement (int /*dummy*/) throw()
  12314. : firstChildElement (0),
  12315. nextElement (0),
  12316. attributes (0)
  12317. {
  12318. }
  12319. XmlElement::XmlElement (const XmlElement& other)
  12320. : tagName (other.tagName),
  12321. firstChildElement (0),
  12322. nextElement (0),
  12323. attributes (0)
  12324. {
  12325. copyChildrenAndAttributesFrom (other);
  12326. }
  12327. XmlElement& XmlElement::operator= (const XmlElement& other)
  12328. {
  12329. if (this != &other)
  12330. {
  12331. removeAllAttributes();
  12332. deleteAllChildElements();
  12333. tagName = other.tagName;
  12334. copyChildrenAndAttributesFrom (other);
  12335. }
  12336. return *this;
  12337. }
  12338. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12339. {
  12340. XmlElement* child = other.firstChildElement;
  12341. XmlElement* lastChild = 0;
  12342. while (child != 0)
  12343. {
  12344. XmlElement* const copiedChild = new XmlElement (*child);
  12345. if (lastChild != 0)
  12346. lastChild->nextElement = copiedChild;
  12347. else
  12348. firstChildElement = copiedChild;
  12349. lastChild = copiedChild;
  12350. child = child->nextElement;
  12351. }
  12352. const XmlAttributeNode* att = other.attributes;
  12353. XmlAttributeNode* lastAtt = 0;
  12354. while (att != 0)
  12355. {
  12356. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12357. if (lastAtt != 0)
  12358. lastAtt->next = newAtt;
  12359. else
  12360. attributes = newAtt;
  12361. lastAtt = newAtt;
  12362. att = att->next;
  12363. }
  12364. }
  12365. XmlElement::~XmlElement() throw()
  12366. {
  12367. XmlElement* child = firstChildElement;
  12368. while (child != 0)
  12369. {
  12370. XmlElement* const nextChild = child->nextElement;
  12371. delete child;
  12372. child = nextChild;
  12373. }
  12374. XmlAttributeNode* att = attributes;
  12375. while (att != 0)
  12376. {
  12377. XmlAttributeNode* const nextAtt = att->next;
  12378. delete att;
  12379. att = nextAtt;
  12380. }
  12381. }
  12382. namespace XmlOutputFunctions
  12383. {
  12384. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12385. {
  12386. if ((character >= 'a' && character <= 'z')
  12387. || (character >= 'A' && character <= 'Z')
  12388. || (character >= '0' && character <= '9'))
  12389. return true;
  12390. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12391. do
  12392. {
  12393. if (((juce_wchar) (uint8) *t) == character)
  12394. return true;
  12395. }
  12396. while (*++t != 0);
  12397. return false;
  12398. }
  12399. static void generateLegalCharConstants()
  12400. {
  12401. uint8 n[32];
  12402. zerostruct (n);
  12403. for (int i = 0; i < 256; ++i)
  12404. if (isLegalXmlCharSlow (i))
  12405. n[i >> 3] |= (1 << (i & 7));
  12406. String s;
  12407. for (int i = 0; i < 32; ++i)
  12408. s << (int) n[i] << ", ";
  12409. DBG (s);
  12410. }*/
  12411. static bool isLegalXmlChar (const uint32 c) throw()
  12412. {
  12413. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12414. return c < sizeof (legalChars) * 8
  12415. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12416. }
  12417. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12418. {
  12419. const juce_wchar* t = text;
  12420. for (;;)
  12421. {
  12422. const juce_wchar character = *t++;
  12423. if (character == 0)
  12424. {
  12425. break;
  12426. }
  12427. else if (isLegalXmlChar ((uint32) character))
  12428. {
  12429. outputStream << (char) character;
  12430. }
  12431. else
  12432. {
  12433. switch (character)
  12434. {
  12435. case '&': outputStream << "&amp;"; break;
  12436. case '"': outputStream << "&quot;"; break;
  12437. case '>': outputStream << "&gt;"; break;
  12438. case '<': outputStream << "&lt;"; break;
  12439. case '\n':
  12440. if (changeNewLines)
  12441. outputStream << "&#10;";
  12442. else
  12443. outputStream << (char) character;
  12444. break;
  12445. case '\r':
  12446. if (changeNewLines)
  12447. outputStream << "&#13;";
  12448. else
  12449. outputStream << (char) character;
  12450. break;
  12451. default:
  12452. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12453. break;
  12454. }
  12455. }
  12456. }
  12457. }
  12458. static void writeSpaces (OutputStream& out, int numSpaces)
  12459. {
  12460. if (numSpaces > 0)
  12461. {
  12462. const char* const blanks = " ";
  12463. const int blankSize = (int) sizeof (blanks) - 1;
  12464. while (numSpaces > blankSize)
  12465. {
  12466. out.write (blanks, blankSize);
  12467. numSpaces -= blankSize;
  12468. }
  12469. out.write (blanks, numSpaces);
  12470. }
  12471. }
  12472. }
  12473. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12474. const int indentationLevel,
  12475. const int lineWrapLength) const
  12476. {
  12477. using namespace XmlOutputFunctions;
  12478. writeSpaces (outputStream, indentationLevel);
  12479. if (! isTextElement())
  12480. {
  12481. outputStream.writeByte ('<');
  12482. outputStream << tagName;
  12483. const int attIndent = indentationLevel + tagName.length() + 1;
  12484. int lineLen = 0;
  12485. const XmlAttributeNode* att = attributes;
  12486. while (att != 0)
  12487. {
  12488. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12489. {
  12490. outputStream.write ("\r\n", 2);
  12491. writeSpaces (outputStream, attIndent);
  12492. lineLen = 0;
  12493. }
  12494. const int64 startPos = outputStream.getPosition();
  12495. outputStream.writeByte (' ');
  12496. outputStream << att->name;
  12497. outputStream.write ("=\"", 2);
  12498. escapeIllegalXmlChars (outputStream, att->value, true);
  12499. outputStream.writeByte ('"');
  12500. lineLen += (int) (outputStream.getPosition() - startPos);
  12501. att = att->next;
  12502. }
  12503. if (firstChildElement != 0)
  12504. {
  12505. XmlElement* child = firstChildElement;
  12506. if (child->nextElement == 0 && child->isTextElement())
  12507. {
  12508. outputStream.writeByte ('>');
  12509. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12510. }
  12511. else
  12512. {
  12513. if (indentationLevel >= 0)
  12514. outputStream.write (">\r\n", 3);
  12515. else
  12516. outputStream.writeByte ('>');
  12517. bool lastWasTextNode = false;
  12518. while (child != 0)
  12519. {
  12520. if (child->isTextElement())
  12521. {
  12522. if ((! lastWasTextNode) && (indentationLevel >= 0))
  12523. writeSpaces (outputStream, indentationLevel + 2);
  12524. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12525. lastWasTextNode = true;
  12526. }
  12527. else
  12528. {
  12529. if (indentationLevel >= 0)
  12530. {
  12531. if (lastWasTextNode)
  12532. outputStream.write ("\r\n", 2);
  12533. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  12534. }
  12535. else
  12536. {
  12537. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  12538. }
  12539. lastWasTextNode = false;
  12540. }
  12541. child = child->nextElement;
  12542. }
  12543. if (indentationLevel >= 0)
  12544. {
  12545. if (lastWasTextNode)
  12546. outputStream.write ("\r\n", 2);
  12547. writeSpaces (outputStream, indentationLevel);
  12548. }
  12549. }
  12550. outputStream.write ("</", 2);
  12551. outputStream << tagName;
  12552. if (indentationLevel >= 0)
  12553. outputStream.write (">\r\n", 3);
  12554. else
  12555. outputStream.writeByte ('>');
  12556. }
  12557. else
  12558. {
  12559. if (indentationLevel >= 0)
  12560. outputStream.write ("/>\r\n", 4);
  12561. else
  12562. outputStream.write ("/>", 2);
  12563. }
  12564. }
  12565. else
  12566. {
  12567. if (indentationLevel >= 0)
  12568. writeSpaces (outputStream, indentationLevel + 2);
  12569. escapeIllegalXmlChars (outputStream, getText(), false);
  12570. }
  12571. }
  12572. const String XmlElement::createDocument (const String& dtdToUse,
  12573. const bool allOnOneLine,
  12574. const bool includeXmlHeader,
  12575. const String& encodingType,
  12576. const int lineWrapLength) const
  12577. {
  12578. MemoryOutputStream mem (2048);
  12579. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12580. return mem.toUTF8();
  12581. }
  12582. void XmlElement::writeToStream (OutputStream& output,
  12583. const String& dtdToUse,
  12584. const bool allOnOneLine,
  12585. const bool includeXmlHeader,
  12586. const String& encodingType,
  12587. const int lineWrapLength) const
  12588. {
  12589. if (includeXmlHeader)
  12590. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  12591. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  12592. if (dtdToUse.isNotEmpty())
  12593. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  12594. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12595. }
  12596. bool XmlElement::writeToFile (const File& file,
  12597. const String& dtdToUse,
  12598. const String& encodingType,
  12599. const int lineWrapLength) const
  12600. {
  12601. if (file.hasWriteAccess())
  12602. {
  12603. TemporaryFile tempFile (file);
  12604. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12605. if (out != 0)
  12606. {
  12607. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12608. out = 0;
  12609. return tempFile.overwriteTargetFileWithTemporary();
  12610. }
  12611. }
  12612. return false;
  12613. }
  12614. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12615. {
  12616. #if JUCE_DEBUG
  12617. // if debugging, check that the case is actually the same, because
  12618. // valid xml is case-sensitive, and although this lets it pass, it's
  12619. // better not to..
  12620. if (tagName.equalsIgnoreCase (tagNameWanted))
  12621. {
  12622. jassert (tagName == tagNameWanted);
  12623. return true;
  12624. }
  12625. else
  12626. {
  12627. return false;
  12628. }
  12629. #else
  12630. return tagName.equalsIgnoreCase (tagNameWanted);
  12631. #endif
  12632. }
  12633. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12634. {
  12635. XmlElement* e = nextElement;
  12636. while (e != 0 && ! e->hasTagName (requiredTagName))
  12637. e = e->nextElement;
  12638. return e;
  12639. }
  12640. int XmlElement::getNumAttributes() const throw()
  12641. {
  12642. const XmlAttributeNode* att = attributes;
  12643. int count = 0;
  12644. while (att != 0)
  12645. {
  12646. att = att->next;
  12647. ++count;
  12648. }
  12649. return count;
  12650. }
  12651. const String& XmlElement::getAttributeName (const int index) const throw()
  12652. {
  12653. const XmlAttributeNode* att = attributes;
  12654. int count = 0;
  12655. while (att != 0)
  12656. {
  12657. if (count == index)
  12658. return att->name;
  12659. att = att->next;
  12660. ++count;
  12661. }
  12662. return String::empty;
  12663. }
  12664. const String& XmlElement::getAttributeValue (const int index) const throw()
  12665. {
  12666. const XmlAttributeNode* att = attributes;
  12667. int count = 0;
  12668. while (att != 0)
  12669. {
  12670. if (count == index)
  12671. return att->value;
  12672. att = att->next;
  12673. ++count;
  12674. }
  12675. return String::empty;
  12676. }
  12677. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12678. {
  12679. const XmlAttributeNode* att = attributes;
  12680. while (att != 0)
  12681. {
  12682. if (att->name.equalsIgnoreCase (attributeName))
  12683. return true;
  12684. att = att->next;
  12685. }
  12686. return false;
  12687. }
  12688. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12689. {
  12690. const XmlAttributeNode* att = attributes;
  12691. while (att != 0)
  12692. {
  12693. if (att->name.equalsIgnoreCase (attributeName))
  12694. return att->value;
  12695. att = att->next;
  12696. }
  12697. return String::empty;
  12698. }
  12699. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12700. {
  12701. const XmlAttributeNode* att = attributes;
  12702. while (att != 0)
  12703. {
  12704. if (att->name.equalsIgnoreCase (attributeName))
  12705. return att->value;
  12706. att = att->next;
  12707. }
  12708. return defaultReturnValue;
  12709. }
  12710. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12711. {
  12712. const XmlAttributeNode* att = attributes;
  12713. while (att != 0)
  12714. {
  12715. if (att->name.equalsIgnoreCase (attributeName))
  12716. return att->value.getIntValue();
  12717. att = att->next;
  12718. }
  12719. return defaultReturnValue;
  12720. }
  12721. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12722. {
  12723. const XmlAttributeNode* att = attributes;
  12724. while (att != 0)
  12725. {
  12726. if (att->name.equalsIgnoreCase (attributeName))
  12727. return att->value.getDoubleValue();
  12728. att = att->next;
  12729. }
  12730. return defaultReturnValue;
  12731. }
  12732. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12733. {
  12734. const XmlAttributeNode* att = attributes;
  12735. while (att != 0)
  12736. {
  12737. if (att->name.equalsIgnoreCase (attributeName))
  12738. {
  12739. juce_wchar firstChar = att->value[0];
  12740. if (CharacterFunctions::isWhitespace (firstChar))
  12741. firstChar = att->value.trimStart() [0];
  12742. return firstChar == '1'
  12743. || firstChar == 't'
  12744. || firstChar == 'y'
  12745. || firstChar == 'T'
  12746. || firstChar == 'Y';
  12747. }
  12748. att = att->next;
  12749. }
  12750. return defaultReturnValue;
  12751. }
  12752. bool XmlElement::compareAttribute (const String& attributeName,
  12753. const String& stringToCompareAgainst,
  12754. const bool ignoreCase) const throw()
  12755. {
  12756. const XmlAttributeNode* att = attributes;
  12757. while (att != 0)
  12758. {
  12759. if (att->name.equalsIgnoreCase (attributeName))
  12760. {
  12761. if (ignoreCase)
  12762. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  12763. else
  12764. return att->value == stringToCompareAgainst;
  12765. }
  12766. att = att->next;
  12767. }
  12768. return false;
  12769. }
  12770. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12771. {
  12772. #if JUCE_DEBUG
  12773. // check the identifier being passed in is legal..
  12774. const juce_wchar* t = attributeName;
  12775. while (*t != 0)
  12776. {
  12777. jassert (CharacterFunctions::isLetterOrDigit (*t)
  12778. || *t == '_'
  12779. || *t == '-'
  12780. || *t == ':');
  12781. ++t;
  12782. }
  12783. #endif
  12784. if (attributes == 0)
  12785. {
  12786. attributes = new XmlAttributeNode (attributeName, value);
  12787. }
  12788. else
  12789. {
  12790. XmlAttributeNode* att = attributes;
  12791. for (;;)
  12792. {
  12793. if (att->name.equalsIgnoreCase (attributeName))
  12794. {
  12795. att->value = value;
  12796. break;
  12797. }
  12798. else if (att->next == 0)
  12799. {
  12800. att->next = new XmlAttributeNode (attributeName, value);
  12801. break;
  12802. }
  12803. att = att->next;
  12804. }
  12805. }
  12806. }
  12807. void XmlElement::setAttribute (const String& attributeName, const int number)
  12808. {
  12809. setAttribute (attributeName, String (number));
  12810. }
  12811. void XmlElement::setAttribute (const String& attributeName, const double number)
  12812. {
  12813. setAttribute (attributeName, String (number));
  12814. }
  12815. void XmlElement::removeAttribute (const String& attributeName) throw()
  12816. {
  12817. XmlAttributeNode* att = attributes;
  12818. XmlAttributeNode* lastAtt = 0;
  12819. while (att != 0)
  12820. {
  12821. if (att->name.equalsIgnoreCase (attributeName))
  12822. {
  12823. if (lastAtt == 0)
  12824. attributes = att->next;
  12825. else
  12826. lastAtt->next = att->next;
  12827. delete att;
  12828. break;
  12829. }
  12830. lastAtt = att;
  12831. att = att->next;
  12832. }
  12833. }
  12834. void XmlElement::removeAllAttributes() throw()
  12835. {
  12836. while (attributes != 0)
  12837. {
  12838. XmlAttributeNode* const nextAtt = attributes->next;
  12839. delete attributes;
  12840. attributes = nextAtt;
  12841. }
  12842. }
  12843. int XmlElement::getNumChildElements() const throw()
  12844. {
  12845. int count = 0;
  12846. const XmlElement* child = firstChildElement;
  12847. while (child != 0)
  12848. {
  12849. ++count;
  12850. child = child->nextElement;
  12851. }
  12852. return count;
  12853. }
  12854. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12855. {
  12856. int count = 0;
  12857. XmlElement* child = firstChildElement;
  12858. while (child != 0 && count < index)
  12859. {
  12860. child = child->nextElement;
  12861. ++count;
  12862. }
  12863. return child;
  12864. }
  12865. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12866. {
  12867. XmlElement* child = firstChildElement;
  12868. while (child != 0)
  12869. {
  12870. if (child->hasTagName (childName))
  12871. break;
  12872. child = child->nextElement;
  12873. }
  12874. return child;
  12875. }
  12876. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12877. {
  12878. if (newNode != 0)
  12879. {
  12880. if (firstChildElement == 0)
  12881. {
  12882. firstChildElement = newNode;
  12883. }
  12884. else
  12885. {
  12886. XmlElement* child = firstChildElement;
  12887. while (child->nextElement != 0)
  12888. child = child->nextElement;
  12889. child->nextElement = newNode;
  12890. // if this is non-zero, then something's probably
  12891. // gone wrong..
  12892. jassert (newNode->nextElement == 0);
  12893. }
  12894. }
  12895. }
  12896. void XmlElement::insertChildElement (XmlElement* const newNode,
  12897. int indexToInsertAt) throw()
  12898. {
  12899. if (newNode != 0)
  12900. {
  12901. removeChildElement (newNode, false);
  12902. if (indexToInsertAt == 0)
  12903. {
  12904. newNode->nextElement = firstChildElement;
  12905. firstChildElement = newNode;
  12906. }
  12907. else
  12908. {
  12909. if (firstChildElement == 0)
  12910. {
  12911. firstChildElement = newNode;
  12912. }
  12913. else
  12914. {
  12915. if (indexToInsertAt < 0)
  12916. indexToInsertAt = std::numeric_limits<int>::max();
  12917. XmlElement* child = firstChildElement;
  12918. while (child->nextElement != 0 && --indexToInsertAt > 0)
  12919. child = child->nextElement;
  12920. newNode->nextElement = child->nextElement;
  12921. child->nextElement = newNode;
  12922. }
  12923. }
  12924. }
  12925. }
  12926. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12927. {
  12928. XmlElement* const newElement = new XmlElement (childTagName);
  12929. addChildElement (newElement);
  12930. return newElement;
  12931. }
  12932. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12933. XmlElement* const newNode) throw()
  12934. {
  12935. if (newNode != 0)
  12936. {
  12937. XmlElement* child = firstChildElement;
  12938. XmlElement* previousNode = 0;
  12939. while (child != 0)
  12940. {
  12941. if (child == currentChildElement)
  12942. {
  12943. if (child != newNode)
  12944. {
  12945. if (previousNode == 0)
  12946. firstChildElement = newNode;
  12947. else
  12948. previousNode->nextElement = newNode;
  12949. newNode->nextElement = child->nextElement;
  12950. delete child;
  12951. }
  12952. return true;
  12953. }
  12954. previousNode = child;
  12955. child = child->nextElement;
  12956. }
  12957. }
  12958. return false;
  12959. }
  12960. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12961. const bool shouldDeleteTheChild) throw()
  12962. {
  12963. if (childToRemove != 0)
  12964. {
  12965. if (firstChildElement == childToRemove)
  12966. {
  12967. firstChildElement = childToRemove->nextElement;
  12968. childToRemove->nextElement = 0;
  12969. }
  12970. else
  12971. {
  12972. XmlElement* child = firstChildElement;
  12973. XmlElement* last = 0;
  12974. while (child != 0)
  12975. {
  12976. if (child == childToRemove)
  12977. {
  12978. if (last == 0)
  12979. firstChildElement = child->nextElement;
  12980. else
  12981. last->nextElement = child->nextElement;
  12982. childToRemove->nextElement = 0;
  12983. break;
  12984. }
  12985. last = child;
  12986. child = child->nextElement;
  12987. }
  12988. }
  12989. if (shouldDeleteTheChild)
  12990. delete childToRemove;
  12991. }
  12992. }
  12993. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12994. const bool ignoreOrderOfAttributes) const throw()
  12995. {
  12996. if (this != other)
  12997. {
  12998. if (other == 0 || tagName != other->tagName)
  12999. {
  13000. return false;
  13001. }
  13002. if (ignoreOrderOfAttributes)
  13003. {
  13004. int totalAtts = 0;
  13005. const XmlAttributeNode* att = attributes;
  13006. while (att != 0)
  13007. {
  13008. if (! other->compareAttribute (att->name, att->value))
  13009. return false;
  13010. att = att->next;
  13011. ++totalAtts;
  13012. }
  13013. if (totalAtts != other->getNumAttributes())
  13014. return false;
  13015. }
  13016. else
  13017. {
  13018. const XmlAttributeNode* thisAtt = attributes;
  13019. const XmlAttributeNode* otherAtt = other->attributes;
  13020. for (;;)
  13021. {
  13022. if (thisAtt == 0 || otherAtt == 0)
  13023. {
  13024. if (thisAtt == otherAtt) // both 0, so it's a match
  13025. break;
  13026. return false;
  13027. }
  13028. if (thisAtt->name != otherAtt->name
  13029. || thisAtt->value != otherAtt->value)
  13030. {
  13031. return false;
  13032. }
  13033. thisAtt = thisAtt->next;
  13034. otherAtt = otherAtt->next;
  13035. }
  13036. }
  13037. const XmlElement* thisChild = firstChildElement;
  13038. const XmlElement* otherChild = other->firstChildElement;
  13039. for (;;)
  13040. {
  13041. if (thisChild == 0 || otherChild == 0)
  13042. {
  13043. if (thisChild == otherChild) // both 0, so it's a match
  13044. break;
  13045. return false;
  13046. }
  13047. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13048. return false;
  13049. thisChild = thisChild->nextElement;
  13050. otherChild = otherChild->nextElement;
  13051. }
  13052. }
  13053. return true;
  13054. }
  13055. void XmlElement::deleteAllChildElements() throw()
  13056. {
  13057. while (firstChildElement != 0)
  13058. {
  13059. XmlElement* const nextChild = firstChildElement->nextElement;
  13060. delete firstChildElement;
  13061. firstChildElement = nextChild;
  13062. }
  13063. }
  13064. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13065. {
  13066. XmlElement* child = firstChildElement;
  13067. while (child != 0)
  13068. {
  13069. if (child->hasTagName (name))
  13070. {
  13071. XmlElement* const nextChild = child->nextElement;
  13072. removeChildElement (child, true);
  13073. child = nextChild;
  13074. }
  13075. else
  13076. {
  13077. child = child->nextElement;
  13078. }
  13079. }
  13080. }
  13081. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13082. {
  13083. const XmlElement* child = firstChildElement;
  13084. while (child != 0)
  13085. {
  13086. if (child == possibleChild)
  13087. return true;
  13088. child = child->nextElement;
  13089. }
  13090. return false;
  13091. }
  13092. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13093. {
  13094. if (this == elementToLookFor || elementToLookFor == 0)
  13095. return 0;
  13096. XmlElement* child = firstChildElement;
  13097. while (child != 0)
  13098. {
  13099. if (elementToLookFor == child)
  13100. return this;
  13101. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13102. if (found != 0)
  13103. return found;
  13104. child = child->nextElement;
  13105. }
  13106. return 0;
  13107. }
  13108. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13109. {
  13110. XmlElement* e = firstChildElement;
  13111. while (e != 0)
  13112. {
  13113. *elems++ = e;
  13114. e = e->nextElement;
  13115. }
  13116. }
  13117. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13118. {
  13119. XmlElement* e = firstChildElement = elems[0];
  13120. for (int i = 1; i < num; ++i)
  13121. {
  13122. e->nextElement = elems[i];
  13123. e = e->nextElement;
  13124. }
  13125. e->nextElement = 0;
  13126. }
  13127. bool XmlElement::isTextElement() const throw()
  13128. {
  13129. return tagName.isEmpty();
  13130. }
  13131. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13132. const String& XmlElement::getText() const throw()
  13133. {
  13134. jassert (isTextElement()); // you're trying to get the text from an element that
  13135. // isn't actually a text element.. If this contains text sub-nodes, you
  13136. // probably want to use getAllSubText instead.
  13137. return getStringAttribute (juce_xmltextContentAttributeName);
  13138. }
  13139. void XmlElement::setText (const String& newText)
  13140. {
  13141. if (isTextElement())
  13142. setAttribute (juce_xmltextContentAttributeName, newText);
  13143. else
  13144. jassertfalse; // you can only change the text in a text element, not a normal one.
  13145. }
  13146. const String XmlElement::getAllSubText() const
  13147. {
  13148. String result;
  13149. String::Concatenator concatenator (result);
  13150. const XmlElement* child = firstChildElement;
  13151. while (child != 0)
  13152. {
  13153. if (child->isTextElement())
  13154. concatenator.append (child->getText());
  13155. child = child->nextElement;
  13156. }
  13157. return result;
  13158. }
  13159. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13160. const String& defaultReturnValue) const
  13161. {
  13162. const XmlElement* const child = getChildByName (childTagName);
  13163. if (child != 0)
  13164. return child->getAllSubText();
  13165. return defaultReturnValue;
  13166. }
  13167. XmlElement* XmlElement::createTextElement (const String& text)
  13168. {
  13169. XmlElement* const e = new XmlElement ((int) 0);
  13170. e->setAttribute (juce_xmltextContentAttributeName, text);
  13171. return e;
  13172. }
  13173. void XmlElement::addTextElement (const String& text)
  13174. {
  13175. addChildElement (createTextElement (text));
  13176. }
  13177. void XmlElement::deleteAllTextElements() throw()
  13178. {
  13179. XmlElement* child = firstChildElement;
  13180. while (child != 0)
  13181. {
  13182. XmlElement* const next = child->nextElement;
  13183. if (child->isTextElement())
  13184. removeChildElement (child, true);
  13185. child = next;
  13186. }
  13187. }
  13188. END_JUCE_NAMESPACE
  13189. /*** End of inlined file: juce_XmlElement.cpp ***/
  13190. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13191. BEGIN_JUCE_NAMESPACE
  13192. ReadWriteLock::ReadWriteLock() throw()
  13193. : numWaitingWriters (0),
  13194. numWriters (0),
  13195. writerThreadId (0)
  13196. {
  13197. }
  13198. ReadWriteLock::~ReadWriteLock() throw()
  13199. {
  13200. jassert (readerThreads.size() == 0);
  13201. jassert (numWriters == 0);
  13202. }
  13203. void ReadWriteLock::enterRead() const throw()
  13204. {
  13205. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13206. const ScopedLock sl (accessLock);
  13207. for (;;)
  13208. {
  13209. jassert (readerThreads.size() % 2 == 0);
  13210. int i;
  13211. for (i = 0; i < readerThreads.size(); i += 2)
  13212. if (readerThreads.getUnchecked(i) == threadId)
  13213. break;
  13214. if (i < readerThreads.size()
  13215. || numWriters + numWaitingWriters == 0
  13216. || (threadId == writerThreadId && numWriters > 0))
  13217. {
  13218. if (i < readerThreads.size())
  13219. {
  13220. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13221. }
  13222. else
  13223. {
  13224. readerThreads.add (threadId);
  13225. readerThreads.add ((Thread::ThreadID) 1);
  13226. }
  13227. return;
  13228. }
  13229. const ScopedUnlock ul (accessLock);
  13230. waitEvent.wait (100);
  13231. }
  13232. }
  13233. void ReadWriteLock::exitRead() const throw()
  13234. {
  13235. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13236. const ScopedLock sl (accessLock);
  13237. for (int i = 0; i < readerThreads.size(); i += 2)
  13238. {
  13239. if (readerThreads.getUnchecked(i) == threadId)
  13240. {
  13241. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13242. if (newCount == 0)
  13243. {
  13244. readerThreads.removeRange (i, 2);
  13245. waitEvent.signal();
  13246. }
  13247. else
  13248. {
  13249. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13250. }
  13251. return;
  13252. }
  13253. }
  13254. jassertfalse; // unlocking a lock that wasn't locked..
  13255. }
  13256. void ReadWriteLock::enterWrite() const throw()
  13257. {
  13258. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13259. const ScopedLock sl (accessLock);
  13260. for (;;)
  13261. {
  13262. if (readerThreads.size() + numWriters == 0
  13263. || threadId == writerThreadId
  13264. || (readerThreads.size() == 2
  13265. && readerThreads.getUnchecked(0) == threadId))
  13266. {
  13267. writerThreadId = threadId;
  13268. ++numWriters;
  13269. break;
  13270. }
  13271. ++numWaitingWriters;
  13272. accessLock.exit();
  13273. waitEvent.wait (100);
  13274. accessLock.enter();
  13275. --numWaitingWriters;
  13276. }
  13277. }
  13278. bool ReadWriteLock::tryEnterWrite() const throw()
  13279. {
  13280. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13281. const ScopedLock sl (accessLock);
  13282. if (readerThreads.size() + numWriters == 0
  13283. || threadId == writerThreadId
  13284. || (readerThreads.size() == 2
  13285. && readerThreads.getUnchecked(0) == threadId))
  13286. {
  13287. writerThreadId = threadId;
  13288. ++numWriters;
  13289. return true;
  13290. }
  13291. return false;
  13292. }
  13293. void ReadWriteLock::exitWrite() const throw()
  13294. {
  13295. const ScopedLock sl (accessLock);
  13296. // check this thread actually had the lock..
  13297. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13298. if (--numWriters == 0)
  13299. {
  13300. writerThreadId = 0;
  13301. waitEvent.signal();
  13302. }
  13303. }
  13304. END_JUCE_NAMESPACE
  13305. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13306. /*** Start of inlined file: juce_Thread.cpp ***/
  13307. BEGIN_JUCE_NAMESPACE
  13308. // these functions are implemented in the platform-specific code.
  13309. void* juce_createThread (void* userData);
  13310. void juce_killThread (void* handle);
  13311. bool juce_setThreadPriority (void* handle, int priority);
  13312. void juce_setCurrentThreadName (const String& name);
  13313. #if JUCE_WINDOWS
  13314. void juce_CloseThreadHandle (void* handle);
  13315. #endif
  13316. void Thread::threadEntryPoint (Thread* const thread)
  13317. {
  13318. {
  13319. const ScopedLock sl (runningThreadsLock);
  13320. runningThreads.add (thread);
  13321. }
  13322. JUCE_TRY
  13323. {
  13324. thread->threadId_ = Thread::getCurrentThreadId();
  13325. if (thread->threadName_.isNotEmpty())
  13326. juce_setCurrentThreadName (thread->threadName_);
  13327. if (thread->startSuspensionEvent_.wait (10000))
  13328. {
  13329. if (thread->affinityMask_ != 0)
  13330. setCurrentThreadAffinityMask (thread->affinityMask_);
  13331. thread->run();
  13332. }
  13333. }
  13334. JUCE_CATCH_ALL_ASSERT
  13335. {
  13336. const ScopedLock sl (runningThreadsLock);
  13337. jassert (runningThreads.contains (thread));
  13338. runningThreads.removeValue (thread);
  13339. }
  13340. #if JUCE_WINDOWS
  13341. juce_CloseThreadHandle (thread->threadHandle_);
  13342. #endif
  13343. thread->threadHandle_ = 0;
  13344. thread->threadId_ = 0;
  13345. }
  13346. // used to wrap the incoming call from the platform-specific code
  13347. void JUCE_API juce_threadEntryPoint (void* userData)
  13348. {
  13349. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13350. }
  13351. Thread::Thread (const String& threadName)
  13352. : threadName_ (threadName),
  13353. threadHandle_ (0),
  13354. threadPriority_ (5),
  13355. threadId_ (0),
  13356. affinityMask_ (0),
  13357. threadShouldExit_ (false)
  13358. {
  13359. }
  13360. Thread::~Thread()
  13361. {
  13362. stopThread (100);
  13363. }
  13364. void Thread::startThread()
  13365. {
  13366. const ScopedLock sl (startStopLock);
  13367. threadShouldExit_ = false;
  13368. if (threadHandle_ == 0)
  13369. {
  13370. threadHandle_ = juce_createThread (this);
  13371. juce_setThreadPriority (threadHandle_, threadPriority_);
  13372. startSuspensionEvent_.signal();
  13373. }
  13374. }
  13375. void Thread::startThread (const int priority)
  13376. {
  13377. const ScopedLock sl (startStopLock);
  13378. if (threadHandle_ == 0)
  13379. {
  13380. threadPriority_ = priority;
  13381. startThread();
  13382. }
  13383. else
  13384. {
  13385. setPriority (priority);
  13386. }
  13387. }
  13388. bool Thread::isThreadRunning() const
  13389. {
  13390. return threadHandle_ != 0;
  13391. }
  13392. void Thread::signalThreadShouldExit()
  13393. {
  13394. threadShouldExit_ = true;
  13395. }
  13396. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13397. {
  13398. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13399. jassert (getThreadId() != getCurrentThreadId());
  13400. const int sleepMsPerIteration = 5;
  13401. int count = timeOutMilliseconds / sleepMsPerIteration;
  13402. while (isThreadRunning())
  13403. {
  13404. if (timeOutMilliseconds > 0 && --count < 0)
  13405. return false;
  13406. sleep (sleepMsPerIteration);
  13407. }
  13408. return true;
  13409. }
  13410. void Thread::stopThread (const int timeOutMilliseconds)
  13411. {
  13412. // agh! You can't stop the thread that's calling this method! How on earth
  13413. // would that work??
  13414. jassert (getCurrentThreadId() != getThreadId());
  13415. const ScopedLock sl (startStopLock);
  13416. if (isThreadRunning())
  13417. {
  13418. signalThreadShouldExit();
  13419. notify();
  13420. if (timeOutMilliseconds != 0)
  13421. waitForThreadToExit (timeOutMilliseconds);
  13422. if (isThreadRunning())
  13423. {
  13424. // very bad karma if this point is reached, as
  13425. // there are bound to be locks and events left in
  13426. // silly states when a thread is killed by force..
  13427. jassertfalse;
  13428. Logger::writeToLog ("!! killing thread by force !!");
  13429. juce_killThread (threadHandle_);
  13430. threadHandle_ = 0;
  13431. threadId_ = 0;
  13432. const ScopedLock sl2 (runningThreadsLock);
  13433. runningThreads.removeValue (this);
  13434. }
  13435. }
  13436. }
  13437. bool Thread::setPriority (const int priority)
  13438. {
  13439. const ScopedLock sl (startStopLock);
  13440. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13441. if (worked)
  13442. threadPriority_ = priority;
  13443. return worked;
  13444. }
  13445. bool Thread::setCurrentThreadPriority (const int priority)
  13446. {
  13447. return juce_setThreadPriority (0, priority);
  13448. }
  13449. void Thread::setAffinityMask (const uint32 affinityMask)
  13450. {
  13451. affinityMask_ = affinityMask;
  13452. }
  13453. bool Thread::wait (const int timeOutMilliseconds) const
  13454. {
  13455. return defaultEvent_.wait (timeOutMilliseconds);
  13456. }
  13457. void Thread::notify() const
  13458. {
  13459. defaultEvent_.signal();
  13460. }
  13461. int Thread::getNumRunningThreads()
  13462. {
  13463. return runningThreads.size();
  13464. }
  13465. Thread* Thread::getCurrentThread()
  13466. {
  13467. const ThreadID thisId = getCurrentThreadId();
  13468. const ScopedLock sl (runningThreadsLock);
  13469. for (int i = runningThreads.size(); --i >= 0;)
  13470. {
  13471. Thread* const t = runningThreads.getUnchecked(i);
  13472. if (t->threadId_ == thisId)
  13473. return t;
  13474. }
  13475. return 0;
  13476. }
  13477. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13478. {
  13479. {
  13480. const ScopedLock sl (runningThreadsLock);
  13481. for (int i = runningThreads.size(); --i >= 0;)
  13482. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13483. }
  13484. for (;;)
  13485. {
  13486. Thread* firstThread;
  13487. {
  13488. const ScopedLock sl (runningThreadsLock);
  13489. firstThread = runningThreads.getFirst();
  13490. }
  13491. if (firstThread == 0)
  13492. break;
  13493. firstThread->stopThread (timeOutMilliseconds);
  13494. }
  13495. }
  13496. Array<Thread*> Thread::runningThreads;
  13497. CriticalSection Thread::runningThreadsLock;
  13498. END_JUCE_NAMESPACE
  13499. /*** End of inlined file: juce_Thread.cpp ***/
  13500. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13501. BEGIN_JUCE_NAMESPACE
  13502. ThreadPoolJob::ThreadPoolJob (const String& name)
  13503. : jobName (name),
  13504. pool (0),
  13505. shouldStop (false),
  13506. isActive (false),
  13507. shouldBeDeleted (false)
  13508. {
  13509. }
  13510. ThreadPoolJob::~ThreadPoolJob()
  13511. {
  13512. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13513. // to remove it first!
  13514. jassert (pool == 0 || ! pool->contains (this));
  13515. }
  13516. const String ThreadPoolJob::getJobName() const
  13517. {
  13518. return jobName;
  13519. }
  13520. void ThreadPoolJob::setJobName (const String& newName)
  13521. {
  13522. jobName = newName;
  13523. }
  13524. void ThreadPoolJob::signalJobShouldExit()
  13525. {
  13526. shouldStop = true;
  13527. }
  13528. class ThreadPool::ThreadPoolThread : public Thread
  13529. {
  13530. public:
  13531. ThreadPoolThread (ThreadPool& pool_)
  13532. : Thread ("Pool"),
  13533. pool (pool_),
  13534. busy (false)
  13535. {
  13536. }
  13537. ~ThreadPoolThread()
  13538. {
  13539. }
  13540. void run()
  13541. {
  13542. while (! threadShouldExit())
  13543. {
  13544. if (! pool.runNextJob())
  13545. wait (500);
  13546. }
  13547. }
  13548. private:
  13549. ThreadPool& pool;
  13550. bool volatile busy;
  13551. ThreadPoolThread (const ThreadPoolThread&);
  13552. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13553. };
  13554. ThreadPool::ThreadPool (const int numThreads,
  13555. const bool startThreadsOnlyWhenNeeded,
  13556. const int stopThreadsWhenNotUsedTimeoutMs)
  13557. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13558. priority (5)
  13559. {
  13560. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13561. for (int i = jmax (1, numThreads); --i >= 0;)
  13562. threads.add (new ThreadPoolThread (*this));
  13563. if (! startThreadsOnlyWhenNeeded)
  13564. for (int i = threads.size(); --i >= 0;)
  13565. threads.getUnchecked(i)->startThread (priority);
  13566. }
  13567. ThreadPool::~ThreadPool()
  13568. {
  13569. removeAllJobs (true, 4000);
  13570. int i;
  13571. for (i = threads.size(); --i >= 0;)
  13572. threads.getUnchecked(i)->signalThreadShouldExit();
  13573. for (i = threads.size(); --i >= 0;)
  13574. threads.getUnchecked(i)->stopThread (500);
  13575. }
  13576. void ThreadPool::addJob (ThreadPoolJob* const job)
  13577. {
  13578. jassert (job != 0);
  13579. jassert (job->pool == 0);
  13580. if (job->pool == 0)
  13581. {
  13582. job->pool = this;
  13583. job->shouldStop = false;
  13584. job->isActive = false;
  13585. {
  13586. const ScopedLock sl (lock);
  13587. jobs.add (job);
  13588. int numRunning = 0;
  13589. for (int i = threads.size(); --i >= 0;)
  13590. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13591. ++numRunning;
  13592. if (numRunning < threads.size())
  13593. {
  13594. bool startedOne = false;
  13595. int n = 1000;
  13596. while (--n >= 0 && ! startedOne)
  13597. {
  13598. for (int i = threads.size(); --i >= 0;)
  13599. {
  13600. if (! threads.getUnchecked(i)->isThreadRunning())
  13601. {
  13602. threads.getUnchecked(i)->startThread (priority);
  13603. startedOne = true;
  13604. break;
  13605. }
  13606. }
  13607. if (! startedOne)
  13608. Thread::sleep (2);
  13609. }
  13610. }
  13611. }
  13612. for (int i = threads.size(); --i >= 0;)
  13613. threads.getUnchecked(i)->notify();
  13614. }
  13615. }
  13616. int ThreadPool::getNumJobs() const
  13617. {
  13618. return jobs.size();
  13619. }
  13620. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13621. {
  13622. const ScopedLock sl (lock);
  13623. return jobs [index];
  13624. }
  13625. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13626. {
  13627. const ScopedLock sl (lock);
  13628. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13629. }
  13630. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13631. {
  13632. const ScopedLock sl (lock);
  13633. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13634. }
  13635. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13636. const int timeOutMs) const
  13637. {
  13638. if (job != 0)
  13639. {
  13640. const uint32 start = Time::getMillisecondCounter();
  13641. while (contains (job))
  13642. {
  13643. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13644. return false;
  13645. jobFinishedSignal.wait (2);
  13646. }
  13647. }
  13648. return true;
  13649. }
  13650. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13651. const bool interruptIfRunning,
  13652. const int timeOutMs)
  13653. {
  13654. bool dontWait = true;
  13655. if (job != 0)
  13656. {
  13657. const ScopedLock sl (lock);
  13658. if (jobs.contains (job))
  13659. {
  13660. if (job->isActive)
  13661. {
  13662. if (interruptIfRunning)
  13663. job->signalJobShouldExit();
  13664. dontWait = false;
  13665. }
  13666. else
  13667. {
  13668. jobs.removeValue (job);
  13669. job->pool = 0;
  13670. }
  13671. }
  13672. }
  13673. return dontWait || waitForJobToFinish (job, timeOutMs);
  13674. }
  13675. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13676. const int timeOutMs,
  13677. const bool deleteInactiveJobs,
  13678. ThreadPool::JobSelector* selectedJobsToRemove)
  13679. {
  13680. Array <ThreadPoolJob*> jobsToWaitFor;
  13681. {
  13682. const ScopedLock sl (lock);
  13683. for (int i = jobs.size(); --i >= 0;)
  13684. {
  13685. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13686. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13687. {
  13688. if (job->isActive)
  13689. {
  13690. jobsToWaitFor.add (job);
  13691. if (interruptRunningJobs)
  13692. job->signalJobShouldExit();
  13693. }
  13694. else
  13695. {
  13696. jobs.remove (i);
  13697. if (deleteInactiveJobs)
  13698. delete job;
  13699. else
  13700. job->pool = 0;
  13701. }
  13702. }
  13703. }
  13704. }
  13705. const uint32 start = Time::getMillisecondCounter();
  13706. for (;;)
  13707. {
  13708. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13709. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13710. jobsToWaitFor.remove (i);
  13711. if (jobsToWaitFor.size() == 0)
  13712. break;
  13713. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13714. return false;
  13715. jobFinishedSignal.wait (20);
  13716. }
  13717. return true;
  13718. }
  13719. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13720. {
  13721. StringArray s;
  13722. const ScopedLock sl (lock);
  13723. for (int i = 0; i < jobs.size(); ++i)
  13724. {
  13725. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13726. if (job->isActive || ! onlyReturnActiveJobs)
  13727. s.add (job->getJobName());
  13728. }
  13729. return s;
  13730. }
  13731. bool ThreadPool::setThreadPriorities (const int newPriority)
  13732. {
  13733. bool ok = true;
  13734. if (priority != newPriority)
  13735. {
  13736. priority = newPriority;
  13737. for (int i = threads.size(); --i >= 0;)
  13738. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13739. ok = false;
  13740. }
  13741. return ok;
  13742. }
  13743. bool ThreadPool::runNextJob()
  13744. {
  13745. ThreadPoolJob* job = 0;
  13746. {
  13747. const ScopedLock sl (lock);
  13748. for (int i = 0; i < jobs.size(); ++i)
  13749. {
  13750. job = jobs[i];
  13751. if (job != 0 && ! (job->isActive || job->shouldStop))
  13752. break;
  13753. job = 0;
  13754. }
  13755. if (job != 0)
  13756. job->isActive = true;
  13757. }
  13758. if (job != 0)
  13759. {
  13760. JUCE_TRY
  13761. {
  13762. ThreadPoolJob::JobStatus result = job->runJob();
  13763. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13764. const ScopedLock sl (lock);
  13765. if (jobs.contains (job))
  13766. {
  13767. job->isActive = false;
  13768. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13769. {
  13770. job->pool = 0;
  13771. job->shouldStop = true;
  13772. jobs.removeValue (job);
  13773. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13774. delete job;
  13775. jobFinishedSignal.signal();
  13776. }
  13777. else
  13778. {
  13779. // move the job to the end of the queue if it wants another go
  13780. jobs.move (jobs.indexOf (job), -1);
  13781. }
  13782. }
  13783. }
  13784. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13785. catch (...)
  13786. {
  13787. const ScopedLock sl (lock);
  13788. jobs.removeValue (job);
  13789. }
  13790. #endif
  13791. }
  13792. else
  13793. {
  13794. if (threadStopTimeout > 0
  13795. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13796. {
  13797. const ScopedLock sl (lock);
  13798. if (jobs.size() == 0)
  13799. for (int i = threads.size(); --i >= 0;)
  13800. threads.getUnchecked(i)->signalThreadShouldExit();
  13801. }
  13802. else
  13803. {
  13804. return false;
  13805. }
  13806. }
  13807. return true;
  13808. }
  13809. END_JUCE_NAMESPACE
  13810. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13811. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13812. BEGIN_JUCE_NAMESPACE
  13813. TimeSliceThread::TimeSliceThread (const String& threadName)
  13814. : Thread (threadName),
  13815. index (0),
  13816. clientBeingCalled (0),
  13817. clientsChanged (false)
  13818. {
  13819. }
  13820. TimeSliceThread::~TimeSliceThread()
  13821. {
  13822. stopThread (2000);
  13823. }
  13824. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  13825. {
  13826. const ScopedLock sl (listLock);
  13827. clients.addIfNotAlreadyThere (client);
  13828. clientsChanged = true;
  13829. notify();
  13830. }
  13831. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13832. {
  13833. const ScopedLock sl1 (listLock);
  13834. clientsChanged = true;
  13835. // if there's a chance we're in the middle of calling this client, we need to
  13836. // also lock the outer lock..
  13837. if (clientBeingCalled == client)
  13838. {
  13839. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13840. const ScopedLock sl2 (callbackLock);
  13841. const ScopedLock sl3 (listLock);
  13842. clients.removeValue (client);
  13843. }
  13844. else
  13845. {
  13846. clients.removeValue (client);
  13847. }
  13848. }
  13849. int TimeSliceThread::getNumClients() const
  13850. {
  13851. return clients.size();
  13852. }
  13853. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13854. {
  13855. const ScopedLock sl (listLock);
  13856. return clients [i];
  13857. }
  13858. void TimeSliceThread::run()
  13859. {
  13860. int numCallsSinceBusy = 0;
  13861. while (! threadShouldExit())
  13862. {
  13863. int timeToWait = 500;
  13864. {
  13865. const ScopedLock sl (callbackLock);
  13866. {
  13867. const ScopedLock sl2 (listLock);
  13868. if (clients.size() > 0)
  13869. {
  13870. index = (index + 1) % clients.size();
  13871. clientBeingCalled = clients [index];
  13872. }
  13873. else
  13874. {
  13875. index = 0;
  13876. clientBeingCalled = 0;
  13877. }
  13878. if (clientsChanged)
  13879. {
  13880. clientsChanged = false;
  13881. numCallsSinceBusy = 0;
  13882. }
  13883. }
  13884. if (clientBeingCalled != 0)
  13885. {
  13886. if (clientBeingCalled->useTimeSlice())
  13887. numCallsSinceBusy = 0;
  13888. else
  13889. ++numCallsSinceBusy;
  13890. if (numCallsSinceBusy >= clients.size())
  13891. timeToWait = 500;
  13892. else if (index == 0)
  13893. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  13894. else
  13895. timeToWait = 0;
  13896. }
  13897. }
  13898. if (timeToWait > 0)
  13899. wait (timeToWait);
  13900. }
  13901. }
  13902. END_JUCE_NAMESPACE
  13903. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13904. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13905. BEGIN_JUCE_NAMESPACE
  13906. DeletedAtShutdown::DeletedAtShutdown()
  13907. {
  13908. const ScopedLock sl (getLock());
  13909. getObjects().add (this);
  13910. }
  13911. DeletedAtShutdown::~DeletedAtShutdown()
  13912. {
  13913. const ScopedLock sl (getLock());
  13914. getObjects().removeValue (this);
  13915. }
  13916. void DeletedAtShutdown::deleteAll()
  13917. {
  13918. // make a local copy of the array, so it can't get into a loop if something
  13919. // creates another DeletedAtShutdown object during its destructor.
  13920. Array <DeletedAtShutdown*> localCopy;
  13921. {
  13922. const ScopedLock sl (getLock());
  13923. localCopy = getObjects();
  13924. }
  13925. for (int i = localCopy.size(); --i >= 0;)
  13926. {
  13927. JUCE_TRY
  13928. {
  13929. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13930. // double-check that it's not already been deleted during another object's destructor.
  13931. {
  13932. const ScopedLock sl (getLock());
  13933. if (! getObjects().contains (deletee))
  13934. deletee = 0;
  13935. }
  13936. delete deletee;
  13937. }
  13938. JUCE_CATCH_EXCEPTION
  13939. }
  13940. // if no objects got re-created during shutdown, this should have been emptied by their
  13941. // destructors
  13942. jassert (getObjects().size() == 0);
  13943. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13944. }
  13945. CriticalSection& DeletedAtShutdown::getLock()
  13946. {
  13947. static CriticalSection lock;
  13948. return lock;
  13949. }
  13950. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13951. {
  13952. static Array <DeletedAtShutdown*> objects;
  13953. return objects;
  13954. }
  13955. END_JUCE_NAMESPACE
  13956. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13957. /*** Start of inlined file: juce_UnitTest.cpp ***/
  13958. BEGIN_JUCE_NAMESPACE
  13959. UnitTest::UnitTest (const String& name_)
  13960. : name (name_), runner (0)
  13961. {
  13962. getAllTests().add (this);
  13963. }
  13964. UnitTest::~UnitTest()
  13965. {
  13966. getAllTests().removeValue (this);
  13967. }
  13968. Array<UnitTest*>& UnitTest::getAllTests()
  13969. {
  13970. static Array<UnitTest*> tests;
  13971. return tests;
  13972. }
  13973. void UnitTest::performTest (UnitTestRunner* const runner_)
  13974. {
  13975. jassert (runner_ != 0);
  13976. runner = runner_;
  13977. runTest();
  13978. }
  13979. void UnitTest::logMessage (const String& message)
  13980. {
  13981. runner->logMessage (message);
  13982. }
  13983. void UnitTest::beginTest (const String& testName)
  13984. {
  13985. runner->beginNewTest (this, testName);
  13986. }
  13987. void UnitTest::expect (const bool result, const String& failureMessage)
  13988. {
  13989. if (result)
  13990. runner->addPass();
  13991. else
  13992. runner->addFail (failureMessage);
  13993. }
  13994. UnitTestRunner::UnitTestRunner()
  13995. : currentTest (0), assertOnFailure (false)
  13996. {
  13997. }
  13998. UnitTestRunner::~UnitTestRunner()
  13999. {
  14000. }
  14001. void UnitTestRunner::resultsUpdated()
  14002. {
  14003. }
  14004. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14005. {
  14006. results.clear();
  14007. assertOnFailure = assertOnFailure_;
  14008. resultsUpdated();
  14009. for (int i = 0; i < tests.size(); ++i)
  14010. {
  14011. try
  14012. {
  14013. tests.getUnchecked(i)->performTest (this);
  14014. }
  14015. catch (...)
  14016. {
  14017. addFail ("An unhandled exception was thrown!");
  14018. }
  14019. }
  14020. endTest();
  14021. }
  14022. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14023. {
  14024. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14025. }
  14026. void UnitTestRunner::logMessage (const String& message)
  14027. {
  14028. Logger::writeToLog (message);
  14029. }
  14030. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14031. {
  14032. endTest();
  14033. currentTest = test;
  14034. TestResult* const r = new TestResult();
  14035. r->unitTestName = test->getName();
  14036. r->subcategoryName = subCategory;
  14037. r->passes = 0;
  14038. r->failures = 0;
  14039. results.add (r);
  14040. logMessage ("-----------------------------------------------------------------");
  14041. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14042. resultsUpdated();
  14043. }
  14044. void UnitTestRunner::endTest()
  14045. {
  14046. if (results.size() > 0)
  14047. {
  14048. TestResult* const r = results.getLast();
  14049. if (r->failures > 0)
  14050. {
  14051. String m ("FAILED!!");
  14052. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14053. << " failed, out of a total of " << (r->passes + r->failures);
  14054. logMessage (String::empty);
  14055. logMessage (m);
  14056. logMessage (String::empty);
  14057. }
  14058. else
  14059. {
  14060. logMessage ("All tests completed successfully");
  14061. }
  14062. }
  14063. }
  14064. void UnitTestRunner::addPass()
  14065. {
  14066. {
  14067. const ScopedLock sl (results.getLock());
  14068. TestResult* const r = results.getLast();
  14069. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14070. r->passes++;
  14071. String message ("Test ");
  14072. message << (r->failures + r->passes) << " passed";
  14073. logMessage (message);
  14074. }
  14075. resultsUpdated();
  14076. }
  14077. void UnitTestRunner::addFail (const String& failureMessage)
  14078. {
  14079. {
  14080. const ScopedLock sl (results.getLock());
  14081. TestResult* const r = results.getLast();
  14082. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14083. r->failures++;
  14084. String message ("!!! Test ");
  14085. message << (r->failures + r->passes) << " failed";
  14086. if (failureMessage.isNotEmpty())
  14087. message << ": " << failureMessage;
  14088. r->messages.add (message);
  14089. logMessage (message);
  14090. }
  14091. resultsUpdated();
  14092. if (assertOnFailure) { jassertfalse }
  14093. }
  14094. END_JUCE_NAMESPACE
  14095. /*** End of inlined file: juce_UnitTest.cpp ***/
  14096. #endif
  14097. #if JUCE_BUILD_MISC
  14098. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14099. BEGIN_JUCE_NAMESPACE
  14100. class ValueTree::SetPropertyAction : public UndoableAction
  14101. {
  14102. public:
  14103. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14104. const var& newValue_, const var& oldValue_,
  14105. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14106. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14107. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14108. {
  14109. }
  14110. ~SetPropertyAction() {}
  14111. bool perform()
  14112. {
  14113. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14114. if (isDeletingProperty)
  14115. target->removeProperty (name, 0);
  14116. else
  14117. target->setProperty (name, newValue, 0);
  14118. return true;
  14119. }
  14120. bool undo()
  14121. {
  14122. if (isAddingNewProperty)
  14123. target->removeProperty (name, 0);
  14124. else
  14125. target->setProperty (name, oldValue, 0);
  14126. return true;
  14127. }
  14128. int getSizeInUnits()
  14129. {
  14130. return (int) sizeof (*this); //xxx should be more accurate
  14131. }
  14132. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14133. {
  14134. if (! (isAddingNewProperty || isDeletingProperty))
  14135. {
  14136. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14137. if (next != 0 && next->target == target && next->name == name
  14138. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14139. {
  14140. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14141. }
  14142. }
  14143. return 0;
  14144. }
  14145. private:
  14146. const SharedObjectPtr target;
  14147. const Identifier name;
  14148. const var newValue;
  14149. var oldValue;
  14150. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14151. SetPropertyAction (const SetPropertyAction&);
  14152. SetPropertyAction& operator= (const SetPropertyAction&);
  14153. };
  14154. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14155. {
  14156. public:
  14157. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14158. const SharedObjectPtr& newChild_)
  14159. : target (target_),
  14160. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14161. childIndex (childIndex_),
  14162. isDeleting (newChild_ == 0)
  14163. {
  14164. jassert (child != 0);
  14165. }
  14166. ~AddOrRemoveChildAction() {}
  14167. bool perform()
  14168. {
  14169. if (isDeleting)
  14170. target->removeChild (childIndex, 0);
  14171. else
  14172. target->addChild (child, childIndex, 0);
  14173. return true;
  14174. }
  14175. bool undo()
  14176. {
  14177. if (isDeleting)
  14178. {
  14179. target->addChild (child, childIndex, 0);
  14180. }
  14181. else
  14182. {
  14183. // If you hit this, it seems that your object's state is getting confused - probably
  14184. // because you've interleaved some undoable and non-undoable operations?
  14185. jassert (childIndex < target->children.size());
  14186. target->removeChild (childIndex, 0);
  14187. }
  14188. return true;
  14189. }
  14190. int getSizeInUnits()
  14191. {
  14192. return (int) sizeof (*this); //xxx should be more accurate
  14193. }
  14194. private:
  14195. const SharedObjectPtr target, child;
  14196. const int childIndex;
  14197. const bool isDeleting;
  14198. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14199. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14200. };
  14201. class ValueTree::MoveChildAction : public UndoableAction
  14202. {
  14203. public:
  14204. MoveChildAction (const SharedObjectPtr& parent_,
  14205. const int startIndex_, const int endIndex_)
  14206. : parent (parent_),
  14207. startIndex (startIndex_),
  14208. endIndex (endIndex_)
  14209. {
  14210. }
  14211. ~MoveChildAction() {}
  14212. bool perform()
  14213. {
  14214. parent->moveChild (startIndex, endIndex, 0);
  14215. return true;
  14216. }
  14217. bool undo()
  14218. {
  14219. parent->moveChild (endIndex, startIndex, 0);
  14220. return true;
  14221. }
  14222. int getSizeInUnits()
  14223. {
  14224. return (int) sizeof (*this); //xxx should be more accurate
  14225. }
  14226. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14227. {
  14228. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14229. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14230. return new MoveChildAction (parent, startIndex, next->endIndex);
  14231. return 0;
  14232. }
  14233. private:
  14234. const SharedObjectPtr parent;
  14235. const int startIndex, endIndex;
  14236. MoveChildAction (const MoveChildAction&);
  14237. MoveChildAction& operator= (const MoveChildAction&);
  14238. };
  14239. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14240. : type (type_), parent (0)
  14241. {
  14242. }
  14243. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14244. : type (other.type), properties (other.properties), parent (0)
  14245. {
  14246. for (int i = 0; i < other.children.size(); ++i)
  14247. {
  14248. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14249. child->parent = this;
  14250. children.add (child);
  14251. }
  14252. }
  14253. ValueTree::SharedObject::~SharedObject()
  14254. {
  14255. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14256. for (int i = children.size(); --i >= 0;)
  14257. {
  14258. const SharedObjectPtr c (children.getUnchecked(i));
  14259. c->parent = 0;
  14260. children.remove (i);
  14261. c->sendParentChangeMessage();
  14262. }
  14263. }
  14264. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14265. {
  14266. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14267. {
  14268. ValueTree* const v = valueTreesWithListeners[i];
  14269. if (v != 0)
  14270. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14271. }
  14272. }
  14273. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14274. {
  14275. ValueTree tree (this);
  14276. ValueTree::SharedObject* t = this;
  14277. while (t != 0)
  14278. {
  14279. t->sendPropertyChangeMessage (tree, property);
  14280. t = t->parent;
  14281. }
  14282. }
  14283. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14284. {
  14285. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14286. {
  14287. ValueTree* const v = valueTreesWithListeners[i];
  14288. if (v != 0)
  14289. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14290. }
  14291. }
  14292. void ValueTree::SharedObject::sendChildChangeMessage()
  14293. {
  14294. ValueTree tree (this);
  14295. ValueTree::SharedObject* t = this;
  14296. while (t != 0)
  14297. {
  14298. t->sendChildChangeMessage (tree);
  14299. t = t->parent;
  14300. }
  14301. }
  14302. void ValueTree::SharedObject::sendParentChangeMessage()
  14303. {
  14304. ValueTree tree (this);
  14305. int i;
  14306. for (i = children.size(); --i >= 0;)
  14307. {
  14308. SharedObject* const t = children[i];
  14309. if (t != 0)
  14310. t->sendParentChangeMessage();
  14311. }
  14312. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14313. {
  14314. ValueTree* const v = valueTreesWithListeners[i];
  14315. if (v != 0)
  14316. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14317. }
  14318. }
  14319. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14320. {
  14321. return properties [name];
  14322. }
  14323. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14324. {
  14325. return properties.getWithDefault (name, defaultReturnValue);
  14326. }
  14327. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14328. {
  14329. if (undoManager == 0)
  14330. {
  14331. if (properties.set (name, newValue))
  14332. sendPropertyChangeMessage (name);
  14333. }
  14334. else
  14335. {
  14336. var* const existingValue = properties.getItem (name);
  14337. if (existingValue != 0)
  14338. {
  14339. if (*existingValue != newValue)
  14340. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14341. }
  14342. else
  14343. {
  14344. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14345. }
  14346. }
  14347. }
  14348. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14349. {
  14350. return properties.contains (name);
  14351. }
  14352. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14353. {
  14354. if (undoManager == 0)
  14355. {
  14356. if (properties.remove (name))
  14357. sendPropertyChangeMessage (name);
  14358. }
  14359. else
  14360. {
  14361. if (properties.contains (name))
  14362. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14363. }
  14364. }
  14365. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14366. {
  14367. if (undoManager == 0)
  14368. {
  14369. while (properties.size() > 0)
  14370. {
  14371. const Identifier name (properties.getName (properties.size() - 1));
  14372. properties.remove (name);
  14373. sendPropertyChangeMessage (name);
  14374. }
  14375. }
  14376. else
  14377. {
  14378. for (int i = properties.size(); --i >= 0;)
  14379. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14380. }
  14381. }
  14382. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14383. {
  14384. for (int i = 0; i < children.size(); ++i)
  14385. if (children.getUnchecked(i)->type == typeToMatch)
  14386. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14387. return ValueTree::invalid;
  14388. }
  14389. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14390. {
  14391. for (int i = 0; i < children.size(); ++i)
  14392. if (children.getUnchecked(i)->type == typeToMatch)
  14393. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14394. SharedObject* const newObject = new SharedObject (typeToMatch);
  14395. addChild (newObject, -1, undoManager);
  14396. return ValueTree (newObject);
  14397. }
  14398. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14399. {
  14400. for (int i = 0; i < children.size(); ++i)
  14401. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14402. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14403. return ValueTree::invalid;
  14404. }
  14405. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14406. {
  14407. const SharedObject* p = parent;
  14408. while (p != 0)
  14409. {
  14410. if (p == possibleParent)
  14411. return true;
  14412. p = p->parent;
  14413. }
  14414. return false;
  14415. }
  14416. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14417. {
  14418. return children.indexOf (child.object);
  14419. }
  14420. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14421. {
  14422. if (child != 0 && child->parent != this)
  14423. {
  14424. if (child != this && ! isAChildOf (child))
  14425. {
  14426. // You should always make sure that a child is removed from its previous parent before
  14427. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14428. // undomanager should be used when removing it from its current parent..
  14429. jassert (child->parent == 0);
  14430. if (child->parent != 0)
  14431. {
  14432. jassert (child->parent->children.indexOf (child) >= 0);
  14433. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14434. }
  14435. if (undoManager == 0)
  14436. {
  14437. children.insert (index, child);
  14438. child->parent = this;
  14439. sendChildChangeMessage();
  14440. child->sendParentChangeMessage();
  14441. }
  14442. else
  14443. {
  14444. if (index < 0)
  14445. index = children.size();
  14446. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14447. }
  14448. }
  14449. else
  14450. {
  14451. // You're attempting to create a recursive loop! A node
  14452. // can't be a child of one of its own children!
  14453. jassertfalse;
  14454. }
  14455. }
  14456. }
  14457. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14458. {
  14459. const SharedObjectPtr child (children [childIndex]);
  14460. if (child != 0)
  14461. {
  14462. if (undoManager == 0)
  14463. {
  14464. children.remove (childIndex);
  14465. child->parent = 0;
  14466. sendChildChangeMessage();
  14467. child->sendParentChangeMessage();
  14468. }
  14469. else
  14470. {
  14471. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14472. }
  14473. }
  14474. }
  14475. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14476. {
  14477. while (children.size() > 0)
  14478. removeChild (children.size() - 1, undoManager);
  14479. }
  14480. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14481. {
  14482. // The source index must be a valid index!
  14483. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14484. if (currentIndex != newIndex
  14485. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14486. {
  14487. if (undoManager == 0)
  14488. {
  14489. children.move (currentIndex, newIndex);
  14490. sendChildChangeMessage();
  14491. }
  14492. else
  14493. {
  14494. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14495. newIndex = children.size() - 1;
  14496. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14497. }
  14498. }
  14499. }
  14500. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14501. {
  14502. if (type != other.type
  14503. || properties.size() != other.properties.size()
  14504. || children.size() != other.children.size()
  14505. || properties != other.properties)
  14506. return false;
  14507. for (int i = 0; i < children.size(); ++i)
  14508. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14509. return false;
  14510. return true;
  14511. }
  14512. ValueTree::ValueTree() throw()
  14513. : object (0)
  14514. {
  14515. }
  14516. const ValueTree ValueTree::invalid;
  14517. ValueTree::ValueTree (const Identifier& type_)
  14518. : object (new ValueTree::SharedObject (type_))
  14519. {
  14520. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14521. }
  14522. ValueTree::ValueTree (SharedObject* const object_)
  14523. : object (object_)
  14524. {
  14525. }
  14526. ValueTree::ValueTree (const ValueTree& other)
  14527. : object (other.object)
  14528. {
  14529. }
  14530. ValueTree& ValueTree::operator= (const ValueTree& other)
  14531. {
  14532. if (listeners.size() > 0)
  14533. {
  14534. if (object != 0)
  14535. object->valueTreesWithListeners.removeValue (this);
  14536. if (other.object != 0)
  14537. other.object->valueTreesWithListeners.add (this);
  14538. }
  14539. object = other.object;
  14540. return *this;
  14541. }
  14542. ValueTree::~ValueTree()
  14543. {
  14544. if (listeners.size() > 0 && object != 0)
  14545. object->valueTreesWithListeners.removeValue (this);
  14546. }
  14547. bool ValueTree::operator== (const ValueTree& other) const throw()
  14548. {
  14549. return object == other.object;
  14550. }
  14551. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14552. {
  14553. return object != other.object;
  14554. }
  14555. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14556. {
  14557. return object == other.object
  14558. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14559. }
  14560. ValueTree ValueTree::createCopy() const
  14561. {
  14562. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14563. }
  14564. bool ValueTree::hasType (const Identifier& typeName) const
  14565. {
  14566. return object != 0 && object->type == typeName;
  14567. }
  14568. const Identifier ValueTree::getType() const
  14569. {
  14570. return object != 0 ? object->type : Identifier();
  14571. }
  14572. ValueTree ValueTree::getParent() const
  14573. {
  14574. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14575. }
  14576. ValueTree ValueTree::getSibling (const int delta) const
  14577. {
  14578. if (object == 0 || object->parent == 0)
  14579. return invalid;
  14580. const int index = object->parent->indexOf (*this) + delta;
  14581. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14582. }
  14583. const var& ValueTree::operator[] (const Identifier& name) const
  14584. {
  14585. return object == 0 ? var::null : object->getProperty (name);
  14586. }
  14587. const var& ValueTree::getProperty (const Identifier& name) const
  14588. {
  14589. return object == 0 ? var::null : object->getProperty (name);
  14590. }
  14591. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14592. {
  14593. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14594. }
  14595. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14596. {
  14597. jassert (name.toString().isNotEmpty());
  14598. if (object != 0 && name.toString().isNotEmpty())
  14599. object->setProperty (name, newValue, undoManager);
  14600. }
  14601. bool ValueTree::hasProperty (const Identifier& name) const
  14602. {
  14603. return object != 0 && object->hasProperty (name);
  14604. }
  14605. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14606. {
  14607. if (object != 0)
  14608. object->removeProperty (name, undoManager);
  14609. }
  14610. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14611. {
  14612. if (object != 0)
  14613. object->removeAllProperties (undoManager);
  14614. }
  14615. int ValueTree::getNumProperties() const
  14616. {
  14617. return object == 0 ? 0 : object->properties.size();
  14618. }
  14619. const Identifier ValueTree::getPropertyName (const int index) const
  14620. {
  14621. return object == 0 ? Identifier()
  14622. : object->properties.getName (index);
  14623. }
  14624. class ValueTreePropertyValueSource : public Value::ValueSource,
  14625. public ValueTree::Listener
  14626. {
  14627. public:
  14628. ValueTreePropertyValueSource (const ValueTree& tree_,
  14629. const Identifier& property_,
  14630. UndoManager* const undoManager_)
  14631. : tree (tree_),
  14632. property (property_),
  14633. undoManager (undoManager_)
  14634. {
  14635. tree.addListener (this);
  14636. }
  14637. ~ValueTreePropertyValueSource()
  14638. {
  14639. tree.removeListener (this);
  14640. }
  14641. const var getValue() const
  14642. {
  14643. return tree [property];
  14644. }
  14645. void setValue (const var& newValue)
  14646. {
  14647. tree.setProperty (property, newValue, undoManager);
  14648. }
  14649. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14650. {
  14651. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14652. sendChangeMessage (false);
  14653. }
  14654. void valueTreeChildrenChanged (ValueTree&) {}
  14655. void valueTreeParentChanged (ValueTree&) {}
  14656. private:
  14657. ValueTree tree;
  14658. const Identifier property;
  14659. UndoManager* const undoManager;
  14660. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14661. };
  14662. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14663. {
  14664. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14665. }
  14666. int ValueTree::getNumChildren() const
  14667. {
  14668. return object == 0 ? 0 : object->children.size();
  14669. }
  14670. ValueTree ValueTree::getChild (int index) const
  14671. {
  14672. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14673. }
  14674. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14675. {
  14676. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14677. }
  14678. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14679. {
  14680. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14681. }
  14682. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14683. {
  14684. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14685. }
  14686. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14687. {
  14688. return object != 0 && object->isAChildOf (possibleParent.object);
  14689. }
  14690. int ValueTree::indexOf (const ValueTree& child) const
  14691. {
  14692. return object != 0 ? object->indexOf (child) : -1;
  14693. }
  14694. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14695. {
  14696. if (object != 0)
  14697. object->addChild (child.object, index, undoManager);
  14698. }
  14699. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14700. {
  14701. if (object != 0)
  14702. object->removeChild (childIndex, undoManager);
  14703. }
  14704. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14705. {
  14706. if (object != 0)
  14707. object->removeChild (object->children.indexOf (child.object), undoManager);
  14708. }
  14709. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14710. {
  14711. if (object != 0)
  14712. object->removeAllChildren (undoManager);
  14713. }
  14714. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14715. {
  14716. if (object != 0)
  14717. object->moveChild (currentIndex, newIndex, undoManager);
  14718. }
  14719. void ValueTree::addListener (Listener* listener)
  14720. {
  14721. if (listener != 0)
  14722. {
  14723. if (listeners.size() == 0 && object != 0)
  14724. object->valueTreesWithListeners.add (this);
  14725. listeners.add (listener);
  14726. }
  14727. }
  14728. void ValueTree::removeListener (Listener* listener)
  14729. {
  14730. listeners.remove (listener);
  14731. if (listeners.size() == 0 && object != 0)
  14732. object->valueTreesWithListeners.removeValue (this);
  14733. }
  14734. XmlElement* ValueTree::SharedObject::createXml() const
  14735. {
  14736. XmlElement* xml = new XmlElement (type.toString());
  14737. int i;
  14738. for (i = 0; i < properties.size(); ++i)
  14739. {
  14740. Identifier name (properties.getName(i));
  14741. const var& v = properties [name];
  14742. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  14743. xml->setAttribute (name.toString(), v.toString());
  14744. }
  14745. for (i = 0; i < children.size(); ++i)
  14746. xml->addChildElement (children.getUnchecked(i)->createXml());
  14747. return xml;
  14748. }
  14749. XmlElement* ValueTree::createXml() const
  14750. {
  14751. return object != 0 ? object->createXml() : 0;
  14752. }
  14753. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14754. {
  14755. ValueTree v (xml.getTagName());
  14756. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  14757. for (int i = 0; i < numAtts; ++i)
  14758. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  14759. forEachXmlChildElement (xml, e)
  14760. {
  14761. v.addChild (fromXml (*e), -1, 0);
  14762. }
  14763. return v;
  14764. }
  14765. void ValueTree::writeToStream (OutputStream& output)
  14766. {
  14767. output.writeString (getType().toString());
  14768. const int numProps = getNumProperties();
  14769. output.writeCompressedInt (numProps);
  14770. int i;
  14771. for (i = 0; i < numProps; ++i)
  14772. {
  14773. const Identifier name (getPropertyName(i));
  14774. output.writeString (name.toString());
  14775. getProperty(name).writeToStream (output);
  14776. }
  14777. const int numChildren = getNumChildren();
  14778. output.writeCompressedInt (numChildren);
  14779. for (i = 0; i < numChildren; ++i)
  14780. getChild (i).writeToStream (output);
  14781. }
  14782. ValueTree ValueTree::readFromStream (InputStream& input)
  14783. {
  14784. const String type (input.readString());
  14785. if (type.isEmpty())
  14786. return ValueTree::invalid;
  14787. ValueTree v (type);
  14788. const int numProps = input.readCompressedInt();
  14789. if (numProps < 0)
  14790. {
  14791. jassertfalse; // trying to read corrupted data!
  14792. return v;
  14793. }
  14794. int i;
  14795. for (i = 0; i < numProps; ++i)
  14796. {
  14797. const String name (input.readString());
  14798. jassert (name.isNotEmpty());
  14799. const var value (var::readFromStream (input));
  14800. v.setProperty (name, value, 0);
  14801. }
  14802. const int numChildren = input.readCompressedInt();
  14803. for (i = 0; i < numChildren; ++i)
  14804. v.addChild (readFromStream (input), -1, 0);
  14805. return v;
  14806. }
  14807. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14808. {
  14809. MemoryInputStream in (data, numBytes, false);
  14810. return readFromStream (in);
  14811. }
  14812. END_JUCE_NAMESPACE
  14813. /*** End of inlined file: juce_ValueTree.cpp ***/
  14814. /*** Start of inlined file: juce_Value.cpp ***/
  14815. BEGIN_JUCE_NAMESPACE
  14816. Value::ValueSource::ValueSource()
  14817. {
  14818. }
  14819. Value::ValueSource::~ValueSource()
  14820. {
  14821. }
  14822. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14823. {
  14824. if (synchronous)
  14825. {
  14826. for (int i = valuesWithListeners.size(); --i >= 0;)
  14827. {
  14828. Value* const v = valuesWithListeners[i];
  14829. if (v != 0)
  14830. v->callListeners();
  14831. }
  14832. }
  14833. else
  14834. {
  14835. triggerAsyncUpdate();
  14836. }
  14837. }
  14838. void Value::ValueSource::handleAsyncUpdate()
  14839. {
  14840. sendChangeMessage (true);
  14841. }
  14842. class SimpleValueSource : public Value::ValueSource
  14843. {
  14844. public:
  14845. SimpleValueSource()
  14846. {
  14847. }
  14848. SimpleValueSource (const var& initialValue)
  14849. : value (initialValue)
  14850. {
  14851. }
  14852. ~SimpleValueSource()
  14853. {
  14854. }
  14855. const var getValue() const
  14856. {
  14857. return value;
  14858. }
  14859. void setValue (const var& newValue)
  14860. {
  14861. if (newValue != value)
  14862. {
  14863. value = newValue;
  14864. sendChangeMessage (false);
  14865. }
  14866. }
  14867. private:
  14868. var value;
  14869. SimpleValueSource (const SimpleValueSource&);
  14870. SimpleValueSource& operator= (const SimpleValueSource&);
  14871. };
  14872. Value::Value()
  14873. : value (new SimpleValueSource())
  14874. {
  14875. }
  14876. Value::Value (ValueSource* const value_)
  14877. : value (value_)
  14878. {
  14879. jassert (value_ != 0);
  14880. }
  14881. Value::Value (const var& initialValue)
  14882. : value (new SimpleValueSource (initialValue))
  14883. {
  14884. }
  14885. Value::Value (const Value& other)
  14886. : value (other.value)
  14887. {
  14888. }
  14889. Value& Value::operator= (const Value& other)
  14890. {
  14891. value = other.value;
  14892. return *this;
  14893. }
  14894. Value::~Value()
  14895. {
  14896. if (listeners.size() > 0)
  14897. value->valuesWithListeners.removeValue (this);
  14898. }
  14899. const var Value::getValue() const
  14900. {
  14901. return value->getValue();
  14902. }
  14903. Value::operator const var() const
  14904. {
  14905. return getValue();
  14906. }
  14907. void Value::setValue (const var& newValue)
  14908. {
  14909. value->setValue (newValue);
  14910. }
  14911. const String Value::toString() const
  14912. {
  14913. return value->getValue().toString();
  14914. }
  14915. Value& Value::operator= (const var& newValue)
  14916. {
  14917. value->setValue (newValue);
  14918. return *this;
  14919. }
  14920. void Value::referTo (const Value& valueToReferTo)
  14921. {
  14922. if (valueToReferTo.value != value)
  14923. {
  14924. if (listeners.size() > 0)
  14925. {
  14926. value->valuesWithListeners.removeValue (this);
  14927. valueToReferTo.value->valuesWithListeners.add (this);
  14928. }
  14929. value = valueToReferTo.value;
  14930. callListeners();
  14931. }
  14932. }
  14933. bool Value::refersToSameSourceAs (const Value& other) const
  14934. {
  14935. return value == other.value;
  14936. }
  14937. bool Value::operator== (const Value& other) const
  14938. {
  14939. return value == other.value || value->getValue() == other.getValue();
  14940. }
  14941. bool Value::operator!= (const Value& other) const
  14942. {
  14943. return value != other.value && value->getValue() != other.getValue();
  14944. }
  14945. void Value::addListener (Listener* const listener)
  14946. {
  14947. if (listener != 0)
  14948. {
  14949. if (listeners.size() == 0)
  14950. value->valuesWithListeners.add (this);
  14951. listeners.add (listener);
  14952. }
  14953. }
  14954. void Value::removeListener (Listener* const listener)
  14955. {
  14956. listeners.remove (listener);
  14957. if (listeners.size() == 0)
  14958. value->valuesWithListeners.removeValue (this);
  14959. }
  14960. void Value::callListeners()
  14961. {
  14962. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14963. listeners.call (&Value::Listener::valueChanged, v);
  14964. }
  14965. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14966. {
  14967. return stream << value.toString();
  14968. }
  14969. END_JUCE_NAMESPACE
  14970. /*** End of inlined file: juce_Value.cpp ***/
  14971. /*** Start of inlined file: juce_Application.cpp ***/
  14972. BEGIN_JUCE_NAMESPACE
  14973. #if JUCE_MAC
  14974. extern void juce_initialiseMacMainMenu();
  14975. #endif
  14976. JUCEApplication::JUCEApplication()
  14977. : appReturnValue (0),
  14978. stillInitialising (true)
  14979. {
  14980. jassert (isStandaloneApp() && appInstance == 0);
  14981. appInstance = this;
  14982. }
  14983. JUCEApplication::~JUCEApplication()
  14984. {
  14985. if (appLock != 0)
  14986. {
  14987. appLock->exit();
  14988. appLock = 0;
  14989. }
  14990. jassert (appInstance == this);
  14991. appInstance = 0;
  14992. }
  14993. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  14994. JUCEApplication* JUCEApplication::appInstance = 0;
  14995. bool JUCEApplication::moreThanOneInstanceAllowed()
  14996. {
  14997. return true;
  14998. }
  14999. void JUCEApplication::anotherInstanceStarted (const String&)
  15000. {
  15001. }
  15002. void JUCEApplication::systemRequestedQuit()
  15003. {
  15004. quit();
  15005. }
  15006. void JUCEApplication::quit()
  15007. {
  15008. MessageManager::getInstance()->stopDispatchLoop();
  15009. }
  15010. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15011. {
  15012. appReturnValue = newReturnValue;
  15013. }
  15014. void JUCEApplication::actionListenerCallback (const String& message)
  15015. {
  15016. if (message.startsWith (getApplicationName() + "/"))
  15017. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15018. }
  15019. void JUCEApplication::unhandledException (const std::exception*,
  15020. const String&,
  15021. const int)
  15022. {
  15023. jassertfalse;
  15024. }
  15025. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15026. const char* const sourceFile,
  15027. const int lineNumber)
  15028. {
  15029. if (appInstance != 0)
  15030. appInstance->unhandledException (e, sourceFile, lineNumber);
  15031. }
  15032. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15033. {
  15034. return 0;
  15035. }
  15036. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15037. {
  15038. commands.add (StandardApplicationCommandIDs::quit);
  15039. }
  15040. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15041. {
  15042. if (commandID == StandardApplicationCommandIDs::quit)
  15043. {
  15044. result.setInfo (TRANS("Quit"),
  15045. TRANS("Quits the application"),
  15046. "Application",
  15047. 0);
  15048. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15049. }
  15050. }
  15051. bool JUCEApplication::perform (const InvocationInfo& info)
  15052. {
  15053. if (info.commandID == StandardApplicationCommandIDs::quit)
  15054. {
  15055. systemRequestedQuit();
  15056. return true;
  15057. }
  15058. return false;
  15059. }
  15060. bool JUCEApplication::initialiseApp (const String& commandLine)
  15061. {
  15062. commandLineParameters = commandLine.trim();
  15063. #if ! JUCE_IOS
  15064. jassert (appLock == 0); // initialiseApp must only be called once!
  15065. if (! moreThanOneInstanceAllowed())
  15066. {
  15067. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15068. if (! appLock->enter(0))
  15069. {
  15070. appLock = 0;
  15071. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15072. DBG ("Another instance is running - quitting...");
  15073. return false;
  15074. }
  15075. }
  15076. #endif
  15077. // let the app do its setting-up..
  15078. initialise (commandLineParameters);
  15079. #if JUCE_MAC
  15080. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15081. #endif
  15082. // register for broadcast new app messages
  15083. MessageManager::getInstance()->registerBroadcastListener (this);
  15084. stillInitialising = false;
  15085. return true;
  15086. }
  15087. int JUCEApplication::shutdownApp()
  15088. {
  15089. jassert (appInstance == this);
  15090. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15091. JUCE_TRY
  15092. {
  15093. // give the app a chance to clean up..
  15094. shutdown();
  15095. }
  15096. JUCE_CATCH_EXCEPTION
  15097. return getApplicationReturnValue();
  15098. }
  15099. int JUCEApplication::main (const String& commandLine)
  15100. {
  15101. ScopedJuceInitialiser_GUI libraryInitialiser;
  15102. jassert (createInstance != 0);
  15103. const ScopedPointer<JUCEApplication> app (createInstance());
  15104. if (! app->initialiseApp (commandLine))
  15105. return 0;
  15106. JUCE_TRY
  15107. {
  15108. // loop until a quit message is received..
  15109. MessageManager::getInstance()->runDispatchLoop();
  15110. }
  15111. JUCE_CATCH_EXCEPTION
  15112. return app->shutdownApp();
  15113. }
  15114. #if JUCE_IOS
  15115. extern int juce_iOSMain (int argc, const char* argv[]);
  15116. #endif
  15117. #if ! JUCE_WINDOWS
  15118. extern const char* juce_Argv0;
  15119. #endif
  15120. int JUCEApplication::main (int argc, const char* argv[])
  15121. {
  15122. JUCE_AUTORELEASEPOOL
  15123. #if ! JUCE_WINDOWS
  15124. jassert (createInstance != 0);
  15125. juce_Argv0 = argv[0];
  15126. #endif
  15127. #if JUCE_IOS
  15128. return juce_iOSMain (argc, argv);
  15129. #else
  15130. String cmd;
  15131. for (int i = 1; i < argc; ++i)
  15132. cmd << argv[i] << ' ';
  15133. return JUCEApplication::main (cmd);
  15134. #endif
  15135. }
  15136. END_JUCE_NAMESPACE
  15137. /*** End of inlined file: juce_Application.cpp ***/
  15138. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15139. BEGIN_JUCE_NAMESPACE
  15140. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15141. : commandID (commandID_),
  15142. flags (0)
  15143. {
  15144. }
  15145. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15146. const String& description_,
  15147. const String& categoryName_,
  15148. const int flags_) throw()
  15149. {
  15150. shortName = shortName_;
  15151. description = description_;
  15152. categoryName = categoryName_;
  15153. flags = flags_;
  15154. }
  15155. void ApplicationCommandInfo::setActive (const bool b) throw()
  15156. {
  15157. if (b)
  15158. flags &= ~isDisabled;
  15159. else
  15160. flags |= isDisabled;
  15161. }
  15162. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15163. {
  15164. if (b)
  15165. flags |= isTicked;
  15166. else
  15167. flags &= ~isTicked;
  15168. }
  15169. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15170. {
  15171. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15172. }
  15173. END_JUCE_NAMESPACE
  15174. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15175. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15176. BEGIN_JUCE_NAMESPACE
  15177. ApplicationCommandManager::ApplicationCommandManager()
  15178. : firstTarget (0)
  15179. {
  15180. keyMappings = new KeyPressMappingSet (this);
  15181. Desktop::getInstance().addFocusChangeListener (this);
  15182. }
  15183. ApplicationCommandManager::~ApplicationCommandManager()
  15184. {
  15185. Desktop::getInstance().removeFocusChangeListener (this);
  15186. keyMappings = 0;
  15187. }
  15188. void ApplicationCommandManager::clearCommands()
  15189. {
  15190. commands.clear();
  15191. keyMappings->clearAllKeyPresses();
  15192. triggerAsyncUpdate();
  15193. }
  15194. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15195. {
  15196. // zero isn't a valid command ID!
  15197. jassert (newCommand.commandID != 0);
  15198. // the name isn't optional!
  15199. jassert (newCommand.shortName.isNotEmpty());
  15200. if (getCommandForID (newCommand.commandID) == 0)
  15201. {
  15202. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15203. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15204. commands.add (newInfo);
  15205. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15206. triggerAsyncUpdate();
  15207. }
  15208. else
  15209. {
  15210. // trying to re-register the same command with different parameters?
  15211. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15212. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15213. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15214. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15215. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15216. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15217. }
  15218. }
  15219. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15220. {
  15221. if (target != 0)
  15222. {
  15223. Array <CommandID> commandIDs;
  15224. target->getAllCommands (commandIDs);
  15225. for (int i = 0; i < commandIDs.size(); ++i)
  15226. {
  15227. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15228. target->getCommandInfo (info.commandID, info);
  15229. registerCommand (info);
  15230. }
  15231. }
  15232. }
  15233. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15234. {
  15235. for (int i = commands.size(); --i >= 0;)
  15236. {
  15237. if (commands.getUnchecked (i)->commandID == commandID)
  15238. {
  15239. commands.remove (i);
  15240. triggerAsyncUpdate();
  15241. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15242. for (int j = keys.size(); --j >= 0;)
  15243. keyMappings->removeKeyPress (keys.getReference (j));
  15244. }
  15245. }
  15246. }
  15247. void ApplicationCommandManager::commandStatusChanged()
  15248. {
  15249. triggerAsyncUpdate();
  15250. }
  15251. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15252. {
  15253. for (int i = commands.size(); --i >= 0;)
  15254. if (commands.getUnchecked(i)->commandID == commandID)
  15255. return commands.getUnchecked(i);
  15256. return 0;
  15257. }
  15258. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15259. {
  15260. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15261. return (ci != 0) ? ci->shortName : String::empty;
  15262. }
  15263. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15264. {
  15265. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15266. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15267. : String::empty;
  15268. }
  15269. const StringArray ApplicationCommandManager::getCommandCategories() const
  15270. {
  15271. StringArray s;
  15272. for (int i = 0; i < commands.size(); ++i)
  15273. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15274. return s;
  15275. }
  15276. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15277. {
  15278. Array <CommandID> results;
  15279. for (int i = 0; i < commands.size(); ++i)
  15280. if (commands.getUnchecked(i)->categoryName == categoryName)
  15281. results.add (commands.getUnchecked(i)->commandID);
  15282. return results;
  15283. }
  15284. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15285. {
  15286. ApplicationCommandTarget::InvocationInfo info (commandID);
  15287. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15288. return invoke (info, asynchronously);
  15289. }
  15290. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15291. {
  15292. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15293. // manager first..
  15294. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15295. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  15296. if (target == 0)
  15297. return false;
  15298. ApplicationCommandInfo commandInfo (0);
  15299. target->getCommandInfo (info_.commandID, commandInfo);
  15300. ApplicationCommandTarget::InvocationInfo info (info_);
  15301. info.commandFlags = commandInfo.flags;
  15302. sendListenerInvokeCallback (info);
  15303. const bool ok = target->invoke (info, asynchronously);
  15304. commandStatusChanged();
  15305. return ok;
  15306. }
  15307. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15308. {
  15309. return firstTarget != 0 ? firstTarget
  15310. : findDefaultComponentTarget();
  15311. }
  15312. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15313. {
  15314. firstTarget = newTarget;
  15315. }
  15316. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15317. ApplicationCommandInfo& upToDateInfo)
  15318. {
  15319. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15320. if (target == 0)
  15321. target = JUCEApplication::getInstance();
  15322. if (target != 0)
  15323. target = target->getTargetForCommand (commandID);
  15324. if (target != 0)
  15325. target->getCommandInfo (commandID, upToDateInfo);
  15326. return target;
  15327. }
  15328. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15329. {
  15330. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15331. if (target == 0 && c != 0)
  15332. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15333. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15334. return target;
  15335. }
  15336. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15337. {
  15338. Component* c = Component::getCurrentlyFocusedComponent();
  15339. if (c == 0)
  15340. {
  15341. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15342. if (activeWindow != 0)
  15343. {
  15344. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15345. if (c == 0)
  15346. c = activeWindow;
  15347. }
  15348. }
  15349. if (c == 0 && Process::isForegroundProcess())
  15350. {
  15351. // getting a bit desperate now - try all desktop comps..
  15352. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15353. {
  15354. ApplicationCommandTarget* const target
  15355. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15356. ->getPeer()->getLastFocusedSubcomponent());
  15357. if (target != 0)
  15358. return target;
  15359. }
  15360. }
  15361. if (c != 0)
  15362. {
  15363. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15364. // if we're focused on a ResizableWindow, chances are that it's the content
  15365. // component that really should get the event. And if not, the event will
  15366. // still be passed up to the top level window anyway, so let's send it to the
  15367. // content comp.
  15368. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15369. c = resizableWindow->getContentComponent();
  15370. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15371. if (target != 0)
  15372. return target;
  15373. }
  15374. return JUCEApplication::getInstance();
  15375. }
  15376. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15377. {
  15378. listeners.add (listener);
  15379. }
  15380. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15381. {
  15382. listeners.remove (listener);
  15383. }
  15384. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15385. {
  15386. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15387. }
  15388. void ApplicationCommandManager::handleAsyncUpdate()
  15389. {
  15390. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15391. }
  15392. void ApplicationCommandManager::globalFocusChanged (Component*)
  15393. {
  15394. commandStatusChanged();
  15395. }
  15396. END_JUCE_NAMESPACE
  15397. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15398. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15399. BEGIN_JUCE_NAMESPACE
  15400. ApplicationCommandTarget::ApplicationCommandTarget()
  15401. {
  15402. }
  15403. ApplicationCommandTarget::~ApplicationCommandTarget()
  15404. {
  15405. messageInvoker = 0;
  15406. }
  15407. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15408. {
  15409. if (isCommandActive (info.commandID))
  15410. {
  15411. if (async)
  15412. {
  15413. if (messageInvoker == 0)
  15414. messageInvoker = new CommandTargetMessageInvoker (this);
  15415. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15416. return true;
  15417. }
  15418. else
  15419. {
  15420. const bool success = perform (info);
  15421. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15422. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15423. // returns the command's info.
  15424. return success;
  15425. }
  15426. }
  15427. return false;
  15428. }
  15429. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15430. {
  15431. Component* c = dynamic_cast <Component*> (this);
  15432. if (c != 0)
  15433. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15434. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15435. return 0;
  15436. }
  15437. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15438. {
  15439. ApplicationCommandTarget* target = this;
  15440. int depth = 0;
  15441. while (target != 0)
  15442. {
  15443. Array <CommandID> commandIDs;
  15444. target->getAllCommands (commandIDs);
  15445. if (commandIDs.contains (commandID))
  15446. return target;
  15447. target = target->getNextCommandTarget();
  15448. ++depth;
  15449. jassert (depth < 100); // could be a recursive command chain??
  15450. jassert (target != this); // definitely a recursive command chain!
  15451. if (depth > 100 || target == this)
  15452. break;
  15453. }
  15454. if (target == 0)
  15455. {
  15456. target = JUCEApplication::getInstance();
  15457. if (target != 0)
  15458. {
  15459. Array <CommandID> commandIDs;
  15460. target->getAllCommands (commandIDs);
  15461. if (commandIDs.contains (commandID))
  15462. return target;
  15463. }
  15464. }
  15465. return 0;
  15466. }
  15467. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15468. {
  15469. ApplicationCommandInfo info (commandID);
  15470. info.flags = ApplicationCommandInfo::isDisabled;
  15471. getCommandInfo (commandID, info);
  15472. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15473. }
  15474. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15475. {
  15476. ApplicationCommandTarget* target = this;
  15477. int depth = 0;
  15478. while (target != 0)
  15479. {
  15480. if (target->tryToInvoke (info, async))
  15481. return true;
  15482. target = target->getNextCommandTarget();
  15483. ++depth;
  15484. jassert (depth < 100); // could be a recursive command chain??
  15485. jassert (target != this); // definitely a recursive command chain!
  15486. if (depth > 100 || target == this)
  15487. break;
  15488. }
  15489. if (target == 0)
  15490. {
  15491. target = JUCEApplication::getInstance();
  15492. if (target != 0)
  15493. return target->tryToInvoke (info, async);
  15494. }
  15495. return false;
  15496. }
  15497. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15498. {
  15499. ApplicationCommandTarget::InvocationInfo info (commandID);
  15500. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15501. return invoke (info, asynchronously);
  15502. }
  15503. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15504. : commandID (commandID_),
  15505. commandFlags (0),
  15506. invocationMethod (direct),
  15507. originatingComponent (0),
  15508. isKeyDown (false),
  15509. millisecsSinceKeyPressed (0)
  15510. {
  15511. }
  15512. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15513. : owner (owner_)
  15514. {
  15515. }
  15516. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15517. {
  15518. }
  15519. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15520. {
  15521. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15522. owner->tryToInvoke (*info, false);
  15523. }
  15524. END_JUCE_NAMESPACE
  15525. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15526. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15527. BEGIN_JUCE_NAMESPACE
  15528. juce_ImplementSingleton (ApplicationProperties)
  15529. ApplicationProperties::ApplicationProperties()
  15530. : msBeforeSaving (3000),
  15531. options (PropertiesFile::storeAsBinary),
  15532. commonSettingsAreReadOnly (0),
  15533. processLock (0)
  15534. {
  15535. }
  15536. ApplicationProperties::~ApplicationProperties()
  15537. {
  15538. closeFiles();
  15539. clearSingletonInstance();
  15540. }
  15541. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15542. const String& fileNameSuffix,
  15543. const String& folderName_,
  15544. const int millisecondsBeforeSaving,
  15545. const int propertiesFileOptions,
  15546. InterProcessLock* processLock_)
  15547. {
  15548. appName = applicationName;
  15549. fileSuffix = fileNameSuffix;
  15550. folderName = folderName_;
  15551. msBeforeSaving = millisecondsBeforeSaving;
  15552. options = propertiesFileOptions;
  15553. processLock = processLock_;
  15554. }
  15555. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15556. const bool testCommonSettings,
  15557. const bool showWarningDialogOnFailure)
  15558. {
  15559. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15560. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15561. if (! (userOk && commonOk))
  15562. {
  15563. if (showWarningDialogOnFailure)
  15564. {
  15565. String filenames;
  15566. if (userProps != 0 && ! userOk)
  15567. filenames << '\n' << userProps->getFile().getFullPathName();
  15568. if (commonProps != 0 && ! commonOk)
  15569. filenames << '\n' << commonProps->getFile().getFullPathName();
  15570. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15571. appName + TRANS(" - Unable to save settings"),
  15572. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15573. + appName + TRANS(" needs to be able to write to the following files:\n")
  15574. + filenames
  15575. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15576. }
  15577. return false;
  15578. }
  15579. return true;
  15580. }
  15581. void ApplicationProperties::openFiles()
  15582. {
  15583. // You need to call setStorageParameters() before trying to get hold of the
  15584. // properties!
  15585. jassert (appName.isNotEmpty());
  15586. if (appName.isNotEmpty())
  15587. {
  15588. if (userProps == 0)
  15589. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15590. false, msBeforeSaving, options, processLock);
  15591. if (commonProps == 0)
  15592. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15593. true, msBeforeSaving, options, processLock);
  15594. userProps->setFallbackPropertySet (commonProps);
  15595. }
  15596. }
  15597. PropertiesFile* ApplicationProperties::getUserSettings()
  15598. {
  15599. if (userProps == 0)
  15600. openFiles();
  15601. return userProps;
  15602. }
  15603. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15604. {
  15605. if (commonProps == 0)
  15606. openFiles();
  15607. if (returnUserPropsIfReadOnly)
  15608. {
  15609. if (commonSettingsAreReadOnly == 0)
  15610. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15611. if (commonSettingsAreReadOnly > 0)
  15612. return userProps;
  15613. }
  15614. return commonProps;
  15615. }
  15616. bool ApplicationProperties::saveIfNeeded()
  15617. {
  15618. return (userProps == 0 || userProps->saveIfNeeded())
  15619. && (commonProps == 0 || commonProps->saveIfNeeded());
  15620. }
  15621. void ApplicationProperties::closeFiles()
  15622. {
  15623. userProps = 0;
  15624. commonProps = 0;
  15625. }
  15626. END_JUCE_NAMESPACE
  15627. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15628. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15629. BEGIN_JUCE_NAMESPACE
  15630. namespace PropertyFileConstants
  15631. {
  15632. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15633. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15634. static const char* const fileTag = "PROPERTIES";
  15635. static const char* const valueTag = "VALUE";
  15636. static const char* const nameAttribute = "name";
  15637. static const char* const valueAttribute = "val";
  15638. }
  15639. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15640. const int options_, InterProcessLock* const processLock_)
  15641. : PropertySet (ignoreCaseOfKeyNames),
  15642. file (f),
  15643. timerInterval (millisecondsBeforeSaving),
  15644. options (options_),
  15645. loadedOk (false),
  15646. needsWriting (false),
  15647. processLock (processLock_)
  15648. {
  15649. // You need to correctly specify just one storage format for the file
  15650. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15651. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15652. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15653. ProcessScopedLock pl (createProcessLock());
  15654. if (pl != 0 && ! pl->isLocked())
  15655. return; // locking failure..
  15656. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15657. if (fileStream != 0)
  15658. {
  15659. int magicNumber = fileStream->readInt();
  15660. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15661. {
  15662. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15663. magicNumber = PropertyFileConstants::magicNumber;
  15664. }
  15665. if (magicNumber == PropertyFileConstants::magicNumber)
  15666. {
  15667. loadedOk = true;
  15668. BufferedInputStream in (fileStream.release(), 2048, true);
  15669. int numValues = in.readInt();
  15670. while (--numValues >= 0 && ! in.isExhausted())
  15671. {
  15672. const String key (in.readString());
  15673. const String value (in.readString());
  15674. jassert (key.isNotEmpty());
  15675. if (key.isNotEmpty())
  15676. getAllProperties().set (key, value);
  15677. }
  15678. }
  15679. else
  15680. {
  15681. // Not a binary props file - let's see if it's XML..
  15682. fileStream = 0;
  15683. XmlDocument parser (f);
  15684. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15685. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15686. {
  15687. doc = parser.getDocumentElement();
  15688. if (doc != 0)
  15689. {
  15690. loadedOk = true;
  15691. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15692. {
  15693. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15694. if (name.isNotEmpty())
  15695. {
  15696. getAllProperties().set (name,
  15697. e->getFirstChildElement() != 0
  15698. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15699. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15700. }
  15701. }
  15702. }
  15703. else
  15704. {
  15705. // must be a pretty broken XML file we're trying to parse here,
  15706. // or a sign that this object needs an InterProcessLock,
  15707. // or just a failure reading the file. This last reason is why
  15708. // we don't jassertfalse here.
  15709. }
  15710. }
  15711. }
  15712. }
  15713. else
  15714. {
  15715. loadedOk = ! f.exists();
  15716. }
  15717. }
  15718. PropertiesFile::~PropertiesFile()
  15719. {
  15720. if (! saveIfNeeded())
  15721. jassertfalse;
  15722. }
  15723. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15724. {
  15725. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15726. }
  15727. bool PropertiesFile::saveIfNeeded()
  15728. {
  15729. const ScopedLock sl (getLock());
  15730. return (! needsWriting) || save();
  15731. }
  15732. bool PropertiesFile::needsToBeSaved() const
  15733. {
  15734. const ScopedLock sl (getLock());
  15735. return needsWriting;
  15736. }
  15737. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15738. {
  15739. const ScopedLock sl (getLock());
  15740. needsWriting = needsToBeSaved_;
  15741. }
  15742. bool PropertiesFile::save()
  15743. {
  15744. const ScopedLock sl (getLock());
  15745. stopTimer();
  15746. if (file == File::nonexistent
  15747. || file.isDirectory()
  15748. || ! file.getParentDirectory().createDirectory())
  15749. return false;
  15750. if ((options & storeAsXML) != 0)
  15751. {
  15752. XmlElement doc (PropertyFileConstants::fileTag);
  15753. for (int i = 0; i < getAllProperties().size(); ++i)
  15754. {
  15755. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15756. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15757. // if the value seems to contain xml, store it as such..
  15758. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  15759. XmlElement* const childElement = xmlContent.getDocumentElement();
  15760. if (childElement != 0)
  15761. e->addChildElement (childElement);
  15762. else
  15763. e->setAttribute (PropertyFileConstants::valueAttribute,
  15764. getAllProperties().getAllValues() [i]);
  15765. }
  15766. ProcessScopedLock pl (createProcessLock());
  15767. if (pl != 0 && ! pl->isLocked())
  15768. return false; // locking failure..
  15769. if (doc.writeToFile (file, String::empty))
  15770. {
  15771. needsWriting = false;
  15772. return true;
  15773. }
  15774. }
  15775. else
  15776. {
  15777. ProcessScopedLock pl (createProcessLock());
  15778. if (pl != 0 && ! pl->isLocked())
  15779. return false; // locking failure..
  15780. TemporaryFile tempFile (file);
  15781. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15782. if (out != 0)
  15783. {
  15784. if ((options & storeAsCompressedBinary) != 0)
  15785. {
  15786. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15787. out->flush();
  15788. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15789. }
  15790. else
  15791. {
  15792. // have you set up the storage option flags correctly?
  15793. jassert ((options & storeAsBinary) != 0);
  15794. out->writeInt (PropertyFileConstants::magicNumber);
  15795. }
  15796. const int numProperties = getAllProperties().size();
  15797. out->writeInt (numProperties);
  15798. for (int i = 0; i < numProperties; ++i)
  15799. {
  15800. out->writeString (getAllProperties().getAllKeys() [i]);
  15801. out->writeString (getAllProperties().getAllValues() [i]);
  15802. }
  15803. out = 0;
  15804. if (tempFile.overwriteTargetFileWithTemporary())
  15805. {
  15806. needsWriting = false;
  15807. return true;
  15808. }
  15809. }
  15810. }
  15811. return false;
  15812. }
  15813. void PropertiesFile::timerCallback()
  15814. {
  15815. saveIfNeeded();
  15816. }
  15817. void PropertiesFile::propertyChanged()
  15818. {
  15819. sendChangeMessage (this);
  15820. needsWriting = true;
  15821. if (timerInterval > 0)
  15822. startTimer (timerInterval);
  15823. else if (timerInterval == 0)
  15824. saveIfNeeded();
  15825. }
  15826. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15827. const String& fileNameSuffix,
  15828. const String& folderName,
  15829. const bool commonToAllUsers)
  15830. {
  15831. // mustn't have illegal characters in this name..
  15832. jassert (applicationName == File::createLegalFileName (applicationName));
  15833. #if JUCE_MAC || JUCE_IOS
  15834. File dir (commonToAllUsers ? "/Library/Preferences"
  15835. : "~/Library/Preferences");
  15836. if (folderName.isNotEmpty())
  15837. dir = dir.getChildFile (folderName);
  15838. #endif
  15839. #ifdef JUCE_LINUX
  15840. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15841. + (folderName.isNotEmpty() ? folderName
  15842. : ("." + applicationName)));
  15843. #endif
  15844. #if JUCE_WINDOWS
  15845. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15846. : File::userApplicationDataDirectory));
  15847. if (dir == File::nonexistent)
  15848. return File::nonexistent;
  15849. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15850. : applicationName);
  15851. #endif
  15852. return dir.getChildFile (applicationName)
  15853. .withFileExtension (fileNameSuffix);
  15854. }
  15855. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15856. const String& fileNameSuffix,
  15857. const String& folderName,
  15858. const bool commonToAllUsers,
  15859. const int millisecondsBeforeSaving,
  15860. const int propertiesFileOptions,
  15861. InterProcessLock* processLock_)
  15862. {
  15863. const File file (getDefaultAppSettingsFile (applicationName,
  15864. fileNameSuffix,
  15865. folderName,
  15866. commonToAllUsers));
  15867. jassert (file != File::nonexistent);
  15868. if (file == File::nonexistent)
  15869. return 0;
  15870. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15871. }
  15872. END_JUCE_NAMESPACE
  15873. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15874. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15875. BEGIN_JUCE_NAMESPACE
  15876. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15877. const String& fileWildcard_,
  15878. const String& openFileDialogTitle_,
  15879. const String& saveFileDialogTitle_)
  15880. : changedSinceSave (false),
  15881. fileExtension (fileExtension_),
  15882. fileWildcard (fileWildcard_),
  15883. openFileDialogTitle (openFileDialogTitle_),
  15884. saveFileDialogTitle (saveFileDialogTitle_)
  15885. {
  15886. }
  15887. FileBasedDocument::~FileBasedDocument()
  15888. {
  15889. }
  15890. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15891. {
  15892. if (changedSinceSave != hasChanged)
  15893. {
  15894. changedSinceSave = hasChanged;
  15895. sendChangeMessage (this);
  15896. }
  15897. }
  15898. void FileBasedDocument::changed()
  15899. {
  15900. changedSinceSave = true;
  15901. sendChangeMessage (this);
  15902. }
  15903. void FileBasedDocument::setFile (const File& newFile)
  15904. {
  15905. if (documentFile != newFile)
  15906. {
  15907. documentFile = newFile;
  15908. changed();
  15909. }
  15910. }
  15911. bool FileBasedDocument::loadFrom (const File& newFile,
  15912. const bool showMessageOnFailure)
  15913. {
  15914. MouseCursor::showWaitCursor();
  15915. const File oldFile (documentFile);
  15916. documentFile = newFile;
  15917. String error;
  15918. if (newFile.existsAsFile())
  15919. {
  15920. error = loadDocument (newFile);
  15921. if (error.isEmpty())
  15922. {
  15923. setChangedFlag (false);
  15924. MouseCursor::hideWaitCursor();
  15925. setLastDocumentOpened (newFile);
  15926. return true;
  15927. }
  15928. }
  15929. else
  15930. {
  15931. error = "The file doesn't exist";
  15932. }
  15933. documentFile = oldFile;
  15934. MouseCursor::hideWaitCursor();
  15935. if (showMessageOnFailure)
  15936. {
  15937. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15938. TRANS("Failed to open file..."),
  15939. TRANS("There was an error while trying to load the file:\n\n")
  15940. + newFile.getFullPathName()
  15941. + "\n\n"
  15942. + error);
  15943. }
  15944. return false;
  15945. }
  15946. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15947. {
  15948. FileChooser fc (openFileDialogTitle,
  15949. getLastDocumentOpened(),
  15950. fileWildcard);
  15951. if (fc.browseForFileToOpen())
  15952. return loadFrom (fc.getResult(), showMessageOnFailure);
  15953. return false;
  15954. }
  15955. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15956. const bool showMessageOnFailure)
  15957. {
  15958. return saveAs (documentFile,
  15959. false,
  15960. askUserForFileIfNotSpecified,
  15961. showMessageOnFailure);
  15962. }
  15963. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  15964. const bool warnAboutOverwritingExistingFiles,
  15965. const bool askUserForFileIfNotSpecified,
  15966. const bool showMessageOnFailure)
  15967. {
  15968. if (newFile == File::nonexistent)
  15969. {
  15970. if (askUserForFileIfNotSpecified)
  15971. {
  15972. return saveAsInteractive (true);
  15973. }
  15974. else
  15975. {
  15976. // can't save to an unspecified file
  15977. jassertfalse;
  15978. return failedToWriteToFile;
  15979. }
  15980. }
  15981. if (warnAboutOverwritingExistingFiles && newFile.exists())
  15982. {
  15983. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15984. TRANS("File already exists"),
  15985. TRANS("There's already a file called:\n\n")
  15986. + newFile.getFullPathName()
  15987. + TRANS("\n\nAre you sure you want to overwrite it?"),
  15988. TRANS("overwrite"),
  15989. TRANS("cancel")))
  15990. {
  15991. return userCancelledSave;
  15992. }
  15993. }
  15994. MouseCursor::showWaitCursor();
  15995. const File oldFile (documentFile);
  15996. documentFile = newFile;
  15997. String error (saveDocument (newFile));
  15998. if (error.isEmpty())
  15999. {
  16000. setChangedFlag (false);
  16001. MouseCursor::hideWaitCursor();
  16002. return savedOk;
  16003. }
  16004. documentFile = oldFile;
  16005. MouseCursor::hideWaitCursor();
  16006. if (showMessageOnFailure)
  16007. {
  16008. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16009. TRANS("Error writing to file..."),
  16010. TRANS("An error occurred while trying to save \"")
  16011. + getDocumentTitle()
  16012. + TRANS("\" to the file:\n\n")
  16013. + newFile.getFullPathName()
  16014. + "\n\n"
  16015. + error);
  16016. }
  16017. return failedToWriteToFile;
  16018. }
  16019. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16020. {
  16021. if (! hasChangedSinceSaved())
  16022. return savedOk;
  16023. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16024. TRANS("Closing document..."),
  16025. TRANS("Do you want to save the changes to \"")
  16026. + getDocumentTitle() + "\"?",
  16027. TRANS("save"),
  16028. TRANS("discard changes"),
  16029. TRANS("cancel"));
  16030. if (r == 1)
  16031. {
  16032. // save changes
  16033. return save (true, true);
  16034. }
  16035. else if (r == 2)
  16036. {
  16037. // discard changes
  16038. return savedOk;
  16039. }
  16040. return userCancelledSave;
  16041. }
  16042. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16043. {
  16044. File f;
  16045. if (documentFile.existsAsFile())
  16046. f = documentFile;
  16047. else
  16048. f = getLastDocumentOpened();
  16049. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16050. if (legalFilename.isEmpty())
  16051. legalFilename = "unnamed";
  16052. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16053. f = f.getSiblingFile (legalFilename);
  16054. else
  16055. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16056. f = f.withFileExtension (fileExtension)
  16057. .getNonexistentSibling (true);
  16058. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16059. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16060. {
  16061. File chosen (fc.getResult());
  16062. if (chosen.getFileExtension().isEmpty())
  16063. {
  16064. chosen = chosen.withFileExtension (fileExtension);
  16065. if (chosen.exists())
  16066. {
  16067. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16068. TRANS("File already exists"),
  16069. TRANS("There's already a file called:")
  16070. + "\n\n" + chosen.getFullPathName()
  16071. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16072. TRANS("overwrite"),
  16073. TRANS("cancel")))
  16074. {
  16075. return userCancelledSave;
  16076. }
  16077. }
  16078. }
  16079. setLastDocumentOpened (chosen);
  16080. return saveAs (chosen, false, false, true);
  16081. }
  16082. return userCancelledSave;
  16083. }
  16084. END_JUCE_NAMESPACE
  16085. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16086. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16087. BEGIN_JUCE_NAMESPACE
  16088. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16089. : maxNumberOfItems (10)
  16090. {
  16091. }
  16092. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16093. {
  16094. }
  16095. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16096. {
  16097. maxNumberOfItems = jmax (1, newMaxNumber);
  16098. while (getNumFiles() > maxNumberOfItems)
  16099. files.remove (getNumFiles() - 1);
  16100. }
  16101. int RecentlyOpenedFilesList::getNumFiles() const
  16102. {
  16103. return files.size();
  16104. }
  16105. const File RecentlyOpenedFilesList::getFile (const int index) const
  16106. {
  16107. return File (files [index]);
  16108. }
  16109. void RecentlyOpenedFilesList::clear()
  16110. {
  16111. files.clear();
  16112. }
  16113. void RecentlyOpenedFilesList::addFile (const File& file)
  16114. {
  16115. const String path (file.getFullPathName());
  16116. files.removeString (path, true);
  16117. files.insert (0, path);
  16118. setMaxNumberOfItems (maxNumberOfItems);
  16119. }
  16120. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16121. {
  16122. for (int i = getNumFiles(); --i >= 0;)
  16123. if (! getFile(i).exists())
  16124. files.remove (i);
  16125. }
  16126. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16127. const int baseItemId,
  16128. const bool showFullPaths,
  16129. const bool dontAddNonExistentFiles,
  16130. const File** filesToAvoid)
  16131. {
  16132. int num = 0;
  16133. for (int i = 0; i < getNumFiles(); ++i)
  16134. {
  16135. const File f (getFile(i));
  16136. if ((! dontAddNonExistentFiles) || f.exists())
  16137. {
  16138. bool needsAvoiding = false;
  16139. if (filesToAvoid != 0)
  16140. {
  16141. const File** avoid = filesToAvoid;
  16142. while (*avoid != 0)
  16143. {
  16144. if (f == **avoid)
  16145. {
  16146. needsAvoiding = true;
  16147. break;
  16148. }
  16149. ++avoid;
  16150. }
  16151. }
  16152. if (! needsAvoiding)
  16153. {
  16154. menuToAddTo.addItem (baseItemId + i,
  16155. showFullPaths ? f.getFullPathName()
  16156. : f.getFileName());
  16157. ++num;
  16158. }
  16159. }
  16160. }
  16161. return num;
  16162. }
  16163. const String RecentlyOpenedFilesList::toString() const
  16164. {
  16165. return files.joinIntoString ("\n");
  16166. }
  16167. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16168. {
  16169. clear();
  16170. files.addLines (stringifiedVersion);
  16171. setMaxNumberOfItems (maxNumberOfItems);
  16172. }
  16173. END_JUCE_NAMESPACE
  16174. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16175. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16176. BEGIN_JUCE_NAMESPACE
  16177. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16178. const int minimumTransactions)
  16179. : totalUnitsStored (0),
  16180. nextIndex (0),
  16181. newTransaction (true),
  16182. reentrancyCheck (false)
  16183. {
  16184. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16185. minimumTransactions);
  16186. }
  16187. UndoManager::~UndoManager()
  16188. {
  16189. clearUndoHistory();
  16190. }
  16191. void UndoManager::clearUndoHistory()
  16192. {
  16193. transactions.clear();
  16194. transactionNames.clear();
  16195. totalUnitsStored = 0;
  16196. nextIndex = 0;
  16197. sendChangeMessage (this);
  16198. }
  16199. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16200. {
  16201. return totalUnitsStored;
  16202. }
  16203. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16204. const int minimumTransactions)
  16205. {
  16206. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16207. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16208. }
  16209. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16210. {
  16211. if (command_ != 0)
  16212. {
  16213. ScopedPointer<UndoableAction> command (command_);
  16214. if (actionName.isNotEmpty())
  16215. currentTransactionName = actionName;
  16216. if (reentrancyCheck)
  16217. {
  16218. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16219. // undo() methods, or else these actions won't actually get done.
  16220. return false;
  16221. }
  16222. else if (command->perform())
  16223. {
  16224. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16225. if (commandSet != 0 && ! newTransaction)
  16226. {
  16227. UndoableAction* lastAction = commandSet->getLast();
  16228. if (lastAction != 0)
  16229. {
  16230. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16231. if (coalescedAction != 0)
  16232. {
  16233. command = coalescedAction;
  16234. totalUnitsStored -= lastAction->getSizeInUnits();
  16235. commandSet->removeLast();
  16236. }
  16237. }
  16238. }
  16239. else
  16240. {
  16241. commandSet = new OwnedArray<UndoableAction>();
  16242. transactions.insert (nextIndex, commandSet);
  16243. transactionNames.insert (nextIndex, currentTransactionName);
  16244. ++nextIndex;
  16245. }
  16246. totalUnitsStored += command->getSizeInUnits();
  16247. commandSet->add (command.release());
  16248. newTransaction = false;
  16249. while (nextIndex < transactions.size())
  16250. {
  16251. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16252. for (int i = lastSet->size(); --i >= 0;)
  16253. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16254. transactions.removeLast();
  16255. transactionNames.remove (transactionNames.size() - 1);
  16256. }
  16257. while (nextIndex > 0
  16258. && totalUnitsStored > maxNumUnitsToKeep
  16259. && transactions.size() > minimumTransactionsToKeep)
  16260. {
  16261. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16262. for (int i = firstSet->size(); --i >= 0;)
  16263. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16264. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16265. transactions.remove (0);
  16266. transactionNames.remove (0);
  16267. --nextIndex;
  16268. }
  16269. sendChangeMessage (this);
  16270. return true;
  16271. }
  16272. }
  16273. return false;
  16274. }
  16275. void UndoManager::beginNewTransaction (const String& actionName)
  16276. {
  16277. newTransaction = true;
  16278. currentTransactionName = actionName;
  16279. }
  16280. void UndoManager::setCurrentTransactionName (const String& newName)
  16281. {
  16282. currentTransactionName = newName;
  16283. }
  16284. bool UndoManager::canUndo() const
  16285. {
  16286. return nextIndex > 0;
  16287. }
  16288. bool UndoManager::canRedo() const
  16289. {
  16290. return nextIndex < transactions.size();
  16291. }
  16292. const String UndoManager::getUndoDescription() const
  16293. {
  16294. return transactionNames [nextIndex - 1];
  16295. }
  16296. const String UndoManager::getRedoDescription() const
  16297. {
  16298. return transactionNames [nextIndex];
  16299. }
  16300. bool UndoManager::undo()
  16301. {
  16302. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16303. if (commandSet == 0)
  16304. return false;
  16305. reentrancyCheck = true;
  16306. bool failed = false;
  16307. for (int i = commandSet->size(); --i >= 0;)
  16308. {
  16309. if (! commandSet->getUnchecked(i)->undo())
  16310. {
  16311. jassertfalse;
  16312. failed = true;
  16313. break;
  16314. }
  16315. }
  16316. reentrancyCheck = false;
  16317. if (failed)
  16318. clearUndoHistory();
  16319. else
  16320. --nextIndex;
  16321. beginNewTransaction();
  16322. sendChangeMessage (this);
  16323. return true;
  16324. }
  16325. bool UndoManager::redo()
  16326. {
  16327. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16328. if (commandSet == 0)
  16329. return false;
  16330. reentrancyCheck = true;
  16331. bool failed = false;
  16332. for (int i = 0; i < commandSet->size(); ++i)
  16333. {
  16334. if (! commandSet->getUnchecked(i)->perform())
  16335. {
  16336. jassertfalse;
  16337. failed = true;
  16338. break;
  16339. }
  16340. }
  16341. reentrancyCheck = false;
  16342. if (failed)
  16343. clearUndoHistory();
  16344. else
  16345. ++nextIndex;
  16346. beginNewTransaction();
  16347. sendChangeMessage (this);
  16348. return true;
  16349. }
  16350. bool UndoManager::undoCurrentTransactionOnly()
  16351. {
  16352. return newTransaction ? false : undo();
  16353. }
  16354. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16355. {
  16356. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16357. if (commandSet != 0 && ! newTransaction)
  16358. {
  16359. for (int i = 0; i < commandSet->size(); ++i)
  16360. actionsFound.add (commandSet->getUnchecked(i));
  16361. }
  16362. }
  16363. int UndoManager::getNumActionsInCurrentTransaction() const
  16364. {
  16365. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16366. if (commandSet != 0 && ! newTransaction)
  16367. return commandSet->size();
  16368. return 0;
  16369. }
  16370. END_JUCE_NAMESPACE
  16371. /*** End of inlined file: juce_UndoManager.cpp ***/
  16372. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16373. BEGIN_JUCE_NAMESPACE
  16374. static const char* const aiffFormatName = "AIFF file";
  16375. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16376. class AiffAudioFormatReader : public AudioFormatReader
  16377. {
  16378. public:
  16379. int bytesPerFrame;
  16380. int64 dataChunkStart;
  16381. bool littleEndian;
  16382. AiffAudioFormatReader (InputStream* in)
  16383. : AudioFormatReader (in, TRANS (aiffFormatName))
  16384. {
  16385. if (input->readInt() == chunkName ("FORM"))
  16386. {
  16387. const int len = input->readIntBigEndian();
  16388. const int64 end = input->getPosition() + len;
  16389. const int nextType = input->readInt();
  16390. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16391. {
  16392. bool hasGotVer = false;
  16393. bool hasGotData = false;
  16394. bool hasGotType = false;
  16395. while (input->getPosition() < end)
  16396. {
  16397. const int type = input->readInt();
  16398. const uint32 length = (uint32) input->readIntBigEndian();
  16399. const int64 chunkEnd = input->getPosition() + length;
  16400. if (type == chunkName ("FVER"))
  16401. {
  16402. hasGotVer = true;
  16403. const int ver = input->readIntBigEndian();
  16404. if (ver != 0 && ver != (int)0xa2805140)
  16405. break;
  16406. }
  16407. else if (type == chunkName ("COMM"))
  16408. {
  16409. hasGotType = true;
  16410. numChannels = (unsigned int)input->readShortBigEndian();
  16411. lengthInSamples = input->readIntBigEndian();
  16412. bitsPerSample = input->readShortBigEndian();
  16413. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16414. unsigned char sampleRateBytes[10];
  16415. input->read (sampleRateBytes, 10);
  16416. const int byte0 = sampleRateBytes[0];
  16417. if ((byte0 & 0x80) != 0
  16418. || byte0 <= 0x3F || byte0 > 0x40
  16419. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16420. break;
  16421. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16422. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16423. sampleRate = (int) sampRate;
  16424. if (length <= 18)
  16425. {
  16426. // some types don't have a chunk large enough to include a compression
  16427. // type, so assume it's just big-endian pcm
  16428. littleEndian = false;
  16429. }
  16430. else
  16431. {
  16432. const int compType = input->readInt();
  16433. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16434. {
  16435. littleEndian = false;
  16436. }
  16437. else if (compType == chunkName ("sowt"))
  16438. {
  16439. littleEndian = true;
  16440. }
  16441. else
  16442. {
  16443. sampleRate = 0;
  16444. break;
  16445. }
  16446. }
  16447. }
  16448. else if (type == chunkName ("SSND"))
  16449. {
  16450. hasGotData = true;
  16451. const int offset = input->readIntBigEndian();
  16452. dataChunkStart = input->getPosition() + 4 + offset;
  16453. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16454. }
  16455. else if ((hasGotVer && hasGotData && hasGotType)
  16456. || chunkEnd < input->getPosition()
  16457. || input->isExhausted())
  16458. {
  16459. break;
  16460. }
  16461. input->setPosition (chunkEnd);
  16462. }
  16463. }
  16464. }
  16465. }
  16466. ~AiffAudioFormatReader()
  16467. {
  16468. }
  16469. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16470. int64 startSampleInFile, int numSamples)
  16471. {
  16472. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16473. if (samplesAvailable < numSamples)
  16474. {
  16475. for (int i = numDestChannels; --i >= 0;)
  16476. if (destSamples[i] != 0)
  16477. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16478. numSamples = (int) samplesAvailable;
  16479. }
  16480. if (numSamples <= 0)
  16481. return true;
  16482. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16483. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16484. char tempBuffer [tempBufSize];
  16485. while (numSamples > 0)
  16486. {
  16487. int* left = destSamples[0];
  16488. if (left != 0)
  16489. left += startOffsetInDestBuffer;
  16490. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  16491. if (right != 0)
  16492. right += startOffsetInDestBuffer;
  16493. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16494. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16495. if (bytesRead < numThisTime * bytesPerFrame)
  16496. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16497. if (bitsPerSample == 16)
  16498. {
  16499. if (littleEndian)
  16500. {
  16501. const short* src = reinterpret_cast <const short*> (tempBuffer);
  16502. if (numChannels > 1)
  16503. {
  16504. if (left == 0)
  16505. {
  16506. for (int i = numThisTime; --i >= 0;)
  16507. {
  16508. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16509. ++src;
  16510. }
  16511. }
  16512. else if (right == 0)
  16513. {
  16514. for (int i = numThisTime; --i >= 0;)
  16515. {
  16516. ++src;
  16517. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16518. }
  16519. }
  16520. else
  16521. {
  16522. for (int i = numThisTime; --i >= 0;)
  16523. {
  16524. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16525. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16526. }
  16527. }
  16528. }
  16529. else
  16530. {
  16531. for (int i = numThisTime; --i >= 0;)
  16532. {
  16533. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16534. }
  16535. }
  16536. }
  16537. else
  16538. {
  16539. const char* src = tempBuffer;
  16540. if (numChannels > 1)
  16541. {
  16542. if (left == 0)
  16543. {
  16544. for (int i = numThisTime; --i >= 0;)
  16545. {
  16546. *right++ = ByteOrder::bigEndianShort (src) << 16;
  16547. src += 4;
  16548. }
  16549. }
  16550. else if (right == 0)
  16551. {
  16552. for (int i = numThisTime; --i >= 0;)
  16553. {
  16554. src += 2;
  16555. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16556. src += 2;
  16557. }
  16558. }
  16559. else
  16560. {
  16561. for (int i = numThisTime; --i >= 0;)
  16562. {
  16563. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16564. src += 2;
  16565. *right++ = ByteOrder::bigEndianShort (src) << 16;
  16566. src += 2;
  16567. }
  16568. }
  16569. }
  16570. else
  16571. {
  16572. for (int i = numThisTime; --i >= 0;)
  16573. {
  16574. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16575. src += 2;
  16576. }
  16577. }
  16578. }
  16579. }
  16580. else if (bitsPerSample == 24)
  16581. {
  16582. const char* src = tempBuffer;
  16583. if (littleEndian)
  16584. {
  16585. if (numChannels > 1)
  16586. {
  16587. if (left == 0)
  16588. {
  16589. for (int i = numThisTime; --i >= 0;)
  16590. {
  16591. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  16592. src += 6;
  16593. }
  16594. }
  16595. else if (right == 0)
  16596. {
  16597. for (int i = numThisTime; --i >= 0;)
  16598. {
  16599. src += 3;
  16600. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16601. src += 3;
  16602. }
  16603. }
  16604. else
  16605. {
  16606. for (int i = numThisTime; --i >= 0;)
  16607. {
  16608. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16609. src += 3;
  16610. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  16611. src += 3;
  16612. }
  16613. }
  16614. }
  16615. else
  16616. {
  16617. for (int i = numThisTime; --i >= 0;)
  16618. {
  16619. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16620. src += 3;
  16621. }
  16622. }
  16623. }
  16624. else
  16625. {
  16626. if (numChannels > 1)
  16627. {
  16628. if (left == 0)
  16629. {
  16630. for (int i = numThisTime; --i >= 0;)
  16631. {
  16632. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  16633. src += 6;
  16634. }
  16635. }
  16636. else if (right == 0)
  16637. {
  16638. for (int i = numThisTime; --i >= 0;)
  16639. {
  16640. src += 3;
  16641. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16642. src += 3;
  16643. }
  16644. }
  16645. else
  16646. {
  16647. for (int i = numThisTime; --i >= 0;)
  16648. {
  16649. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16650. src += 3;
  16651. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  16652. src += 3;
  16653. }
  16654. }
  16655. }
  16656. else
  16657. {
  16658. for (int i = numThisTime; --i >= 0;)
  16659. {
  16660. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16661. src += 3;
  16662. }
  16663. }
  16664. }
  16665. }
  16666. else if (bitsPerSample == 32)
  16667. {
  16668. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  16669. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  16670. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  16671. if (littleEndian)
  16672. {
  16673. if (numChannels > 1)
  16674. {
  16675. if (l == 0)
  16676. {
  16677. for (int i = numThisTime; --i >= 0;)
  16678. {
  16679. ++src;
  16680. *r++ = ByteOrder::swapIfBigEndian (*src++);
  16681. }
  16682. }
  16683. else if (r == 0)
  16684. {
  16685. for (int i = numThisTime; --i >= 0;)
  16686. {
  16687. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16688. ++src;
  16689. }
  16690. }
  16691. else
  16692. {
  16693. for (int i = numThisTime; --i >= 0;)
  16694. {
  16695. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16696. *r++ = ByteOrder::swapIfBigEndian (*src++);
  16697. }
  16698. }
  16699. }
  16700. else
  16701. {
  16702. for (int i = numThisTime; --i >= 0;)
  16703. {
  16704. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16705. }
  16706. }
  16707. }
  16708. else
  16709. {
  16710. if (numChannels > 1)
  16711. {
  16712. if (l == 0)
  16713. {
  16714. for (int i = numThisTime; --i >= 0;)
  16715. {
  16716. ++src;
  16717. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  16718. }
  16719. }
  16720. else if (r == 0)
  16721. {
  16722. for (int i = numThisTime; --i >= 0;)
  16723. {
  16724. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16725. ++src;
  16726. }
  16727. }
  16728. else
  16729. {
  16730. for (int i = numThisTime; --i >= 0;)
  16731. {
  16732. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16733. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  16734. }
  16735. }
  16736. }
  16737. else
  16738. {
  16739. for (int i = numThisTime; --i >= 0;)
  16740. {
  16741. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16742. }
  16743. }
  16744. }
  16745. left = reinterpret_cast <int*> (l);
  16746. right = reinterpret_cast <int*> (r);
  16747. }
  16748. else if (bitsPerSample == 8)
  16749. {
  16750. const char* src = tempBuffer;
  16751. if (numChannels > 1)
  16752. {
  16753. if (left == 0)
  16754. {
  16755. for (int i = numThisTime; --i >= 0;)
  16756. {
  16757. *right++ = ((int) *src++) << 24;
  16758. ++src;
  16759. }
  16760. }
  16761. else if (right == 0)
  16762. {
  16763. for (int i = numThisTime; --i >= 0;)
  16764. {
  16765. ++src;
  16766. *left++ = ((int) *src++) << 24;
  16767. }
  16768. }
  16769. else
  16770. {
  16771. for (int i = numThisTime; --i >= 0;)
  16772. {
  16773. *left++ = ((int) *src++) << 24;
  16774. *right++ = ((int) *src++) << 24;
  16775. }
  16776. }
  16777. }
  16778. else
  16779. {
  16780. for (int i = numThisTime; --i >= 0;)
  16781. {
  16782. *left++ = ((int) *src++) << 24;
  16783. }
  16784. }
  16785. }
  16786. startOffsetInDestBuffer += numThisTime;
  16787. numSamples -= numThisTime;
  16788. }
  16789. if (numSamples > 0)
  16790. {
  16791. for (int i = numDestChannels; --i >= 0;)
  16792. if (destSamples[i] != 0)
  16793. zeromem (destSamples[i] + startOffsetInDestBuffer,
  16794. sizeof (int) * numSamples);
  16795. }
  16796. return true;
  16797. }
  16798. juce_UseDebuggingNewOperator
  16799. private:
  16800. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16801. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16802. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16803. };
  16804. class AiffAudioFormatWriter : public AudioFormatWriter
  16805. {
  16806. MemoryBlock tempBlock;
  16807. uint32 lengthInSamples, bytesWritten;
  16808. int64 headerPosition;
  16809. bool writeFailed;
  16810. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16811. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16812. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16813. void writeHeader()
  16814. {
  16815. const bool couldSeekOk = output->setPosition (headerPosition);
  16816. (void) couldSeekOk;
  16817. // if this fails, you've given it an output stream that can't seek! It needs
  16818. // to be able to seek back to write the header
  16819. jassert (couldSeekOk);
  16820. const int headerLen = 54;
  16821. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16822. audioBytes += (audioBytes & 1);
  16823. output->writeInt (chunkName ("FORM"));
  16824. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16825. output->writeInt (chunkName ("AIFF"));
  16826. output->writeInt (chunkName ("COMM"));
  16827. output->writeIntBigEndian (18);
  16828. output->writeShortBigEndian ((short) numChannels);
  16829. output->writeIntBigEndian (lengthInSamples);
  16830. output->writeShortBigEndian ((short) bitsPerSample);
  16831. uint8 sampleRateBytes[10];
  16832. zeromem (sampleRateBytes, 10);
  16833. if (sampleRate <= 1)
  16834. {
  16835. sampleRateBytes[0] = 0x3f;
  16836. sampleRateBytes[1] = 0xff;
  16837. sampleRateBytes[2] = 0x80;
  16838. }
  16839. else
  16840. {
  16841. int mask = 0x40000000;
  16842. sampleRateBytes[0] = 0x40;
  16843. if (sampleRate >= mask)
  16844. {
  16845. jassertfalse;
  16846. sampleRateBytes[1] = 0x1d;
  16847. }
  16848. else
  16849. {
  16850. int n = (int) sampleRate;
  16851. int i;
  16852. for (i = 0; i <= 32 ; ++i)
  16853. {
  16854. if ((n & mask) != 0)
  16855. break;
  16856. mask >>= 1;
  16857. }
  16858. n = n << (i + 1);
  16859. sampleRateBytes[1] = (uint8) (29 - i);
  16860. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16861. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16862. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16863. sampleRateBytes[5] = (uint8) (n & 0xff);
  16864. }
  16865. }
  16866. output->write (sampleRateBytes, 10);
  16867. output->writeInt (chunkName ("SSND"));
  16868. output->writeIntBigEndian (audioBytes + 8);
  16869. output->writeInt (0);
  16870. output->writeInt (0);
  16871. jassert (output->getPosition() == headerLen);
  16872. }
  16873. public:
  16874. AiffAudioFormatWriter (OutputStream* out,
  16875. const double sampleRate_,
  16876. const unsigned int chans,
  16877. const int bits)
  16878. : AudioFormatWriter (out,
  16879. TRANS (aiffFormatName),
  16880. sampleRate_,
  16881. chans,
  16882. bits),
  16883. lengthInSamples (0),
  16884. bytesWritten (0),
  16885. writeFailed (false)
  16886. {
  16887. headerPosition = out->getPosition();
  16888. writeHeader();
  16889. }
  16890. ~AiffAudioFormatWriter()
  16891. {
  16892. if ((bytesWritten & 1) != 0)
  16893. output->writeByte (0);
  16894. writeHeader();
  16895. }
  16896. bool write (const int** data, int numSamples)
  16897. {
  16898. if (writeFailed)
  16899. return false;
  16900. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16901. tempBlock.ensureSize (bytes, false);
  16902. char* buffer = static_cast <char*> (tempBlock.getData());
  16903. const int* left = data[0];
  16904. const int* right = data[1];
  16905. if (right == 0)
  16906. right = left;
  16907. if (bitsPerSample == 16)
  16908. {
  16909. short* b = reinterpret_cast <short*> (buffer);
  16910. if (numChannels > 1)
  16911. {
  16912. for (int i = numSamples; --i >= 0;)
  16913. {
  16914. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  16915. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  16916. }
  16917. }
  16918. else
  16919. {
  16920. for (int i = numSamples; --i >= 0;)
  16921. {
  16922. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  16923. }
  16924. }
  16925. }
  16926. else if (bitsPerSample == 24)
  16927. {
  16928. char* b = buffer;
  16929. if (numChannels > 1)
  16930. {
  16931. for (int i = numSamples; --i >= 0;)
  16932. {
  16933. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  16934. b += 3;
  16935. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  16936. b += 3;
  16937. }
  16938. }
  16939. else
  16940. {
  16941. for (int i = numSamples; --i >= 0;)
  16942. {
  16943. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  16944. b += 3;
  16945. }
  16946. }
  16947. }
  16948. else if (bitsPerSample == 32)
  16949. {
  16950. uint32* b = reinterpret_cast <uint32*> (buffer);
  16951. if (numChannels > 1)
  16952. {
  16953. for (int i = numSamples; --i >= 0;)
  16954. {
  16955. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  16956. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  16957. }
  16958. }
  16959. else
  16960. {
  16961. for (int i = numSamples; --i >= 0;)
  16962. {
  16963. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  16964. }
  16965. }
  16966. }
  16967. else if (bitsPerSample == 8)
  16968. {
  16969. char* b = buffer;
  16970. if (numChannels > 1)
  16971. {
  16972. for (int i = numSamples; --i >= 0;)
  16973. {
  16974. *b++ = (char) (*left++ >> 24);
  16975. *b++ = (char) (*right++ >> 24);
  16976. }
  16977. }
  16978. else
  16979. {
  16980. for (int i = numSamples; --i >= 0;)
  16981. {
  16982. *b++ = (char) (*left++ >> 24);
  16983. }
  16984. }
  16985. }
  16986. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16987. || ! output->write (buffer, bytes))
  16988. {
  16989. // failed to write to disk, so let's try writing the header.
  16990. // If it's just run out of disk space, then if it does manage
  16991. // to write the header, we'll still have a useable file..
  16992. writeHeader();
  16993. writeFailed = true;
  16994. return false;
  16995. }
  16996. else
  16997. {
  16998. bytesWritten += bytes;
  16999. lengthInSamples += numSamples;
  17000. return true;
  17001. }
  17002. }
  17003. juce_UseDebuggingNewOperator
  17004. };
  17005. AiffAudioFormat::AiffAudioFormat()
  17006. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  17007. {
  17008. }
  17009. AiffAudioFormat::~AiffAudioFormat()
  17010. {
  17011. }
  17012. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  17013. {
  17014. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17015. return Array <int> (rates);
  17016. }
  17017. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  17018. {
  17019. const int depths[] = { 8, 16, 24, 0 };
  17020. return Array <int> (depths);
  17021. }
  17022. bool AiffAudioFormat::canDoStereo()
  17023. {
  17024. return true;
  17025. }
  17026. bool AiffAudioFormat::canDoMono()
  17027. {
  17028. return true;
  17029. }
  17030. #if JUCE_MAC
  17031. bool AiffAudioFormat::canHandleFile (const File& f)
  17032. {
  17033. if (AudioFormat::canHandleFile (f))
  17034. return true;
  17035. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  17036. return type == 'AIFF' || type == 'AIFC'
  17037. || type == 'aiff' || type == 'aifc';
  17038. }
  17039. #endif
  17040. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  17041. const bool deleteStreamIfOpeningFails)
  17042. {
  17043. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  17044. if (w->sampleRate != 0)
  17045. return w.release();
  17046. if (! deleteStreamIfOpeningFails)
  17047. w->input = 0;
  17048. return 0;
  17049. }
  17050. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  17051. double sampleRate,
  17052. unsigned int chans,
  17053. int bitsPerSample,
  17054. const StringPairArray& /*metadataValues*/,
  17055. int /*qualityOptionIndex*/)
  17056. {
  17057. if (getPossibleBitDepths().contains (bitsPerSample))
  17058. {
  17059. return new AiffAudioFormatWriter (out,
  17060. sampleRate,
  17061. chans,
  17062. bitsPerSample);
  17063. }
  17064. return 0;
  17065. }
  17066. END_JUCE_NAMESPACE
  17067. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  17068. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  17069. BEGIN_JUCE_NAMESPACE
  17070. AudioFormatReader::AudioFormatReader (InputStream* const in,
  17071. const String& formatName_)
  17072. : sampleRate (0),
  17073. bitsPerSample (0),
  17074. lengthInSamples (0),
  17075. numChannels (0),
  17076. usesFloatingPointData (false),
  17077. input (in),
  17078. formatName (formatName_)
  17079. {
  17080. }
  17081. AudioFormatReader::~AudioFormatReader()
  17082. {
  17083. delete input;
  17084. }
  17085. bool AudioFormatReader::read (int* const* destSamples,
  17086. int numDestChannels,
  17087. int64 startSampleInSource,
  17088. int numSamplesToRead,
  17089. const bool fillLeftoverChannelsWithCopies)
  17090. {
  17091. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  17092. int startOffsetInDestBuffer = 0;
  17093. if (startSampleInSource < 0)
  17094. {
  17095. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  17096. for (int i = numDestChannels; --i >= 0;)
  17097. if (destSamples[i] != 0)
  17098. zeromem (destSamples[i], sizeof (int) * silence);
  17099. startOffsetInDestBuffer += silence;
  17100. numSamplesToRead -= silence;
  17101. startSampleInSource = 0;
  17102. }
  17103. if (numSamplesToRead <= 0)
  17104. return true;
  17105. if (! readSamples (const_cast<int**> (destSamples),
  17106. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17107. startSampleInSource, numSamplesToRead))
  17108. return false;
  17109. if (numDestChannels > (int) numChannels)
  17110. {
  17111. if (fillLeftoverChannelsWithCopies)
  17112. {
  17113. int* lastFullChannel = destSamples[0];
  17114. for (int i = (int) numChannels; --i > 0;)
  17115. {
  17116. if (destSamples[i] != 0)
  17117. {
  17118. lastFullChannel = destSamples[i];
  17119. break;
  17120. }
  17121. }
  17122. if (lastFullChannel != 0)
  17123. for (int i = numChannels; i < numDestChannels; ++i)
  17124. if (destSamples[i] != 0)
  17125. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17126. }
  17127. else
  17128. {
  17129. for (int i = numChannels; i < numDestChannels; ++i)
  17130. if (destSamples[i] != 0)
  17131. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17132. }
  17133. }
  17134. return true;
  17135. }
  17136. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17137. {
  17138. float mn = buffer[0];
  17139. float mx = mn;
  17140. for (int i = 1; i < num; ++i)
  17141. {
  17142. const float s = buffer[i];
  17143. if (s > mx) mx = s;
  17144. if (s < mn) mn = s;
  17145. }
  17146. maxVal = mx;
  17147. minVal = mn;
  17148. }
  17149. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17150. int64 numSamples,
  17151. float& lowestLeft, float& highestLeft,
  17152. float& lowestRight, float& highestRight)
  17153. {
  17154. if (numSamples <= 0)
  17155. {
  17156. lowestLeft = 0;
  17157. lowestRight = 0;
  17158. highestLeft = 0;
  17159. highestRight = 0;
  17160. return;
  17161. }
  17162. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17163. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17164. int* tempBuffer[3];
  17165. tempBuffer[0] = tempSpace.getData();
  17166. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17167. tempBuffer[2] = 0;
  17168. if (usesFloatingPointData)
  17169. {
  17170. float lmin = 1.0e6f;
  17171. float lmax = -lmin;
  17172. float rmin = lmin;
  17173. float rmax = lmax;
  17174. while (numSamples > 0)
  17175. {
  17176. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17177. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17178. numSamples -= numToDo;
  17179. startSampleInFile += numToDo;
  17180. float bufmin, bufmax;
  17181. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17182. lmin = jmin (lmin, bufmin);
  17183. lmax = jmax (lmax, bufmax);
  17184. if (numChannels > 1)
  17185. {
  17186. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17187. rmin = jmin (rmin, bufmin);
  17188. rmax = jmax (rmax, bufmax);
  17189. }
  17190. }
  17191. if (numChannels <= 1)
  17192. {
  17193. rmax = lmax;
  17194. rmin = lmin;
  17195. }
  17196. lowestLeft = lmin;
  17197. highestLeft = lmax;
  17198. lowestRight = rmin;
  17199. highestRight = rmax;
  17200. }
  17201. else
  17202. {
  17203. int lmax = std::numeric_limits<int>::min();
  17204. int lmin = std::numeric_limits<int>::max();
  17205. int rmax = std::numeric_limits<int>::min();
  17206. int rmin = std::numeric_limits<int>::max();
  17207. while (numSamples > 0)
  17208. {
  17209. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17210. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17211. numSamples -= numToDo;
  17212. startSampleInFile += numToDo;
  17213. for (int j = numChannels; --j >= 0;)
  17214. {
  17215. int bufMax = std::numeric_limits<int>::min();
  17216. int bufMin = std::numeric_limits<int>::max();
  17217. const int* const b = tempBuffer[j];
  17218. for (int i = 0; i < numToDo; ++i)
  17219. {
  17220. const int samp = b[i];
  17221. if (samp < bufMin)
  17222. bufMin = samp;
  17223. if (samp > bufMax)
  17224. bufMax = samp;
  17225. }
  17226. if (j == 0)
  17227. {
  17228. lmax = jmax (lmax, bufMax);
  17229. lmin = jmin (lmin, bufMin);
  17230. }
  17231. else
  17232. {
  17233. rmax = jmax (rmax, bufMax);
  17234. rmin = jmin (rmin, bufMin);
  17235. }
  17236. }
  17237. }
  17238. if (numChannels <= 1)
  17239. {
  17240. rmax = lmax;
  17241. rmin = lmin;
  17242. }
  17243. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17244. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17245. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17246. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17247. }
  17248. }
  17249. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17250. int64 numSamplesToSearch,
  17251. const double magnitudeRangeMinimum,
  17252. const double magnitudeRangeMaximum,
  17253. const int minimumConsecutiveSamples)
  17254. {
  17255. if (numSamplesToSearch == 0)
  17256. return -1;
  17257. const int bufferSize = 4096;
  17258. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17259. int* tempBuffer[3];
  17260. tempBuffer[0] = tempSpace.getData();
  17261. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17262. tempBuffer[2] = 0;
  17263. int consecutive = 0;
  17264. int64 firstMatchPos = -1;
  17265. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17266. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17267. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17268. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17269. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17270. while (numSamplesToSearch != 0)
  17271. {
  17272. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17273. int64 bufferStart = startSample;
  17274. if (numSamplesToSearch < 0)
  17275. bufferStart -= numThisTime;
  17276. if (bufferStart >= (int) lengthInSamples)
  17277. break;
  17278. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17279. int num = numThisTime;
  17280. while (--num >= 0)
  17281. {
  17282. if (numSamplesToSearch < 0)
  17283. --startSample;
  17284. bool matches = false;
  17285. const int index = (int) (startSample - bufferStart);
  17286. if (usesFloatingPointData)
  17287. {
  17288. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17289. if (sample1 >= magnitudeRangeMinimum
  17290. && sample1 <= magnitudeRangeMaximum)
  17291. {
  17292. matches = true;
  17293. }
  17294. else if (numChannels > 1)
  17295. {
  17296. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17297. matches = (sample2 >= magnitudeRangeMinimum
  17298. && sample2 <= magnitudeRangeMaximum);
  17299. }
  17300. }
  17301. else
  17302. {
  17303. const int sample1 = abs (tempBuffer[0] [index]);
  17304. if (sample1 >= intMagnitudeRangeMinimum
  17305. && sample1 <= intMagnitudeRangeMaximum)
  17306. {
  17307. matches = true;
  17308. }
  17309. else if (numChannels > 1)
  17310. {
  17311. const int sample2 = abs (tempBuffer[1][index]);
  17312. matches = (sample2 >= intMagnitudeRangeMinimum
  17313. && sample2 <= intMagnitudeRangeMaximum);
  17314. }
  17315. }
  17316. if (matches)
  17317. {
  17318. if (firstMatchPos < 0)
  17319. firstMatchPos = startSample;
  17320. if (++consecutive >= minimumConsecutiveSamples)
  17321. {
  17322. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17323. return -1;
  17324. return firstMatchPos;
  17325. }
  17326. }
  17327. else
  17328. {
  17329. consecutive = 0;
  17330. firstMatchPos = -1;
  17331. }
  17332. if (numSamplesToSearch > 0)
  17333. ++startSample;
  17334. }
  17335. if (numSamplesToSearch > 0)
  17336. numSamplesToSearch -= numThisTime;
  17337. else
  17338. numSamplesToSearch += numThisTime;
  17339. }
  17340. return -1;
  17341. }
  17342. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17343. const String& formatName_,
  17344. const double rate,
  17345. const unsigned int numChannels_,
  17346. const unsigned int bitsPerSample_)
  17347. : sampleRate (rate),
  17348. numChannels (numChannels_),
  17349. bitsPerSample (bitsPerSample_),
  17350. usesFloatingPointData (false),
  17351. output (out),
  17352. formatName (formatName_)
  17353. {
  17354. }
  17355. AudioFormatWriter::~AudioFormatWriter()
  17356. {
  17357. delete output;
  17358. }
  17359. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17360. int64 startSample,
  17361. int64 numSamplesToRead)
  17362. {
  17363. const int bufferSize = 16384;
  17364. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17365. int* buffers [128];
  17366. zerostruct (buffers);
  17367. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17368. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17369. if (numSamplesToRead < 0)
  17370. numSamplesToRead = reader.lengthInSamples;
  17371. while (numSamplesToRead > 0)
  17372. {
  17373. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17374. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17375. return false;
  17376. if (reader.usesFloatingPointData != isFloatingPoint())
  17377. {
  17378. int** bufferChan = buffers;
  17379. while (*bufferChan != 0)
  17380. {
  17381. int* b = *bufferChan++;
  17382. if (isFloatingPoint())
  17383. {
  17384. // int -> float
  17385. const double factor = 1.0 / std::numeric_limits<int>::max();
  17386. for (int i = 0; i < numToDo; ++i)
  17387. ((float*) b)[i] = (float) (factor * b[i]);
  17388. }
  17389. else
  17390. {
  17391. // float -> int
  17392. for (int i = 0; i < numToDo; ++i)
  17393. {
  17394. const double samp = *(const float*) b;
  17395. if (samp <= -1.0)
  17396. *b++ = std::numeric_limits<int>::min();
  17397. else if (samp >= 1.0)
  17398. *b++ = std::numeric_limits<int>::max();
  17399. else
  17400. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17401. }
  17402. }
  17403. }
  17404. }
  17405. if (! write (const_cast<const int**> (buffers), numToDo))
  17406. return false;
  17407. numSamplesToRead -= numToDo;
  17408. startSample += numToDo;
  17409. }
  17410. return true;
  17411. }
  17412. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  17413. int numSamplesToRead,
  17414. const int samplesPerBlock)
  17415. {
  17416. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17417. int* buffers [128];
  17418. zerostruct (buffers);
  17419. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17420. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17421. while (numSamplesToRead > 0)
  17422. {
  17423. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17424. AudioSourceChannelInfo info;
  17425. info.buffer = &tempBuffer;
  17426. info.startSample = 0;
  17427. info.numSamples = numToDo;
  17428. info.clearActiveBufferRegion();
  17429. source.getNextAudioBlock (info);
  17430. if (! isFloatingPoint())
  17431. {
  17432. int** bufferChan = buffers;
  17433. while (*bufferChan != 0)
  17434. {
  17435. int* b = *bufferChan++;
  17436. // float -> int
  17437. for (int j = numToDo; --j >= 0;)
  17438. {
  17439. const double samp = *(const float*) b;
  17440. if (samp <= -1.0)
  17441. *b++ = std::numeric_limits<int>::min();
  17442. else if (samp >= 1.0)
  17443. *b++ = std::numeric_limits<int>::max();
  17444. else
  17445. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17446. }
  17447. }
  17448. }
  17449. if (! write ((const int**) buffers, numToDo))
  17450. return false;
  17451. numSamplesToRead -= numToDo;
  17452. }
  17453. return true;
  17454. }
  17455. AudioFormat::AudioFormat (const String& name,
  17456. const StringArray& extensions)
  17457. : formatName (name),
  17458. fileExtensions (extensions)
  17459. {
  17460. }
  17461. AudioFormat::~AudioFormat()
  17462. {
  17463. }
  17464. const String& AudioFormat::getFormatName() const
  17465. {
  17466. return formatName;
  17467. }
  17468. const StringArray& AudioFormat::getFileExtensions() const
  17469. {
  17470. return fileExtensions;
  17471. }
  17472. bool AudioFormat::canHandleFile (const File& f)
  17473. {
  17474. for (int i = 0; i < fileExtensions.size(); ++i)
  17475. if (f.hasFileExtension (fileExtensions[i]))
  17476. return true;
  17477. return false;
  17478. }
  17479. bool AudioFormat::isCompressed()
  17480. {
  17481. return false;
  17482. }
  17483. const StringArray AudioFormat::getQualityOptions()
  17484. {
  17485. return StringArray();
  17486. }
  17487. END_JUCE_NAMESPACE
  17488. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17489. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17490. BEGIN_JUCE_NAMESPACE
  17491. AudioFormatManager::AudioFormatManager()
  17492. : defaultFormatIndex (0)
  17493. {
  17494. }
  17495. AudioFormatManager::~AudioFormatManager()
  17496. {
  17497. clearFormats();
  17498. clearSingletonInstance();
  17499. }
  17500. juce_ImplementSingleton (AudioFormatManager);
  17501. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17502. const bool makeThisTheDefaultFormat)
  17503. {
  17504. jassert (newFormat != 0);
  17505. if (newFormat != 0)
  17506. {
  17507. #if JUCE_DEBUG
  17508. for (int i = getNumKnownFormats(); --i >= 0;)
  17509. {
  17510. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17511. {
  17512. jassertfalse; // trying to add the same format twice!
  17513. }
  17514. }
  17515. #endif
  17516. if (makeThisTheDefaultFormat)
  17517. defaultFormatIndex = getNumKnownFormats();
  17518. knownFormats.add (newFormat);
  17519. }
  17520. }
  17521. void AudioFormatManager::registerBasicFormats()
  17522. {
  17523. #if JUCE_MAC
  17524. registerFormat (new AiffAudioFormat(), true);
  17525. registerFormat (new WavAudioFormat(), false);
  17526. #else
  17527. registerFormat (new WavAudioFormat(), true);
  17528. registerFormat (new AiffAudioFormat(), false);
  17529. #endif
  17530. #if JUCE_USE_FLAC
  17531. registerFormat (new FlacAudioFormat(), false);
  17532. #endif
  17533. #if JUCE_USE_OGGVORBIS
  17534. registerFormat (new OggVorbisAudioFormat(), false);
  17535. #endif
  17536. }
  17537. void AudioFormatManager::clearFormats()
  17538. {
  17539. knownFormats.clear();
  17540. defaultFormatIndex = 0;
  17541. }
  17542. int AudioFormatManager::getNumKnownFormats() const
  17543. {
  17544. return knownFormats.size();
  17545. }
  17546. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17547. {
  17548. return knownFormats [index];
  17549. }
  17550. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17551. {
  17552. return getKnownFormat (defaultFormatIndex);
  17553. }
  17554. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17555. {
  17556. String e (fileExtension);
  17557. if (! e.startsWithChar ('.'))
  17558. e = "." + e;
  17559. for (int i = 0; i < getNumKnownFormats(); ++i)
  17560. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17561. return getKnownFormat(i);
  17562. return 0;
  17563. }
  17564. const String AudioFormatManager::getWildcardForAllFormats() const
  17565. {
  17566. StringArray allExtensions;
  17567. int i;
  17568. for (i = 0; i < getNumKnownFormats(); ++i)
  17569. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17570. allExtensions.trim();
  17571. allExtensions.removeEmptyStrings();
  17572. String s;
  17573. for (i = 0; i < allExtensions.size(); ++i)
  17574. {
  17575. s << '*';
  17576. if (! allExtensions[i].startsWithChar ('.'))
  17577. s << '.';
  17578. s << allExtensions[i];
  17579. if (i < allExtensions.size() - 1)
  17580. s << ';';
  17581. }
  17582. return s;
  17583. }
  17584. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17585. {
  17586. // you need to actually register some formats before the manager can
  17587. // use them to open a file!
  17588. jassert (getNumKnownFormats() > 0);
  17589. for (int i = 0; i < getNumKnownFormats(); ++i)
  17590. {
  17591. AudioFormat* const af = getKnownFormat(i);
  17592. if (af->canHandleFile (file))
  17593. {
  17594. InputStream* const in = file.createInputStream();
  17595. if (in != 0)
  17596. {
  17597. AudioFormatReader* const r = af->createReaderFor (in, true);
  17598. if (r != 0)
  17599. return r;
  17600. }
  17601. }
  17602. }
  17603. return 0;
  17604. }
  17605. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17606. {
  17607. // you need to actually register some formats before the manager can
  17608. // use them to open a file!
  17609. jassert (getNumKnownFormats() > 0);
  17610. ScopedPointer <InputStream> in (audioFileStream);
  17611. if (in != 0)
  17612. {
  17613. const int64 originalStreamPos = in->getPosition();
  17614. for (int i = 0; i < getNumKnownFormats(); ++i)
  17615. {
  17616. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17617. if (r != 0)
  17618. {
  17619. in.release();
  17620. return r;
  17621. }
  17622. in->setPosition (originalStreamPos);
  17623. // the stream that is passed-in must be capable of being repositioned so
  17624. // that all the formats can have a go at opening it.
  17625. jassert (in->getPosition() == originalStreamPos);
  17626. }
  17627. }
  17628. return 0;
  17629. }
  17630. END_JUCE_NAMESPACE
  17631. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17632. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17633. BEGIN_JUCE_NAMESPACE
  17634. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17635. const int64 startSample_,
  17636. const int64 length_,
  17637. const bool deleteSourceWhenDeleted_)
  17638. : AudioFormatReader (0, source_->getFormatName()),
  17639. source (source_),
  17640. startSample (startSample_),
  17641. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17642. {
  17643. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17644. sampleRate = source->sampleRate;
  17645. bitsPerSample = source->bitsPerSample;
  17646. lengthInSamples = length;
  17647. numChannels = source->numChannels;
  17648. usesFloatingPointData = source->usesFloatingPointData;
  17649. }
  17650. AudioSubsectionReader::~AudioSubsectionReader()
  17651. {
  17652. if (deleteSourceWhenDeleted)
  17653. delete source;
  17654. }
  17655. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17656. int64 startSampleInFile, int numSamples)
  17657. {
  17658. if (startSampleInFile + numSamples > length)
  17659. {
  17660. for (int i = numDestChannels; --i >= 0;)
  17661. if (destSamples[i] != 0)
  17662. zeromem (destSamples[i], sizeof (int) * numSamples);
  17663. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17664. if (numSamples <= 0)
  17665. return true;
  17666. }
  17667. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17668. startSampleInFile + startSample, numSamples);
  17669. }
  17670. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17671. int64 numSamples,
  17672. float& lowestLeft,
  17673. float& highestLeft,
  17674. float& lowestRight,
  17675. float& highestRight)
  17676. {
  17677. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17678. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17679. source->readMaxLevels (startSampleInFile + startSample,
  17680. numSamples,
  17681. lowestLeft,
  17682. highestLeft,
  17683. lowestRight,
  17684. highestRight);
  17685. }
  17686. END_JUCE_NAMESPACE
  17687. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17688. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17689. BEGIN_JUCE_NAMESPACE
  17690. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17691. AudioFormatManager& formatManagerToUse_,
  17692. AudioThumbnailCache& cacheToUse)
  17693. : formatManagerToUse (formatManagerToUse_),
  17694. cache (cacheToUse),
  17695. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17696. timeBeforeDeletingReader (2000)
  17697. {
  17698. clear();
  17699. }
  17700. AudioThumbnail::~AudioThumbnail()
  17701. {
  17702. cache.removeThumbnail (this);
  17703. const ScopedLock sl (readerLock);
  17704. reader = 0;
  17705. }
  17706. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17707. {
  17708. jassert (data.getData() != 0);
  17709. return static_cast <DataFormat*> (data.getData());
  17710. }
  17711. void AudioThumbnail::setSource (InputSource* const newSource)
  17712. {
  17713. cache.removeThumbnail (this);
  17714. timerCallback(); // stops the timer and deletes the reader
  17715. source = newSource;
  17716. clear();
  17717. if (newSource != 0
  17718. && ! (cache.loadThumb (*this, newSource->hashCode())
  17719. && isFullyLoaded()))
  17720. {
  17721. {
  17722. const ScopedLock sl (readerLock);
  17723. reader = createReader();
  17724. }
  17725. if (reader != 0)
  17726. {
  17727. initialiseFromAudioFile (*reader);
  17728. cache.addThumbnail (this);
  17729. }
  17730. }
  17731. sendChangeMessage (this);
  17732. }
  17733. bool AudioThumbnail::useTimeSlice()
  17734. {
  17735. const ScopedLock sl (readerLock);
  17736. if (isFullyLoaded())
  17737. {
  17738. if (reader != 0)
  17739. startTimer (timeBeforeDeletingReader);
  17740. cache.removeThumbnail (this);
  17741. return false;
  17742. }
  17743. if (reader == 0)
  17744. reader = createReader();
  17745. if (reader != 0)
  17746. {
  17747. readNextBlockFromAudioFile (*reader);
  17748. stopTimer();
  17749. sendChangeMessage (this);
  17750. const bool justFinished = isFullyLoaded();
  17751. if (justFinished)
  17752. cache.storeThumb (*this, source->hashCode());
  17753. return ! justFinished;
  17754. }
  17755. return false;
  17756. }
  17757. AudioFormatReader* AudioThumbnail::createReader() const
  17758. {
  17759. if (source != 0)
  17760. {
  17761. InputStream* const audioFileStream = source->createInputStream();
  17762. if (audioFileStream != 0)
  17763. return formatManagerToUse.createReaderFor (audioFileStream);
  17764. }
  17765. return 0;
  17766. }
  17767. void AudioThumbnail::timerCallback()
  17768. {
  17769. stopTimer();
  17770. const ScopedLock sl (readerLock);
  17771. reader = 0;
  17772. }
  17773. void AudioThumbnail::clear()
  17774. {
  17775. data.setSize (sizeof (DataFormat) + 3);
  17776. DataFormat* const d = getData();
  17777. d->thumbnailMagic[0] = 'j';
  17778. d->thumbnailMagic[1] = 'a';
  17779. d->thumbnailMagic[2] = 't';
  17780. d->thumbnailMagic[3] = 'm';
  17781. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17782. d->totalSamples = 0;
  17783. d->numFinishedSamples = 0;
  17784. d->numThumbnailSamples = 0;
  17785. d->numChannels = 0;
  17786. d->sampleRate = 0;
  17787. numSamplesCached = 0;
  17788. cacheNeedsRefilling = true;
  17789. }
  17790. void AudioThumbnail::loadFrom (InputStream& input)
  17791. {
  17792. const ScopedLock sl (readerLock);
  17793. data.setSize (0);
  17794. input.readIntoMemoryBlock (data);
  17795. DataFormat* const d = getData();
  17796. d->flipEndiannessIfBigEndian();
  17797. if (! (d->thumbnailMagic[0] == 'j'
  17798. && d->thumbnailMagic[1] == 'a'
  17799. && d->thumbnailMagic[2] == 't'
  17800. && d->thumbnailMagic[3] == 'm'))
  17801. {
  17802. clear();
  17803. }
  17804. numSamplesCached = 0;
  17805. cacheNeedsRefilling = true;
  17806. }
  17807. void AudioThumbnail::saveTo (OutputStream& output) const
  17808. {
  17809. const ScopedLock sl (readerLock);
  17810. DataFormat* const d = getData();
  17811. d->flipEndiannessIfBigEndian();
  17812. output.write (d, (int) data.getSize());
  17813. d->flipEndiannessIfBigEndian();
  17814. }
  17815. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17816. {
  17817. DataFormat* d = getData();
  17818. d->totalSamples = fileReader.lengthInSamples;
  17819. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17820. d->numFinishedSamples = 0;
  17821. d->sampleRate = roundToInt (fileReader.sampleRate);
  17822. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17823. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17824. d = getData();
  17825. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17826. return d->totalSamples > 0;
  17827. }
  17828. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17829. {
  17830. DataFormat* const d = getData();
  17831. if (d->numFinishedSamples < d->totalSamples)
  17832. {
  17833. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17834. generateSection (fileReader,
  17835. d->numFinishedSamples,
  17836. numToDo);
  17837. d->numFinishedSamples += numToDo;
  17838. }
  17839. cacheNeedsRefilling = true;
  17840. return d->numFinishedSamples < d->totalSamples;
  17841. }
  17842. int AudioThumbnail::getNumChannels() const throw()
  17843. {
  17844. return getData()->numChannels;
  17845. }
  17846. double AudioThumbnail::getTotalLength() const throw()
  17847. {
  17848. const DataFormat* const d = getData();
  17849. if (d->sampleRate > 0)
  17850. return d->totalSamples / (double) d->sampleRate;
  17851. else
  17852. return 0.0;
  17853. }
  17854. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17855. int64 startSample,
  17856. int numSamples)
  17857. {
  17858. DataFormat* const d = getData();
  17859. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17860. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17861. char* const l = getChannelData (0);
  17862. char* const r = getChannelData (1);
  17863. for (int i = firstDataPos; i < lastDataPos; ++i)
  17864. {
  17865. const int sourceStart = i * d->samplesPerThumbSample;
  17866. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17867. float lowestLeft, highestLeft, lowestRight, highestRight;
  17868. fileReader.readMaxLevels (sourceStart,
  17869. sourceEnd - sourceStart,
  17870. lowestLeft,
  17871. highestLeft,
  17872. lowestRight,
  17873. highestRight);
  17874. int n = i * 2;
  17875. if (r != 0)
  17876. {
  17877. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17878. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17879. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17880. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17881. }
  17882. else
  17883. {
  17884. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17885. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17886. }
  17887. }
  17888. }
  17889. char* AudioThumbnail::getChannelData (int channel) const
  17890. {
  17891. DataFormat* const d = getData();
  17892. if (channel >= 0 && channel < d->numChannels)
  17893. return d->data + (channel * 2 * d->numThumbnailSamples);
  17894. return 0;
  17895. }
  17896. bool AudioThumbnail::isFullyLoaded() const throw()
  17897. {
  17898. const DataFormat* const d = getData();
  17899. return d->numFinishedSamples >= d->totalSamples;
  17900. }
  17901. void AudioThumbnail::refillCache (const int numSamples,
  17902. double startTime,
  17903. const double timePerPixel)
  17904. {
  17905. const DataFormat* const d = getData();
  17906. if (numSamples <= 0
  17907. || timePerPixel <= 0.0
  17908. || d->sampleRate <= 0)
  17909. {
  17910. numSamplesCached = 0;
  17911. cacheNeedsRefilling = true;
  17912. return;
  17913. }
  17914. if (numSamples == numSamplesCached
  17915. && numChannelsCached == d->numChannels
  17916. && startTime == cachedStart
  17917. && timePerPixel == cachedTimePerPixel
  17918. && ! cacheNeedsRefilling)
  17919. {
  17920. return;
  17921. }
  17922. numSamplesCached = numSamples;
  17923. numChannelsCached = d->numChannels;
  17924. cachedStart = startTime;
  17925. cachedTimePerPixel = timePerPixel;
  17926. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17927. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17928. const ScopedLock sl (readerLock);
  17929. cacheNeedsRefilling = false;
  17930. if (needExtraDetail && reader == 0)
  17931. reader = createReader();
  17932. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17933. {
  17934. startTimer (timeBeforeDeletingReader);
  17935. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17936. int sample = roundToInt (startTime * d->sampleRate);
  17937. for (int i = numSamples; --i >= 0;)
  17938. {
  17939. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17940. if (sample >= 0)
  17941. {
  17942. if (sample >= reader->lengthInSamples)
  17943. break;
  17944. float lmin, lmax, rmin, rmax;
  17945. reader->readMaxLevels (sample,
  17946. jmax (1, nextSample - sample),
  17947. lmin, lmax, rmin, rmax);
  17948. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17949. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17950. if (numChannelsCached > 1)
  17951. {
  17952. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17953. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17954. }
  17955. cacheData += 2 * numChannelsCached;
  17956. }
  17957. startTime += timePerPixel;
  17958. sample = nextSample;
  17959. }
  17960. }
  17961. else
  17962. {
  17963. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17964. {
  17965. char* const channelData = getChannelData (channelNum);
  17966. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17967. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17968. startTime = cachedStart;
  17969. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17970. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17971. for (int i = numSamples; --i >= 0;)
  17972. {
  17973. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17974. if (sample >= 0 && channelData != 0)
  17975. {
  17976. char mx = -128;
  17977. char mn = 127;
  17978. while (sample <= nextSample)
  17979. {
  17980. if (sample >= numFinished)
  17981. break;
  17982. const int n = sample << 1;
  17983. const char sampMin = channelData [n];
  17984. const char sampMax = channelData [n + 1];
  17985. if (sampMin < mn)
  17986. mn = sampMin;
  17987. if (sampMax > mx)
  17988. mx = sampMax;
  17989. ++sample;
  17990. }
  17991. if (mn <= mx)
  17992. {
  17993. cacheData[0] = mn;
  17994. cacheData[1] = mx;
  17995. }
  17996. else
  17997. {
  17998. cacheData[0] = 1;
  17999. cacheData[1] = 0;
  18000. }
  18001. }
  18002. else
  18003. {
  18004. cacheData[0] = 1;
  18005. cacheData[1] = 0;
  18006. }
  18007. cacheData += numChannelsCached * 2;
  18008. startTime += timePerPixel;
  18009. sample = nextSample;
  18010. }
  18011. }
  18012. }
  18013. }
  18014. void AudioThumbnail::drawChannel (Graphics& g,
  18015. int x, int y, int w, int h,
  18016. double startTime,
  18017. double endTime,
  18018. int channelNum,
  18019. const float verticalZoomFactor)
  18020. {
  18021. refillCache (w, startTime, (endTime - startTime) / w);
  18022. if (numSamplesCached >= w
  18023. && channelNum >= 0
  18024. && channelNum < numChannelsCached)
  18025. {
  18026. const float topY = (float) y;
  18027. const float bottomY = topY + h;
  18028. const float midY = topY + h * 0.5f;
  18029. const float vscale = verticalZoomFactor * h / 256.0f;
  18030. const Rectangle<int> clip (g.getClipBounds());
  18031. const int skipLeft = jlimit (0, w, clip.getX() - x);
  18032. w -= skipLeft;
  18033. x += skipLeft;
  18034. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  18035. + (channelNum << 1)
  18036. + skipLeft * (numChannelsCached << 1);
  18037. while (--w >= 0)
  18038. {
  18039. const char mn = cacheData[0];
  18040. const char mx = cacheData[1];
  18041. cacheData += numChannelsCached << 1;
  18042. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  18043. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  18044. jmin (midY - mn * vscale + 0.3f, bottomY));
  18045. if (++x >= clip.getRight())
  18046. break;
  18047. }
  18048. }
  18049. }
  18050. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  18051. {
  18052. #if JUCE_BIG_ENDIAN
  18053. struct Flipper
  18054. {
  18055. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18056. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18057. };
  18058. Flipper::flip (samplesPerThumbSample);
  18059. Flipper::flip (totalSamples);
  18060. Flipper::flip (numFinishedSamples);
  18061. Flipper::flip (numThumbnailSamples);
  18062. Flipper::flip (numChannels);
  18063. Flipper::flip (sampleRate);
  18064. #endif
  18065. }
  18066. END_JUCE_NAMESPACE
  18067. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18068. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18069. BEGIN_JUCE_NAMESPACE
  18070. struct ThumbnailCacheEntry
  18071. {
  18072. int64 hash;
  18073. uint32 lastUsed;
  18074. MemoryBlock data;
  18075. juce_UseDebuggingNewOperator
  18076. };
  18077. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18078. : TimeSliceThread ("thumb cache"),
  18079. maxNumThumbsToStore (maxNumThumbsToStore_)
  18080. {
  18081. startThread (2);
  18082. }
  18083. AudioThumbnailCache::~AudioThumbnailCache()
  18084. {
  18085. }
  18086. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18087. {
  18088. for (int i = thumbs.size(); --i >= 0;)
  18089. {
  18090. if (thumbs[i]->hash == hashCode)
  18091. {
  18092. MemoryInputStream in (thumbs[i]->data, false);
  18093. thumb.loadFrom (in);
  18094. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18095. return true;
  18096. }
  18097. }
  18098. return false;
  18099. }
  18100. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18101. const int64 hashCode)
  18102. {
  18103. MemoryOutputStream out;
  18104. thumb.saveTo (out);
  18105. ThumbnailCacheEntry* te = 0;
  18106. for (int i = thumbs.size(); --i >= 0;)
  18107. {
  18108. if (thumbs[i]->hash == hashCode)
  18109. {
  18110. te = thumbs[i];
  18111. break;
  18112. }
  18113. }
  18114. if (te == 0)
  18115. {
  18116. te = new ThumbnailCacheEntry();
  18117. te->hash = hashCode;
  18118. if (thumbs.size() < maxNumThumbsToStore)
  18119. {
  18120. thumbs.add (te);
  18121. }
  18122. else
  18123. {
  18124. int oldest = 0;
  18125. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18126. int i;
  18127. for (i = thumbs.size(); --i >= 0;)
  18128. if (thumbs[i]->lastUsed < oldestTime)
  18129. oldest = i;
  18130. thumbs.set (i, te);
  18131. }
  18132. }
  18133. te->lastUsed = Time::getMillisecondCounter();
  18134. te->data.setSize (0);
  18135. te->data.append (out.getData(), out.getDataSize());
  18136. }
  18137. void AudioThumbnailCache::clear()
  18138. {
  18139. thumbs.clear();
  18140. }
  18141. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18142. {
  18143. addTimeSliceClient (thumb);
  18144. }
  18145. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18146. {
  18147. removeTimeSliceClient (thumb);
  18148. }
  18149. END_JUCE_NAMESPACE
  18150. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18151. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18152. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18153. #if ! JUCE_WINDOWS
  18154. #include <QuickTime/Movies.h>
  18155. #include <QuickTime/QTML.h>
  18156. #include <QuickTime/QuickTimeComponents.h>
  18157. #include <QuickTime/MediaHandlers.h>
  18158. #include <QuickTime/ImageCodec.h>
  18159. #else
  18160. #if JUCE_MSVC
  18161. #pragma warning (push)
  18162. #pragma warning (disable : 4100)
  18163. #endif
  18164. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18165. add its header directory to your include path.
  18166. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  18167. flag in juce_Config.h
  18168. */
  18169. #include <Movies.h>
  18170. #include <QTML.h>
  18171. #include <QuickTimeComponents.h>
  18172. #include <MediaHandlers.h>
  18173. #include <ImageCodec.h>
  18174. #if JUCE_MSVC
  18175. #pragma warning (pop)
  18176. #endif
  18177. #endif
  18178. BEGIN_JUCE_NAMESPACE
  18179. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18180. static const char* const quickTimeFormatName = "QuickTime file";
  18181. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  18182. class QTAudioReader : public AudioFormatReader
  18183. {
  18184. public:
  18185. QTAudioReader (InputStream* const input_, const int trackNum_)
  18186. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18187. ok (false),
  18188. movie (0),
  18189. trackNum (trackNum_),
  18190. lastSampleRead (0),
  18191. lastThreadId (0),
  18192. extractor (0),
  18193. dataHandle (0)
  18194. {
  18195. bufferList.calloc (256, 1);
  18196. #if JUCE_WINDOWS
  18197. if (InitializeQTML (0) != noErr)
  18198. return;
  18199. #endif
  18200. if (EnterMovies() != noErr)
  18201. return;
  18202. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18203. if (! opened)
  18204. return;
  18205. {
  18206. const int numTracks = GetMovieTrackCount (movie);
  18207. int trackCount = 0;
  18208. for (int i = 1; i <= numTracks; ++i)
  18209. {
  18210. track = GetMovieIndTrack (movie, i);
  18211. media = GetTrackMedia (track);
  18212. OSType mediaType;
  18213. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18214. if (mediaType == SoundMediaType
  18215. && trackCount++ == trackNum_)
  18216. {
  18217. ok = true;
  18218. break;
  18219. }
  18220. }
  18221. }
  18222. if (! ok)
  18223. return;
  18224. ok = false;
  18225. lengthInSamples = GetMediaDecodeDuration (media);
  18226. usesFloatingPointData = false;
  18227. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18228. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18229. / GetMediaTimeScale (media);
  18230. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18231. unsigned long output_layout_size;
  18232. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18233. kQTPropertyClass_MovieAudioExtraction_Audio,
  18234. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18235. 0, &output_layout_size, 0);
  18236. if (err != noErr)
  18237. return;
  18238. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18239. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18240. err = MovieAudioExtractionGetProperty (extractor,
  18241. kQTPropertyClass_MovieAudioExtraction_Audio,
  18242. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18243. output_layout_size, qt_audio_channel_layout, 0);
  18244. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18245. err = MovieAudioExtractionSetProperty (extractor,
  18246. kQTPropertyClass_MovieAudioExtraction_Audio,
  18247. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18248. output_layout_size,
  18249. qt_audio_channel_layout);
  18250. err = MovieAudioExtractionGetProperty (extractor,
  18251. kQTPropertyClass_MovieAudioExtraction_Audio,
  18252. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18253. sizeof (inputStreamDesc),
  18254. &inputStreamDesc, 0);
  18255. if (err != noErr)
  18256. return;
  18257. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18258. | kAudioFormatFlagIsPacked
  18259. | kAudioFormatFlagsNativeEndian;
  18260. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18261. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18262. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18263. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18264. err = MovieAudioExtractionSetProperty (extractor,
  18265. kQTPropertyClass_MovieAudioExtraction_Audio,
  18266. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18267. sizeof (inputStreamDesc),
  18268. &inputStreamDesc);
  18269. if (err != noErr)
  18270. return;
  18271. Boolean allChannelsDiscrete = false;
  18272. err = MovieAudioExtractionSetProperty (extractor,
  18273. kQTPropertyClass_MovieAudioExtraction_Movie,
  18274. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18275. sizeof (allChannelsDiscrete),
  18276. &allChannelsDiscrete);
  18277. if (err != noErr)
  18278. return;
  18279. bufferList->mNumberBuffers = 1;
  18280. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18281. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  18282. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18283. bufferList->mBuffers[0].mData = dataBuffer;
  18284. sampleRate = inputStreamDesc.mSampleRate;
  18285. bitsPerSample = 16;
  18286. numChannels = inputStreamDesc.mChannelsPerFrame;
  18287. detachThread();
  18288. ok = true;
  18289. }
  18290. ~QTAudioReader()
  18291. {
  18292. if (dataHandle != 0)
  18293. DisposeHandle (dataHandle);
  18294. if (extractor != 0)
  18295. {
  18296. MovieAudioExtractionEnd (extractor);
  18297. extractor = 0;
  18298. }
  18299. checkThreadIsAttached();
  18300. DisposeMovie (movie);
  18301. #if JUCE_MAC
  18302. ExitMoviesOnThread ();
  18303. #endif
  18304. }
  18305. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18306. int64 startSampleInFile, int numSamples)
  18307. {
  18308. checkThreadIsAttached();
  18309. while (numSamples > 0)
  18310. {
  18311. if (! loadFrame ((int) startSampleInFile))
  18312. return false;
  18313. const int numToDo = jmin (numSamples, samplesPerFrame);
  18314. for (int j = numDestChannels; --j >= 0;)
  18315. {
  18316. if (destSamples[j] != 0)
  18317. {
  18318. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18319. for (int i = 0; i < numToDo; ++i)
  18320. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18321. }
  18322. }
  18323. startOffsetInDestBuffer += numToDo;
  18324. startSampleInFile += numToDo;
  18325. numSamples -= numToDo;
  18326. }
  18327. detachThread();
  18328. return true;
  18329. }
  18330. bool loadFrame (const int sampleNum)
  18331. {
  18332. if (lastSampleRead != sampleNum)
  18333. {
  18334. TimeRecord time;
  18335. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18336. time.base = 0;
  18337. time.value.hi = 0;
  18338. time.value.lo = (UInt32) sampleNum;
  18339. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18340. kQTPropertyClass_MovieAudioExtraction_Movie,
  18341. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18342. sizeof (time), &time);
  18343. if (err != noErr)
  18344. return false;
  18345. }
  18346. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  18347. UInt32 outFlags = 0;
  18348. UInt32 actualNumSamples = samplesPerFrame;
  18349. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  18350. bufferList, &outFlags);
  18351. lastSampleRead = sampleNum + samplesPerFrame;
  18352. return err == noErr;
  18353. }
  18354. juce_UseDebuggingNewOperator
  18355. bool ok;
  18356. private:
  18357. Movie movie;
  18358. Media media;
  18359. Track track;
  18360. const int trackNum;
  18361. double trackUnitsPerFrame;
  18362. int samplesPerFrame;
  18363. int lastSampleRead;
  18364. Thread::ThreadID lastThreadId;
  18365. MovieAudioExtractionRef extractor;
  18366. AudioStreamBasicDescription inputStreamDesc;
  18367. HeapBlock <AudioBufferList> bufferList;
  18368. HeapBlock <char> dataBuffer;
  18369. Handle dataHandle;
  18370. void checkThreadIsAttached()
  18371. {
  18372. #if JUCE_MAC
  18373. if (Thread::getCurrentThreadId() != lastThreadId)
  18374. EnterMoviesOnThread (0);
  18375. AttachMovieToCurrentThread (movie);
  18376. #endif
  18377. }
  18378. void detachThread()
  18379. {
  18380. #if JUCE_MAC
  18381. DetachMovieFromCurrentThread (movie);
  18382. #endif
  18383. }
  18384. QTAudioReader (const QTAudioReader&);
  18385. QTAudioReader& operator= (const QTAudioReader&);
  18386. };
  18387. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18388. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18389. {
  18390. }
  18391. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18392. {
  18393. }
  18394. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  18395. {
  18396. return Array<int>();
  18397. }
  18398. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  18399. {
  18400. return Array<int>();
  18401. }
  18402. bool QuickTimeAudioFormat::canDoStereo()
  18403. {
  18404. return true;
  18405. }
  18406. bool QuickTimeAudioFormat::canDoMono()
  18407. {
  18408. return true;
  18409. }
  18410. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18411. const bool deleteStreamIfOpeningFails)
  18412. {
  18413. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18414. if (r->ok)
  18415. return r.release();
  18416. if (! deleteStreamIfOpeningFails)
  18417. r->input = 0;
  18418. return 0;
  18419. }
  18420. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18421. double /*sampleRateToUse*/,
  18422. unsigned int /*numberOfChannels*/,
  18423. int /*bitsPerSample*/,
  18424. const StringPairArray& /*metadataValues*/,
  18425. int /*qualityOptionIndex*/)
  18426. {
  18427. jassertfalse; // not yet implemented!
  18428. return 0;
  18429. }
  18430. END_JUCE_NAMESPACE
  18431. #endif
  18432. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18433. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18434. BEGIN_JUCE_NAMESPACE
  18435. static const char* const wavFormatName = "WAV file";
  18436. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18437. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18438. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18439. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18440. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18441. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18442. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18443. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18444. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18445. const String& originator,
  18446. const String& originatorRef,
  18447. const Time& date,
  18448. const int64 timeReferenceSamples,
  18449. const String& codingHistory)
  18450. {
  18451. StringPairArray m;
  18452. m.set (bwavDescription, description);
  18453. m.set (bwavOriginator, originator);
  18454. m.set (bwavOriginatorRef, originatorRef);
  18455. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18456. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18457. m.set (bwavTimeReference, String (timeReferenceSamples));
  18458. m.set (bwavCodingHistory, codingHistory);
  18459. return m;
  18460. }
  18461. #if JUCE_MSVC
  18462. #pragma pack (push, 1)
  18463. #define PACKED
  18464. #elif JUCE_GCC
  18465. #define PACKED __attribute__((packed))
  18466. #else
  18467. #define PACKED
  18468. #endif
  18469. struct BWAVChunk
  18470. {
  18471. char description [256];
  18472. char originator [32];
  18473. char originatorRef [32];
  18474. char originationDate [10];
  18475. char originationTime [8];
  18476. uint32 timeRefLow;
  18477. uint32 timeRefHigh;
  18478. uint16 version;
  18479. uint8 umid[64];
  18480. uint8 reserved[190];
  18481. char codingHistory[1];
  18482. void copyTo (StringPairArray& values) const
  18483. {
  18484. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18485. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18486. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18487. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18488. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18489. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18490. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18491. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18492. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18493. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18494. }
  18495. static MemoryBlock createFrom (const StringPairArray& values)
  18496. {
  18497. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18498. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18499. data.fillWith (0);
  18500. BWAVChunk* b = (BWAVChunk*) data.getData();
  18501. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18502. // as they get called in the right order..
  18503. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18504. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18505. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18506. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18507. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18508. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18509. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18510. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18511. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18512. if (b->description[0] != 0
  18513. || b->originator[0] != 0
  18514. || b->originationDate[0] != 0
  18515. || b->originationTime[0] != 0
  18516. || b->codingHistory[0] != 0
  18517. || time != 0)
  18518. {
  18519. return data;
  18520. }
  18521. return MemoryBlock();
  18522. }
  18523. } PACKED;
  18524. struct SMPLChunk
  18525. {
  18526. struct SampleLoop
  18527. {
  18528. uint32 identifier;
  18529. uint32 type;
  18530. uint32 start;
  18531. uint32 end;
  18532. uint32 fraction;
  18533. uint32 playCount;
  18534. } PACKED;
  18535. uint32 manufacturer;
  18536. uint32 product;
  18537. uint32 samplePeriod;
  18538. uint32 midiUnityNote;
  18539. uint32 midiPitchFraction;
  18540. uint32 smpteFormat;
  18541. uint32 smpteOffset;
  18542. uint32 numSampleLoops;
  18543. uint32 samplerData;
  18544. SampleLoop loops[1];
  18545. void copyTo (StringPairArray& values, const int totalSize) const
  18546. {
  18547. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18548. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18549. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18550. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18551. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18552. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18553. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18554. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18555. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18556. for (uint32 i = 0; i < numSampleLoops; ++i)
  18557. {
  18558. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18559. break;
  18560. const String prefix ("Loop" + String(i));
  18561. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18562. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18563. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18564. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18565. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18566. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18567. }
  18568. }
  18569. static MemoryBlock createFrom (const StringPairArray& values)
  18570. {
  18571. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18572. if (numLoops <= 0)
  18573. return MemoryBlock();
  18574. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18575. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18576. data.fillWith (0);
  18577. SMPLChunk* s = (SMPLChunk*) data.getData();
  18578. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18579. // as they get called in the right order..
  18580. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18581. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18582. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18583. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18584. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18585. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18586. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18587. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18588. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18589. for (int i = 0; i < numLoops; ++i)
  18590. {
  18591. const String prefix ("Loop" + String(i));
  18592. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18593. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18594. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18595. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18596. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18597. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18598. }
  18599. return data;
  18600. }
  18601. } PACKED;
  18602. struct ExtensibleWavSubFormat
  18603. {
  18604. uint32 data1;
  18605. uint16 data2;
  18606. uint16 data3;
  18607. uint8 data4[8];
  18608. } PACKED;
  18609. #if JUCE_MSVC
  18610. #pragma pack (pop)
  18611. #endif
  18612. #undef PACKED
  18613. class WavAudioFormatReader : public AudioFormatReader
  18614. {
  18615. int bytesPerFrame;
  18616. int64 dataChunkStart, dataLength;
  18617. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18618. WavAudioFormatReader (const WavAudioFormatReader&);
  18619. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18620. public:
  18621. int64 bwavChunkStart, bwavSize;
  18622. WavAudioFormatReader (InputStream* const in)
  18623. : AudioFormatReader (in, TRANS (wavFormatName)),
  18624. dataLength (0),
  18625. bwavChunkStart (0),
  18626. bwavSize (0)
  18627. {
  18628. if (input->readInt() == chunkName ("RIFF"))
  18629. {
  18630. const uint32 len = (uint32) input->readInt();
  18631. const int64 end = input->getPosition() + len;
  18632. bool hasGotType = false;
  18633. bool hasGotData = false;
  18634. if (input->readInt() == chunkName ("WAVE"))
  18635. {
  18636. while (input->getPosition() < end
  18637. && ! input->isExhausted())
  18638. {
  18639. const int chunkType = input->readInt();
  18640. uint32 length = (uint32) input->readInt();
  18641. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18642. if (chunkType == chunkName ("fmt "))
  18643. {
  18644. // read the format chunk
  18645. const unsigned short format = input->readShort();
  18646. const short numChans = input->readShort();
  18647. sampleRate = input->readInt();
  18648. const int bytesPerSec = input->readInt();
  18649. numChannels = numChans;
  18650. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18651. bitsPerSample = 8 * bytesPerFrame / numChans;
  18652. if (format == 3)
  18653. {
  18654. usesFloatingPointData = true;
  18655. }
  18656. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18657. {
  18658. if (length < 40) // too short
  18659. {
  18660. bytesPerFrame = 0;
  18661. }
  18662. else
  18663. {
  18664. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18665. ExtensibleWavSubFormat subFormat;
  18666. subFormat.data1 = input->readInt();
  18667. subFormat.data2 = input->readShort();
  18668. subFormat.data3 = input->readShort();
  18669. input->read (subFormat.data4, sizeof (subFormat.data4));
  18670. const ExtensibleWavSubFormat pcmFormat
  18671. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18672. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18673. {
  18674. const ExtensibleWavSubFormat ambisonicFormat
  18675. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18676. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18677. bytesPerFrame = 0;
  18678. }
  18679. }
  18680. }
  18681. else if (format != 1)
  18682. {
  18683. bytesPerFrame = 0;
  18684. }
  18685. hasGotType = true;
  18686. }
  18687. else if (chunkType == chunkName ("data"))
  18688. {
  18689. // get the data chunk's position
  18690. dataLength = length;
  18691. dataChunkStart = input->getPosition();
  18692. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18693. hasGotData = true;
  18694. }
  18695. else if (chunkType == chunkName ("bext"))
  18696. {
  18697. bwavChunkStart = input->getPosition();
  18698. bwavSize = length;
  18699. // Broadcast-wav extension chunk..
  18700. HeapBlock <BWAVChunk> bwav;
  18701. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18702. input->read (bwav, length);
  18703. bwav->copyTo (metadataValues);
  18704. }
  18705. else if (chunkType == chunkName ("smpl"))
  18706. {
  18707. HeapBlock <SMPLChunk> smpl;
  18708. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18709. input->read (smpl, length);
  18710. smpl->copyTo (metadataValues, length);
  18711. }
  18712. else if (chunkEnd <= input->getPosition())
  18713. {
  18714. break;
  18715. }
  18716. input->setPosition (chunkEnd);
  18717. }
  18718. }
  18719. }
  18720. }
  18721. ~WavAudioFormatReader()
  18722. {
  18723. }
  18724. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18725. int64 startSampleInFile, int numSamples)
  18726. {
  18727. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18728. if (samplesAvailable < numSamples)
  18729. {
  18730. for (int i = numDestChannels; --i >= 0;)
  18731. if (destSamples[i] != 0)
  18732. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18733. numSamples = (int) samplesAvailable;
  18734. }
  18735. if (numSamples <= 0)
  18736. return true;
  18737. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18738. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18739. char tempBuffer [tempBufSize];
  18740. while (numSamples > 0)
  18741. {
  18742. int* left = destSamples[0];
  18743. if (left != 0)
  18744. left += startOffsetInDestBuffer;
  18745. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  18746. if (right != 0)
  18747. right += startOffsetInDestBuffer;
  18748. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18749. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18750. if (bytesRead < numThisTime * bytesPerFrame)
  18751. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18752. if (bitsPerSample == 16)
  18753. {
  18754. const short* src = reinterpret_cast <const short*> (tempBuffer);
  18755. if (numChannels > 1)
  18756. {
  18757. if (left == 0)
  18758. {
  18759. for (int i = numThisTime; --i >= 0;)
  18760. {
  18761. ++src;
  18762. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18763. }
  18764. }
  18765. else if (right == 0)
  18766. {
  18767. for (int i = numThisTime; --i >= 0;)
  18768. {
  18769. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18770. ++src;
  18771. }
  18772. }
  18773. else
  18774. {
  18775. for (int i = numThisTime; --i >= 0;)
  18776. {
  18777. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18778. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18779. }
  18780. }
  18781. }
  18782. else
  18783. {
  18784. for (int i = numThisTime; --i >= 0;)
  18785. {
  18786. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18787. }
  18788. }
  18789. }
  18790. else if (bitsPerSample == 24)
  18791. {
  18792. const char* src = tempBuffer;
  18793. if (numChannels > 1)
  18794. {
  18795. if (left == 0)
  18796. {
  18797. for (int i = numThisTime; --i >= 0;)
  18798. {
  18799. src += 3;
  18800. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  18801. src += 3;
  18802. }
  18803. }
  18804. else if (right == 0)
  18805. {
  18806. for (int i = numThisTime; --i >= 0;)
  18807. {
  18808. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18809. src += 6;
  18810. }
  18811. }
  18812. else
  18813. {
  18814. for (int i = 0; i < numThisTime; ++i)
  18815. {
  18816. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18817. src += 3;
  18818. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  18819. src += 3;
  18820. }
  18821. }
  18822. }
  18823. else
  18824. {
  18825. for (int i = 0; i < numThisTime; ++i)
  18826. {
  18827. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18828. src += 3;
  18829. }
  18830. }
  18831. }
  18832. else if (bitsPerSample == 32)
  18833. {
  18834. const unsigned int* src = (const unsigned int*) tempBuffer;
  18835. unsigned int* l = reinterpret_cast<unsigned int*> (left);
  18836. unsigned int* r = reinterpret_cast<unsigned int*> (right);
  18837. if (numChannels > 1)
  18838. {
  18839. if (l == 0)
  18840. {
  18841. for (int i = numThisTime; --i >= 0;)
  18842. {
  18843. ++src;
  18844. *r++ = ByteOrder::swapIfBigEndian (*src++);
  18845. }
  18846. }
  18847. else if (r == 0)
  18848. {
  18849. for (int i = numThisTime; --i >= 0;)
  18850. {
  18851. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18852. ++src;
  18853. }
  18854. }
  18855. else
  18856. {
  18857. for (int i = numThisTime; --i >= 0;)
  18858. {
  18859. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18860. *r++ = ByteOrder::swapIfBigEndian (*src++);
  18861. }
  18862. }
  18863. }
  18864. else
  18865. {
  18866. for (int i = numThisTime; --i >= 0;)
  18867. {
  18868. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18869. }
  18870. }
  18871. left = reinterpret_cast<int*> (l);
  18872. right = reinterpret_cast<int*> (r);
  18873. }
  18874. else if (bitsPerSample == 8)
  18875. {
  18876. const unsigned char* src = reinterpret_cast<const unsigned char*> (tempBuffer);
  18877. if (numChannels > 1)
  18878. {
  18879. if (left == 0)
  18880. {
  18881. for (int i = numThisTime; --i >= 0;)
  18882. {
  18883. ++src;
  18884. *right++ = ((int) *src++ - 128) << 24;
  18885. }
  18886. }
  18887. else if (right == 0)
  18888. {
  18889. for (int i = numThisTime; --i >= 0;)
  18890. {
  18891. *left++ = ((int) *src++ - 128) << 24;
  18892. ++src;
  18893. }
  18894. }
  18895. else
  18896. {
  18897. for (int i = numThisTime; --i >= 0;)
  18898. {
  18899. *left++ = ((int) *src++ - 128) << 24;
  18900. *right++ = ((int) *src++ - 128) << 24;
  18901. }
  18902. }
  18903. }
  18904. else
  18905. {
  18906. for (int i = numThisTime; --i >= 0;)
  18907. {
  18908. *left++ = ((int)*src++ - 128) << 24;
  18909. }
  18910. }
  18911. }
  18912. startOffsetInDestBuffer += numThisTime;
  18913. numSamples -= numThisTime;
  18914. }
  18915. if (numSamples > 0)
  18916. {
  18917. for (int i = numDestChannels; --i >= 0;)
  18918. if (destSamples[i] != 0)
  18919. zeromem (destSamples[i] + startOffsetInDestBuffer,
  18920. sizeof (int) * numSamples);
  18921. }
  18922. return true;
  18923. }
  18924. juce_UseDebuggingNewOperator
  18925. };
  18926. class WavAudioFormatWriter : public AudioFormatWriter
  18927. {
  18928. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18929. uint32 lengthInSamples, bytesWritten;
  18930. int64 headerPosition;
  18931. bool writeFailed;
  18932. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18933. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18934. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18935. void writeHeader()
  18936. {
  18937. const bool seekedOk = output->setPosition (headerPosition);
  18938. (void) seekedOk;
  18939. // if this fails, you've given it an output stream that can't seek! It needs
  18940. // to be able to seek back to write the header
  18941. jassert (seekedOk);
  18942. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18943. output->writeInt (chunkName ("RIFF"));
  18944. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18945. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18946. output->writeInt (chunkName ("WAVE"));
  18947. output->writeInt (chunkName ("fmt "));
  18948. output->writeInt (16);
  18949. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18950. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18951. output->writeShort ((short) numChannels);
  18952. output->writeInt ((int) sampleRate);
  18953. output->writeInt (bytesPerFrame * (int) sampleRate);
  18954. output->writeShort ((short) bytesPerFrame);
  18955. output->writeShort ((short) bitsPerSample);
  18956. if (bwavChunk.getSize() > 0)
  18957. {
  18958. output->writeInt (chunkName ("bext"));
  18959. output->writeInt ((int) bwavChunk.getSize());
  18960. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18961. }
  18962. if (smplChunk.getSize() > 0)
  18963. {
  18964. output->writeInt (chunkName ("smpl"));
  18965. output->writeInt ((int) smplChunk.getSize());
  18966. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18967. }
  18968. output->writeInt (chunkName ("data"));
  18969. output->writeInt (lengthInSamples * bytesPerFrame);
  18970. usesFloatingPointData = (bitsPerSample == 32);
  18971. }
  18972. public:
  18973. WavAudioFormatWriter (OutputStream* const out,
  18974. const double sampleRate_,
  18975. const unsigned int numChannels_,
  18976. const int bits,
  18977. const StringPairArray& metadataValues)
  18978. : AudioFormatWriter (out,
  18979. TRANS (wavFormatName),
  18980. sampleRate_,
  18981. numChannels_,
  18982. bits),
  18983. lengthInSamples (0),
  18984. bytesWritten (0),
  18985. writeFailed (false)
  18986. {
  18987. if (metadataValues.size() > 0)
  18988. {
  18989. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18990. smplChunk = SMPLChunk::createFrom (metadataValues);
  18991. }
  18992. headerPosition = out->getPosition();
  18993. writeHeader();
  18994. }
  18995. ~WavAudioFormatWriter()
  18996. {
  18997. writeHeader();
  18998. }
  18999. bool write (const int** data, int numSamples)
  19000. {
  19001. if (writeFailed)
  19002. return false;
  19003. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  19004. tempBlock.ensureSize (bytes, false);
  19005. char* buffer = static_cast <char*> (tempBlock.getData());
  19006. const int* left = data[0];
  19007. const int* right = data[1];
  19008. if (right == 0)
  19009. right = left;
  19010. if (bitsPerSample == 16)
  19011. {
  19012. short* b = (short*) buffer;
  19013. if (numChannels > 1)
  19014. {
  19015. for (int i = numSamples; --i >= 0;)
  19016. {
  19017. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  19018. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  19019. }
  19020. }
  19021. else
  19022. {
  19023. for (int i = numSamples; --i >= 0;)
  19024. {
  19025. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  19026. }
  19027. }
  19028. }
  19029. else if (bitsPerSample == 24)
  19030. {
  19031. char* b = buffer;
  19032. if (numChannels > 1)
  19033. {
  19034. for (int i = numSamples; --i >= 0;)
  19035. {
  19036. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  19037. b += 3;
  19038. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  19039. b += 3;
  19040. }
  19041. }
  19042. else
  19043. {
  19044. for (int i = numSamples; --i >= 0;)
  19045. {
  19046. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  19047. b += 3;
  19048. }
  19049. }
  19050. }
  19051. else if (bitsPerSample == 32)
  19052. {
  19053. unsigned int* b = (unsigned int*) buffer;
  19054. if (numChannels > 1)
  19055. {
  19056. for (int i = numSamples; --i >= 0;)
  19057. {
  19058. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  19059. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  19060. }
  19061. }
  19062. else
  19063. {
  19064. for (int i = numSamples; --i >= 0;)
  19065. {
  19066. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  19067. }
  19068. }
  19069. }
  19070. else if (bitsPerSample == 8)
  19071. {
  19072. unsigned char* b = (unsigned char*) buffer;
  19073. if (numChannels > 1)
  19074. {
  19075. for (int i = numSamples; --i >= 0;)
  19076. {
  19077. *b++ = (unsigned char) (128 + (*left++ >> 24));
  19078. *b++ = (unsigned char) (128 + (*right++ >> 24));
  19079. }
  19080. }
  19081. else
  19082. {
  19083. for (int i = numSamples; --i >= 0;)
  19084. {
  19085. *b++ = (unsigned char) (128 + (*left++ >> 24));
  19086. }
  19087. }
  19088. }
  19089. if (bytesWritten + bytes >= (uint32) 0xfff00000
  19090. || ! output->write (buffer, bytes))
  19091. {
  19092. // failed to write to disk, so let's try writing the header.
  19093. // If it's just run out of disk space, then if it does manage
  19094. // to write the header, we'll still have a useable file..
  19095. writeHeader();
  19096. writeFailed = true;
  19097. return false;
  19098. }
  19099. else
  19100. {
  19101. bytesWritten += bytes;
  19102. lengthInSamples += numSamples;
  19103. return true;
  19104. }
  19105. }
  19106. juce_UseDebuggingNewOperator
  19107. };
  19108. WavAudioFormat::WavAudioFormat()
  19109. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  19110. {
  19111. }
  19112. WavAudioFormat::~WavAudioFormat()
  19113. {
  19114. }
  19115. const Array <int> WavAudioFormat::getPossibleSampleRates()
  19116. {
  19117. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  19118. return Array <int> (rates);
  19119. }
  19120. const Array <int> WavAudioFormat::getPossibleBitDepths()
  19121. {
  19122. const int depths[] = { 8, 16, 24, 32, 0 };
  19123. return Array <int> (depths);
  19124. }
  19125. bool WavAudioFormat::canDoStereo()
  19126. {
  19127. return true;
  19128. }
  19129. bool WavAudioFormat::canDoMono()
  19130. {
  19131. return true;
  19132. }
  19133. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  19134. const bool deleteStreamIfOpeningFails)
  19135. {
  19136. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  19137. if (r->sampleRate != 0)
  19138. return r.release();
  19139. if (! deleteStreamIfOpeningFails)
  19140. r->input = 0;
  19141. return 0;
  19142. }
  19143. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  19144. double sampleRate,
  19145. unsigned int numChannels,
  19146. int bitsPerSample,
  19147. const StringPairArray& metadataValues,
  19148. int /*qualityOptionIndex*/)
  19149. {
  19150. if (getPossibleBitDepths().contains (bitsPerSample))
  19151. {
  19152. return new WavAudioFormatWriter (out,
  19153. sampleRate,
  19154. numChannels,
  19155. bitsPerSample,
  19156. metadataValues);
  19157. }
  19158. return 0;
  19159. }
  19160. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  19161. {
  19162. TemporaryFile tempFile (file);
  19163. WavAudioFormat wav;
  19164. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  19165. if (reader != 0)
  19166. {
  19167. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  19168. if (outStream != 0)
  19169. {
  19170. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  19171. reader->numChannels, reader->bitsPerSample,
  19172. metadata, 0));
  19173. if (writer != 0)
  19174. {
  19175. outStream.release();
  19176. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  19177. writer = 0;
  19178. reader = 0;
  19179. return ok && tempFile.overwriteTargetFileWithTemporary();
  19180. }
  19181. }
  19182. }
  19183. return false;
  19184. }
  19185. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  19186. {
  19187. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  19188. if (reader != 0)
  19189. {
  19190. const int64 bwavPos = reader->bwavChunkStart;
  19191. const int64 bwavSize = reader->bwavSize;
  19192. reader = 0;
  19193. if (bwavSize > 0)
  19194. {
  19195. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  19196. if (chunk.getSize() <= (size_t) bwavSize)
  19197. {
  19198. // the new one will fit in the space available, so write it directly..
  19199. const int64 oldSize = wavFile.getSize();
  19200. {
  19201. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  19202. out->setPosition (bwavPos);
  19203. out->write (chunk.getData(), (int) chunk.getSize());
  19204. out->setPosition (oldSize);
  19205. }
  19206. jassert (wavFile.getSize() == oldSize);
  19207. return true;
  19208. }
  19209. }
  19210. }
  19211. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  19212. }
  19213. END_JUCE_NAMESPACE
  19214. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  19215. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  19216. #if JUCE_USE_CDREADER
  19217. BEGIN_JUCE_NAMESPACE
  19218. int AudioCDReader::getNumTracks() const
  19219. {
  19220. return trackStartSamples.size() - 1;
  19221. }
  19222. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  19223. {
  19224. return trackStartSamples [trackNum];
  19225. }
  19226. const Array<int>& AudioCDReader::getTrackOffsets() const
  19227. {
  19228. return trackStartSamples;
  19229. }
  19230. int AudioCDReader::getCDDBId()
  19231. {
  19232. int checksum = 0;
  19233. const int numTracks = getNumTracks();
  19234. for (int i = 0; i < numTracks; ++i)
  19235. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  19236. checksum += offset % 10;
  19237. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  19238. // CCLLLLTT: checksum, length, tracks
  19239. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  19240. }
  19241. END_JUCE_NAMESPACE
  19242. #endif
  19243. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  19244. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19245. BEGIN_JUCE_NAMESPACE
  19246. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  19247. const bool deleteReaderWhenThisIsDeleted)
  19248. : reader (reader_),
  19249. deleteReader (deleteReaderWhenThisIsDeleted),
  19250. nextPlayPos (0),
  19251. looping (false)
  19252. {
  19253. jassert (reader != 0);
  19254. }
  19255. AudioFormatReaderSource::~AudioFormatReaderSource()
  19256. {
  19257. releaseResources();
  19258. if (deleteReader)
  19259. delete reader;
  19260. }
  19261. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19262. {
  19263. nextPlayPos = newPosition;
  19264. }
  19265. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19266. {
  19267. looping = shouldLoop;
  19268. }
  19269. int AudioFormatReaderSource::getNextReadPosition() const
  19270. {
  19271. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19272. : nextPlayPos;
  19273. }
  19274. int AudioFormatReaderSource::getTotalLength() const
  19275. {
  19276. return (int) reader->lengthInSamples;
  19277. }
  19278. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19279. double /*sampleRate*/)
  19280. {
  19281. }
  19282. void AudioFormatReaderSource::releaseResources()
  19283. {
  19284. }
  19285. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19286. {
  19287. if (info.numSamples > 0)
  19288. {
  19289. const int start = nextPlayPos;
  19290. if (looping)
  19291. {
  19292. const int newStart = start % (int) reader->lengthInSamples;
  19293. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19294. if (newEnd > newStart)
  19295. {
  19296. info.buffer->readFromAudioReader (reader,
  19297. info.startSample,
  19298. newEnd - newStart,
  19299. newStart,
  19300. true, true);
  19301. }
  19302. else
  19303. {
  19304. const int endSamps = (int) reader->lengthInSamples - newStart;
  19305. info.buffer->readFromAudioReader (reader,
  19306. info.startSample,
  19307. endSamps,
  19308. newStart,
  19309. true, true);
  19310. info.buffer->readFromAudioReader (reader,
  19311. info.startSample + endSamps,
  19312. newEnd,
  19313. 0,
  19314. true, true);
  19315. }
  19316. nextPlayPos = newEnd;
  19317. }
  19318. else
  19319. {
  19320. info.buffer->readFromAudioReader (reader,
  19321. info.startSample,
  19322. info.numSamples,
  19323. start,
  19324. true, true);
  19325. nextPlayPos += info.numSamples;
  19326. }
  19327. }
  19328. }
  19329. END_JUCE_NAMESPACE
  19330. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19331. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19332. BEGIN_JUCE_NAMESPACE
  19333. AudioSourcePlayer::AudioSourcePlayer()
  19334. : source (0),
  19335. sampleRate (0),
  19336. bufferSize (0),
  19337. tempBuffer (2, 8),
  19338. lastGain (1.0f),
  19339. gain (1.0f)
  19340. {
  19341. }
  19342. AudioSourcePlayer::~AudioSourcePlayer()
  19343. {
  19344. setSource (0);
  19345. }
  19346. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19347. {
  19348. if (source != newSource)
  19349. {
  19350. AudioSource* const oldSource = source;
  19351. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19352. newSource->prepareToPlay (bufferSize, sampleRate);
  19353. {
  19354. const ScopedLock sl (readLock);
  19355. source = newSource;
  19356. }
  19357. if (oldSource != 0)
  19358. oldSource->releaseResources();
  19359. }
  19360. }
  19361. void AudioSourcePlayer::setGain (const float newGain) throw()
  19362. {
  19363. gain = newGain;
  19364. }
  19365. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19366. int totalNumInputChannels,
  19367. float** outputChannelData,
  19368. int totalNumOutputChannels,
  19369. int numSamples)
  19370. {
  19371. // these should have been prepared by audioDeviceAboutToStart()...
  19372. jassert (sampleRate > 0 && bufferSize > 0);
  19373. const ScopedLock sl (readLock);
  19374. if (source != 0)
  19375. {
  19376. AudioSourceChannelInfo info;
  19377. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19378. // messy stuff needed to compact the channels down into an array
  19379. // of non-zero pointers..
  19380. for (i = 0; i < totalNumInputChannels; ++i)
  19381. {
  19382. if (inputChannelData[i] != 0)
  19383. {
  19384. inputChans [numInputs++] = inputChannelData[i];
  19385. if (numInputs >= numElementsInArray (inputChans))
  19386. break;
  19387. }
  19388. }
  19389. for (i = 0; i < totalNumOutputChannels; ++i)
  19390. {
  19391. if (outputChannelData[i] != 0)
  19392. {
  19393. outputChans [numOutputs++] = outputChannelData[i];
  19394. if (numOutputs >= numElementsInArray (outputChans))
  19395. break;
  19396. }
  19397. }
  19398. if (numInputs > numOutputs)
  19399. {
  19400. // if there aren't enough output channels for the number of
  19401. // inputs, we need to create some temporary extra ones (can't
  19402. // use the input data in case it gets written to)
  19403. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19404. false, false, true);
  19405. for (i = 0; i < numOutputs; ++i)
  19406. {
  19407. channels[numActiveChans] = outputChans[i];
  19408. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19409. ++numActiveChans;
  19410. }
  19411. for (i = numOutputs; i < numInputs; ++i)
  19412. {
  19413. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19414. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19415. ++numActiveChans;
  19416. }
  19417. }
  19418. else
  19419. {
  19420. for (i = 0; i < numInputs; ++i)
  19421. {
  19422. channels[numActiveChans] = outputChans[i];
  19423. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19424. ++numActiveChans;
  19425. }
  19426. for (i = numInputs; i < numOutputs; ++i)
  19427. {
  19428. channels[numActiveChans] = outputChans[i];
  19429. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19430. ++numActiveChans;
  19431. }
  19432. }
  19433. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19434. info.buffer = &buffer;
  19435. info.startSample = 0;
  19436. info.numSamples = numSamples;
  19437. source->getNextAudioBlock (info);
  19438. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19439. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19440. lastGain = gain;
  19441. }
  19442. else
  19443. {
  19444. for (int i = 0; i < totalNumOutputChannels; ++i)
  19445. if (outputChannelData[i] != 0)
  19446. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19447. }
  19448. }
  19449. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19450. {
  19451. sampleRate = device->getCurrentSampleRate();
  19452. bufferSize = device->getCurrentBufferSizeSamples();
  19453. zeromem (channels, sizeof (channels));
  19454. if (source != 0)
  19455. source->prepareToPlay (bufferSize, sampleRate);
  19456. }
  19457. void AudioSourcePlayer::audioDeviceStopped()
  19458. {
  19459. if (source != 0)
  19460. source->releaseResources();
  19461. sampleRate = 0.0;
  19462. bufferSize = 0;
  19463. tempBuffer.setSize (2, 8);
  19464. }
  19465. END_JUCE_NAMESPACE
  19466. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19467. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19468. BEGIN_JUCE_NAMESPACE
  19469. AudioTransportSource::AudioTransportSource()
  19470. : source (0),
  19471. resamplerSource (0),
  19472. bufferingSource (0),
  19473. positionableSource (0),
  19474. masterSource (0),
  19475. gain (1.0f),
  19476. lastGain (1.0f),
  19477. playing (false),
  19478. stopped (true),
  19479. sampleRate (44100.0),
  19480. sourceSampleRate (0.0),
  19481. blockSize (128),
  19482. readAheadBufferSize (0),
  19483. isPrepared (false),
  19484. inputStreamEOF (false)
  19485. {
  19486. }
  19487. AudioTransportSource::~AudioTransportSource()
  19488. {
  19489. setSource (0);
  19490. releaseResources();
  19491. }
  19492. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19493. int readAheadBufferSize_,
  19494. double sourceSampleRateToCorrectFor)
  19495. {
  19496. if (source == newSource)
  19497. {
  19498. if (source == 0)
  19499. return;
  19500. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19501. }
  19502. readAheadBufferSize = readAheadBufferSize_;
  19503. sourceSampleRate = sourceSampleRateToCorrectFor;
  19504. ResamplingAudioSource* newResamplerSource = 0;
  19505. BufferingAudioSource* newBufferingSource = 0;
  19506. PositionableAudioSource* newPositionableSource = 0;
  19507. AudioSource* newMasterSource = 0;
  19508. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19509. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19510. AudioSource* oldMasterSource = masterSource;
  19511. if (newSource != 0)
  19512. {
  19513. newPositionableSource = newSource;
  19514. if (readAheadBufferSize_ > 0)
  19515. newPositionableSource = newBufferingSource
  19516. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19517. newPositionableSource->setNextReadPosition (0);
  19518. if (sourceSampleRateToCorrectFor != 0)
  19519. newMasterSource = newResamplerSource
  19520. = new ResamplingAudioSource (newPositionableSource, false);
  19521. else
  19522. newMasterSource = newPositionableSource;
  19523. if (isPrepared)
  19524. {
  19525. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19526. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19527. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19528. }
  19529. }
  19530. {
  19531. const ScopedLock sl (callbackLock);
  19532. source = newSource;
  19533. resamplerSource = newResamplerSource;
  19534. bufferingSource = newBufferingSource;
  19535. masterSource = newMasterSource;
  19536. positionableSource = newPositionableSource;
  19537. playing = false;
  19538. }
  19539. if (oldMasterSource != 0)
  19540. oldMasterSource->releaseResources();
  19541. }
  19542. void AudioTransportSource::start()
  19543. {
  19544. if ((! playing) && masterSource != 0)
  19545. {
  19546. {
  19547. const ScopedLock sl (callbackLock);
  19548. playing = true;
  19549. stopped = false;
  19550. inputStreamEOF = false;
  19551. }
  19552. sendChangeMessage (this);
  19553. }
  19554. }
  19555. void AudioTransportSource::stop()
  19556. {
  19557. if (playing)
  19558. {
  19559. {
  19560. const ScopedLock sl (callbackLock);
  19561. playing = false;
  19562. }
  19563. int n = 500;
  19564. while (--n >= 0 && ! stopped)
  19565. Thread::sleep (2);
  19566. sendChangeMessage (this);
  19567. }
  19568. }
  19569. void AudioTransportSource::setPosition (double newPosition)
  19570. {
  19571. if (sampleRate > 0.0)
  19572. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19573. }
  19574. double AudioTransportSource::getCurrentPosition() const
  19575. {
  19576. if (sampleRate > 0.0)
  19577. return getNextReadPosition() / sampleRate;
  19578. else
  19579. return 0.0;
  19580. }
  19581. void AudioTransportSource::setNextReadPosition (int newPosition)
  19582. {
  19583. if (positionableSource != 0)
  19584. {
  19585. if (sampleRate > 0 && sourceSampleRate > 0)
  19586. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19587. positionableSource->setNextReadPosition (newPosition);
  19588. }
  19589. }
  19590. int AudioTransportSource::getNextReadPosition() const
  19591. {
  19592. if (positionableSource != 0)
  19593. {
  19594. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19595. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19596. }
  19597. return 0;
  19598. }
  19599. int AudioTransportSource::getTotalLength() const
  19600. {
  19601. const ScopedLock sl (callbackLock);
  19602. if (positionableSource != 0)
  19603. {
  19604. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19605. return roundToInt (positionableSource->getTotalLength() * ratio);
  19606. }
  19607. return 0;
  19608. }
  19609. bool AudioTransportSource::isLooping() const
  19610. {
  19611. const ScopedLock sl (callbackLock);
  19612. return positionableSource != 0
  19613. && positionableSource->isLooping();
  19614. }
  19615. void AudioTransportSource::setGain (const float newGain) throw()
  19616. {
  19617. gain = newGain;
  19618. }
  19619. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19620. double sampleRate_)
  19621. {
  19622. const ScopedLock sl (callbackLock);
  19623. sampleRate = sampleRate_;
  19624. blockSize = samplesPerBlockExpected;
  19625. if (masterSource != 0)
  19626. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19627. if (resamplerSource != 0 && sourceSampleRate != 0)
  19628. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19629. isPrepared = true;
  19630. }
  19631. void AudioTransportSource::releaseResources()
  19632. {
  19633. const ScopedLock sl (callbackLock);
  19634. if (masterSource != 0)
  19635. masterSource->releaseResources();
  19636. isPrepared = false;
  19637. }
  19638. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19639. {
  19640. const ScopedLock sl (callbackLock);
  19641. inputStreamEOF = false;
  19642. if (masterSource != 0 && ! stopped)
  19643. {
  19644. masterSource->getNextAudioBlock (info);
  19645. if (! playing)
  19646. {
  19647. // just stopped playing, so fade out the last block..
  19648. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19649. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19650. if (info.numSamples > 256)
  19651. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19652. }
  19653. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19654. && ! positionableSource->isLooping())
  19655. {
  19656. playing = false;
  19657. inputStreamEOF = true;
  19658. sendChangeMessage (this);
  19659. }
  19660. stopped = ! playing;
  19661. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19662. {
  19663. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19664. lastGain, gain);
  19665. }
  19666. }
  19667. else
  19668. {
  19669. info.clearActiveBufferRegion();
  19670. stopped = true;
  19671. }
  19672. lastGain = gain;
  19673. }
  19674. END_JUCE_NAMESPACE
  19675. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19676. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19677. BEGIN_JUCE_NAMESPACE
  19678. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19679. public Thread,
  19680. private Timer
  19681. {
  19682. public:
  19683. SharedBufferingAudioSourceThread()
  19684. : Thread ("Audio Buffer")
  19685. {
  19686. }
  19687. ~SharedBufferingAudioSourceThread()
  19688. {
  19689. stopThread (10000);
  19690. clearSingletonInstance();
  19691. }
  19692. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19693. void addSource (BufferingAudioSource* source)
  19694. {
  19695. const ScopedLock sl (lock);
  19696. if (! sources.contains (source))
  19697. {
  19698. sources.add (source);
  19699. startThread();
  19700. stopTimer();
  19701. }
  19702. notify();
  19703. }
  19704. void removeSource (BufferingAudioSource* source)
  19705. {
  19706. const ScopedLock sl (lock);
  19707. sources.removeValue (source);
  19708. if (sources.size() == 0)
  19709. startTimer (5000);
  19710. }
  19711. private:
  19712. Array <BufferingAudioSource*> sources;
  19713. CriticalSection lock;
  19714. void run()
  19715. {
  19716. while (! threadShouldExit())
  19717. {
  19718. bool busy = false;
  19719. for (int i = sources.size(); --i >= 0;)
  19720. {
  19721. if (threadShouldExit())
  19722. return;
  19723. const ScopedLock sl (lock);
  19724. BufferingAudioSource* const b = sources[i];
  19725. if (b != 0 && b->readNextBufferChunk())
  19726. busy = true;
  19727. }
  19728. if (! busy)
  19729. wait (500);
  19730. }
  19731. }
  19732. void timerCallback()
  19733. {
  19734. stopTimer();
  19735. if (sources.size() == 0)
  19736. deleteInstance();
  19737. }
  19738. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19739. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19740. };
  19741. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19742. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19743. const bool deleteSourceWhenDeleted_,
  19744. int numberOfSamplesToBuffer_)
  19745. : source (source_),
  19746. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19747. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19748. buffer (2, 0),
  19749. bufferValidStart (0),
  19750. bufferValidEnd (0),
  19751. nextPlayPos (0),
  19752. wasSourceLooping (false)
  19753. {
  19754. jassert (source_ != 0);
  19755. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19756. // not using a larger buffer..
  19757. }
  19758. BufferingAudioSource::~BufferingAudioSource()
  19759. {
  19760. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19761. if (thread != 0)
  19762. thread->removeSource (this);
  19763. if (deleteSourceWhenDeleted)
  19764. delete source;
  19765. }
  19766. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19767. {
  19768. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19769. sampleRate = sampleRate_;
  19770. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19771. buffer.clear();
  19772. bufferValidStart = 0;
  19773. bufferValidEnd = 0;
  19774. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19775. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19776. buffer.getNumSamples() / 2))
  19777. {
  19778. SharedBufferingAudioSourceThread::getInstance()->notify();
  19779. Thread::sleep (5);
  19780. }
  19781. }
  19782. void BufferingAudioSource::releaseResources()
  19783. {
  19784. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19785. if (thread != 0)
  19786. thread->removeSource (this);
  19787. buffer.setSize (2, 0);
  19788. source->releaseResources();
  19789. }
  19790. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19791. {
  19792. const ScopedLock sl (bufferStartPosLock);
  19793. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19794. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19795. if (validStart == validEnd)
  19796. {
  19797. // total cache miss
  19798. info.clearActiveBufferRegion();
  19799. }
  19800. else
  19801. {
  19802. if (validStart > 0)
  19803. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19804. if (validEnd < info.numSamples)
  19805. info.buffer->clear (info.startSample + validEnd,
  19806. info.numSamples - validEnd); // partial cache miss at end
  19807. if (validStart < validEnd)
  19808. {
  19809. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19810. {
  19811. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19812. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19813. if (startBufferIndex < endBufferIndex)
  19814. {
  19815. info.buffer->copyFrom (chan, info.startSample + validStart,
  19816. buffer,
  19817. chan, startBufferIndex,
  19818. validEnd - validStart);
  19819. }
  19820. else
  19821. {
  19822. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19823. info.buffer->copyFrom (chan, info.startSample + validStart,
  19824. buffer,
  19825. chan, startBufferIndex,
  19826. initialSize);
  19827. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19828. buffer,
  19829. chan, 0,
  19830. (validEnd - validStart) - initialSize);
  19831. }
  19832. }
  19833. }
  19834. nextPlayPos += info.numSamples;
  19835. if (source->isLooping() && nextPlayPos > 0)
  19836. nextPlayPos %= source->getTotalLength();
  19837. }
  19838. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19839. if (thread != 0)
  19840. thread->notify();
  19841. }
  19842. int BufferingAudioSource::getNextReadPosition() const
  19843. {
  19844. return (source->isLooping() && nextPlayPos > 0)
  19845. ? nextPlayPos % source->getTotalLength()
  19846. : nextPlayPos;
  19847. }
  19848. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19849. {
  19850. const ScopedLock sl (bufferStartPosLock);
  19851. nextPlayPos = newPosition;
  19852. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19853. if (thread != 0)
  19854. thread->notify();
  19855. }
  19856. bool BufferingAudioSource::readNextBufferChunk()
  19857. {
  19858. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19859. {
  19860. const ScopedLock sl (bufferStartPosLock);
  19861. if (wasSourceLooping != isLooping())
  19862. {
  19863. wasSourceLooping = isLooping();
  19864. bufferValidStart = 0;
  19865. bufferValidEnd = 0;
  19866. }
  19867. newBVS = jmax (0, nextPlayPos);
  19868. newBVE = newBVS + buffer.getNumSamples() - 4;
  19869. sectionToReadStart = 0;
  19870. sectionToReadEnd = 0;
  19871. const int maxChunkSize = 2048;
  19872. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19873. {
  19874. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19875. sectionToReadStart = newBVS;
  19876. sectionToReadEnd = newBVE;
  19877. bufferValidStart = 0;
  19878. bufferValidEnd = 0;
  19879. }
  19880. else if (abs (newBVS - bufferValidStart) > 512
  19881. || abs (newBVE - bufferValidEnd) > 512)
  19882. {
  19883. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19884. sectionToReadStart = bufferValidEnd;
  19885. sectionToReadEnd = newBVE;
  19886. bufferValidStart = newBVS;
  19887. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19888. }
  19889. }
  19890. if (sectionToReadStart != sectionToReadEnd)
  19891. {
  19892. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19893. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19894. if (bufferIndexStart < bufferIndexEnd)
  19895. {
  19896. readBufferSection (sectionToReadStart,
  19897. sectionToReadEnd - sectionToReadStart,
  19898. bufferIndexStart);
  19899. }
  19900. else
  19901. {
  19902. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19903. readBufferSection (sectionToReadStart,
  19904. initialSize,
  19905. bufferIndexStart);
  19906. readBufferSection (sectionToReadStart + initialSize,
  19907. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19908. 0);
  19909. }
  19910. const ScopedLock sl2 (bufferStartPosLock);
  19911. bufferValidStart = newBVS;
  19912. bufferValidEnd = newBVE;
  19913. return true;
  19914. }
  19915. else
  19916. {
  19917. return false;
  19918. }
  19919. }
  19920. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19921. {
  19922. if (source->getNextReadPosition() != start)
  19923. source->setNextReadPosition (start);
  19924. AudioSourceChannelInfo info;
  19925. info.buffer = &buffer;
  19926. info.startSample = bufferOffset;
  19927. info.numSamples = length;
  19928. source->getNextAudioBlock (info);
  19929. }
  19930. END_JUCE_NAMESPACE
  19931. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19932. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19933. BEGIN_JUCE_NAMESPACE
  19934. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19935. const bool deleteSourceWhenDeleted_)
  19936. : requiredNumberOfChannels (2),
  19937. source (source_),
  19938. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19939. buffer (2, 16)
  19940. {
  19941. remappedInfo.buffer = &buffer;
  19942. remappedInfo.startSample = 0;
  19943. }
  19944. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19945. {
  19946. if (deleteSourceWhenDeleted)
  19947. delete source;
  19948. }
  19949. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19950. {
  19951. const ScopedLock sl (lock);
  19952. requiredNumberOfChannels = requiredNumberOfChannels_;
  19953. }
  19954. void ChannelRemappingAudioSource::clearAllMappings()
  19955. {
  19956. const ScopedLock sl (lock);
  19957. remappedInputs.clear();
  19958. remappedOutputs.clear();
  19959. }
  19960. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19961. {
  19962. const ScopedLock sl (lock);
  19963. while (remappedInputs.size() < destIndex)
  19964. remappedInputs.add (-1);
  19965. remappedInputs.set (destIndex, sourceIndex);
  19966. }
  19967. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19968. {
  19969. const ScopedLock sl (lock);
  19970. while (remappedOutputs.size() < sourceIndex)
  19971. remappedOutputs.add (-1);
  19972. remappedOutputs.set (sourceIndex, destIndex);
  19973. }
  19974. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19975. {
  19976. const ScopedLock sl (lock);
  19977. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19978. return remappedInputs.getUnchecked (inputChannelIndex);
  19979. return -1;
  19980. }
  19981. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19982. {
  19983. const ScopedLock sl (lock);
  19984. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19985. return remappedOutputs .getUnchecked (outputChannelIndex);
  19986. return -1;
  19987. }
  19988. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19989. {
  19990. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19991. }
  19992. void ChannelRemappingAudioSource::releaseResources()
  19993. {
  19994. source->releaseResources();
  19995. }
  19996. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19997. {
  19998. const ScopedLock sl (lock);
  19999. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  20000. const int numChans = bufferToFill.buffer->getNumChannels();
  20001. int i;
  20002. for (i = 0; i < buffer.getNumChannels(); ++i)
  20003. {
  20004. const int remappedChan = getRemappedInputChannel (i);
  20005. if (remappedChan >= 0 && remappedChan < numChans)
  20006. {
  20007. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  20008. remappedChan,
  20009. bufferToFill.startSample,
  20010. bufferToFill.numSamples);
  20011. }
  20012. else
  20013. {
  20014. buffer.clear (i, 0, bufferToFill.numSamples);
  20015. }
  20016. }
  20017. remappedInfo.numSamples = bufferToFill.numSamples;
  20018. source->getNextAudioBlock (remappedInfo);
  20019. bufferToFill.clearActiveBufferRegion();
  20020. for (i = 0; i < requiredNumberOfChannels; ++i)
  20021. {
  20022. const int remappedChan = getRemappedOutputChannel (i);
  20023. if (remappedChan >= 0 && remappedChan < numChans)
  20024. {
  20025. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  20026. buffer, i, 0, bufferToFill.numSamples);
  20027. }
  20028. }
  20029. }
  20030. XmlElement* ChannelRemappingAudioSource::createXml() const
  20031. {
  20032. XmlElement* e = new XmlElement ("MAPPINGS");
  20033. String ins, outs;
  20034. int i;
  20035. const ScopedLock sl (lock);
  20036. for (i = 0; i < remappedInputs.size(); ++i)
  20037. ins << remappedInputs.getUnchecked(i) << ' ';
  20038. for (i = 0; i < remappedOutputs.size(); ++i)
  20039. outs << remappedOutputs.getUnchecked(i) << ' ';
  20040. e->setAttribute ("inputs", ins.trimEnd());
  20041. e->setAttribute ("outputs", outs.trimEnd());
  20042. return e;
  20043. }
  20044. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  20045. {
  20046. if (e.hasTagName ("MAPPINGS"))
  20047. {
  20048. const ScopedLock sl (lock);
  20049. clearAllMappings();
  20050. StringArray ins, outs;
  20051. ins.addTokens (e.getStringAttribute ("inputs"), false);
  20052. outs.addTokens (e.getStringAttribute ("outputs"), false);
  20053. int i;
  20054. for (i = 0; i < ins.size(); ++i)
  20055. remappedInputs.add (ins[i].getIntValue());
  20056. for (i = 0; i < outs.size(); ++i)
  20057. remappedOutputs.add (outs[i].getIntValue());
  20058. }
  20059. }
  20060. END_JUCE_NAMESPACE
  20061. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  20062. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  20063. BEGIN_JUCE_NAMESPACE
  20064. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  20065. const bool deleteInputWhenDeleted_)
  20066. : input (inputSource),
  20067. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  20068. {
  20069. jassert (inputSource != 0);
  20070. for (int i = 2; --i >= 0;)
  20071. iirFilters.add (new IIRFilter());
  20072. }
  20073. IIRFilterAudioSource::~IIRFilterAudioSource()
  20074. {
  20075. if (deleteInputWhenDeleted)
  20076. delete input;
  20077. }
  20078. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  20079. {
  20080. for (int i = iirFilters.size(); --i >= 0;)
  20081. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  20082. }
  20083. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  20084. {
  20085. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20086. for (int i = iirFilters.size(); --i >= 0;)
  20087. iirFilters.getUnchecked(i)->reset();
  20088. }
  20089. void IIRFilterAudioSource::releaseResources()
  20090. {
  20091. input->releaseResources();
  20092. }
  20093. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  20094. {
  20095. input->getNextAudioBlock (bufferToFill);
  20096. const int numChannels = bufferToFill.buffer->getNumChannels();
  20097. while (numChannels > iirFilters.size())
  20098. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  20099. for (int i = 0; i < numChannels; ++i)
  20100. iirFilters.getUnchecked(i)
  20101. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  20102. bufferToFill.numSamples);
  20103. }
  20104. END_JUCE_NAMESPACE
  20105. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  20106. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  20107. BEGIN_JUCE_NAMESPACE
  20108. MixerAudioSource::MixerAudioSource()
  20109. : tempBuffer (2, 0),
  20110. currentSampleRate (0.0),
  20111. bufferSizeExpected (0)
  20112. {
  20113. }
  20114. MixerAudioSource::~MixerAudioSource()
  20115. {
  20116. removeAllInputs();
  20117. }
  20118. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  20119. {
  20120. if (input != 0 && ! inputs.contains (input))
  20121. {
  20122. double localRate;
  20123. int localBufferSize;
  20124. {
  20125. const ScopedLock sl (lock);
  20126. localRate = currentSampleRate;
  20127. localBufferSize = bufferSizeExpected;
  20128. }
  20129. if (localRate != 0.0)
  20130. input->prepareToPlay (localBufferSize, localRate);
  20131. const ScopedLock sl (lock);
  20132. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  20133. inputs.add (input);
  20134. }
  20135. }
  20136. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  20137. {
  20138. if (input != 0)
  20139. {
  20140. int index;
  20141. {
  20142. const ScopedLock sl (lock);
  20143. index = inputs.indexOf (input);
  20144. if (index >= 0)
  20145. {
  20146. inputsToDelete.shiftBits (index, 1);
  20147. inputs.remove (index);
  20148. }
  20149. }
  20150. if (index >= 0)
  20151. {
  20152. input->releaseResources();
  20153. if (deleteInput)
  20154. delete input;
  20155. }
  20156. }
  20157. }
  20158. void MixerAudioSource::removeAllInputs()
  20159. {
  20160. OwnedArray<AudioSource> toDelete;
  20161. {
  20162. const ScopedLock sl (lock);
  20163. for (int i = inputs.size(); --i >= 0;)
  20164. if (inputsToDelete[i])
  20165. toDelete.add (inputs.getUnchecked(i));
  20166. }
  20167. }
  20168. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  20169. {
  20170. tempBuffer.setSize (2, samplesPerBlockExpected);
  20171. const ScopedLock sl (lock);
  20172. currentSampleRate = sampleRate;
  20173. bufferSizeExpected = samplesPerBlockExpected;
  20174. for (int i = inputs.size(); --i >= 0;)
  20175. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20176. }
  20177. void MixerAudioSource::releaseResources()
  20178. {
  20179. const ScopedLock sl (lock);
  20180. for (int i = inputs.size(); --i >= 0;)
  20181. inputs.getUnchecked(i)->releaseResources();
  20182. tempBuffer.setSize (2, 0);
  20183. currentSampleRate = 0;
  20184. bufferSizeExpected = 0;
  20185. }
  20186. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20187. {
  20188. const ScopedLock sl (lock);
  20189. if (inputs.size() > 0)
  20190. {
  20191. inputs.getUnchecked(0)->getNextAudioBlock (info);
  20192. if (inputs.size() > 1)
  20193. {
  20194. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  20195. info.buffer->getNumSamples());
  20196. AudioSourceChannelInfo info2;
  20197. info2.buffer = &tempBuffer;
  20198. info2.numSamples = info.numSamples;
  20199. info2.startSample = 0;
  20200. for (int i = 1; i < inputs.size(); ++i)
  20201. {
  20202. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  20203. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  20204. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  20205. }
  20206. }
  20207. }
  20208. else
  20209. {
  20210. info.clearActiveBufferRegion();
  20211. }
  20212. }
  20213. END_JUCE_NAMESPACE
  20214. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  20215. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  20216. BEGIN_JUCE_NAMESPACE
  20217. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  20218. const bool deleteInputWhenDeleted_,
  20219. const int numChannels_)
  20220. : input (inputSource),
  20221. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  20222. ratio (1.0),
  20223. lastRatio (1.0),
  20224. buffer (numChannels_, 0),
  20225. sampsInBuffer (0),
  20226. numChannels (numChannels_)
  20227. {
  20228. jassert (input != 0);
  20229. }
  20230. ResamplingAudioSource::~ResamplingAudioSource()
  20231. {
  20232. if (deleteInputWhenDeleted)
  20233. delete input;
  20234. }
  20235. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  20236. {
  20237. jassert (samplesInPerOutputSample > 0);
  20238. const ScopedLock sl (ratioLock);
  20239. ratio = jmax (0.0, samplesInPerOutputSample);
  20240. }
  20241. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  20242. double sampleRate)
  20243. {
  20244. const ScopedLock sl (ratioLock);
  20245. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20246. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  20247. buffer.clear();
  20248. sampsInBuffer = 0;
  20249. bufferPos = 0;
  20250. subSampleOffset = 0.0;
  20251. filterStates.calloc (numChannels);
  20252. srcBuffers.calloc (numChannels);
  20253. destBuffers.calloc (numChannels);
  20254. createLowPass (ratio);
  20255. resetFilters();
  20256. }
  20257. void ResamplingAudioSource::releaseResources()
  20258. {
  20259. input->releaseResources();
  20260. buffer.setSize (numChannels, 0);
  20261. }
  20262. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20263. {
  20264. const ScopedLock sl (ratioLock);
  20265. if (lastRatio != ratio)
  20266. {
  20267. createLowPass (ratio);
  20268. lastRatio = ratio;
  20269. }
  20270. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20271. int bufferSize = buffer.getNumSamples();
  20272. if (bufferSize < sampsNeeded + 8)
  20273. {
  20274. bufferPos %= bufferSize;
  20275. bufferSize = sampsNeeded + 32;
  20276. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20277. }
  20278. bufferPos %= bufferSize;
  20279. int endOfBufferPos = bufferPos + sampsInBuffer;
  20280. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20281. while (sampsNeeded > sampsInBuffer)
  20282. {
  20283. endOfBufferPos %= bufferSize;
  20284. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20285. bufferSize - endOfBufferPos);
  20286. AudioSourceChannelInfo readInfo;
  20287. readInfo.buffer = &buffer;
  20288. readInfo.numSamples = numToDo;
  20289. readInfo.startSample = endOfBufferPos;
  20290. input->getNextAudioBlock (readInfo);
  20291. if (ratio > 1.0001)
  20292. {
  20293. // for down-sampling, pre-apply the filter..
  20294. for (int i = channelsToProcess; --i >= 0;)
  20295. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20296. }
  20297. sampsInBuffer += numToDo;
  20298. endOfBufferPos += numToDo;
  20299. }
  20300. for (int channel = 0; channel < channelsToProcess; ++channel)
  20301. {
  20302. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20303. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20304. }
  20305. int nextPos = (bufferPos + 1) % bufferSize;
  20306. for (int m = info.numSamples; --m >= 0;)
  20307. {
  20308. const float alpha = (float) subSampleOffset;
  20309. const float invAlpha = 1.0f - alpha;
  20310. for (int channel = 0; channel < channelsToProcess; ++channel)
  20311. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20312. subSampleOffset += ratio;
  20313. jassert (sampsInBuffer > 0);
  20314. while (subSampleOffset >= 1.0)
  20315. {
  20316. if (++bufferPos >= bufferSize)
  20317. bufferPos = 0;
  20318. --sampsInBuffer;
  20319. nextPos = (bufferPos + 1) % bufferSize;
  20320. subSampleOffset -= 1.0;
  20321. }
  20322. }
  20323. if (ratio < 0.9999)
  20324. {
  20325. // for up-sampling, apply the filter after transposing..
  20326. for (int i = channelsToProcess; --i >= 0;)
  20327. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20328. }
  20329. else if (ratio <= 1.0001)
  20330. {
  20331. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20332. for (int i = channelsToProcess; --i >= 0;)
  20333. {
  20334. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20335. FilterState& fs = filterStates[i];
  20336. if (info.numSamples > 1)
  20337. {
  20338. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20339. }
  20340. else
  20341. {
  20342. fs.y2 = fs.y1;
  20343. fs.x2 = fs.x1;
  20344. }
  20345. fs.y1 = fs.x1 = *endOfBuffer;
  20346. }
  20347. }
  20348. jassert (sampsInBuffer >= 0);
  20349. }
  20350. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20351. {
  20352. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20353. : 0.5 * frequencyRatio;
  20354. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20355. const double nSquared = n * n;
  20356. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20357. setFilterCoefficients (c1,
  20358. c1 * 2.0f,
  20359. c1,
  20360. 1.0,
  20361. c1 * 2.0 * (1.0 - nSquared),
  20362. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20363. }
  20364. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20365. {
  20366. const double a = 1.0 / c4;
  20367. c1 *= a;
  20368. c2 *= a;
  20369. c3 *= a;
  20370. c5 *= a;
  20371. c6 *= a;
  20372. coefficients[0] = c1;
  20373. coefficients[1] = c2;
  20374. coefficients[2] = c3;
  20375. coefficients[3] = c4;
  20376. coefficients[4] = c5;
  20377. coefficients[5] = c6;
  20378. }
  20379. void ResamplingAudioSource::resetFilters()
  20380. {
  20381. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20382. }
  20383. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20384. {
  20385. while (--num >= 0)
  20386. {
  20387. const double in = *samples;
  20388. double out = coefficients[0] * in
  20389. + coefficients[1] * fs.x1
  20390. + coefficients[2] * fs.x2
  20391. - coefficients[4] * fs.y1
  20392. - coefficients[5] * fs.y2;
  20393. #if JUCE_INTEL
  20394. if (! (out < -1.0e-8 || out > 1.0e-8))
  20395. out = 0;
  20396. #endif
  20397. fs.x2 = fs.x1;
  20398. fs.x1 = in;
  20399. fs.y2 = fs.y1;
  20400. fs.y1 = out;
  20401. *samples++ = (float) out;
  20402. }
  20403. }
  20404. END_JUCE_NAMESPACE
  20405. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20406. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20407. BEGIN_JUCE_NAMESPACE
  20408. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20409. : frequency (1000.0),
  20410. sampleRate (44100.0),
  20411. currentPhase (0.0),
  20412. phasePerSample (0.0),
  20413. amplitude (0.5f)
  20414. {
  20415. }
  20416. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20417. {
  20418. }
  20419. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20420. {
  20421. amplitude = newAmplitude;
  20422. }
  20423. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20424. {
  20425. frequency = newFrequencyHz;
  20426. phasePerSample = 0.0;
  20427. }
  20428. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20429. double sampleRate_)
  20430. {
  20431. currentPhase = 0.0;
  20432. phasePerSample = 0.0;
  20433. sampleRate = sampleRate_;
  20434. }
  20435. void ToneGeneratorAudioSource::releaseResources()
  20436. {
  20437. }
  20438. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20439. {
  20440. if (phasePerSample == 0.0)
  20441. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20442. for (int i = 0; i < info.numSamples; ++i)
  20443. {
  20444. const float sample = amplitude * (float) std::sin (currentPhase);
  20445. currentPhase += phasePerSample;
  20446. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20447. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20448. }
  20449. }
  20450. END_JUCE_NAMESPACE
  20451. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20452. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20453. BEGIN_JUCE_NAMESPACE
  20454. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20455. : sampleRate (0),
  20456. bufferSize (0),
  20457. useDefaultInputChannels (true),
  20458. useDefaultOutputChannels (true)
  20459. {
  20460. }
  20461. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20462. {
  20463. return outputDeviceName == other.outputDeviceName
  20464. && inputDeviceName == other.inputDeviceName
  20465. && sampleRate == other.sampleRate
  20466. && bufferSize == other.bufferSize
  20467. && inputChannels == other.inputChannels
  20468. && useDefaultInputChannels == other.useDefaultInputChannels
  20469. && outputChannels == other.outputChannels
  20470. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20471. }
  20472. AudioDeviceManager::AudioDeviceManager()
  20473. : currentAudioDevice (0),
  20474. numInputChansNeeded (0),
  20475. numOutputChansNeeded (2),
  20476. listNeedsScanning (true),
  20477. useInputNames (false),
  20478. inputLevelMeasurementEnabledCount (0),
  20479. inputLevel (0),
  20480. tempBuffer (2, 2),
  20481. defaultMidiOutput (0),
  20482. cpuUsageMs (0),
  20483. timeToCpuScale (0)
  20484. {
  20485. callbackHandler.owner = this;
  20486. }
  20487. AudioDeviceManager::~AudioDeviceManager()
  20488. {
  20489. currentAudioDevice = 0;
  20490. defaultMidiOutput = 0;
  20491. }
  20492. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20493. {
  20494. if (availableDeviceTypes.size() == 0)
  20495. {
  20496. createAudioDeviceTypes (availableDeviceTypes);
  20497. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20498. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20499. if (availableDeviceTypes.size() > 0)
  20500. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20501. }
  20502. }
  20503. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20504. {
  20505. scanDevicesIfNeeded();
  20506. return availableDeviceTypes;
  20507. }
  20508. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20509. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20510. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20511. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20512. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20513. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20514. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20515. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20516. {
  20517. (void) list; // (to avoid 'unused param' warnings)
  20518. #if JUCE_WINDOWS
  20519. #if JUCE_WASAPI
  20520. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20521. list.add (juce_createAudioIODeviceType_WASAPI());
  20522. #endif
  20523. #if JUCE_DIRECTSOUND
  20524. list.add (juce_createAudioIODeviceType_DirectSound());
  20525. #endif
  20526. #if JUCE_ASIO
  20527. list.add (juce_createAudioIODeviceType_ASIO());
  20528. #endif
  20529. #endif
  20530. #if JUCE_MAC
  20531. list.add (juce_createAudioIODeviceType_CoreAudio());
  20532. #endif
  20533. #if JUCE_IOS
  20534. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20535. #endif
  20536. #if JUCE_LINUX && JUCE_ALSA
  20537. list.add (juce_createAudioIODeviceType_ALSA());
  20538. #endif
  20539. #if JUCE_LINUX && JUCE_JACK
  20540. list.add (juce_createAudioIODeviceType_JACK());
  20541. #endif
  20542. }
  20543. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20544. const int numOutputChannelsNeeded,
  20545. const XmlElement* const e,
  20546. const bool selectDefaultDeviceOnFailure,
  20547. const String& preferredDefaultDeviceName,
  20548. const AudioDeviceSetup* preferredSetupOptions)
  20549. {
  20550. scanDevicesIfNeeded();
  20551. numInputChansNeeded = numInputChannelsNeeded;
  20552. numOutputChansNeeded = numOutputChannelsNeeded;
  20553. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20554. {
  20555. lastExplicitSettings = new XmlElement (*e);
  20556. String error;
  20557. AudioDeviceSetup setup;
  20558. if (preferredSetupOptions != 0)
  20559. setup = *preferredSetupOptions;
  20560. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20561. {
  20562. setup.inputDeviceName = setup.outputDeviceName
  20563. = e->getStringAttribute ("audioDeviceName");
  20564. }
  20565. else
  20566. {
  20567. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20568. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20569. }
  20570. currentDeviceType = e->getStringAttribute ("deviceType");
  20571. if (currentDeviceType.isEmpty())
  20572. {
  20573. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20574. if (type != 0)
  20575. currentDeviceType = type->getTypeName();
  20576. else if (availableDeviceTypes.size() > 0)
  20577. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20578. }
  20579. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20580. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20581. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20582. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20583. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20584. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20585. error = setAudioDeviceSetup (setup, true);
  20586. midiInsFromXml.clear();
  20587. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20588. midiInsFromXml.add (c->getStringAttribute ("name"));
  20589. const StringArray allMidiIns (MidiInput::getDevices());
  20590. for (int i = allMidiIns.size(); --i >= 0;)
  20591. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20592. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20593. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20594. false, preferredDefaultDeviceName);
  20595. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20596. return error;
  20597. }
  20598. else
  20599. {
  20600. AudioDeviceSetup setup;
  20601. if (preferredSetupOptions != 0)
  20602. {
  20603. setup = *preferredSetupOptions;
  20604. }
  20605. else if (preferredDefaultDeviceName.isNotEmpty())
  20606. {
  20607. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20608. {
  20609. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20610. StringArray outs (type->getDeviceNames (false));
  20611. int i;
  20612. for (i = 0; i < outs.size(); ++i)
  20613. {
  20614. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20615. {
  20616. setup.outputDeviceName = outs[i];
  20617. break;
  20618. }
  20619. }
  20620. StringArray ins (type->getDeviceNames (true));
  20621. for (i = 0; i < ins.size(); ++i)
  20622. {
  20623. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20624. {
  20625. setup.inputDeviceName = ins[i];
  20626. break;
  20627. }
  20628. }
  20629. }
  20630. }
  20631. insertDefaultDeviceNames (setup);
  20632. return setAudioDeviceSetup (setup, false);
  20633. }
  20634. }
  20635. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20636. {
  20637. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20638. if (type != 0)
  20639. {
  20640. if (setup.outputDeviceName.isEmpty())
  20641. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20642. if (setup.inputDeviceName.isEmpty())
  20643. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20644. }
  20645. }
  20646. XmlElement* AudioDeviceManager::createStateXml() const
  20647. {
  20648. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20649. }
  20650. void AudioDeviceManager::scanDevicesIfNeeded()
  20651. {
  20652. if (listNeedsScanning)
  20653. {
  20654. listNeedsScanning = false;
  20655. createDeviceTypesIfNeeded();
  20656. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20657. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20658. }
  20659. }
  20660. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20661. {
  20662. scanDevicesIfNeeded();
  20663. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20664. {
  20665. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20666. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20667. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20668. {
  20669. return type;
  20670. }
  20671. }
  20672. return 0;
  20673. }
  20674. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20675. {
  20676. setup = currentSetup;
  20677. }
  20678. void AudioDeviceManager::deleteCurrentDevice()
  20679. {
  20680. currentAudioDevice = 0;
  20681. currentSetup.inputDeviceName = String::empty;
  20682. currentSetup.outputDeviceName = String::empty;
  20683. }
  20684. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20685. const bool treatAsChosenDevice)
  20686. {
  20687. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20688. {
  20689. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20690. && currentDeviceType != type)
  20691. {
  20692. currentDeviceType = type;
  20693. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20694. insertDefaultDeviceNames (s);
  20695. setAudioDeviceSetup (s, treatAsChosenDevice);
  20696. sendChangeMessage (this);
  20697. break;
  20698. }
  20699. }
  20700. }
  20701. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20702. {
  20703. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20704. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20705. return availableDeviceTypes[i];
  20706. return availableDeviceTypes[0];
  20707. }
  20708. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20709. const bool treatAsChosenDevice)
  20710. {
  20711. jassert (&newSetup != &currentSetup); // this will have no effect
  20712. if (newSetup == currentSetup && currentAudioDevice != 0)
  20713. return String::empty;
  20714. if (! (newSetup == currentSetup))
  20715. sendChangeMessage (this);
  20716. stopDevice();
  20717. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20718. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20719. String error;
  20720. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20721. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20722. {
  20723. deleteCurrentDevice();
  20724. if (treatAsChosenDevice)
  20725. updateXml();
  20726. return String::empty;
  20727. }
  20728. if (currentSetup.inputDeviceName != newInputDeviceName
  20729. || currentSetup.outputDeviceName != newOutputDeviceName
  20730. || currentAudioDevice == 0)
  20731. {
  20732. deleteCurrentDevice();
  20733. scanDevicesIfNeeded();
  20734. if (newOutputDeviceName.isNotEmpty()
  20735. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20736. {
  20737. return "No such device: " + newOutputDeviceName;
  20738. }
  20739. if (newInputDeviceName.isNotEmpty()
  20740. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20741. {
  20742. return "No such device: " + newInputDeviceName;
  20743. }
  20744. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20745. if (currentAudioDevice == 0)
  20746. 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!";
  20747. else
  20748. error = currentAudioDevice->getLastError();
  20749. if (error.isNotEmpty())
  20750. {
  20751. deleteCurrentDevice();
  20752. return error;
  20753. }
  20754. if (newSetup.useDefaultInputChannels)
  20755. {
  20756. inputChannels.clear();
  20757. inputChannels.setRange (0, numInputChansNeeded, true);
  20758. }
  20759. if (newSetup.useDefaultOutputChannels)
  20760. {
  20761. outputChannels.clear();
  20762. outputChannels.setRange (0, numOutputChansNeeded, true);
  20763. }
  20764. if (newInputDeviceName.isEmpty())
  20765. inputChannels.clear();
  20766. if (newOutputDeviceName.isEmpty())
  20767. outputChannels.clear();
  20768. }
  20769. if (! newSetup.useDefaultInputChannels)
  20770. inputChannels = newSetup.inputChannels;
  20771. if (! newSetup.useDefaultOutputChannels)
  20772. outputChannels = newSetup.outputChannels;
  20773. currentSetup = newSetup;
  20774. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20775. error = currentAudioDevice->open (inputChannels,
  20776. outputChannels,
  20777. currentSetup.sampleRate,
  20778. currentSetup.bufferSize);
  20779. if (error.isEmpty())
  20780. {
  20781. currentDeviceType = currentAudioDevice->getTypeName();
  20782. currentAudioDevice->start (&callbackHandler);
  20783. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20784. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20785. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20786. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20787. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20788. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20789. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20790. if (treatAsChosenDevice)
  20791. updateXml();
  20792. }
  20793. else
  20794. {
  20795. deleteCurrentDevice();
  20796. }
  20797. return error;
  20798. }
  20799. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20800. {
  20801. jassert (currentAudioDevice != 0);
  20802. if (rate > 0)
  20803. {
  20804. bool ok = false;
  20805. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20806. {
  20807. const double sr = currentAudioDevice->getSampleRate (i);
  20808. if (sr == rate)
  20809. ok = true;
  20810. }
  20811. if (! ok)
  20812. rate = 0;
  20813. }
  20814. if (rate == 0)
  20815. {
  20816. double lowestAbove44 = 0.0;
  20817. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20818. {
  20819. const double sr = currentAudioDevice->getSampleRate (i);
  20820. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20821. lowestAbove44 = sr;
  20822. }
  20823. if (lowestAbove44 == 0.0)
  20824. rate = currentAudioDevice->getSampleRate (0);
  20825. else
  20826. rate = lowestAbove44;
  20827. }
  20828. return rate;
  20829. }
  20830. void AudioDeviceManager::stopDevice()
  20831. {
  20832. if (currentAudioDevice != 0)
  20833. currentAudioDevice->stop();
  20834. testSound = 0;
  20835. }
  20836. void AudioDeviceManager::closeAudioDevice()
  20837. {
  20838. stopDevice();
  20839. currentAudioDevice = 0;
  20840. }
  20841. void AudioDeviceManager::restartLastAudioDevice()
  20842. {
  20843. if (currentAudioDevice == 0)
  20844. {
  20845. if (currentSetup.inputDeviceName.isEmpty()
  20846. && currentSetup.outputDeviceName.isEmpty())
  20847. {
  20848. // This method will only reload the last device that was running
  20849. // before closeAudioDevice() was called - you need to actually open
  20850. // one first, with setAudioDevice().
  20851. jassertfalse;
  20852. return;
  20853. }
  20854. AudioDeviceSetup s (currentSetup);
  20855. setAudioDeviceSetup (s, false);
  20856. }
  20857. }
  20858. void AudioDeviceManager::updateXml()
  20859. {
  20860. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20861. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20862. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20863. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20864. if (currentAudioDevice != 0)
  20865. {
  20866. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20867. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20868. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20869. if (! currentSetup.useDefaultInputChannels)
  20870. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20871. if (! currentSetup.useDefaultOutputChannels)
  20872. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20873. }
  20874. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20875. {
  20876. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20877. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20878. }
  20879. if (midiInsFromXml.size() > 0)
  20880. {
  20881. // Add any midi devices that have been enabled before, but which aren't currently
  20882. // open because the device has been disconnected.
  20883. const StringArray availableMidiDevices (MidiInput::getDevices());
  20884. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20885. {
  20886. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20887. {
  20888. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20889. m->setAttribute ("name", midiInsFromXml[i]);
  20890. }
  20891. }
  20892. }
  20893. if (defaultMidiOutputName.isNotEmpty())
  20894. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20895. }
  20896. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20897. {
  20898. {
  20899. const ScopedLock sl (audioCallbackLock);
  20900. if (callbacks.contains (newCallback))
  20901. return;
  20902. }
  20903. if (currentAudioDevice != 0 && newCallback != 0)
  20904. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20905. const ScopedLock sl (audioCallbackLock);
  20906. callbacks.add (newCallback);
  20907. }
  20908. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20909. {
  20910. if (callback != 0)
  20911. {
  20912. bool needsDeinitialising = currentAudioDevice != 0;
  20913. {
  20914. const ScopedLock sl (audioCallbackLock);
  20915. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20916. callbacks.removeValue (callback);
  20917. }
  20918. if (needsDeinitialising)
  20919. callback->audioDeviceStopped();
  20920. }
  20921. }
  20922. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20923. int numInputChannels,
  20924. float** outputChannelData,
  20925. int numOutputChannels,
  20926. int numSamples)
  20927. {
  20928. const ScopedLock sl (audioCallbackLock);
  20929. if (inputLevelMeasurementEnabledCount > 0)
  20930. {
  20931. for (int j = 0; j < numSamples; ++j)
  20932. {
  20933. float s = 0;
  20934. for (int i = 0; i < numInputChannels; ++i)
  20935. s += std::abs (inputChannelData[i][j]);
  20936. s /= numInputChannels;
  20937. const double decayFactor = 0.99992;
  20938. if (s > inputLevel)
  20939. inputLevel = s;
  20940. else if (inputLevel > 0.001f)
  20941. inputLevel *= decayFactor;
  20942. else
  20943. inputLevel = 0;
  20944. }
  20945. }
  20946. if (callbacks.size() > 0)
  20947. {
  20948. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20949. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20950. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20951. outputChannelData, numOutputChannels, numSamples);
  20952. float** const tempChans = tempBuffer.getArrayOfChannels();
  20953. for (int i = callbacks.size(); --i > 0;)
  20954. {
  20955. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20956. tempChans, numOutputChannels, numSamples);
  20957. for (int chan = 0; chan < numOutputChannels; ++chan)
  20958. {
  20959. const float* const src = tempChans [chan];
  20960. float* const dst = outputChannelData [chan];
  20961. if (src != 0 && dst != 0)
  20962. for (int j = 0; j < numSamples; ++j)
  20963. dst[j] += src[j];
  20964. }
  20965. }
  20966. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20967. const double filterAmount = 0.2;
  20968. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20969. }
  20970. else
  20971. {
  20972. for (int i = 0; i < numOutputChannels; ++i)
  20973. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20974. }
  20975. if (testSound != 0)
  20976. {
  20977. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20978. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20979. for (int i = 0; i < numOutputChannels; ++i)
  20980. for (int j = 0; j < numSamps; ++j)
  20981. outputChannelData [i][j] += src[j];
  20982. testSoundPosition += numSamps;
  20983. if (testSoundPosition >= testSound->getNumSamples())
  20984. testSound = 0;
  20985. }
  20986. }
  20987. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20988. {
  20989. cpuUsageMs = 0;
  20990. const double sampleRate = device->getCurrentSampleRate();
  20991. const int blockSize = device->getCurrentBufferSizeSamples();
  20992. if (sampleRate > 0.0 && blockSize > 0)
  20993. {
  20994. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20995. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20996. }
  20997. {
  20998. const ScopedLock sl (audioCallbackLock);
  20999. for (int i = callbacks.size(); --i >= 0;)
  21000. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  21001. }
  21002. sendChangeMessage (this);
  21003. }
  21004. void AudioDeviceManager::audioDeviceStoppedInt()
  21005. {
  21006. cpuUsageMs = 0;
  21007. timeToCpuScale = 0;
  21008. sendChangeMessage (this);
  21009. const ScopedLock sl (audioCallbackLock);
  21010. for (int i = callbacks.size(); --i >= 0;)
  21011. callbacks.getUnchecked(i)->audioDeviceStopped();
  21012. }
  21013. double AudioDeviceManager::getCpuUsage() const
  21014. {
  21015. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  21016. }
  21017. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  21018. const bool enabled)
  21019. {
  21020. if (enabled != isMidiInputEnabled (name))
  21021. {
  21022. if (enabled)
  21023. {
  21024. const int index = MidiInput::getDevices().indexOf (name);
  21025. if (index >= 0)
  21026. {
  21027. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  21028. if (min != 0)
  21029. {
  21030. enabledMidiInputs.add (min);
  21031. min->start();
  21032. }
  21033. }
  21034. }
  21035. else
  21036. {
  21037. for (int i = enabledMidiInputs.size(); --i >= 0;)
  21038. if (enabledMidiInputs[i]->getName() == name)
  21039. enabledMidiInputs.remove (i);
  21040. }
  21041. updateXml();
  21042. sendChangeMessage (this);
  21043. }
  21044. }
  21045. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  21046. {
  21047. for (int i = enabledMidiInputs.size(); --i >= 0;)
  21048. if (enabledMidiInputs[i]->getName() == name)
  21049. return true;
  21050. return false;
  21051. }
  21052. void AudioDeviceManager::addMidiInputCallback (const String& name,
  21053. MidiInputCallback* callback)
  21054. {
  21055. removeMidiInputCallback (name, callback);
  21056. if (name.isEmpty())
  21057. {
  21058. midiCallbacks.add (callback);
  21059. midiCallbackDevices.add (0);
  21060. }
  21061. else
  21062. {
  21063. for (int i = enabledMidiInputs.size(); --i >= 0;)
  21064. {
  21065. if (enabledMidiInputs[i]->getName() == name)
  21066. {
  21067. const ScopedLock sl (midiCallbackLock);
  21068. midiCallbacks.add (callback);
  21069. midiCallbackDevices.add (enabledMidiInputs[i]);
  21070. break;
  21071. }
  21072. }
  21073. }
  21074. }
  21075. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  21076. MidiInputCallback* /*callback*/)
  21077. {
  21078. const ScopedLock sl (midiCallbackLock);
  21079. for (int i = midiCallbacks.size(); --i >= 0;)
  21080. {
  21081. String devName;
  21082. if (midiCallbackDevices.getUnchecked(i) != 0)
  21083. devName = midiCallbackDevices.getUnchecked(i)->getName();
  21084. if (devName == name)
  21085. {
  21086. midiCallbacks.remove (i);
  21087. midiCallbackDevices.remove (i);
  21088. }
  21089. }
  21090. }
  21091. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  21092. const MidiMessage& message)
  21093. {
  21094. if (! message.isActiveSense())
  21095. {
  21096. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  21097. const ScopedLock sl (midiCallbackLock);
  21098. for (int i = midiCallbackDevices.size(); --i >= 0;)
  21099. {
  21100. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  21101. if (md == source || (md == 0 && isDefaultSource))
  21102. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  21103. }
  21104. }
  21105. }
  21106. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  21107. {
  21108. if (defaultMidiOutputName != deviceName)
  21109. {
  21110. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  21111. {
  21112. const ScopedLock sl (audioCallbackLock);
  21113. oldCallbacks = callbacks;
  21114. callbacks.clear();
  21115. }
  21116. if (currentAudioDevice != 0)
  21117. for (int i = oldCallbacks.size(); --i >= 0;)
  21118. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  21119. defaultMidiOutput = 0;
  21120. defaultMidiOutputName = deviceName;
  21121. if (deviceName.isNotEmpty())
  21122. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  21123. if (currentAudioDevice != 0)
  21124. for (int i = oldCallbacks.size(); --i >= 0;)
  21125. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  21126. {
  21127. const ScopedLock sl (audioCallbackLock);
  21128. callbacks = oldCallbacks;
  21129. }
  21130. updateXml();
  21131. sendChangeMessage (this);
  21132. }
  21133. }
  21134. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  21135. int numInputChannels,
  21136. float** outputChannelData,
  21137. int numOutputChannels,
  21138. int numSamples)
  21139. {
  21140. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  21141. }
  21142. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  21143. {
  21144. owner->audioDeviceAboutToStartInt (device);
  21145. }
  21146. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  21147. {
  21148. owner->audioDeviceStoppedInt();
  21149. }
  21150. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  21151. {
  21152. owner->handleIncomingMidiMessageInt (source, message);
  21153. }
  21154. void AudioDeviceManager::playTestSound()
  21155. {
  21156. { // cunningly nested to swap, unlock and delete in that order.
  21157. ScopedPointer <AudioSampleBuffer> oldSound;
  21158. {
  21159. const ScopedLock sl (audioCallbackLock);
  21160. oldSound = testSound;
  21161. }
  21162. }
  21163. testSoundPosition = 0;
  21164. if (currentAudioDevice != 0)
  21165. {
  21166. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  21167. const int soundLength = (int) sampleRate;
  21168. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  21169. float* samples = newSound->getSampleData (0);
  21170. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  21171. const float amplitude = 0.5f;
  21172. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  21173. for (int i = 0; i < soundLength; ++i)
  21174. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  21175. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  21176. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  21177. const ScopedLock sl (audioCallbackLock);
  21178. testSound = newSound;
  21179. }
  21180. }
  21181. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  21182. {
  21183. const ScopedLock sl (audioCallbackLock);
  21184. if (enableMeasurement)
  21185. ++inputLevelMeasurementEnabledCount;
  21186. else
  21187. --inputLevelMeasurementEnabledCount;
  21188. inputLevel = 0;
  21189. }
  21190. double AudioDeviceManager::getCurrentInputLevel() const
  21191. {
  21192. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  21193. return inputLevel;
  21194. }
  21195. END_JUCE_NAMESPACE
  21196. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  21197. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  21198. BEGIN_JUCE_NAMESPACE
  21199. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  21200. : name (deviceName),
  21201. typeName (typeName_)
  21202. {
  21203. }
  21204. AudioIODevice::~AudioIODevice()
  21205. {
  21206. }
  21207. bool AudioIODevice::hasControlPanel() const
  21208. {
  21209. return false;
  21210. }
  21211. bool AudioIODevice::showControlPanel()
  21212. {
  21213. jassertfalse; // this should only be called for devices which return true from
  21214. // their hasControlPanel() method.
  21215. return false;
  21216. }
  21217. END_JUCE_NAMESPACE
  21218. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  21219. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  21220. BEGIN_JUCE_NAMESPACE
  21221. AudioIODeviceType::AudioIODeviceType (const String& name)
  21222. : typeName (name)
  21223. {
  21224. }
  21225. AudioIODeviceType::~AudioIODeviceType()
  21226. {
  21227. }
  21228. END_JUCE_NAMESPACE
  21229. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  21230. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  21231. BEGIN_JUCE_NAMESPACE
  21232. MidiOutput::MidiOutput()
  21233. : Thread ("midi out"),
  21234. internal (0),
  21235. firstMessage (0)
  21236. {
  21237. }
  21238. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  21239. const double sampleNumber)
  21240. : message (data, len, sampleNumber)
  21241. {
  21242. }
  21243. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  21244. const double millisecondCounterToStartAt,
  21245. double samplesPerSecondForBuffer)
  21246. {
  21247. // You've got to call startBackgroundThread() for this to actually work..
  21248. jassert (isThreadRunning());
  21249. // this needs to be a value in the future - RTFM for this method!
  21250. jassert (millisecondCounterToStartAt > 0);
  21251. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  21252. MidiBuffer::Iterator i (buffer);
  21253. const uint8* data;
  21254. int len, time;
  21255. while (i.getNextEvent (data, len, time))
  21256. {
  21257. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  21258. PendingMessage* const m
  21259. = new PendingMessage (data, len, eventTime);
  21260. const ScopedLock sl (lock);
  21261. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21262. {
  21263. m->next = firstMessage;
  21264. firstMessage = m;
  21265. }
  21266. else
  21267. {
  21268. PendingMessage* mm = firstMessage;
  21269. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21270. mm = mm->next;
  21271. m->next = mm->next;
  21272. mm->next = m;
  21273. }
  21274. }
  21275. notify();
  21276. }
  21277. void MidiOutput::clearAllPendingMessages()
  21278. {
  21279. const ScopedLock sl (lock);
  21280. while (firstMessage != 0)
  21281. {
  21282. PendingMessage* const m = firstMessage;
  21283. firstMessage = firstMessage->next;
  21284. delete m;
  21285. }
  21286. }
  21287. void MidiOutput::startBackgroundThread()
  21288. {
  21289. startThread (9);
  21290. }
  21291. void MidiOutput::stopBackgroundThread()
  21292. {
  21293. stopThread (5000);
  21294. }
  21295. void MidiOutput::run()
  21296. {
  21297. while (! threadShouldExit())
  21298. {
  21299. uint32 now = Time::getMillisecondCounter();
  21300. uint32 eventTime = 0;
  21301. uint32 timeToWait = 500;
  21302. PendingMessage* message;
  21303. {
  21304. const ScopedLock sl (lock);
  21305. message = firstMessage;
  21306. if (message != 0)
  21307. {
  21308. eventTime = roundToInt (message->message.getTimeStamp());
  21309. if (eventTime > now + 20)
  21310. {
  21311. timeToWait = eventTime - (now + 20);
  21312. message = 0;
  21313. }
  21314. else
  21315. {
  21316. firstMessage = message->next;
  21317. }
  21318. }
  21319. }
  21320. if (message != 0)
  21321. {
  21322. if (eventTime > now)
  21323. {
  21324. Time::waitForMillisecondCounter (eventTime);
  21325. if (threadShouldExit())
  21326. break;
  21327. }
  21328. if (eventTime > now - 200)
  21329. sendMessageNow (message->message);
  21330. delete message;
  21331. }
  21332. else
  21333. {
  21334. jassert (timeToWait < 1000 * 30);
  21335. wait (timeToWait);
  21336. }
  21337. }
  21338. clearAllPendingMessages();
  21339. }
  21340. END_JUCE_NAMESPACE
  21341. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21342. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21343. BEGIN_JUCE_NAMESPACE
  21344. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21345. {
  21346. const double maxVal = (double) 0x7fff;
  21347. char* intData = static_cast <char*> (dest);
  21348. if (dest != (void*) source || destBytesPerSample <= 4)
  21349. {
  21350. for (int i = 0; i < numSamples; ++i)
  21351. {
  21352. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21353. intData += destBytesPerSample;
  21354. }
  21355. }
  21356. else
  21357. {
  21358. intData += destBytesPerSample * numSamples;
  21359. for (int i = numSamples; --i >= 0;)
  21360. {
  21361. intData -= destBytesPerSample;
  21362. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21363. }
  21364. }
  21365. }
  21366. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21367. {
  21368. const double maxVal = (double) 0x7fff;
  21369. char* intData = static_cast <char*> (dest);
  21370. if (dest != (void*) source || destBytesPerSample <= 4)
  21371. {
  21372. for (int i = 0; i < numSamples; ++i)
  21373. {
  21374. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21375. intData += destBytesPerSample;
  21376. }
  21377. }
  21378. else
  21379. {
  21380. intData += destBytesPerSample * numSamples;
  21381. for (int i = numSamples; --i >= 0;)
  21382. {
  21383. intData -= destBytesPerSample;
  21384. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21385. }
  21386. }
  21387. }
  21388. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21389. {
  21390. const double maxVal = (double) 0x7fffff;
  21391. char* intData = static_cast <char*> (dest);
  21392. if (dest != (void*) source || destBytesPerSample <= 4)
  21393. {
  21394. for (int i = 0; i < numSamples; ++i)
  21395. {
  21396. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21397. intData += destBytesPerSample;
  21398. }
  21399. }
  21400. else
  21401. {
  21402. intData += destBytesPerSample * numSamples;
  21403. for (int i = numSamples; --i >= 0;)
  21404. {
  21405. intData -= destBytesPerSample;
  21406. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21407. }
  21408. }
  21409. }
  21410. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21411. {
  21412. const double maxVal = (double) 0x7fffff;
  21413. char* intData = static_cast <char*> (dest);
  21414. if (dest != (void*) source || destBytesPerSample <= 4)
  21415. {
  21416. for (int i = 0; i < numSamples; ++i)
  21417. {
  21418. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21419. intData += destBytesPerSample;
  21420. }
  21421. }
  21422. else
  21423. {
  21424. intData += destBytesPerSample * numSamples;
  21425. for (int i = numSamples; --i >= 0;)
  21426. {
  21427. intData -= destBytesPerSample;
  21428. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21429. }
  21430. }
  21431. }
  21432. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21433. {
  21434. const double maxVal = (double) 0x7fffffff;
  21435. char* intData = static_cast <char*> (dest);
  21436. if (dest != (void*) source || destBytesPerSample <= 4)
  21437. {
  21438. for (int i = 0; i < numSamples; ++i)
  21439. {
  21440. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21441. intData += destBytesPerSample;
  21442. }
  21443. }
  21444. else
  21445. {
  21446. intData += destBytesPerSample * numSamples;
  21447. for (int i = numSamples; --i >= 0;)
  21448. {
  21449. intData -= destBytesPerSample;
  21450. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21451. }
  21452. }
  21453. }
  21454. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21455. {
  21456. const double maxVal = (double) 0x7fffffff;
  21457. char* intData = static_cast <char*> (dest);
  21458. if (dest != (void*) source || destBytesPerSample <= 4)
  21459. {
  21460. for (int i = 0; i < numSamples; ++i)
  21461. {
  21462. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21463. intData += destBytesPerSample;
  21464. }
  21465. }
  21466. else
  21467. {
  21468. intData += destBytesPerSample * numSamples;
  21469. for (int i = numSamples; --i >= 0;)
  21470. {
  21471. intData -= destBytesPerSample;
  21472. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21473. }
  21474. }
  21475. }
  21476. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21477. {
  21478. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21479. char* d = static_cast <char*> (dest);
  21480. for (int i = 0; i < numSamples; ++i)
  21481. {
  21482. *(float*) d = source[i];
  21483. #if JUCE_BIG_ENDIAN
  21484. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21485. #endif
  21486. d += destBytesPerSample;
  21487. }
  21488. }
  21489. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21490. {
  21491. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21492. char* d = static_cast <char*> (dest);
  21493. for (int i = 0; i < numSamples; ++i)
  21494. {
  21495. *(float*) d = source[i];
  21496. #if JUCE_LITTLE_ENDIAN
  21497. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21498. #endif
  21499. d += destBytesPerSample;
  21500. }
  21501. }
  21502. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21503. {
  21504. const float scale = 1.0f / 0x7fff;
  21505. const char* intData = static_cast <const char*> (source);
  21506. if (source != (void*) dest || srcBytesPerSample >= 4)
  21507. {
  21508. for (int i = 0; i < numSamples; ++i)
  21509. {
  21510. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21511. intData += srcBytesPerSample;
  21512. }
  21513. }
  21514. else
  21515. {
  21516. intData += srcBytesPerSample * numSamples;
  21517. for (int i = numSamples; --i >= 0;)
  21518. {
  21519. intData -= srcBytesPerSample;
  21520. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21521. }
  21522. }
  21523. }
  21524. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21525. {
  21526. const float scale = 1.0f / 0x7fff;
  21527. const char* intData = static_cast <const char*> (source);
  21528. if (source != (void*) dest || srcBytesPerSample >= 4)
  21529. {
  21530. for (int i = 0; i < numSamples; ++i)
  21531. {
  21532. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21533. intData += srcBytesPerSample;
  21534. }
  21535. }
  21536. else
  21537. {
  21538. intData += srcBytesPerSample * numSamples;
  21539. for (int i = numSamples; --i >= 0;)
  21540. {
  21541. intData -= srcBytesPerSample;
  21542. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21543. }
  21544. }
  21545. }
  21546. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21547. {
  21548. const float scale = 1.0f / 0x7fffff;
  21549. const char* intData = static_cast <const char*> (source);
  21550. if (source != (void*) dest || srcBytesPerSample >= 4)
  21551. {
  21552. for (int i = 0; i < numSamples; ++i)
  21553. {
  21554. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21555. intData += srcBytesPerSample;
  21556. }
  21557. }
  21558. else
  21559. {
  21560. intData += srcBytesPerSample * numSamples;
  21561. for (int i = numSamples; --i >= 0;)
  21562. {
  21563. intData -= srcBytesPerSample;
  21564. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21565. }
  21566. }
  21567. }
  21568. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21569. {
  21570. const float scale = 1.0f / 0x7fffff;
  21571. const char* intData = static_cast <const char*> (source);
  21572. if (source != (void*) dest || srcBytesPerSample >= 4)
  21573. {
  21574. for (int i = 0; i < numSamples; ++i)
  21575. {
  21576. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21577. intData += srcBytesPerSample;
  21578. }
  21579. }
  21580. else
  21581. {
  21582. intData += srcBytesPerSample * numSamples;
  21583. for (int i = numSamples; --i >= 0;)
  21584. {
  21585. intData -= srcBytesPerSample;
  21586. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21587. }
  21588. }
  21589. }
  21590. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21591. {
  21592. const float scale = 1.0f / 0x7fffffff;
  21593. const char* intData = static_cast <const char*> (source);
  21594. if (source != (void*) dest || srcBytesPerSample >= 4)
  21595. {
  21596. for (int i = 0; i < numSamples; ++i)
  21597. {
  21598. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21599. intData += srcBytesPerSample;
  21600. }
  21601. }
  21602. else
  21603. {
  21604. intData += srcBytesPerSample * numSamples;
  21605. for (int i = numSamples; --i >= 0;)
  21606. {
  21607. intData -= srcBytesPerSample;
  21608. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21609. }
  21610. }
  21611. }
  21612. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21613. {
  21614. const float scale = 1.0f / 0x7fffffff;
  21615. const char* intData = static_cast <const char*> (source);
  21616. if (source != (void*) dest || srcBytesPerSample >= 4)
  21617. {
  21618. for (int i = 0; i < numSamples; ++i)
  21619. {
  21620. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21621. intData += srcBytesPerSample;
  21622. }
  21623. }
  21624. else
  21625. {
  21626. intData += srcBytesPerSample * numSamples;
  21627. for (int i = numSamples; --i >= 0;)
  21628. {
  21629. intData -= srcBytesPerSample;
  21630. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21631. }
  21632. }
  21633. }
  21634. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21635. {
  21636. const char* s = static_cast <const char*> (source);
  21637. for (int i = 0; i < numSamples; ++i)
  21638. {
  21639. dest[i] = *(float*)s;
  21640. #if JUCE_BIG_ENDIAN
  21641. uint32* const d = (uint32*) (dest + i);
  21642. *d = ByteOrder::swap (*d);
  21643. #endif
  21644. s += srcBytesPerSample;
  21645. }
  21646. }
  21647. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21648. {
  21649. const char* s = static_cast <const char*> (source);
  21650. for (int i = 0; i < numSamples; ++i)
  21651. {
  21652. dest[i] = *(float*)s;
  21653. #if JUCE_LITTLE_ENDIAN
  21654. uint32* const d = (uint32*) (dest + i);
  21655. *d = ByteOrder::swap (*d);
  21656. #endif
  21657. s += srcBytesPerSample;
  21658. }
  21659. }
  21660. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21661. const float* const source,
  21662. void* const dest,
  21663. const int numSamples)
  21664. {
  21665. switch (destFormat)
  21666. {
  21667. case int16LE:
  21668. convertFloatToInt16LE (source, dest, numSamples);
  21669. break;
  21670. case int16BE:
  21671. convertFloatToInt16BE (source, dest, numSamples);
  21672. break;
  21673. case int24LE:
  21674. convertFloatToInt24LE (source, dest, numSamples);
  21675. break;
  21676. case int24BE:
  21677. convertFloatToInt24BE (source, dest, numSamples);
  21678. break;
  21679. case int32LE:
  21680. convertFloatToInt32LE (source, dest, numSamples);
  21681. break;
  21682. case int32BE:
  21683. convertFloatToInt32BE (source, dest, numSamples);
  21684. break;
  21685. case float32LE:
  21686. convertFloatToFloat32LE (source, dest, numSamples);
  21687. break;
  21688. case float32BE:
  21689. convertFloatToFloat32BE (source, dest, numSamples);
  21690. break;
  21691. default:
  21692. jassertfalse;
  21693. break;
  21694. }
  21695. }
  21696. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21697. const void* const source,
  21698. float* const dest,
  21699. const int numSamples)
  21700. {
  21701. switch (sourceFormat)
  21702. {
  21703. case int16LE:
  21704. convertInt16LEToFloat (source, dest, numSamples);
  21705. break;
  21706. case int16BE:
  21707. convertInt16BEToFloat (source, dest, numSamples);
  21708. break;
  21709. case int24LE:
  21710. convertInt24LEToFloat (source, dest, numSamples);
  21711. break;
  21712. case int24BE:
  21713. convertInt24BEToFloat (source, dest, numSamples);
  21714. break;
  21715. case int32LE:
  21716. convertInt32LEToFloat (source, dest, numSamples);
  21717. break;
  21718. case int32BE:
  21719. convertInt32BEToFloat (source, dest, numSamples);
  21720. break;
  21721. case float32LE:
  21722. convertFloat32LEToFloat (source, dest, numSamples);
  21723. break;
  21724. case float32BE:
  21725. convertFloat32BEToFloat (source, dest, numSamples);
  21726. break;
  21727. default:
  21728. jassertfalse;
  21729. break;
  21730. }
  21731. }
  21732. void AudioDataConverters::interleaveSamples (const float** const source,
  21733. float* const dest,
  21734. const int numSamples,
  21735. const int numChannels)
  21736. {
  21737. for (int chan = 0; chan < numChannels; ++chan)
  21738. {
  21739. int i = chan;
  21740. const float* src = source [chan];
  21741. for (int j = 0; j < numSamples; ++j)
  21742. {
  21743. dest [i] = src [j];
  21744. i += numChannels;
  21745. }
  21746. }
  21747. }
  21748. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21749. float** const dest,
  21750. const int numSamples,
  21751. const int numChannels)
  21752. {
  21753. for (int chan = 0; chan < numChannels; ++chan)
  21754. {
  21755. int i = chan;
  21756. float* dst = dest [chan];
  21757. for (int j = 0; j < numSamples; ++j)
  21758. {
  21759. dst [j] = source [i];
  21760. i += numChannels;
  21761. }
  21762. }
  21763. }
  21764. END_JUCE_NAMESPACE
  21765. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21766. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21767. BEGIN_JUCE_NAMESPACE
  21768. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21769. const int numSamples) throw()
  21770. : numChannels (numChannels_),
  21771. size (numSamples)
  21772. {
  21773. jassert (numSamples >= 0);
  21774. jassert (numChannels_ > 0);
  21775. allocateData();
  21776. }
  21777. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21778. : numChannels (other.numChannels),
  21779. size (other.size)
  21780. {
  21781. allocateData();
  21782. const size_t numBytes = size * sizeof (float);
  21783. for (int i = 0; i < numChannels; ++i)
  21784. memcpy (channels[i], other.channels[i], numBytes);
  21785. }
  21786. void AudioSampleBuffer::allocateData()
  21787. {
  21788. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21789. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21790. allocatedData.malloc (allocatedBytes);
  21791. channels = reinterpret_cast <float**> (allocatedData.getData());
  21792. float* chan = (float*) (allocatedData + channelListSize);
  21793. for (int i = 0; i < numChannels; ++i)
  21794. {
  21795. channels[i] = chan;
  21796. chan += size;
  21797. }
  21798. channels [numChannels] = 0;
  21799. }
  21800. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21801. const int numChannels_,
  21802. const int numSamples) throw()
  21803. : numChannels (numChannels_),
  21804. size (numSamples),
  21805. allocatedBytes (0)
  21806. {
  21807. jassert (numChannels_ > 0);
  21808. allocateChannels (dataToReferTo);
  21809. }
  21810. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21811. const int newNumChannels,
  21812. const int newNumSamples) throw()
  21813. {
  21814. jassert (newNumChannels > 0);
  21815. allocatedBytes = 0;
  21816. allocatedData.free();
  21817. numChannels = newNumChannels;
  21818. size = newNumSamples;
  21819. allocateChannels (dataToReferTo);
  21820. }
  21821. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21822. {
  21823. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21824. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21825. {
  21826. channels = static_cast <float**> (preallocatedChannelSpace);
  21827. }
  21828. else
  21829. {
  21830. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21831. channels = reinterpret_cast <float**> (allocatedData.getData());
  21832. }
  21833. for (int i = 0; i < numChannels; ++i)
  21834. {
  21835. // you have to pass in the same number of valid pointers as numChannels
  21836. jassert (dataToReferTo[i] != 0);
  21837. channels[i] = dataToReferTo[i];
  21838. }
  21839. channels [numChannels] = 0;
  21840. }
  21841. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21842. {
  21843. if (this != &other)
  21844. {
  21845. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21846. const size_t numBytes = size * sizeof (float);
  21847. for (int i = 0; i < numChannels; ++i)
  21848. memcpy (channels[i], other.channels[i], numBytes);
  21849. }
  21850. return *this;
  21851. }
  21852. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21853. {
  21854. }
  21855. void AudioSampleBuffer::setSize (const int newNumChannels,
  21856. const int newNumSamples,
  21857. const bool keepExistingContent,
  21858. const bool clearExtraSpace,
  21859. const bool avoidReallocating) throw()
  21860. {
  21861. jassert (newNumChannels > 0);
  21862. if (newNumSamples != size || newNumChannels != numChannels)
  21863. {
  21864. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21865. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21866. if (keepExistingContent)
  21867. {
  21868. HeapBlock <char> newData;
  21869. newData.allocate (newTotalBytes, clearExtraSpace);
  21870. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21871. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21872. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21873. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21874. for (int i = 0; i < numChansToCopy; ++i)
  21875. {
  21876. memcpy (newChan, channels[i], numBytesToCopy);
  21877. newChannels[i] = newChan;
  21878. newChan += newNumSamples;
  21879. }
  21880. allocatedData.swapWith (newData);
  21881. allocatedBytes = (int) newTotalBytes;
  21882. channels = newChannels;
  21883. }
  21884. else
  21885. {
  21886. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21887. {
  21888. if (clearExtraSpace)
  21889. zeromem (allocatedData, newTotalBytes);
  21890. }
  21891. else
  21892. {
  21893. allocatedBytes = newTotalBytes;
  21894. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21895. channels = reinterpret_cast <float**> (allocatedData.getData());
  21896. }
  21897. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21898. for (int i = 0; i < newNumChannels; ++i)
  21899. {
  21900. channels[i] = chan;
  21901. chan += newNumSamples;
  21902. }
  21903. }
  21904. channels [newNumChannels] = 0;
  21905. size = newNumSamples;
  21906. numChannels = newNumChannels;
  21907. }
  21908. }
  21909. void AudioSampleBuffer::clear() throw()
  21910. {
  21911. for (int i = 0; i < numChannels; ++i)
  21912. zeromem (channels[i], size * sizeof (float));
  21913. }
  21914. void AudioSampleBuffer::clear (const int startSample,
  21915. const int numSamples) throw()
  21916. {
  21917. jassert (startSample >= 0 && startSample + numSamples <= size);
  21918. for (int i = 0; i < numChannels; ++i)
  21919. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21920. }
  21921. void AudioSampleBuffer::clear (const int channel,
  21922. const int startSample,
  21923. const int numSamples) throw()
  21924. {
  21925. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21926. jassert (startSample >= 0 && startSample + numSamples <= size);
  21927. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21928. }
  21929. void AudioSampleBuffer::applyGain (const int channel,
  21930. const int startSample,
  21931. int numSamples,
  21932. const float gain) throw()
  21933. {
  21934. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21935. jassert (startSample >= 0 && startSample + numSamples <= size);
  21936. if (gain != 1.0f)
  21937. {
  21938. float* d = channels [channel] + startSample;
  21939. if (gain == 0.0f)
  21940. {
  21941. zeromem (d, sizeof (float) * numSamples);
  21942. }
  21943. else
  21944. {
  21945. while (--numSamples >= 0)
  21946. *d++ *= gain;
  21947. }
  21948. }
  21949. }
  21950. void AudioSampleBuffer::applyGainRamp (const int channel,
  21951. const int startSample,
  21952. int numSamples,
  21953. float startGain,
  21954. float endGain) throw()
  21955. {
  21956. if (startGain == endGain)
  21957. {
  21958. applyGain (channel, startSample, numSamples, startGain);
  21959. }
  21960. else
  21961. {
  21962. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21963. jassert (startSample >= 0 && startSample + numSamples <= size);
  21964. const float increment = (endGain - startGain) / numSamples;
  21965. float* d = channels [channel] + startSample;
  21966. while (--numSamples >= 0)
  21967. {
  21968. *d++ *= startGain;
  21969. startGain += increment;
  21970. }
  21971. }
  21972. }
  21973. void AudioSampleBuffer::applyGain (const int startSample,
  21974. const int numSamples,
  21975. const float gain) throw()
  21976. {
  21977. for (int i = 0; i < numChannels; ++i)
  21978. applyGain (i, startSample, numSamples, gain);
  21979. }
  21980. void AudioSampleBuffer::addFrom (const int destChannel,
  21981. const int destStartSample,
  21982. const AudioSampleBuffer& source,
  21983. const int sourceChannel,
  21984. const int sourceStartSample,
  21985. int numSamples,
  21986. const float gain) throw()
  21987. {
  21988. jassert (&source != this || sourceChannel != destChannel);
  21989. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21990. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21991. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21992. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21993. if (gain != 0.0f && numSamples > 0)
  21994. {
  21995. float* d = channels [destChannel] + destStartSample;
  21996. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21997. if (gain != 1.0f)
  21998. {
  21999. while (--numSamples >= 0)
  22000. *d++ += gain * *s++;
  22001. }
  22002. else
  22003. {
  22004. while (--numSamples >= 0)
  22005. *d++ += *s++;
  22006. }
  22007. }
  22008. }
  22009. void AudioSampleBuffer::addFrom (const int destChannel,
  22010. const int destStartSample,
  22011. const float* source,
  22012. int numSamples,
  22013. const float gain) throw()
  22014. {
  22015. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22016. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22017. jassert (source != 0);
  22018. if (gain != 0.0f && numSamples > 0)
  22019. {
  22020. float* d = channels [destChannel] + destStartSample;
  22021. if (gain != 1.0f)
  22022. {
  22023. while (--numSamples >= 0)
  22024. *d++ += gain * *source++;
  22025. }
  22026. else
  22027. {
  22028. while (--numSamples >= 0)
  22029. *d++ += *source++;
  22030. }
  22031. }
  22032. }
  22033. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  22034. const int destStartSample,
  22035. const float* source,
  22036. int numSamples,
  22037. float startGain,
  22038. const float endGain) throw()
  22039. {
  22040. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22041. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22042. jassert (source != 0);
  22043. if (startGain == endGain)
  22044. {
  22045. addFrom (destChannel,
  22046. destStartSample,
  22047. source,
  22048. numSamples,
  22049. startGain);
  22050. }
  22051. else
  22052. {
  22053. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22054. {
  22055. const float increment = (endGain - startGain) / numSamples;
  22056. float* d = channels [destChannel] + destStartSample;
  22057. while (--numSamples >= 0)
  22058. {
  22059. *d++ += startGain * *source++;
  22060. startGain += increment;
  22061. }
  22062. }
  22063. }
  22064. }
  22065. void AudioSampleBuffer::copyFrom (const int destChannel,
  22066. const int destStartSample,
  22067. const AudioSampleBuffer& source,
  22068. const int sourceChannel,
  22069. const int sourceStartSample,
  22070. int numSamples) throw()
  22071. {
  22072. jassert (&source != this || sourceChannel != destChannel);
  22073. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22074. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22075. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  22076. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  22077. if (numSamples > 0)
  22078. {
  22079. memcpy (channels [destChannel] + destStartSample,
  22080. source.channels [sourceChannel] + sourceStartSample,
  22081. sizeof (float) * numSamples);
  22082. }
  22083. }
  22084. void AudioSampleBuffer::copyFrom (const int destChannel,
  22085. const int destStartSample,
  22086. const float* source,
  22087. int numSamples) throw()
  22088. {
  22089. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22090. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22091. jassert (source != 0);
  22092. if (numSamples > 0)
  22093. {
  22094. memcpy (channels [destChannel] + destStartSample,
  22095. source,
  22096. sizeof (float) * numSamples);
  22097. }
  22098. }
  22099. void AudioSampleBuffer::copyFrom (const int destChannel,
  22100. const int destStartSample,
  22101. const float* source,
  22102. int numSamples,
  22103. const float gain) throw()
  22104. {
  22105. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22106. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22107. jassert (source != 0);
  22108. if (numSamples > 0)
  22109. {
  22110. float* d = channels [destChannel] + destStartSample;
  22111. if (gain != 1.0f)
  22112. {
  22113. if (gain == 0)
  22114. {
  22115. zeromem (d, sizeof (float) * numSamples);
  22116. }
  22117. else
  22118. {
  22119. while (--numSamples >= 0)
  22120. *d++ = gain * *source++;
  22121. }
  22122. }
  22123. else
  22124. {
  22125. memcpy (d, source, sizeof (float) * numSamples);
  22126. }
  22127. }
  22128. }
  22129. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  22130. const int destStartSample,
  22131. const float* source,
  22132. int numSamples,
  22133. float startGain,
  22134. float endGain) throw()
  22135. {
  22136. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22137. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22138. jassert (source != 0);
  22139. if (startGain == endGain)
  22140. {
  22141. copyFrom (destChannel,
  22142. destStartSample,
  22143. source,
  22144. numSamples,
  22145. startGain);
  22146. }
  22147. else
  22148. {
  22149. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22150. {
  22151. const float increment = (endGain - startGain) / numSamples;
  22152. float* d = channels [destChannel] + destStartSample;
  22153. while (--numSamples >= 0)
  22154. {
  22155. *d++ = startGain * *source++;
  22156. startGain += increment;
  22157. }
  22158. }
  22159. }
  22160. }
  22161. void AudioSampleBuffer::findMinMax (const int channel,
  22162. const int startSample,
  22163. int numSamples,
  22164. float& minVal,
  22165. float& maxVal) const throw()
  22166. {
  22167. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22168. jassert (startSample >= 0 && startSample + numSamples <= size);
  22169. if (numSamples <= 0)
  22170. {
  22171. minVal = 0.0f;
  22172. maxVal = 0.0f;
  22173. }
  22174. else
  22175. {
  22176. const float* d = channels [channel] + startSample;
  22177. float mn = *d++;
  22178. float mx = mn;
  22179. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  22180. {
  22181. const float samp = *d++;
  22182. if (samp > mx)
  22183. mx = samp;
  22184. if (samp < mn)
  22185. mn = samp;
  22186. }
  22187. maxVal = mx;
  22188. minVal = mn;
  22189. }
  22190. }
  22191. float AudioSampleBuffer::getMagnitude (const int channel,
  22192. const int startSample,
  22193. const int numSamples) const throw()
  22194. {
  22195. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22196. jassert (startSample >= 0 && startSample + numSamples <= size);
  22197. float mn, mx;
  22198. findMinMax (channel, startSample, numSamples, mn, mx);
  22199. return jmax (mn, -mn, mx, -mx);
  22200. }
  22201. float AudioSampleBuffer::getMagnitude (const int startSample,
  22202. const int numSamples) const throw()
  22203. {
  22204. float mag = 0.0f;
  22205. for (int i = 0; i < numChannels; ++i)
  22206. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22207. return mag;
  22208. }
  22209. float AudioSampleBuffer::getRMSLevel (const int channel,
  22210. const int startSample,
  22211. const int numSamples) const throw()
  22212. {
  22213. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22214. jassert (startSample >= 0 && startSample + numSamples <= size);
  22215. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22216. return 0.0f;
  22217. const float* const data = channels [channel] + startSample;
  22218. double sum = 0.0;
  22219. for (int i = 0; i < numSamples; ++i)
  22220. {
  22221. const float sample = data [i];
  22222. sum += sample * sample;
  22223. }
  22224. return (float) std::sqrt (sum / numSamples);
  22225. }
  22226. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22227. const int startSample,
  22228. const int numSamples,
  22229. const int readerStartSample,
  22230. const bool useLeftChan,
  22231. const bool useRightChan)
  22232. {
  22233. jassert (reader != 0);
  22234. jassert (startSample >= 0 && startSample + numSamples <= size);
  22235. if (numSamples > 0)
  22236. {
  22237. int* chans[3];
  22238. if (useLeftChan == useRightChan)
  22239. {
  22240. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22241. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22242. }
  22243. else if (useLeftChan || (reader->numChannels == 1))
  22244. {
  22245. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22246. chans[1] = 0;
  22247. }
  22248. else if (useRightChan)
  22249. {
  22250. chans[0] = 0;
  22251. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22252. }
  22253. chans[2] = 0;
  22254. reader->read (chans, 2, readerStartSample, numSamples, true);
  22255. if (! reader->usesFloatingPointData)
  22256. {
  22257. for (int j = 0; j < 2; ++j)
  22258. {
  22259. float* const d = reinterpret_cast <float*> (chans[j]);
  22260. if (d != 0)
  22261. {
  22262. const float multiplier = 1.0f / 0x7fffffff;
  22263. for (int i = 0; i < numSamples; ++i)
  22264. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22265. }
  22266. }
  22267. }
  22268. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22269. {
  22270. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22271. memcpy (getSampleData (1, startSample),
  22272. getSampleData (0, startSample),
  22273. sizeof (float) * numSamples);
  22274. }
  22275. }
  22276. }
  22277. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22278. const int startSample,
  22279. const int numSamples) const
  22280. {
  22281. jassert (startSample >= 0 && startSample + numSamples <= size && numChannels > 0);
  22282. if (numSamples > 0)
  22283. {
  22284. HeapBlock<int> tempBuffer;
  22285. HeapBlock<int*> chans (numChannels + 1);
  22286. chans [numChannels] = 0;
  22287. if (writer->isFloatingPoint())
  22288. {
  22289. for (int i = numChannels; --i >= 0;)
  22290. chans[i] = reinterpret_cast<int*> (channels[i] + startSample);
  22291. }
  22292. else
  22293. {
  22294. tempBuffer.malloc (numSamples * numChannels);
  22295. for (int j = 0; j < numChannels; ++j)
  22296. {
  22297. int* const dest = tempBuffer + j * numSamples;
  22298. const float* const src = channels[j] + startSample;
  22299. chans[j] = dest;
  22300. for (int i = 0; i < numSamples; ++i)
  22301. {
  22302. const double samp = src[i];
  22303. if (samp <= -1.0)
  22304. dest[i] = std::numeric_limits<int>::min();
  22305. else if (samp >= 1.0)
  22306. dest[i] = std::numeric_limits<int>::max();
  22307. else
  22308. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  22309. }
  22310. }
  22311. }
  22312. writer->write ((const int**) chans.getData(), numSamples);
  22313. }
  22314. }
  22315. END_JUCE_NAMESPACE
  22316. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22317. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22318. BEGIN_JUCE_NAMESPACE
  22319. IIRFilter::IIRFilter()
  22320. : active (false)
  22321. {
  22322. reset();
  22323. }
  22324. IIRFilter::IIRFilter (const IIRFilter& other)
  22325. : active (other.active)
  22326. {
  22327. const ScopedLock sl (other.processLock);
  22328. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22329. reset();
  22330. }
  22331. IIRFilter::~IIRFilter()
  22332. {
  22333. }
  22334. void IIRFilter::reset() throw()
  22335. {
  22336. const ScopedLock sl (processLock);
  22337. x1 = 0;
  22338. x2 = 0;
  22339. y1 = 0;
  22340. y2 = 0;
  22341. }
  22342. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22343. {
  22344. float out = coefficients[0] * in
  22345. + coefficients[1] * x1
  22346. + coefficients[2] * x2
  22347. - coefficients[4] * y1
  22348. - coefficients[5] * y2;
  22349. #if JUCE_INTEL
  22350. if (! (out < -1.0e-8 || out > 1.0e-8))
  22351. out = 0;
  22352. #endif
  22353. x2 = x1;
  22354. x1 = in;
  22355. y2 = y1;
  22356. y1 = out;
  22357. return out;
  22358. }
  22359. void IIRFilter::processSamples (float* const samples,
  22360. const int numSamples) throw()
  22361. {
  22362. const ScopedLock sl (processLock);
  22363. if (active)
  22364. {
  22365. for (int i = 0; i < numSamples; ++i)
  22366. {
  22367. const float in = samples[i];
  22368. float out = coefficients[0] * in
  22369. + coefficients[1] * x1
  22370. + coefficients[2] * x2
  22371. - coefficients[4] * y1
  22372. - coefficients[5] * y2;
  22373. #if JUCE_INTEL
  22374. if (! (out < -1.0e-8 || out > 1.0e-8))
  22375. out = 0;
  22376. #endif
  22377. x2 = x1;
  22378. x1 = in;
  22379. y2 = y1;
  22380. y1 = out;
  22381. samples[i] = out;
  22382. }
  22383. }
  22384. }
  22385. void IIRFilter::makeLowPass (const double sampleRate,
  22386. const double frequency) throw()
  22387. {
  22388. jassert (sampleRate > 0);
  22389. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22390. const double nSquared = n * n;
  22391. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22392. setCoefficients (c1,
  22393. c1 * 2.0f,
  22394. c1,
  22395. 1.0,
  22396. c1 * 2.0 * (1.0 - nSquared),
  22397. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22398. }
  22399. void IIRFilter::makeHighPass (const double sampleRate,
  22400. const double frequency) throw()
  22401. {
  22402. const double n = tan (double_Pi * frequency / sampleRate);
  22403. const double nSquared = n * n;
  22404. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22405. setCoefficients (c1,
  22406. c1 * -2.0f,
  22407. c1,
  22408. 1.0,
  22409. c1 * 2.0 * (nSquared - 1.0),
  22410. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22411. }
  22412. void IIRFilter::makeLowShelf (const double sampleRate,
  22413. const double cutOffFrequency,
  22414. const double Q,
  22415. const float gainFactor) throw()
  22416. {
  22417. jassert (sampleRate > 0);
  22418. jassert (Q > 0);
  22419. const double A = jmax (0.0f, gainFactor);
  22420. const double aminus1 = A - 1.0;
  22421. const double aplus1 = A + 1.0;
  22422. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22423. const double coso = std::cos (omega);
  22424. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22425. const double aminus1TimesCoso = aminus1 * coso;
  22426. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22427. A * 2.0 * (aminus1 - aplus1 * coso),
  22428. A * (aplus1 - aminus1TimesCoso - beta),
  22429. aplus1 + aminus1TimesCoso + beta,
  22430. -2.0 * (aminus1 + aplus1 * coso),
  22431. aplus1 + aminus1TimesCoso - beta);
  22432. }
  22433. void IIRFilter::makeHighShelf (const double sampleRate,
  22434. const double cutOffFrequency,
  22435. const double Q,
  22436. const float gainFactor) throw()
  22437. {
  22438. jassert (sampleRate > 0);
  22439. jassert (Q > 0);
  22440. const double A = jmax (0.0f, gainFactor);
  22441. const double aminus1 = A - 1.0;
  22442. const double aplus1 = A + 1.0;
  22443. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22444. const double coso = std::cos (omega);
  22445. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22446. const double aminus1TimesCoso = aminus1 * coso;
  22447. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22448. A * -2.0 * (aminus1 + aplus1 * coso),
  22449. A * (aplus1 + aminus1TimesCoso - beta),
  22450. aplus1 - aminus1TimesCoso + beta,
  22451. 2.0 * (aminus1 - aplus1 * coso),
  22452. aplus1 - aminus1TimesCoso - beta);
  22453. }
  22454. void IIRFilter::makeBandPass (const double sampleRate,
  22455. const double centreFrequency,
  22456. const double Q,
  22457. const float gainFactor) throw()
  22458. {
  22459. jassert (sampleRate > 0);
  22460. jassert (Q > 0);
  22461. const double A = jmax (0.0f, gainFactor);
  22462. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22463. const double alpha = 0.5 * std::sin (omega) / Q;
  22464. const double c2 = -2.0 * std::cos (omega);
  22465. const double alphaTimesA = alpha * A;
  22466. const double alphaOverA = alpha / A;
  22467. setCoefficients (1.0 + alphaTimesA,
  22468. c2,
  22469. 1.0 - alphaTimesA,
  22470. 1.0 + alphaOverA,
  22471. c2,
  22472. 1.0 - alphaOverA);
  22473. }
  22474. void IIRFilter::makeInactive() throw()
  22475. {
  22476. const ScopedLock sl (processLock);
  22477. active = false;
  22478. }
  22479. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22480. {
  22481. const ScopedLock sl (processLock);
  22482. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22483. active = other.active;
  22484. }
  22485. void IIRFilter::setCoefficients (double c1,
  22486. double c2,
  22487. double c3,
  22488. double c4,
  22489. double c5,
  22490. double c6) throw()
  22491. {
  22492. const double a = 1.0 / c4;
  22493. c1 *= a;
  22494. c2 *= a;
  22495. c3 *= a;
  22496. c5 *= a;
  22497. c6 *= a;
  22498. const ScopedLock sl (processLock);
  22499. coefficients[0] = (float) c1;
  22500. coefficients[1] = (float) c2;
  22501. coefficients[2] = (float) c3;
  22502. coefficients[3] = (float) c4;
  22503. coefficients[4] = (float) c5;
  22504. coefficients[5] = (float) c6;
  22505. active = true;
  22506. }
  22507. END_JUCE_NAMESPACE
  22508. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22509. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22510. BEGIN_JUCE_NAMESPACE
  22511. MidiBuffer::MidiBuffer() throw()
  22512. : bytesUsed (0)
  22513. {
  22514. }
  22515. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22516. : bytesUsed (0)
  22517. {
  22518. addEvent (message, 0);
  22519. }
  22520. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22521. : data (other.data),
  22522. bytesUsed (other.bytesUsed)
  22523. {
  22524. }
  22525. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22526. {
  22527. bytesUsed = other.bytesUsed;
  22528. data = other.data;
  22529. return *this;
  22530. }
  22531. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22532. {
  22533. data.swapWith (other.data);
  22534. swapVariables <int> (bytesUsed, other.bytesUsed);
  22535. }
  22536. MidiBuffer::~MidiBuffer()
  22537. {
  22538. }
  22539. inline uint8* MidiBuffer::getData() const throw()
  22540. {
  22541. return static_cast <uint8*> (data.getData());
  22542. }
  22543. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22544. {
  22545. return *static_cast <const int*> (d);
  22546. }
  22547. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22548. {
  22549. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22550. }
  22551. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22552. {
  22553. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22554. }
  22555. void MidiBuffer::clear() throw()
  22556. {
  22557. bytesUsed = 0;
  22558. }
  22559. void MidiBuffer::clear (const int startSample, const int numSamples)
  22560. {
  22561. uint8* const start = findEventAfter (getData(), startSample - 1);
  22562. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22563. if (end > start)
  22564. {
  22565. const int bytesToMove = bytesUsed - (int) (end - getData());
  22566. if (bytesToMove > 0)
  22567. memmove (start, end, bytesToMove);
  22568. bytesUsed -= (int) (end - start);
  22569. }
  22570. }
  22571. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22572. {
  22573. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22574. }
  22575. static int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22576. {
  22577. unsigned int byte = (unsigned int) *data;
  22578. int size = 0;
  22579. if (byte == 0xf0 || byte == 0xf7)
  22580. {
  22581. const uint8* d = data + 1;
  22582. while (d < data + maxBytes)
  22583. if (*d++ == 0xf7)
  22584. break;
  22585. size = (int) (d - data);
  22586. }
  22587. else if (byte == 0xff)
  22588. {
  22589. int n;
  22590. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22591. size = jmin (maxBytes, n + 2 + bytesLeft);
  22592. }
  22593. else if (byte >= 0x80)
  22594. {
  22595. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22596. }
  22597. return size;
  22598. }
  22599. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22600. {
  22601. const int numBytes = findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22602. if (numBytes > 0)
  22603. {
  22604. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22605. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22606. uint8* d = findEventAfter (getData(), sampleNumber);
  22607. const int bytesToMove = bytesUsed - (int) (d - getData());
  22608. if (bytesToMove > 0)
  22609. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22610. *reinterpret_cast <int*> (d) = sampleNumber;
  22611. d += sizeof (int);
  22612. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22613. d += sizeof (uint16);
  22614. memcpy (d, newData, numBytes);
  22615. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22616. }
  22617. }
  22618. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22619. const int startSample,
  22620. const int numSamples,
  22621. const int sampleDeltaToAdd)
  22622. {
  22623. Iterator i (otherBuffer);
  22624. i.setNextSamplePosition (startSample);
  22625. const uint8* eventData;
  22626. int eventSize, position;
  22627. while (i.getNextEvent (eventData, eventSize, position)
  22628. && (position < startSample + numSamples || numSamples < 0))
  22629. {
  22630. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22631. }
  22632. }
  22633. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22634. {
  22635. data.ensureSize (minimumNumBytes);
  22636. }
  22637. bool MidiBuffer::isEmpty() const throw()
  22638. {
  22639. return bytesUsed == 0;
  22640. }
  22641. int MidiBuffer::getNumEvents() const throw()
  22642. {
  22643. int n = 0;
  22644. const uint8* d = getData();
  22645. const uint8* const end = d + bytesUsed;
  22646. while (d < end)
  22647. {
  22648. d += getEventTotalSize (d);
  22649. ++n;
  22650. }
  22651. return n;
  22652. }
  22653. int MidiBuffer::getFirstEventTime() const throw()
  22654. {
  22655. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22656. }
  22657. int MidiBuffer::getLastEventTime() const throw()
  22658. {
  22659. if (bytesUsed == 0)
  22660. return 0;
  22661. const uint8* d = getData();
  22662. const uint8* const endData = d + bytesUsed;
  22663. for (;;)
  22664. {
  22665. const uint8* const nextOne = d + getEventTotalSize (d);
  22666. if (nextOne >= endData)
  22667. return getEventTime (d);
  22668. d = nextOne;
  22669. }
  22670. }
  22671. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22672. {
  22673. const uint8* const endData = getData() + bytesUsed;
  22674. while (d < endData && getEventTime (d) <= samplePosition)
  22675. d += getEventTotalSize (d);
  22676. return d;
  22677. }
  22678. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22679. : buffer (buffer_),
  22680. data (buffer_.getData())
  22681. {
  22682. }
  22683. MidiBuffer::Iterator::~Iterator() throw()
  22684. {
  22685. }
  22686. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22687. {
  22688. data = buffer.getData();
  22689. const uint8* dataEnd = data + buffer.bytesUsed;
  22690. while (data < dataEnd && getEventTime (data) < samplePosition)
  22691. data += getEventTotalSize (data);
  22692. }
  22693. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22694. {
  22695. if (data >= buffer.getData() + buffer.bytesUsed)
  22696. return false;
  22697. samplePosition = getEventTime (data);
  22698. numBytes = getEventDataSize (data);
  22699. data += sizeof (int) + sizeof (uint16);
  22700. midiData = data;
  22701. data += numBytes;
  22702. return true;
  22703. }
  22704. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22705. {
  22706. if (data >= buffer.getData() + buffer.bytesUsed)
  22707. return false;
  22708. samplePosition = getEventTime (data);
  22709. const int numBytes = getEventDataSize (data);
  22710. data += sizeof (int) + sizeof (uint16);
  22711. result = MidiMessage (data, numBytes, samplePosition);
  22712. data += numBytes;
  22713. return true;
  22714. }
  22715. END_JUCE_NAMESPACE
  22716. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22717. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22718. BEGIN_JUCE_NAMESPACE
  22719. namespace MidiFileHelpers
  22720. {
  22721. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22722. {
  22723. unsigned int buffer = v & 0x7F;
  22724. while ((v >>= 7) != 0)
  22725. {
  22726. buffer <<= 8;
  22727. buffer |= ((v & 0x7F) | 0x80);
  22728. }
  22729. for (;;)
  22730. {
  22731. out.writeByte ((char) buffer);
  22732. if (buffer & 0x80)
  22733. buffer >>= 8;
  22734. else
  22735. break;
  22736. }
  22737. }
  22738. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22739. {
  22740. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22741. data += 4;
  22742. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22743. {
  22744. bool ok = false;
  22745. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22746. {
  22747. for (int i = 0; i < 8; ++i)
  22748. {
  22749. ch = ByteOrder::bigEndianInt (data);
  22750. data += 4;
  22751. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22752. {
  22753. ok = true;
  22754. break;
  22755. }
  22756. }
  22757. }
  22758. if (! ok)
  22759. return false;
  22760. }
  22761. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22762. data += 4;
  22763. fileType = (short) ByteOrder::bigEndianShort (data);
  22764. data += 2;
  22765. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22766. data += 2;
  22767. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22768. data += 2;
  22769. bytesRemaining -= 6;
  22770. data += bytesRemaining;
  22771. return true;
  22772. }
  22773. static double convertTicksToSeconds (const double time,
  22774. const MidiMessageSequence& tempoEvents,
  22775. const int timeFormat)
  22776. {
  22777. if (timeFormat > 0)
  22778. {
  22779. int numer = 4, denom = 4;
  22780. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22781. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22782. double secsPerTick = 0.5 * tickLen;
  22783. const int numEvents = tempoEvents.getNumEvents();
  22784. for (int i = 0; i < numEvents; ++i)
  22785. {
  22786. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22787. if (time <= m.getTimeStamp())
  22788. break;
  22789. if (timeFormat > 0)
  22790. {
  22791. correctedTempoTime = correctedTempoTime
  22792. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22793. }
  22794. else
  22795. {
  22796. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22797. }
  22798. tempoTime = m.getTimeStamp();
  22799. if (m.isTempoMetaEvent())
  22800. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22801. else if (m.isTimeSignatureMetaEvent())
  22802. m.getTimeSignatureInfo (numer, denom);
  22803. while (i + 1 < numEvents)
  22804. {
  22805. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22806. if (m2.getTimeStamp() == tempoTime)
  22807. {
  22808. ++i;
  22809. if (m2.isTempoMetaEvent())
  22810. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22811. else if (m2.isTimeSignatureMetaEvent())
  22812. m2.getTimeSignatureInfo (numer, denom);
  22813. }
  22814. else
  22815. {
  22816. break;
  22817. }
  22818. }
  22819. }
  22820. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22821. }
  22822. else
  22823. {
  22824. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22825. }
  22826. }
  22827. // a comparator that puts all the note-offs before note-ons that have the same time
  22828. struct Sorter
  22829. {
  22830. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22831. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22832. {
  22833. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22834. if (diff == 0)
  22835. {
  22836. if (first->message.isNoteOff() && second->message.isNoteOn())
  22837. return -1;
  22838. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22839. return 1;
  22840. else
  22841. return 0;
  22842. }
  22843. else
  22844. {
  22845. return (diff > 0) ? 1 : -1;
  22846. }
  22847. }
  22848. };
  22849. }
  22850. MidiFile::MidiFile()
  22851. : timeFormat ((short) (unsigned short) 0xe728)
  22852. {
  22853. }
  22854. MidiFile::~MidiFile()
  22855. {
  22856. clear();
  22857. }
  22858. void MidiFile::clear()
  22859. {
  22860. tracks.clear();
  22861. }
  22862. int MidiFile::getNumTracks() const throw()
  22863. {
  22864. return tracks.size();
  22865. }
  22866. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22867. {
  22868. return tracks [index];
  22869. }
  22870. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22871. {
  22872. tracks.add (new MidiMessageSequence (trackSequence));
  22873. }
  22874. short MidiFile::getTimeFormat() const throw()
  22875. {
  22876. return timeFormat;
  22877. }
  22878. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22879. {
  22880. timeFormat = (short) ticks;
  22881. }
  22882. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22883. const int subframeResolution) throw()
  22884. {
  22885. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22886. }
  22887. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22888. {
  22889. for (int i = tracks.size(); --i >= 0;)
  22890. {
  22891. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22892. for (int j = 0; j < numEvents; ++j)
  22893. {
  22894. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22895. if (m.isTempoMetaEvent())
  22896. tempoChangeEvents.addEvent (m);
  22897. }
  22898. }
  22899. }
  22900. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22901. {
  22902. for (int i = tracks.size(); --i >= 0;)
  22903. {
  22904. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22905. for (int j = 0; j < numEvents; ++j)
  22906. {
  22907. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22908. if (m.isTimeSignatureMetaEvent())
  22909. timeSigEvents.addEvent (m);
  22910. }
  22911. }
  22912. }
  22913. double MidiFile::getLastTimestamp() const
  22914. {
  22915. double t = 0.0;
  22916. for (int i = tracks.size(); --i >= 0;)
  22917. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22918. return t;
  22919. }
  22920. bool MidiFile::readFrom (InputStream& sourceStream)
  22921. {
  22922. clear();
  22923. MemoryBlock data;
  22924. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22925. // (put a sanity-check on the file size, as midi files are generally small)
  22926. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22927. {
  22928. size_t size = data.getSize();
  22929. const uint8* d = static_cast <const uint8*> (data.getData());
  22930. short fileType, expectedTracks;
  22931. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22932. {
  22933. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22934. int track = 0;
  22935. while (size > 0 && track < expectedTracks)
  22936. {
  22937. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22938. d += 4;
  22939. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22940. d += 4;
  22941. if (chunkSize <= 0)
  22942. break;
  22943. if (size < 0)
  22944. return false;
  22945. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22946. {
  22947. readNextTrack (d, chunkSize);
  22948. }
  22949. size -= chunkSize + 8;
  22950. d += chunkSize;
  22951. ++track;
  22952. }
  22953. return true;
  22954. }
  22955. }
  22956. return false;
  22957. }
  22958. void MidiFile::readNextTrack (const uint8* data, int size)
  22959. {
  22960. double time = 0;
  22961. char lastStatusByte = 0;
  22962. MidiMessageSequence result;
  22963. while (size > 0)
  22964. {
  22965. int bytesUsed;
  22966. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22967. data += bytesUsed;
  22968. size -= bytesUsed;
  22969. time += delay;
  22970. int messSize = 0;
  22971. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22972. if (messSize <= 0)
  22973. break;
  22974. size -= messSize;
  22975. data += messSize;
  22976. result.addEvent (mm);
  22977. const char firstByte = *(mm.getRawData());
  22978. if ((firstByte & 0xf0) != 0xf0)
  22979. lastStatusByte = firstByte;
  22980. }
  22981. // use a sort that puts all the note-offs before note-ons that have the same time
  22982. MidiFileHelpers::Sorter sorter;
  22983. result.list.sort (sorter, true);
  22984. result.updateMatchedPairs();
  22985. addTrack (result);
  22986. }
  22987. void MidiFile::convertTimestampTicksToSeconds()
  22988. {
  22989. MidiMessageSequence tempoEvents;
  22990. findAllTempoEvents (tempoEvents);
  22991. findAllTimeSigEvents (tempoEvents);
  22992. for (int i = 0; i < tracks.size(); ++i)
  22993. {
  22994. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22995. for (int j = ms.getNumEvents(); --j >= 0;)
  22996. {
  22997. MidiMessage& m = ms.getEventPointer(j)->message;
  22998. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22999. tempoEvents,
  23000. timeFormat));
  23001. }
  23002. }
  23003. }
  23004. bool MidiFile::writeTo (OutputStream& out)
  23005. {
  23006. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  23007. out.writeIntBigEndian (6);
  23008. out.writeShortBigEndian (1); // type
  23009. out.writeShortBigEndian ((short) tracks.size());
  23010. out.writeShortBigEndian (timeFormat);
  23011. for (int i = 0; i < tracks.size(); ++i)
  23012. writeTrack (out, i);
  23013. out.flush();
  23014. return true;
  23015. }
  23016. void MidiFile::writeTrack (OutputStream& mainOut,
  23017. const int trackNum)
  23018. {
  23019. MemoryOutputStream out;
  23020. const MidiMessageSequence& ms = *tracks[trackNum];
  23021. int lastTick = 0;
  23022. char lastStatusByte = 0;
  23023. for (int i = 0; i < ms.getNumEvents(); ++i)
  23024. {
  23025. const MidiMessage& mm = ms.getEventPointer(i)->message;
  23026. const int tick = roundToInt (mm.getTimeStamp());
  23027. const int delta = jmax (0, tick - lastTick);
  23028. MidiFileHelpers::writeVariableLengthInt (out, delta);
  23029. lastTick = tick;
  23030. const char statusByte = *(mm.getRawData());
  23031. if ((statusByte == lastStatusByte)
  23032. && ((statusByte & 0xf0) != 0xf0)
  23033. && i > 0
  23034. && mm.getRawDataSize() > 1)
  23035. {
  23036. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  23037. }
  23038. else
  23039. {
  23040. out.write (mm.getRawData(), mm.getRawDataSize());
  23041. }
  23042. lastStatusByte = statusByte;
  23043. }
  23044. out.writeByte (0);
  23045. const MidiMessage m (MidiMessage::endOfTrack());
  23046. out.write (m.getRawData(),
  23047. m.getRawDataSize());
  23048. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  23049. mainOut.writeIntBigEndian ((int) out.getDataSize());
  23050. mainOut.write (out.getData(), (int) out.getDataSize());
  23051. }
  23052. END_JUCE_NAMESPACE
  23053. /*** End of inlined file: juce_MidiFile.cpp ***/
  23054. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  23055. BEGIN_JUCE_NAMESPACE
  23056. MidiKeyboardState::MidiKeyboardState()
  23057. {
  23058. zerostruct (noteStates);
  23059. }
  23060. MidiKeyboardState::~MidiKeyboardState()
  23061. {
  23062. }
  23063. void MidiKeyboardState::reset()
  23064. {
  23065. const ScopedLock sl (lock);
  23066. zerostruct (noteStates);
  23067. eventsToAdd.clear();
  23068. }
  23069. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  23070. {
  23071. jassert (midiChannel >= 0 && midiChannel <= 16);
  23072. return ((unsigned int) n) < 128
  23073. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  23074. }
  23075. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  23076. {
  23077. return ((unsigned int) n) < 128
  23078. && (noteStates[n] & midiChannelMask) != 0;
  23079. }
  23080. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  23081. {
  23082. jassert (midiChannel >= 0 && midiChannel <= 16);
  23083. jassert (((unsigned int) midiNoteNumber) < 128);
  23084. const ScopedLock sl (lock);
  23085. if (((unsigned int) midiNoteNumber) < 128)
  23086. {
  23087. const int timeNow = (int) Time::getMillisecondCounter();
  23088. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  23089. eventsToAdd.clear (0, timeNow - 500);
  23090. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  23091. }
  23092. }
  23093. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  23094. {
  23095. if (((unsigned int) midiNoteNumber) < 128)
  23096. {
  23097. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  23098. for (int i = listeners.size(); --i >= 0;)
  23099. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  23100. }
  23101. }
  23102. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  23103. {
  23104. const ScopedLock sl (lock);
  23105. if (isNoteOn (midiChannel, midiNoteNumber))
  23106. {
  23107. const int timeNow = (int) Time::getMillisecondCounter();
  23108. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  23109. eventsToAdd.clear (0, timeNow - 500);
  23110. noteOffInternal (midiChannel, midiNoteNumber);
  23111. }
  23112. }
  23113. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  23114. {
  23115. if (isNoteOn (midiChannel, midiNoteNumber))
  23116. {
  23117. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  23118. for (int i = listeners.size(); --i >= 0;)
  23119. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  23120. }
  23121. }
  23122. void MidiKeyboardState::allNotesOff (const int midiChannel)
  23123. {
  23124. const ScopedLock sl (lock);
  23125. if (midiChannel <= 0)
  23126. {
  23127. for (int i = 1; i <= 16; ++i)
  23128. allNotesOff (i);
  23129. }
  23130. else
  23131. {
  23132. for (int i = 0; i < 128; ++i)
  23133. noteOff (midiChannel, i);
  23134. }
  23135. }
  23136. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  23137. {
  23138. if (message.isNoteOn())
  23139. {
  23140. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  23141. }
  23142. else if (message.isNoteOff())
  23143. {
  23144. noteOffInternal (message.getChannel(), message.getNoteNumber());
  23145. }
  23146. else if (message.isAllNotesOff())
  23147. {
  23148. for (int i = 0; i < 128; ++i)
  23149. noteOffInternal (message.getChannel(), i);
  23150. }
  23151. }
  23152. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  23153. const int startSample,
  23154. const int numSamples,
  23155. const bool injectIndirectEvents)
  23156. {
  23157. MidiBuffer::Iterator i (buffer);
  23158. MidiMessage message (0xf4, 0.0);
  23159. int time;
  23160. const ScopedLock sl (lock);
  23161. while (i.getNextEvent (message, time))
  23162. processNextMidiEvent (message);
  23163. if (injectIndirectEvents)
  23164. {
  23165. MidiBuffer::Iterator i2 (eventsToAdd);
  23166. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  23167. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  23168. while (i2.getNextEvent (message, time))
  23169. {
  23170. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  23171. buffer.addEvent (message, startSample + pos);
  23172. }
  23173. }
  23174. eventsToAdd.clear();
  23175. }
  23176. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  23177. {
  23178. const ScopedLock sl (lock);
  23179. listeners.addIfNotAlreadyThere (listener);
  23180. }
  23181. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  23182. {
  23183. const ScopedLock sl (lock);
  23184. listeners.removeValue (listener);
  23185. }
  23186. END_JUCE_NAMESPACE
  23187. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  23188. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  23189. BEGIN_JUCE_NAMESPACE
  23190. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  23191. {
  23192. numBytesUsed = 0;
  23193. int v = 0;
  23194. int i;
  23195. do
  23196. {
  23197. i = (int) *data++;
  23198. if (++numBytesUsed > 6)
  23199. break;
  23200. v = (v << 7) + (i & 0x7f);
  23201. } while (i & 0x80);
  23202. return v;
  23203. }
  23204. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23205. {
  23206. // this method only works for valid starting bytes of a short midi message
  23207. jassert (firstByte >= 0x80
  23208. && firstByte != 0xf0
  23209. && firstByte != 0xf7);
  23210. static const char messageLengths[] =
  23211. {
  23212. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23213. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23214. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23215. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23216. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23217. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23218. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23219. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23220. };
  23221. return messageLengths [firstByte & 0x7f];
  23222. }
  23223. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23224. : timeStamp (t),
  23225. size (dataSize)
  23226. {
  23227. jassert (dataSize > 0);
  23228. if (dataSize <= 4)
  23229. data = static_cast<uint8*> (preallocatedData.asBytes);
  23230. else
  23231. data = new uint8 [dataSize];
  23232. memcpy (data, d, dataSize);
  23233. // check that the length matches the data..
  23234. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23235. }
  23236. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23237. : timeStamp (t),
  23238. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23239. size (1)
  23240. {
  23241. data[0] = (uint8) byte1;
  23242. // check that the length matches the data..
  23243. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23244. }
  23245. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23246. : timeStamp (t),
  23247. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23248. size (2)
  23249. {
  23250. data[0] = (uint8) byte1;
  23251. data[1] = (uint8) byte2;
  23252. // check that the length matches the data..
  23253. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23254. }
  23255. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23256. : timeStamp (t),
  23257. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23258. size (3)
  23259. {
  23260. data[0] = (uint8) byte1;
  23261. data[1] = (uint8) byte2;
  23262. data[2] = (uint8) byte3;
  23263. // check that the length matches the data..
  23264. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23265. }
  23266. MidiMessage::MidiMessage (const MidiMessage& other)
  23267. : timeStamp (other.timeStamp),
  23268. size (other.size)
  23269. {
  23270. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23271. {
  23272. data = new uint8 [size];
  23273. memcpy (data, other.data, size);
  23274. }
  23275. else
  23276. {
  23277. data = static_cast<uint8*> (preallocatedData.asBytes);
  23278. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23279. }
  23280. }
  23281. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23282. : timeStamp (newTimeStamp),
  23283. size (other.size)
  23284. {
  23285. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23286. {
  23287. data = new uint8 [size];
  23288. memcpy (data, other.data, size);
  23289. }
  23290. else
  23291. {
  23292. data = static_cast<uint8*> (preallocatedData.asBytes);
  23293. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23294. }
  23295. }
  23296. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23297. : timeStamp (t),
  23298. data (static_cast<uint8*> (preallocatedData.asBytes))
  23299. {
  23300. const uint8* src = static_cast <const uint8*> (src_);
  23301. unsigned int byte = (unsigned int) *src;
  23302. if (byte < 0x80)
  23303. {
  23304. byte = (unsigned int) (uint8) lastStatusByte;
  23305. numBytesUsed = -1;
  23306. }
  23307. else
  23308. {
  23309. numBytesUsed = 0;
  23310. --sz;
  23311. ++src;
  23312. }
  23313. if (byte >= 0x80)
  23314. {
  23315. if (byte == 0xf0)
  23316. {
  23317. const uint8* d = src;
  23318. while (d < src + sz)
  23319. {
  23320. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  23321. {
  23322. if (*d == 0xf7) // include an 0xf7 if we hit one
  23323. ++d;
  23324. break;
  23325. }
  23326. ++d;
  23327. }
  23328. size = 1 + (int) (d - src);
  23329. data = new uint8 [size];
  23330. *data = (uint8) byte;
  23331. memcpy (data + 1, src, size - 1);
  23332. }
  23333. else if (byte == 0xff)
  23334. {
  23335. int n;
  23336. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23337. size = jmin (sz + 1, n + 2 + bytesLeft);
  23338. data = new uint8 [size];
  23339. *data = (uint8) byte;
  23340. memcpy (data + 1, src, size - 1);
  23341. }
  23342. else
  23343. {
  23344. preallocatedData.asInt32 = 0;
  23345. size = getMessageLengthFromFirstByte ((uint8) byte);
  23346. data[0] = (uint8) byte;
  23347. if (size > 1)
  23348. {
  23349. data[1] = src[0];
  23350. if (size > 2)
  23351. data[2] = src[1];
  23352. }
  23353. }
  23354. numBytesUsed += size;
  23355. }
  23356. else
  23357. {
  23358. preallocatedData.asInt32 = 0;
  23359. size = 0;
  23360. }
  23361. }
  23362. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23363. {
  23364. if (this != &other)
  23365. {
  23366. timeStamp = other.timeStamp;
  23367. size = other.size;
  23368. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23369. delete[] data;
  23370. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23371. {
  23372. data = new uint8 [size];
  23373. memcpy (data, other.data, size);
  23374. }
  23375. else
  23376. {
  23377. data = static_cast<uint8*> (preallocatedData.asBytes);
  23378. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23379. }
  23380. }
  23381. return *this;
  23382. }
  23383. MidiMessage::~MidiMessage()
  23384. {
  23385. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23386. delete[] data;
  23387. }
  23388. int MidiMessage::getChannel() const throw()
  23389. {
  23390. if ((data[0] & 0xf0) != 0xf0)
  23391. return (data[0] & 0xf) + 1;
  23392. else
  23393. return 0;
  23394. }
  23395. bool MidiMessage::isForChannel (const int channel) const throw()
  23396. {
  23397. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23398. return ((data[0] & 0xf) == channel - 1)
  23399. && ((data[0] & 0xf0) != 0xf0);
  23400. }
  23401. void MidiMessage::setChannel (const int channel) throw()
  23402. {
  23403. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23404. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23405. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23406. | (uint8)(channel - 1));
  23407. }
  23408. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23409. {
  23410. return ((data[0] & 0xf0) == 0x90)
  23411. && (returnTrueForVelocity0 || data[2] != 0);
  23412. }
  23413. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23414. {
  23415. return ((data[0] & 0xf0) == 0x80)
  23416. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23417. }
  23418. bool MidiMessage::isNoteOnOrOff() const throw()
  23419. {
  23420. const int d = data[0] & 0xf0;
  23421. return (d == 0x90) || (d == 0x80);
  23422. }
  23423. int MidiMessage::getNoteNumber() const throw()
  23424. {
  23425. return data[1];
  23426. }
  23427. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23428. {
  23429. if (isNoteOnOrOff())
  23430. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23431. }
  23432. uint8 MidiMessage::getVelocity() const throw()
  23433. {
  23434. if (isNoteOnOrOff())
  23435. return data[2];
  23436. else
  23437. return 0;
  23438. }
  23439. float MidiMessage::getFloatVelocity() const throw()
  23440. {
  23441. return getVelocity() * (1.0f / 127.0f);
  23442. }
  23443. void MidiMessage::setVelocity (const float newVelocity) throw()
  23444. {
  23445. if (isNoteOnOrOff())
  23446. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23447. }
  23448. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23449. {
  23450. if (isNoteOnOrOff())
  23451. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23452. }
  23453. bool MidiMessage::isAftertouch() const throw()
  23454. {
  23455. return (data[0] & 0xf0) == 0xa0;
  23456. }
  23457. int MidiMessage::getAfterTouchValue() const throw()
  23458. {
  23459. return data[2];
  23460. }
  23461. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23462. const int noteNum,
  23463. const int aftertouchValue) throw()
  23464. {
  23465. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23466. jassert (((unsigned int) noteNum) <= 127);
  23467. jassert (((unsigned int) aftertouchValue) <= 127);
  23468. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23469. noteNum & 0x7f,
  23470. aftertouchValue & 0x7f);
  23471. }
  23472. bool MidiMessage::isChannelPressure() const throw()
  23473. {
  23474. return (data[0] & 0xf0) == 0xd0;
  23475. }
  23476. int MidiMessage::getChannelPressureValue() const throw()
  23477. {
  23478. jassert (isChannelPressure());
  23479. return data[1];
  23480. }
  23481. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23482. const int pressure) throw()
  23483. {
  23484. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23485. jassert (((unsigned int) pressure) <= 127);
  23486. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23487. pressure & 0x7f);
  23488. }
  23489. bool MidiMessage::isProgramChange() const throw()
  23490. {
  23491. return (data[0] & 0xf0) == 0xc0;
  23492. }
  23493. int MidiMessage::getProgramChangeNumber() const throw()
  23494. {
  23495. return data[1];
  23496. }
  23497. const MidiMessage MidiMessage::programChange (const int channel,
  23498. const int programNumber) throw()
  23499. {
  23500. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23501. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23502. programNumber & 0x7f);
  23503. }
  23504. bool MidiMessage::isPitchWheel() const throw()
  23505. {
  23506. return (data[0] & 0xf0) == 0xe0;
  23507. }
  23508. int MidiMessage::getPitchWheelValue() const throw()
  23509. {
  23510. return data[1] | (data[2] << 7);
  23511. }
  23512. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23513. const int position) throw()
  23514. {
  23515. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23516. jassert (((unsigned int) position) <= 0x3fff);
  23517. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23518. position & 127,
  23519. (position >> 7) & 127);
  23520. }
  23521. bool MidiMessage::isController() const throw()
  23522. {
  23523. return (data[0] & 0xf0) == 0xb0;
  23524. }
  23525. int MidiMessage::getControllerNumber() const throw()
  23526. {
  23527. jassert (isController());
  23528. return data[1];
  23529. }
  23530. int MidiMessage::getControllerValue() const throw()
  23531. {
  23532. jassert (isController());
  23533. return data[2];
  23534. }
  23535. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23536. const int controllerType,
  23537. const int value) throw()
  23538. {
  23539. // the channel must be between 1 and 16 inclusive
  23540. jassert (channel > 0 && channel <= 16);
  23541. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23542. controllerType & 127,
  23543. value & 127);
  23544. }
  23545. const MidiMessage MidiMessage::noteOn (const int channel,
  23546. const int noteNumber,
  23547. const float velocity) throw()
  23548. {
  23549. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23550. }
  23551. const MidiMessage MidiMessage::noteOn (const int channel,
  23552. const int noteNumber,
  23553. const uint8 velocity) throw()
  23554. {
  23555. jassert (channel > 0 && channel <= 16);
  23556. jassert (((unsigned int) noteNumber) <= 127);
  23557. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23558. noteNumber & 127,
  23559. jlimit (0, 127, roundToInt (velocity)));
  23560. }
  23561. const MidiMessage MidiMessage::noteOff (const int channel,
  23562. const int noteNumber) throw()
  23563. {
  23564. jassert (channel > 0 && channel <= 16);
  23565. jassert (((unsigned int) noteNumber) <= 127);
  23566. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23567. }
  23568. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23569. {
  23570. return controllerEvent (channel, 123, 0);
  23571. }
  23572. bool MidiMessage::isAllNotesOff() const throw()
  23573. {
  23574. return (data[0] & 0xf0) == 0xb0
  23575. && data[1] == 123;
  23576. }
  23577. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23578. {
  23579. return controllerEvent (channel, 120, 0);
  23580. }
  23581. bool MidiMessage::isAllSoundOff() const throw()
  23582. {
  23583. return (data[0] & 0xf0) == 0xb0
  23584. && data[1] == 120;
  23585. }
  23586. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23587. {
  23588. return controllerEvent (channel, 121, 0);
  23589. }
  23590. const MidiMessage MidiMessage::masterVolume (const float volume)
  23591. {
  23592. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23593. uint8 buf[8];
  23594. buf[0] = 0xf0;
  23595. buf[1] = 0x7f;
  23596. buf[2] = 0x7f;
  23597. buf[3] = 0x04;
  23598. buf[4] = 0x01;
  23599. buf[5] = (uint8) (vol & 0x7f);
  23600. buf[6] = (uint8) (vol >> 7);
  23601. buf[7] = 0xf7;
  23602. return MidiMessage (buf, 8);
  23603. }
  23604. bool MidiMessage::isSysEx() const throw()
  23605. {
  23606. return *data == 0xf0;
  23607. }
  23608. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23609. {
  23610. MemoryBlock mm (dataSize + 2);
  23611. uint8* const m = static_cast <uint8*> (mm.getData());
  23612. m[0] = 0xf0;
  23613. memcpy (m + 1, sysexData, dataSize);
  23614. m[dataSize + 1] = 0xf7;
  23615. return MidiMessage (m, dataSize + 2);
  23616. }
  23617. const uint8* MidiMessage::getSysExData() const throw()
  23618. {
  23619. return (isSysEx()) ? getRawData() + 1 : 0;
  23620. }
  23621. int MidiMessage::getSysExDataSize() const throw()
  23622. {
  23623. return (isSysEx()) ? size - 2 : 0;
  23624. }
  23625. bool MidiMessage::isMetaEvent() const throw()
  23626. {
  23627. return *data == 0xff;
  23628. }
  23629. bool MidiMessage::isActiveSense() const throw()
  23630. {
  23631. return *data == 0xfe;
  23632. }
  23633. int MidiMessage::getMetaEventType() const throw()
  23634. {
  23635. if (*data != 0xff)
  23636. return -1;
  23637. else
  23638. return data[1];
  23639. }
  23640. int MidiMessage::getMetaEventLength() const throw()
  23641. {
  23642. if (*data == 0xff)
  23643. {
  23644. int n;
  23645. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23646. }
  23647. return 0;
  23648. }
  23649. const uint8* MidiMessage::getMetaEventData() const throw()
  23650. {
  23651. int n;
  23652. const uint8* d = data + 2;
  23653. readVariableLengthVal (d, n);
  23654. return d + n;
  23655. }
  23656. bool MidiMessage::isTrackMetaEvent() const throw()
  23657. {
  23658. return getMetaEventType() == 0;
  23659. }
  23660. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23661. {
  23662. return getMetaEventType() == 47;
  23663. }
  23664. bool MidiMessage::isTextMetaEvent() const throw()
  23665. {
  23666. const int t = getMetaEventType();
  23667. return t > 0 && t < 16;
  23668. }
  23669. const String MidiMessage::getTextFromTextMetaEvent() const
  23670. {
  23671. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23672. }
  23673. bool MidiMessage::isTrackNameEvent() const throw()
  23674. {
  23675. return (data[1] == 3)
  23676. && (*data == 0xff);
  23677. }
  23678. bool MidiMessage::isTempoMetaEvent() const throw()
  23679. {
  23680. return (data[1] == 81)
  23681. && (*data == 0xff);
  23682. }
  23683. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23684. {
  23685. return (data[1] == 0x20)
  23686. && (*data == 0xff)
  23687. && (data[2] == 1);
  23688. }
  23689. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23690. {
  23691. return data[3] + 1;
  23692. }
  23693. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23694. {
  23695. if (! isTempoMetaEvent())
  23696. return 0.0;
  23697. const uint8* const d = getMetaEventData();
  23698. return (((unsigned int) d[0] << 16)
  23699. | ((unsigned int) d[1] << 8)
  23700. | d[2])
  23701. / 1000000.0;
  23702. }
  23703. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23704. {
  23705. if (timeFormat > 0)
  23706. {
  23707. if (! isTempoMetaEvent())
  23708. return 0.5 / timeFormat;
  23709. return getTempoSecondsPerQuarterNote() / timeFormat;
  23710. }
  23711. else
  23712. {
  23713. const int frameCode = (-timeFormat) >> 8;
  23714. double framesPerSecond;
  23715. switch (frameCode)
  23716. {
  23717. case 24: framesPerSecond = 24.0; break;
  23718. case 25: framesPerSecond = 25.0; break;
  23719. case 29: framesPerSecond = 29.97; break;
  23720. case 30: framesPerSecond = 30.0; break;
  23721. default: framesPerSecond = 30.0; break;
  23722. }
  23723. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23724. }
  23725. }
  23726. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23727. {
  23728. uint8 d[8];
  23729. d[0] = 0xff;
  23730. d[1] = 81;
  23731. d[2] = 3;
  23732. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23733. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23734. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23735. return MidiMessage (d, 6, 0.0);
  23736. }
  23737. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23738. {
  23739. return (data[1] == 0x58)
  23740. && (*data == (uint8) 0xff);
  23741. }
  23742. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23743. {
  23744. if (isTimeSignatureMetaEvent())
  23745. {
  23746. const uint8* const d = getMetaEventData();
  23747. numerator = d[0];
  23748. denominator = 1 << d[1];
  23749. }
  23750. else
  23751. {
  23752. numerator = 4;
  23753. denominator = 4;
  23754. }
  23755. }
  23756. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23757. {
  23758. uint8 d[8];
  23759. d[0] = 0xff;
  23760. d[1] = 0x58;
  23761. d[2] = 0x04;
  23762. d[3] = (uint8) numerator;
  23763. int n = 1;
  23764. int powerOfTwo = 0;
  23765. while (n < denominator)
  23766. {
  23767. n <<= 1;
  23768. ++powerOfTwo;
  23769. }
  23770. d[4] = (uint8) powerOfTwo;
  23771. d[5] = 0x01;
  23772. d[6] = 96;
  23773. return MidiMessage (d, 7, 0.0);
  23774. }
  23775. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23776. {
  23777. uint8 d[8];
  23778. d[0] = 0xff;
  23779. d[1] = 0x20;
  23780. d[2] = 0x01;
  23781. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23782. return MidiMessage (d, 4, 0.0);
  23783. }
  23784. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23785. {
  23786. return getMetaEventType() == 89;
  23787. }
  23788. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23789. {
  23790. return (int) *getMetaEventData();
  23791. }
  23792. const MidiMessage MidiMessage::endOfTrack() throw()
  23793. {
  23794. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23795. }
  23796. bool MidiMessage::isSongPositionPointer() const throw()
  23797. {
  23798. return *data == 0xf2;
  23799. }
  23800. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23801. {
  23802. return data[1] | (data[2] << 7);
  23803. }
  23804. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23805. {
  23806. return MidiMessage (0xf2,
  23807. positionInMidiBeats & 127,
  23808. (positionInMidiBeats >> 7) & 127);
  23809. }
  23810. bool MidiMessage::isMidiStart() const throw()
  23811. {
  23812. return *data == 0xfa;
  23813. }
  23814. const MidiMessage MidiMessage::midiStart() throw()
  23815. {
  23816. return MidiMessage (0xfa);
  23817. }
  23818. bool MidiMessage::isMidiContinue() const throw()
  23819. {
  23820. return *data == 0xfb;
  23821. }
  23822. const MidiMessage MidiMessage::midiContinue() throw()
  23823. {
  23824. return MidiMessage (0xfb);
  23825. }
  23826. bool MidiMessage::isMidiStop() const throw()
  23827. {
  23828. return *data == 0xfc;
  23829. }
  23830. const MidiMessage MidiMessage::midiStop() throw()
  23831. {
  23832. return MidiMessage (0xfc);
  23833. }
  23834. bool MidiMessage::isMidiClock() const throw()
  23835. {
  23836. return *data == 0xf8;
  23837. }
  23838. const MidiMessage MidiMessage::midiClock() throw()
  23839. {
  23840. return MidiMessage (0xf8);
  23841. }
  23842. bool MidiMessage::isQuarterFrame() const throw()
  23843. {
  23844. return *data == 0xf1;
  23845. }
  23846. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23847. {
  23848. return ((int) data[1]) >> 4;
  23849. }
  23850. int MidiMessage::getQuarterFrameValue() const throw()
  23851. {
  23852. return ((int) data[1]) & 0x0f;
  23853. }
  23854. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23855. const int value) throw()
  23856. {
  23857. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23858. }
  23859. bool MidiMessage::isFullFrame() const throw()
  23860. {
  23861. return data[0] == 0xf0
  23862. && data[1] == 0x7f
  23863. && size >= 10
  23864. && data[3] == 0x01
  23865. && data[4] == 0x01;
  23866. }
  23867. void MidiMessage::getFullFrameParameters (int& hours,
  23868. int& minutes,
  23869. int& seconds,
  23870. int& frames,
  23871. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23872. {
  23873. jassert (isFullFrame());
  23874. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23875. hours = data[5] & 0x1f;
  23876. minutes = data[6];
  23877. seconds = data[7];
  23878. frames = data[8];
  23879. }
  23880. const MidiMessage MidiMessage::fullFrame (const int hours,
  23881. const int minutes,
  23882. const int seconds,
  23883. const int frames,
  23884. MidiMessage::SmpteTimecodeType timecodeType)
  23885. {
  23886. uint8 d[10];
  23887. d[0] = 0xf0;
  23888. d[1] = 0x7f;
  23889. d[2] = 0x7f;
  23890. d[3] = 0x01;
  23891. d[4] = 0x01;
  23892. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23893. d[6] = (uint8) minutes;
  23894. d[7] = (uint8) seconds;
  23895. d[8] = (uint8) frames;
  23896. d[9] = 0xf7;
  23897. return MidiMessage (d, 10, 0.0);
  23898. }
  23899. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23900. {
  23901. return data[0] == 0xf0
  23902. && data[1] == 0x7f
  23903. && data[3] == 0x06
  23904. && size > 5;
  23905. }
  23906. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23907. {
  23908. jassert (isMidiMachineControlMessage());
  23909. return (MidiMachineControlCommand) data[4];
  23910. }
  23911. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23912. {
  23913. uint8 d[6];
  23914. d[0] = 0xf0;
  23915. d[1] = 0x7f;
  23916. d[2] = 0x00;
  23917. d[3] = 0x06;
  23918. d[4] = (uint8) command;
  23919. d[5] = 0xf7;
  23920. return MidiMessage (d, 6, 0.0);
  23921. }
  23922. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23923. int& minutes,
  23924. int& seconds,
  23925. int& frames) const throw()
  23926. {
  23927. if (size >= 12
  23928. && data[0] == 0xf0
  23929. && data[1] == 0x7f
  23930. && data[3] == 0x06
  23931. && data[4] == 0x44
  23932. && data[5] == 0x06
  23933. && data[6] == 0x01)
  23934. {
  23935. hours = data[7] % 24; // (that some machines send out hours > 24)
  23936. minutes = data[8];
  23937. seconds = data[9];
  23938. frames = data[10];
  23939. return true;
  23940. }
  23941. return false;
  23942. }
  23943. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23944. int minutes,
  23945. int seconds,
  23946. int frames)
  23947. {
  23948. uint8 d[12];
  23949. d[0] = 0xf0;
  23950. d[1] = 0x7f;
  23951. d[2] = 0x00;
  23952. d[3] = 0x06;
  23953. d[4] = 0x44;
  23954. d[5] = 0x06;
  23955. d[6] = 0x01;
  23956. d[7] = (uint8) hours;
  23957. d[8] = (uint8) minutes;
  23958. d[9] = (uint8) seconds;
  23959. d[10] = (uint8) frames;
  23960. d[11] = 0xf7;
  23961. return MidiMessage (d, 12, 0.0);
  23962. }
  23963. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23964. {
  23965. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23966. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23967. if (((unsigned int) note) < 128)
  23968. {
  23969. String s (useSharps ? sharpNoteNames [note % 12]
  23970. : flatNoteNames [note % 12]);
  23971. if (includeOctaveNumber)
  23972. s << (note / 12 + (octaveNumForMiddleC - 5));
  23973. return s;
  23974. }
  23975. return String::empty;
  23976. }
  23977. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  23978. {
  23979. noteNumber -= 12 * 6 + 9; // now 0 = A440
  23980. return 440.0 * pow (2.0, noteNumber / 12.0);
  23981. }
  23982. const String MidiMessage::getGMInstrumentName (const int n)
  23983. {
  23984. const char *names[] =
  23985. {
  23986. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23987. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23988. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23989. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23990. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23991. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23992. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23993. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23994. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23995. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23996. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23997. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23998. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23999. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  24000. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  24001. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  24002. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  24003. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  24004. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  24005. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  24006. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  24007. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  24008. "Applause", "Gunshot"
  24009. };
  24010. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  24011. }
  24012. const String MidiMessage::getGMInstrumentBankName (const int n)
  24013. {
  24014. const char* names[] =
  24015. {
  24016. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  24017. "Bass", "Strings", "Ensemble", "Brass",
  24018. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  24019. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  24020. };
  24021. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  24022. }
  24023. const String MidiMessage::getRhythmInstrumentName (const int n)
  24024. {
  24025. const char* names[] =
  24026. {
  24027. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  24028. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  24029. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  24030. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  24031. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  24032. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  24033. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  24034. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  24035. "Mute Triangle", "Open Triangle"
  24036. };
  24037. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  24038. }
  24039. const String MidiMessage::getControllerName (const int n)
  24040. {
  24041. const char* names[] =
  24042. {
  24043. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  24044. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  24045. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  24046. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  24047. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  24048. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  24049. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  24050. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  24051. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  24052. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  24053. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  24054. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  24055. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  24056. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  24057. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  24058. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  24059. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  24060. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  24061. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  24062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  24063. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  24064. "Poly Operation"
  24065. };
  24066. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  24067. }
  24068. END_JUCE_NAMESPACE
  24069. /*** End of inlined file: juce_MidiMessage.cpp ***/
  24070. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  24071. BEGIN_JUCE_NAMESPACE
  24072. MidiMessageCollector::MidiMessageCollector()
  24073. : lastCallbackTime (0),
  24074. sampleRate (44100.0001)
  24075. {
  24076. }
  24077. MidiMessageCollector::~MidiMessageCollector()
  24078. {
  24079. }
  24080. void MidiMessageCollector::reset (const double sampleRate_)
  24081. {
  24082. jassert (sampleRate_ > 0);
  24083. const ScopedLock sl (midiCallbackLock);
  24084. sampleRate = sampleRate_;
  24085. incomingMessages.clear();
  24086. lastCallbackTime = Time::getMillisecondCounterHiRes();
  24087. }
  24088. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  24089. {
  24090. // you need to call reset() to set the correct sample rate before using this object
  24091. jassert (sampleRate != 44100.0001);
  24092. // the messages that come in here need to be time-stamped correctly - see MidiInput
  24093. // for details of what the number should be.
  24094. jassert (message.getTimeStamp() != 0);
  24095. const ScopedLock sl (midiCallbackLock);
  24096. const int sampleNumber
  24097. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  24098. incomingMessages.addEvent (message, sampleNumber);
  24099. // if the messages don't get used for over a second, we'd better
  24100. // get rid of any old ones to avoid the queue getting too big
  24101. if (sampleNumber > sampleRate)
  24102. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  24103. }
  24104. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  24105. const int numSamples)
  24106. {
  24107. // you need to call reset() to set the correct sample rate before using this object
  24108. jassert (sampleRate != 44100.0001);
  24109. const double timeNow = Time::getMillisecondCounterHiRes();
  24110. const double msElapsed = timeNow - lastCallbackTime;
  24111. const ScopedLock sl (midiCallbackLock);
  24112. lastCallbackTime = timeNow;
  24113. if (! incomingMessages.isEmpty())
  24114. {
  24115. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  24116. int startSample = 0;
  24117. int scale = 1 << 16;
  24118. const uint8* midiData;
  24119. int numBytes, samplePosition;
  24120. MidiBuffer::Iterator iter (incomingMessages);
  24121. if (numSourceSamples > numSamples)
  24122. {
  24123. // if our list of events is longer than the buffer we're being
  24124. // asked for, scale them down to squeeze them all in..
  24125. const int maxBlockLengthToUse = numSamples << 5;
  24126. if (numSourceSamples > maxBlockLengthToUse)
  24127. {
  24128. startSample = numSourceSamples - maxBlockLengthToUse;
  24129. numSourceSamples = maxBlockLengthToUse;
  24130. iter.setNextSamplePosition (startSample);
  24131. }
  24132. scale = (numSamples << 10) / numSourceSamples;
  24133. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24134. {
  24135. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  24136. destBuffer.addEvent (midiData, numBytes,
  24137. jlimit (0, numSamples - 1, samplePosition));
  24138. }
  24139. }
  24140. else
  24141. {
  24142. // if our event list is shorter than the number we need, put them
  24143. // towards the end of the buffer
  24144. startSample = numSamples - numSourceSamples;
  24145. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24146. {
  24147. destBuffer.addEvent (midiData, numBytes,
  24148. jlimit (0, numSamples - 1, samplePosition + startSample));
  24149. }
  24150. }
  24151. incomingMessages.clear();
  24152. }
  24153. }
  24154. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  24155. {
  24156. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  24157. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24158. addMessageToQueue (m);
  24159. }
  24160. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  24161. {
  24162. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  24163. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24164. addMessageToQueue (m);
  24165. }
  24166. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  24167. {
  24168. addMessageToQueue (message);
  24169. }
  24170. END_JUCE_NAMESPACE
  24171. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  24172. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  24173. BEGIN_JUCE_NAMESPACE
  24174. MidiMessageSequence::MidiMessageSequence()
  24175. {
  24176. }
  24177. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  24178. {
  24179. list.ensureStorageAllocated (other.list.size());
  24180. for (int i = 0; i < other.list.size(); ++i)
  24181. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  24182. }
  24183. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  24184. {
  24185. MidiMessageSequence otherCopy (other);
  24186. swapWith (otherCopy);
  24187. return *this;
  24188. }
  24189. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  24190. {
  24191. list.swapWithArray (other.list);
  24192. }
  24193. MidiMessageSequence::~MidiMessageSequence()
  24194. {
  24195. }
  24196. void MidiMessageSequence::clear()
  24197. {
  24198. list.clear();
  24199. }
  24200. int MidiMessageSequence::getNumEvents() const
  24201. {
  24202. return list.size();
  24203. }
  24204. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24205. {
  24206. return list [index];
  24207. }
  24208. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24209. {
  24210. const MidiEventHolder* const meh = list [index];
  24211. if (meh != 0 && meh->noteOffObject != 0)
  24212. return meh->noteOffObject->message.getTimeStamp();
  24213. else
  24214. return 0.0;
  24215. }
  24216. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24217. {
  24218. const MidiEventHolder* const meh = list [index];
  24219. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24220. }
  24221. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24222. {
  24223. return list.indexOf (event);
  24224. }
  24225. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24226. {
  24227. const int numEvents = list.size();
  24228. int i;
  24229. for (i = 0; i < numEvents; ++i)
  24230. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24231. break;
  24232. return i;
  24233. }
  24234. double MidiMessageSequence::getStartTime() const
  24235. {
  24236. if (list.size() > 0)
  24237. return list.getUnchecked(0)->message.getTimeStamp();
  24238. else
  24239. return 0;
  24240. }
  24241. double MidiMessageSequence::getEndTime() const
  24242. {
  24243. if (list.size() > 0)
  24244. return list.getLast()->message.getTimeStamp();
  24245. else
  24246. return 0;
  24247. }
  24248. double MidiMessageSequence::getEventTime (const int index) const
  24249. {
  24250. if (((unsigned int) index) < (unsigned int) list.size())
  24251. return list.getUnchecked (index)->message.getTimeStamp();
  24252. return 0.0;
  24253. }
  24254. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24255. double timeAdjustment)
  24256. {
  24257. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24258. timeAdjustment += newMessage.getTimeStamp();
  24259. newOne->message.setTimeStamp (timeAdjustment);
  24260. int i;
  24261. for (i = list.size(); --i >= 0;)
  24262. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24263. break;
  24264. list.insert (i + 1, newOne);
  24265. }
  24266. void MidiMessageSequence::deleteEvent (const int index,
  24267. const bool deleteMatchingNoteUp)
  24268. {
  24269. if (((unsigned int) index) < (unsigned int) list.size())
  24270. {
  24271. if (deleteMatchingNoteUp)
  24272. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24273. list.remove (index);
  24274. }
  24275. }
  24276. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24277. double timeAdjustment,
  24278. double firstAllowableTime,
  24279. double endOfAllowableDestTimes)
  24280. {
  24281. firstAllowableTime -= timeAdjustment;
  24282. endOfAllowableDestTimes -= timeAdjustment;
  24283. for (int i = 0; i < other.list.size(); ++i)
  24284. {
  24285. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24286. const double t = m.getTimeStamp();
  24287. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24288. {
  24289. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24290. newOne->message.setTimeStamp (timeAdjustment + t);
  24291. list.add (newOne);
  24292. }
  24293. }
  24294. sort();
  24295. }
  24296. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24297. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24298. {
  24299. const double diff = first->message.getTimeStamp()
  24300. - second->message.getTimeStamp();
  24301. return (diff > 0) - (diff < 0);
  24302. }
  24303. void MidiMessageSequence::sort()
  24304. {
  24305. list.sort (*this, true);
  24306. }
  24307. void MidiMessageSequence::updateMatchedPairs()
  24308. {
  24309. for (int i = 0; i < list.size(); ++i)
  24310. {
  24311. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24312. if (m1.isNoteOn())
  24313. {
  24314. list.getUnchecked(i)->noteOffObject = 0;
  24315. const int note = m1.getNoteNumber();
  24316. const int chan = m1.getChannel();
  24317. const int len = list.size();
  24318. for (int j = i + 1; j < len; ++j)
  24319. {
  24320. const MidiMessage& m = list.getUnchecked(j)->message;
  24321. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24322. {
  24323. if (m.isNoteOff())
  24324. {
  24325. list.getUnchecked(i)->noteOffObject = list[j];
  24326. break;
  24327. }
  24328. else if (m.isNoteOn())
  24329. {
  24330. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24331. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24332. list.getUnchecked(i)->noteOffObject = list[j];
  24333. break;
  24334. }
  24335. }
  24336. }
  24337. }
  24338. }
  24339. }
  24340. void MidiMessageSequence::addTimeToMessages (const double delta)
  24341. {
  24342. for (int i = list.size(); --i >= 0;)
  24343. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24344. + delta);
  24345. }
  24346. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24347. MidiMessageSequence& destSequence,
  24348. const bool alsoIncludeMetaEvents) const
  24349. {
  24350. for (int i = 0; i < list.size(); ++i)
  24351. {
  24352. const MidiMessage& mm = list.getUnchecked(i)->message;
  24353. if (mm.isForChannel (channelNumberToExtract)
  24354. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24355. {
  24356. destSequence.addEvent (mm);
  24357. }
  24358. }
  24359. }
  24360. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24361. {
  24362. for (int i = 0; i < list.size(); ++i)
  24363. {
  24364. const MidiMessage& mm = list.getUnchecked(i)->message;
  24365. if (mm.isSysEx())
  24366. destSequence.addEvent (mm);
  24367. }
  24368. }
  24369. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24370. {
  24371. for (int i = list.size(); --i >= 0;)
  24372. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24373. list.remove(i);
  24374. }
  24375. void MidiMessageSequence::deleteSysExMessages()
  24376. {
  24377. for (int i = list.size(); --i >= 0;)
  24378. if (list.getUnchecked(i)->message.isSysEx())
  24379. list.remove(i);
  24380. }
  24381. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24382. const double time,
  24383. OwnedArray<MidiMessage>& dest)
  24384. {
  24385. bool doneProg = false;
  24386. bool donePitchWheel = false;
  24387. Array <int> doneControllers;
  24388. doneControllers.ensureStorageAllocated (32);
  24389. for (int i = list.size(); --i >= 0;)
  24390. {
  24391. const MidiMessage& mm = list.getUnchecked(i)->message;
  24392. if (mm.isForChannel (channelNumber)
  24393. && mm.getTimeStamp() <= time)
  24394. {
  24395. if (mm.isProgramChange())
  24396. {
  24397. if (! doneProg)
  24398. {
  24399. dest.add (new MidiMessage (mm, 0.0));
  24400. doneProg = true;
  24401. }
  24402. }
  24403. else if (mm.isController())
  24404. {
  24405. if (! doneControllers.contains (mm.getControllerNumber()))
  24406. {
  24407. dest.add (new MidiMessage (mm, 0.0));
  24408. doneControllers.add (mm.getControllerNumber());
  24409. }
  24410. }
  24411. else if (mm.isPitchWheel())
  24412. {
  24413. if (! donePitchWheel)
  24414. {
  24415. dest.add (new MidiMessage (mm, 0.0));
  24416. donePitchWheel = true;
  24417. }
  24418. }
  24419. }
  24420. }
  24421. }
  24422. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24423. : message (message_),
  24424. noteOffObject (0)
  24425. {
  24426. }
  24427. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24428. {
  24429. }
  24430. END_JUCE_NAMESPACE
  24431. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24432. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24433. BEGIN_JUCE_NAMESPACE
  24434. AudioPluginFormat::AudioPluginFormat() throw()
  24435. {
  24436. }
  24437. AudioPluginFormat::~AudioPluginFormat()
  24438. {
  24439. }
  24440. END_JUCE_NAMESPACE
  24441. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24442. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24443. BEGIN_JUCE_NAMESPACE
  24444. AudioPluginFormatManager::AudioPluginFormatManager()
  24445. {
  24446. }
  24447. AudioPluginFormatManager::~AudioPluginFormatManager()
  24448. {
  24449. clearSingletonInstance();
  24450. }
  24451. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24452. void AudioPluginFormatManager::addDefaultFormats()
  24453. {
  24454. #if JUCE_DEBUG
  24455. // you should only call this method once!
  24456. for (int i = formats.size(); --i >= 0;)
  24457. {
  24458. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24459. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24460. #endif
  24461. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24462. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24463. #endif
  24464. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24465. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24466. #endif
  24467. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24468. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24469. #endif
  24470. }
  24471. #endif
  24472. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24473. formats.add (new AudioUnitPluginFormat());
  24474. #endif
  24475. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24476. formats.add (new VSTPluginFormat());
  24477. #endif
  24478. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24479. formats.add (new DirectXPluginFormat());
  24480. #endif
  24481. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24482. formats.add (new LADSPAPluginFormat());
  24483. #endif
  24484. }
  24485. int AudioPluginFormatManager::getNumFormats()
  24486. {
  24487. return formats.size();
  24488. }
  24489. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24490. {
  24491. return formats [index];
  24492. }
  24493. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24494. {
  24495. formats.add (format);
  24496. }
  24497. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24498. String& errorMessage) const
  24499. {
  24500. AudioPluginInstance* result = 0;
  24501. for (int i = 0; i < formats.size(); ++i)
  24502. {
  24503. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24504. if (result != 0)
  24505. break;
  24506. }
  24507. if (result == 0)
  24508. {
  24509. if (! doesPluginStillExist (description))
  24510. errorMessage = TRANS ("This plug-in file no longer exists");
  24511. else
  24512. errorMessage = TRANS ("This plug-in failed to load correctly");
  24513. }
  24514. return result;
  24515. }
  24516. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24517. {
  24518. for (int i = 0; i < formats.size(); ++i)
  24519. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24520. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24521. return false;
  24522. }
  24523. END_JUCE_NAMESPACE
  24524. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24525. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24526. #define JUCE_PLUGIN_HOST 1
  24527. BEGIN_JUCE_NAMESPACE
  24528. AudioPluginInstance::AudioPluginInstance()
  24529. {
  24530. }
  24531. AudioPluginInstance::~AudioPluginInstance()
  24532. {
  24533. }
  24534. END_JUCE_NAMESPACE
  24535. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24536. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24537. BEGIN_JUCE_NAMESPACE
  24538. KnownPluginList::KnownPluginList()
  24539. {
  24540. }
  24541. KnownPluginList::~KnownPluginList()
  24542. {
  24543. }
  24544. void KnownPluginList::clear()
  24545. {
  24546. if (types.size() > 0)
  24547. {
  24548. types.clear();
  24549. sendChangeMessage (this);
  24550. }
  24551. }
  24552. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24553. {
  24554. for (int i = 0; i < types.size(); ++i)
  24555. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24556. return types.getUnchecked(i);
  24557. return 0;
  24558. }
  24559. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24560. {
  24561. for (int i = 0; i < types.size(); ++i)
  24562. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24563. return types.getUnchecked(i);
  24564. return 0;
  24565. }
  24566. bool KnownPluginList::addType (const PluginDescription& type)
  24567. {
  24568. for (int i = types.size(); --i >= 0;)
  24569. {
  24570. if (types.getUnchecked(i)->isDuplicateOf (type))
  24571. {
  24572. // strange - found a duplicate plugin with different info..
  24573. jassert (types.getUnchecked(i)->name == type.name);
  24574. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24575. *types.getUnchecked(i) = type;
  24576. return false;
  24577. }
  24578. }
  24579. types.add (new PluginDescription (type));
  24580. sendChangeMessage (this);
  24581. return true;
  24582. }
  24583. void KnownPluginList::removeType (const int index)
  24584. {
  24585. types.remove (index);
  24586. sendChangeMessage (this);
  24587. }
  24588. static const Time getPluginFileModTime (const String& fileOrIdentifier)
  24589. {
  24590. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24591. return File (fileOrIdentifier).getLastModificationTime();
  24592. return Time (0);
  24593. }
  24594. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24595. {
  24596. return t1 != t2 || t1 == Time (0);
  24597. }
  24598. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24599. {
  24600. if (getTypeForFile (fileOrIdentifier) == 0)
  24601. return false;
  24602. for (int i = types.size(); --i >= 0;)
  24603. {
  24604. const PluginDescription* const d = types.getUnchecked(i);
  24605. if (d->fileOrIdentifier == fileOrIdentifier
  24606. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24607. {
  24608. return false;
  24609. }
  24610. }
  24611. return true;
  24612. }
  24613. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24614. const bool dontRescanIfAlreadyInList,
  24615. OwnedArray <PluginDescription>& typesFound,
  24616. AudioPluginFormat& format)
  24617. {
  24618. bool addedOne = false;
  24619. if (dontRescanIfAlreadyInList
  24620. && getTypeForFile (fileOrIdentifier) != 0)
  24621. {
  24622. bool needsRescanning = false;
  24623. for (int i = types.size(); --i >= 0;)
  24624. {
  24625. const PluginDescription* const d = types.getUnchecked(i);
  24626. if (d->fileOrIdentifier == fileOrIdentifier)
  24627. {
  24628. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24629. needsRescanning = true;
  24630. else
  24631. typesFound.add (new PluginDescription (*d));
  24632. }
  24633. }
  24634. if (! needsRescanning)
  24635. return false;
  24636. }
  24637. OwnedArray <PluginDescription> found;
  24638. format.findAllTypesForFile (found, fileOrIdentifier);
  24639. for (int i = 0; i < found.size(); ++i)
  24640. {
  24641. PluginDescription* const desc = found.getUnchecked(i);
  24642. jassert (desc != 0);
  24643. if (addType (*desc))
  24644. addedOne = true;
  24645. typesFound.add (new PluginDescription (*desc));
  24646. }
  24647. return addedOne;
  24648. }
  24649. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24650. OwnedArray <PluginDescription>& typesFound)
  24651. {
  24652. for (int i = 0; i < files.size(); ++i)
  24653. {
  24654. bool loaded = false;
  24655. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24656. {
  24657. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24658. if (scanAndAddFile (files[i], true, typesFound, *format))
  24659. loaded = true;
  24660. }
  24661. if (! loaded)
  24662. {
  24663. const File f (files[i]);
  24664. if (f.isDirectory())
  24665. {
  24666. StringArray s;
  24667. {
  24668. Array<File> subFiles;
  24669. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24670. for (int j = 0; j < subFiles.size(); ++j)
  24671. s.add (subFiles.getReference(j).getFullPathName());
  24672. }
  24673. scanAndAddDragAndDroppedFiles (s, typesFound);
  24674. }
  24675. }
  24676. }
  24677. }
  24678. class PluginSorter
  24679. {
  24680. public:
  24681. KnownPluginList::SortMethod method;
  24682. PluginSorter() throw() {}
  24683. int compareElements (const PluginDescription* const first,
  24684. const PluginDescription* const second) const
  24685. {
  24686. int diff = 0;
  24687. if (method == KnownPluginList::sortByCategory)
  24688. diff = first->category.compareLexicographically (second->category);
  24689. else if (method == KnownPluginList::sortByManufacturer)
  24690. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24691. else if (method == KnownPluginList::sortByFileSystemLocation)
  24692. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24693. .upToLastOccurrenceOf ("/", false, false)
  24694. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24695. .upToLastOccurrenceOf ("/", false, false));
  24696. if (diff == 0)
  24697. diff = first->name.compareLexicographically (second->name);
  24698. return diff;
  24699. }
  24700. };
  24701. void KnownPluginList::sort (const SortMethod method)
  24702. {
  24703. if (method != defaultOrder)
  24704. {
  24705. PluginSorter sorter;
  24706. sorter.method = method;
  24707. types.sort (sorter, true);
  24708. sendChangeMessage (this);
  24709. }
  24710. }
  24711. XmlElement* KnownPluginList::createXml() const
  24712. {
  24713. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24714. for (int i = 0; i < types.size(); ++i)
  24715. e->addChildElement (types.getUnchecked(i)->createXml());
  24716. return e;
  24717. }
  24718. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24719. {
  24720. clear();
  24721. if (xml.hasTagName ("KNOWNPLUGINS"))
  24722. {
  24723. forEachXmlChildElement (xml, e)
  24724. {
  24725. PluginDescription info;
  24726. if (info.loadFromXml (*e))
  24727. addType (info);
  24728. }
  24729. }
  24730. }
  24731. const int menuIdBase = 0x324503f4;
  24732. // This is used to turn a bunch of paths into a nested menu structure.
  24733. struct PluginFilesystemTree
  24734. {
  24735. private:
  24736. String folder;
  24737. OwnedArray <PluginFilesystemTree> subFolders;
  24738. Array <PluginDescription*> plugins;
  24739. void addPlugin (PluginDescription* const pd, const String& path)
  24740. {
  24741. if (path.isEmpty())
  24742. {
  24743. plugins.add (pd);
  24744. }
  24745. else
  24746. {
  24747. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24748. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24749. for (int i = subFolders.size(); --i >= 0;)
  24750. {
  24751. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24752. {
  24753. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24754. return;
  24755. }
  24756. }
  24757. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24758. newFolder->folder = firstSubFolder;
  24759. subFolders.add (newFolder);
  24760. newFolder->addPlugin (pd, remainingPath);
  24761. }
  24762. }
  24763. // removes any deeply nested folders that don't contain any actual plugins
  24764. void optimise()
  24765. {
  24766. for (int i = subFolders.size(); --i >= 0;)
  24767. {
  24768. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24769. sub->optimise();
  24770. if (sub->plugins.size() == 0)
  24771. {
  24772. for (int j = 0; j < sub->subFolders.size(); ++j)
  24773. subFolders.add (sub->subFolders.getUnchecked(j));
  24774. sub->subFolders.clear (false);
  24775. subFolders.remove (i);
  24776. }
  24777. }
  24778. }
  24779. public:
  24780. void buildTree (const Array <PluginDescription*>& allPlugins)
  24781. {
  24782. for (int i = 0; i < allPlugins.size(); ++i)
  24783. {
  24784. String path (allPlugins.getUnchecked(i)
  24785. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24786. .upToLastOccurrenceOf ("/", false, false));
  24787. if (path.substring (1, 2) == ":")
  24788. path = path.substring (2);
  24789. addPlugin (allPlugins.getUnchecked(i), path);
  24790. }
  24791. optimise();
  24792. }
  24793. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24794. {
  24795. int i;
  24796. for (i = 0; i < subFolders.size(); ++i)
  24797. {
  24798. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24799. PopupMenu subMenu;
  24800. sub->addToMenu (subMenu, allPlugins);
  24801. #if JUCE_MAC
  24802. // avoid the special AU formatting nonsense on Mac..
  24803. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24804. #else
  24805. m.addSubMenu (sub->folder, subMenu);
  24806. #endif
  24807. }
  24808. for (i = 0; i < plugins.size(); ++i)
  24809. {
  24810. PluginDescription* const plugin = plugins.getUnchecked(i);
  24811. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24812. plugin->name, true, false);
  24813. }
  24814. }
  24815. };
  24816. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24817. {
  24818. Array <PluginDescription*> sorted;
  24819. {
  24820. PluginSorter sorter;
  24821. sorter.method = sortMethod;
  24822. for (int i = 0; i < types.size(); ++i)
  24823. sorted.addSorted (sorter, types.getUnchecked(i));
  24824. }
  24825. if (sortMethod == sortByCategory
  24826. || sortMethod == sortByManufacturer)
  24827. {
  24828. String lastSubMenuName;
  24829. PopupMenu sub;
  24830. for (int i = 0; i < sorted.size(); ++i)
  24831. {
  24832. const PluginDescription* const pd = sorted.getUnchecked(i);
  24833. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24834. : pd->manufacturerName);
  24835. if (! thisSubMenuName.containsNonWhitespaceChars())
  24836. thisSubMenuName = "Other";
  24837. if (thisSubMenuName != lastSubMenuName)
  24838. {
  24839. if (sub.getNumItems() > 0)
  24840. {
  24841. menu.addSubMenu (lastSubMenuName, sub);
  24842. sub.clear();
  24843. }
  24844. lastSubMenuName = thisSubMenuName;
  24845. }
  24846. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24847. }
  24848. if (sub.getNumItems() > 0)
  24849. menu.addSubMenu (lastSubMenuName, sub);
  24850. }
  24851. else if (sortMethod == sortByFileSystemLocation)
  24852. {
  24853. PluginFilesystemTree root;
  24854. root.buildTree (sorted);
  24855. root.addToMenu (menu, types);
  24856. }
  24857. else
  24858. {
  24859. for (int i = 0; i < sorted.size(); ++i)
  24860. {
  24861. const PluginDescription* const pd = sorted.getUnchecked(i);
  24862. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24863. }
  24864. }
  24865. }
  24866. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24867. {
  24868. const int i = menuResultCode - menuIdBase;
  24869. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24870. }
  24871. END_JUCE_NAMESPACE
  24872. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24873. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24874. BEGIN_JUCE_NAMESPACE
  24875. PluginDescription::PluginDescription()
  24876. : uid (0),
  24877. isInstrument (false),
  24878. numInputChannels (0),
  24879. numOutputChannels (0)
  24880. {
  24881. }
  24882. PluginDescription::~PluginDescription()
  24883. {
  24884. }
  24885. PluginDescription::PluginDescription (const PluginDescription& other)
  24886. : name (other.name),
  24887. pluginFormatName (other.pluginFormatName),
  24888. category (other.category),
  24889. manufacturerName (other.manufacturerName),
  24890. version (other.version),
  24891. fileOrIdentifier (other.fileOrIdentifier),
  24892. lastFileModTime (other.lastFileModTime),
  24893. uid (other.uid),
  24894. isInstrument (other.isInstrument),
  24895. numInputChannels (other.numInputChannels),
  24896. numOutputChannels (other.numOutputChannels)
  24897. {
  24898. }
  24899. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24900. {
  24901. name = other.name;
  24902. pluginFormatName = other.pluginFormatName;
  24903. category = other.category;
  24904. manufacturerName = other.manufacturerName;
  24905. version = other.version;
  24906. fileOrIdentifier = other.fileOrIdentifier;
  24907. uid = other.uid;
  24908. isInstrument = other.isInstrument;
  24909. lastFileModTime = other.lastFileModTime;
  24910. numInputChannels = other.numInputChannels;
  24911. numOutputChannels = other.numOutputChannels;
  24912. return *this;
  24913. }
  24914. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24915. {
  24916. return fileOrIdentifier == other.fileOrIdentifier
  24917. && uid == other.uid;
  24918. }
  24919. const String PluginDescription::createIdentifierString() const
  24920. {
  24921. return pluginFormatName
  24922. + "-" + name
  24923. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24924. + "-" + String::toHexString (uid);
  24925. }
  24926. XmlElement* PluginDescription::createXml() const
  24927. {
  24928. XmlElement* const e = new XmlElement ("PLUGIN");
  24929. e->setAttribute ("name", name);
  24930. e->setAttribute ("format", pluginFormatName);
  24931. e->setAttribute ("category", category);
  24932. e->setAttribute ("manufacturer", manufacturerName);
  24933. e->setAttribute ("version", version);
  24934. e->setAttribute ("file", fileOrIdentifier);
  24935. e->setAttribute ("uid", String::toHexString (uid));
  24936. e->setAttribute ("isInstrument", isInstrument);
  24937. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24938. e->setAttribute ("numInputs", numInputChannels);
  24939. e->setAttribute ("numOutputs", numOutputChannels);
  24940. return e;
  24941. }
  24942. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24943. {
  24944. if (xml.hasTagName ("PLUGIN"))
  24945. {
  24946. name = xml.getStringAttribute ("name");
  24947. pluginFormatName = xml.getStringAttribute ("format");
  24948. category = xml.getStringAttribute ("category");
  24949. manufacturerName = xml.getStringAttribute ("manufacturer");
  24950. version = xml.getStringAttribute ("version");
  24951. fileOrIdentifier = xml.getStringAttribute ("file");
  24952. uid = xml.getStringAttribute ("uid").getHexValue32();
  24953. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24954. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24955. numInputChannels = xml.getIntAttribute ("numInputs");
  24956. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24957. return true;
  24958. }
  24959. return false;
  24960. }
  24961. END_JUCE_NAMESPACE
  24962. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24963. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24964. BEGIN_JUCE_NAMESPACE
  24965. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24966. AudioPluginFormat& formatToLookFor,
  24967. FileSearchPath directoriesToSearch,
  24968. const bool recursive,
  24969. const File& deadMansPedalFile_)
  24970. : list (listToAddTo),
  24971. format (formatToLookFor),
  24972. deadMansPedalFile (deadMansPedalFile_),
  24973. nextIndex (0),
  24974. progress (0)
  24975. {
  24976. directoriesToSearch.removeRedundantPaths();
  24977. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24978. // If any plugins have crashed recently when being loaded, move them to the
  24979. // end of the list to give the others a chance to load correctly..
  24980. const StringArray crashedPlugins (getDeadMansPedalFile());
  24981. for (int i = 0; i < crashedPlugins.size(); ++i)
  24982. {
  24983. const String f = crashedPlugins[i];
  24984. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24985. if (f == filesOrIdentifiersToScan[j])
  24986. filesOrIdentifiersToScan.move (j, -1);
  24987. }
  24988. }
  24989. PluginDirectoryScanner::~PluginDirectoryScanner()
  24990. {
  24991. }
  24992. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24993. {
  24994. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24995. }
  24996. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24997. {
  24998. String file (filesOrIdentifiersToScan [nextIndex]);
  24999. if (file.isNotEmpty())
  25000. {
  25001. if (! list.isListingUpToDate (file))
  25002. {
  25003. OwnedArray <PluginDescription> typesFound;
  25004. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  25005. StringArray crashedPlugins (getDeadMansPedalFile());
  25006. crashedPlugins.removeString (file);
  25007. crashedPlugins.add (file);
  25008. setDeadMansPedalFile (crashedPlugins);
  25009. list.scanAndAddFile (file,
  25010. dontRescanIfAlreadyInList,
  25011. typesFound,
  25012. format);
  25013. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  25014. crashedPlugins.removeString (file);
  25015. setDeadMansPedalFile (crashedPlugins);
  25016. if (typesFound.size() == 0)
  25017. failedFiles.add (file);
  25018. }
  25019. ++nextIndex;
  25020. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  25021. }
  25022. return nextIndex < filesOrIdentifiersToScan.size();
  25023. }
  25024. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  25025. {
  25026. StringArray lines;
  25027. if (deadMansPedalFile != File::nonexistent)
  25028. {
  25029. lines.addLines (deadMansPedalFile.loadFileAsString());
  25030. lines.removeEmptyStrings();
  25031. }
  25032. return lines;
  25033. }
  25034. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  25035. {
  25036. if (deadMansPedalFile != File::nonexistent)
  25037. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  25038. }
  25039. END_JUCE_NAMESPACE
  25040. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  25041. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  25042. BEGIN_JUCE_NAMESPACE
  25043. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  25044. const File& deadMansPedalFile_,
  25045. PropertiesFile* const propertiesToUse_)
  25046. : list (listToEdit),
  25047. deadMansPedalFile (deadMansPedalFile_),
  25048. propertiesToUse (propertiesToUse_)
  25049. {
  25050. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  25051. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  25052. optionsButton->addButtonListener (this);
  25053. optionsButton->setTriggeredOnMouseDown (true);
  25054. setSize (400, 600);
  25055. list.addChangeListener (this);
  25056. changeListenerCallback (0);
  25057. }
  25058. PluginListComponent::~PluginListComponent()
  25059. {
  25060. list.removeChangeListener (this);
  25061. deleteAllChildren();
  25062. }
  25063. void PluginListComponent::resized()
  25064. {
  25065. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  25066. optionsButton->changeWidthToFitText (24);
  25067. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  25068. }
  25069. void PluginListComponent::changeListenerCallback (void*)
  25070. {
  25071. listBox->updateContent();
  25072. listBox->repaint();
  25073. }
  25074. int PluginListComponent::getNumRows()
  25075. {
  25076. return list.getNumTypes();
  25077. }
  25078. void PluginListComponent::paintListBoxItem (int row,
  25079. Graphics& g,
  25080. int width, int height,
  25081. bool rowIsSelected)
  25082. {
  25083. if (rowIsSelected)
  25084. g.fillAll (findColour (TextEditor::highlightColourId));
  25085. const PluginDescription* const pd = list.getType (row);
  25086. if (pd != 0)
  25087. {
  25088. GlyphArrangement ga;
  25089. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  25090. g.setColour (Colours::black);
  25091. ga.draw (g);
  25092. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  25093. String desc;
  25094. desc << pd->pluginFormatName
  25095. << (pd->isInstrument ? " instrument" : " effect")
  25096. << " - "
  25097. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  25098. << " / "
  25099. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  25100. if (pd->manufacturerName.isNotEmpty())
  25101. desc << " - " << pd->manufacturerName;
  25102. if (pd->version.isNotEmpty())
  25103. desc << " - " << pd->version;
  25104. if (pd->category.isNotEmpty())
  25105. desc << " - category: '" << pd->category << '\'';
  25106. g.setColour (Colours::grey);
  25107. ga.clear();
  25108. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  25109. ga.draw (g);
  25110. }
  25111. }
  25112. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  25113. {
  25114. list.removeType (lastRowSelected);
  25115. }
  25116. void PluginListComponent::buttonClicked (Button* b)
  25117. {
  25118. if (optionsButton == b)
  25119. {
  25120. PopupMenu menu;
  25121. menu.addItem (1, TRANS("Clear list"));
  25122. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  25123. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  25124. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  25125. menu.addSeparator();
  25126. menu.addItem (2, TRANS("Sort alphabetically"));
  25127. menu.addItem (3, TRANS("Sort by category"));
  25128. menu.addItem (4, TRANS("Sort by manufacturer"));
  25129. menu.addSeparator();
  25130. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  25131. {
  25132. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  25133. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  25134. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  25135. }
  25136. const int r = menu.showAt (optionsButton);
  25137. if (r == 1)
  25138. {
  25139. list.clear();
  25140. }
  25141. else if (r == 2)
  25142. {
  25143. list.sort (KnownPluginList::sortAlphabetically);
  25144. }
  25145. else if (r == 3)
  25146. {
  25147. list.sort (KnownPluginList::sortByCategory);
  25148. }
  25149. else if (r == 4)
  25150. {
  25151. list.sort (KnownPluginList::sortByManufacturer);
  25152. }
  25153. else if (r == 5)
  25154. {
  25155. const SparseSet <int> selected (listBox->getSelectedRows());
  25156. for (int i = list.getNumTypes(); --i >= 0;)
  25157. if (selected.contains (i))
  25158. list.removeType (i);
  25159. }
  25160. else if (r == 6)
  25161. {
  25162. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  25163. if (desc != 0)
  25164. {
  25165. if (File (desc->fileOrIdentifier).existsAsFile())
  25166. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  25167. }
  25168. }
  25169. else if (r == 7)
  25170. {
  25171. for (int i = list.getNumTypes(); --i >= 0;)
  25172. {
  25173. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  25174. {
  25175. list.removeType (i);
  25176. }
  25177. }
  25178. }
  25179. else if (r != 0)
  25180. {
  25181. typeToScan = r - 10;
  25182. startTimer (1);
  25183. }
  25184. }
  25185. }
  25186. void PluginListComponent::timerCallback()
  25187. {
  25188. stopTimer();
  25189. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  25190. }
  25191. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25192. {
  25193. return true;
  25194. }
  25195. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25196. {
  25197. OwnedArray <PluginDescription> typesFound;
  25198. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25199. }
  25200. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25201. {
  25202. if (format == 0)
  25203. return;
  25204. FileSearchPath path (format->getDefaultLocationsToSearch());
  25205. if (propertiesToUse != 0)
  25206. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25207. {
  25208. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25209. FileSearchPathListComponent pathList;
  25210. pathList.setSize (500, 300);
  25211. pathList.setPath (path);
  25212. aw.addCustomComponent (&pathList);
  25213. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25214. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25215. if (aw.runModalLoop() == 0)
  25216. return;
  25217. path = pathList.getPath();
  25218. }
  25219. if (propertiesToUse != 0)
  25220. {
  25221. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25222. propertiesToUse->saveIfNeeded();
  25223. }
  25224. double progress = 0.0;
  25225. AlertWindow aw (TRANS("Scanning for plugins..."),
  25226. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25227. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25228. aw.addProgressBarComponent (progress);
  25229. aw.enterModalState();
  25230. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25231. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25232. for (;;)
  25233. {
  25234. aw.setMessage (TRANS("Testing:\n\n")
  25235. + scanner.getNextPluginFileThatWillBeScanned());
  25236. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25237. if (! scanner.scanNextFile (true))
  25238. break;
  25239. if (! aw.isCurrentlyModal())
  25240. break;
  25241. progress = scanner.getProgress();
  25242. }
  25243. if (scanner.getFailedFiles().size() > 0)
  25244. {
  25245. StringArray shortNames;
  25246. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25247. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25248. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25249. TRANS("Scan complete"),
  25250. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25251. + shortNames.joinIntoString (", "));
  25252. }
  25253. }
  25254. END_JUCE_NAMESPACE
  25255. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25256. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25257. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25258. #include <AudioUnit/AudioUnit.h>
  25259. #include <AudioUnit/AUCocoaUIView.h>
  25260. #include <CoreAudioKit/AUGenericView.h>
  25261. #if JUCE_SUPPORT_CARBON
  25262. #include <AudioToolbox/AudioUnitUtilities.h>
  25263. #include <AudioUnit/AudioUnitCarbonView.h>
  25264. #endif
  25265. BEGIN_JUCE_NAMESPACE
  25266. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25267. #endif
  25268. #if JUCE_MAC
  25269. // Change this to disable logging of various activities
  25270. #ifndef AU_LOGGING
  25271. #define AU_LOGGING 1
  25272. #endif
  25273. #if AU_LOGGING
  25274. #define log(a) Logger::writeToLog(a);
  25275. #else
  25276. #define log(a)
  25277. #endif
  25278. namespace AudioUnitFormatHelpers
  25279. {
  25280. static int insideCallback = 0;
  25281. static const String osTypeToString (OSType type)
  25282. {
  25283. char s[4];
  25284. s[0] = (char) (((uint32) type) >> 24);
  25285. s[1] = (char) (((uint32) type) >> 16);
  25286. s[2] = (char) (((uint32) type) >> 8);
  25287. s[3] = (char) ((uint32) type);
  25288. return String (s, 4);
  25289. }
  25290. static OSType stringToOSType (const String& s1)
  25291. {
  25292. const String s (s1 + " ");
  25293. return (((OSType) (unsigned char) s[0]) << 24)
  25294. | (((OSType) (unsigned char) s[1]) << 16)
  25295. | (((OSType) (unsigned char) s[2]) << 8)
  25296. | ((OSType) (unsigned char) s[3]);
  25297. }
  25298. static const char* auIdentifierPrefix = "AudioUnit:";
  25299. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25300. {
  25301. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25302. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25303. String s (auIdentifierPrefix);
  25304. if (desc.componentType == kAudioUnitType_MusicDevice)
  25305. s << "Synths/";
  25306. else if (desc.componentType == kAudioUnitType_MusicEffect
  25307. || desc.componentType == kAudioUnitType_Effect)
  25308. s << "Effects/";
  25309. else if (desc.componentType == kAudioUnitType_Generator)
  25310. s << "Generators/";
  25311. else if (desc.componentType == kAudioUnitType_Panner)
  25312. s << "Panners/";
  25313. s << osTypeToString (desc.componentType) << ","
  25314. << osTypeToString (desc.componentSubType) << ","
  25315. << osTypeToString (desc.componentManufacturer);
  25316. return s;
  25317. }
  25318. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25319. {
  25320. Handle componentNameHandle = NewHandle (sizeof (void*));
  25321. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25322. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25323. {
  25324. ComponentDescription desc;
  25325. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25326. {
  25327. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25328. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25329. if (nameString != 0 && nameString[0] != 0)
  25330. {
  25331. const String all ((const char*) nameString + 1, nameString[0]);
  25332. DBG ("name: "+ all);
  25333. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25334. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25335. }
  25336. if (infoString != 0 && infoString[0] != 0)
  25337. {
  25338. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25339. }
  25340. if (name.isEmpty())
  25341. name = "<Unknown>";
  25342. }
  25343. DisposeHandle (componentNameHandle);
  25344. DisposeHandle (componentInfoHandle);
  25345. }
  25346. }
  25347. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25348. String& name, String& version, String& manufacturer)
  25349. {
  25350. zerostruct (desc);
  25351. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25352. {
  25353. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25354. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25355. StringArray tokens;
  25356. tokens.addTokens (s, ",", String::empty);
  25357. tokens.trim();
  25358. tokens.removeEmptyStrings();
  25359. if (tokens.size() == 3)
  25360. {
  25361. desc.componentType = stringToOSType (tokens[0]);
  25362. desc.componentSubType = stringToOSType (tokens[1]);
  25363. desc.componentManufacturer = stringToOSType (tokens[2]);
  25364. ComponentRecord* comp = FindNextComponent (0, &desc);
  25365. if (comp != 0)
  25366. {
  25367. getAUDetails (comp, name, manufacturer);
  25368. return true;
  25369. }
  25370. }
  25371. }
  25372. return false;
  25373. }
  25374. }
  25375. class AudioUnitPluginWindowCarbon;
  25376. class AudioUnitPluginWindowCocoa;
  25377. class AudioUnitPluginInstance : public AudioPluginInstance
  25378. {
  25379. public:
  25380. ~AudioUnitPluginInstance();
  25381. // AudioPluginInstance methods:
  25382. void fillInPluginDescription (PluginDescription& desc) const
  25383. {
  25384. desc.name = pluginName;
  25385. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25386. desc.uid = ((int) componentDesc.componentType)
  25387. ^ ((int) componentDesc.componentSubType)
  25388. ^ ((int) componentDesc.componentManufacturer);
  25389. desc.lastFileModTime = 0;
  25390. desc.pluginFormatName = "AudioUnit";
  25391. desc.category = getCategory();
  25392. desc.manufacturerName = manufacturer;
  25393. desc.version = version;
  25394. desc.numInputChannels = getNumInputChannels();
  25395. desc.numOutputChannels = getNumOutputChannels();
  25396. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25397. }
  25398. const String getName() const { return pluginName; }
  25399. bool acceptsMidi() const { return wantsMidiMessages; }
  25400. bool producesMidi() const { return false; }
  25401. // AudioProcessor methods:
  25402. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25403. void releaseResources();
  25404. void processBlock (AudioSampleBuffer& buffer,
  25405. MidiBuffer& midiMessages);
  25406. AudioProcessorEditor* createEditor();
  25407. const String getInputChannelName (int index) const;
  25408. bool isInputChannelStereoPair (int index) const;
  25409. const String getOutputChannelName (int index) const;
  25410. bool isOutputChannelStereoPair (int index) const;
  25411. int getNumParameters();
  25412. float getParameter (int index);
  25413. void setParameter (int index, float newValue);
  25414. const String getParameterName (int index);
  25415. const String getParameterText (int index);
  25416. bool isParameterAutomatable (int index) const;
  25417. int getNumPrograms();
  25418. int getCurrentProgram();
  25419. void setCurrentProgram (int index);
  25420. const String getProgramName (int index);
  25421. void changeProgramName (int index, const String& newName);
  25422. void getStateInformation (MemoryBlock& destData);
  25423. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25424. void setStateInformation (const void* data, int sizeInBytes);
  25425. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25426. juce_UseDebuggingNewOperator
  25427. private:
  25428. friend class AudioUnitPluginWindowCarbon;
  25429. friend class AudioUnitPluginWindowCocoa;
  25430. friend class AudioUnitPluginFormat;
  25431. ComponentDescription componentDesc;
  25432. String pluginName, manufacturer, version;
  25433. String fileOrIdentifier;
  25434. CriticalSection lock;
  25435. bool initialised, wantsMidiMessages, wasPlaying;
  25436. HeapBlock <AudioBufferList> outputBufferList;
  25437. AudioTimeStamp timeStamp;
  25438. AudioSampleBuffer* currentBuffer;
  25439. AudioUnit audioUnit;
  25440. Array <int> parameterIds;
  25441. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25442. void initialise();
  25443. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25444. const AudioTimeStamp* inTimeStamp,
  25445. UInt32 inBusNumber,
  25446. UInt32 inNumberFrames,
  25447. AudioBufferList* ioData) const;
  25448. static OSStatus renderGetInputCallback (void* inRefCon,
  25449. AudioUnitRenderActionFlags* ioActionFlags,
  25450. const AudioTimeStamp* inTimeStamp,
  25451. UInt32 inBusNumber,
  25452. UInt32 inNumberFrames,
  25453. AudioBufferList* ioData)
  25454. {
  25455. return ((AudioUnitPluginInstance*) inRefCon)
  25456. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25457. }
  25458. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25459. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25460. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25461. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25462. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25463. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25464. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25465. {
  25466. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25467. }
  25468. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25469. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25470. Float64* outCurrentMeasureDownBeat)
  25471. {
  25472. return ((AudioUnitPluginInstance*) inHostUserData)
  25473. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25474. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25475. }
  25476. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25477. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25478. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25479. {
  25480. return ((AudioUnitPluginInstance*) inHostUserData)
  25481. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25482. outCurrentSampleInTimeLine, outIsCycling,
  25483. outCycleStartBeat, outCycleEndBeat);
  25484. }
  25485. void getNumChannels (int& numIns, int& numOuts)
  25486. {
  25487. numIns = 0;
  25488. numOuts = 0;
  25489. AUChannelInfo supportedChannels [128];
  25490. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25491. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25492. 0, supportedChannels, &supportedChannelsSize) == noErr
  25493. && supportedChannelsSize > 0)
  25494. {
  25495. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25496. {
  25497. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  25498. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  25499. }
  25500. }
  25501. else
  25502. {
  25503. // (this really means the plugin will take any number of ins/outs as long
  25504. // as they are the same)
  25505. numIns = numOuts = 2;
  25506. }
  25507. }
  25508. const String getCategory() const;
  25509. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25510. };
  25511. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25512. : fileOrIdentifier (fileOrIdentifier),
  25513. initialised (false),
  25514. wantsMidiMessages (false),
  25515. audioUnit (0),
  25516. currentBuffer (0)
  25517. {
  25518. using namespace AudioUnitFormatHelpers;
  25519. try
  25520. {
  25521. ++insideCallback;
  25522. log ("Opening AU: " + fileOrIdentifier);
  25523. if (getComponentDescFromFile (fileOrIdentifier))
  25524. {
  25525. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25526. if (comp != 0)
  25527. {
  25528. audioUnit = (AudioUnit) OpenComponent (comp);
  25529. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25530. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25531. }
  25532. }
  25533. --insideCallback;
  25534. }
  25535. catch (...)
  25536. {
  25537. --insideCallback;
  25538. }
  25539. }
  25540. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25541. {
  25542. const ScopedLock sl (lock);
  25543. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25544. if (audioUnit != 0)
  25545. {
  25546. AudioUnitUninitialize (audioUnit);
  25547. CloseComponent (audioUnit);
  25548. audioUnit = 0;
  25549. }
  25550. }
  25551. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25552. {
  25553. zerostruct (componentDesc);
  25554. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25555. return true;
  25556. const File file (fileOrIdentifier);
  25557. if (! file.hasFileExtension (".component"))
  25558. return false;
  25559. const char* const utf8 = fileOrIdentifier.toUTF8();
  25560. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25561. strlen (utf8), file.isDirectory());
  25562. if (url != 0)
  25563. {
  25564. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25565. CFRelease (url);
  25566. if (bundleRef != 0)
  25567. {
  25568. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25569. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25570. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25571. if (pluginName.isEmpty())
  25572. pluginName = file.getFileNameWithoutExtension();
  25573. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25574. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25575. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25576. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25577. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25578. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25579. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25580. UseResFile (resFileId);
  25581. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25582. {
  25583. Handle h = Get1IndResource ('thng', i);
  25584. if (h != 0)
  25585. {
  25586. HLock (h);
  25587. const uint32* const types = (const uint32*) *h;
  25588. if (types[0] == kAudioUnitType_MusicDevice
  25589. || types[0] == kAudioUnitType_MusicEffect
  25590. || types[0] == kAudioUnitType_Effect
  25591. || types[0] == kAudioUnitType_Generator
  25592. || types[0] == kAudioUnitType_Panner)
  25593. {
  25594. componentDesc.componentType = types[0];
  25595. componentDesc.componentSubType = types[1];
  25596. componentDesc.componentManufacturer = types[2];
  25597. break;
  25598. }
  25599. HUnlock (h);
  25600. ReleaseResource (h);
  25601. }
  25602. }
  25603. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25604. CFRelease (bundleRef);
  25605. }
  25606. }
  25607. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25608. }
  25609. void AudioUnitPluginInstance::initialise()
  25610. {
  25611. if (initialised || audioUnit == 0)
  25612. return;
  25613. log ("Initialising AU: " + pluginName);
  25614. parameterIds.clear();
  25615. {
  25616. UInt32 paramListSize = 0;
  25617. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25618. 0, 0, &paramListSize);
  25619. if (paramListSize > 0)
  25620. {
  25621. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25622. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25623. 0, &parameterIds.getReference(0), &paramListSize);
  25624. }
  25625. }
  25626. {
  25627. AURenderCallbackStruct info;
  25628. zerostruct (info);
  25629. info.inputProcRefCon = this;
  25630. info.inputProc = renderGetInputCallback;
  25631. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25632. 0, &info, sizeof (info));
  25633. }
  25634. {
  25635. HostCallbackInfo info;
  25636. zerostruct (info);
  25637. info.hostUserData = this;
  25638. info.beatAndTempoProc = getBeatAndTempoCallback;
  25639. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25640. info.transportStateProc = getTransportStateCallback;
  25641. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25642. 0, &info, sizeof (info));
  25643. }
  25644. int numIns, numOuts;
  25645. getNumChannels (numIns, numOuts);
  25646. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25647. initialised = AudioUnitInitialize (audioUnit) == noErr;
  25648. setLatencySamples (0);
  25649. }
  25650. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25651. int samplesPerBlockExpected)
  25652. {
  25653. if (audioUnit != 0)
  25654. {
  25655. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25656. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25657. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25658. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25659. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25660. {
  25661. if (initialised)
  25662. {
  25663. AudioUnitUninitialize (audioUnit);
  25664. initialised = false;
  25665. }
  25666. Float64 sr = sampleRate_;
  25667. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25668. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25669. }
  25670. }
  25671. initialise();
  25672. if (initialised)
  25673. {
  25674. int numIns, numOuts;
  25675. getNumChannels (numIns, numOuts);
  25676. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25677. Float64 latencySecs = 0.0;
  25678. UInt32 latencySize = sizeof (latencySecs);
  25679. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25680. 0, &latencySecs, &latencySize);
  25681. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25682. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25683. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25684. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25685. AudioStreamBasicDescription stream;
  25686. zerostruct (stream);
  25687. stream.mSampleRate = sampleRate_;
  25688. stream.mFormatID = kAudioFormatLinearPCM;
  25689. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25690. stream.mFramesPerPacket = 1;
  25691. stream.mBytesPerPacket = 4;
  25692. stream.mBytesPerFrame = 4;
  25693. stream.mBitsPerChannel = 32;
  25694. stream.mChannelsPerFrame = numIns;
  25695. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25696. 0, &stream, sizeof (stream));
  25697. stream.mChannelsPerFrame = numOuts;
  25698. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25699. 0, &stream, sizeof (stream));
  25700. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25701. outputBufferList->mNumberBuffers = numOuts;
  25702. for (int i = numOuts; --i >= 0;)
  25703. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25704. zerostruct (timeStamp);
  25705. timeStamp.mSampleTime = 0;
  25706. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25707. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25708. currentBuffer = 0;
  25709. wasPlaying = false;
  25710. }
  25711. }
  25712. void AudioUnitPluginInstance::releaseResources()
  25713. {
  25714. if (initialised)
  25715. {
  25716. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25717. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25718. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25719. outputBufferList.free();
  25720. currentBuffer = 0;
  25721. }
  25722. }
  25723. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25724. const AudioTimeStamp* inTimeStamp,
  25725. UInt32 inBusNumber,
  25726. UInt32 inNumberFrames,
  25727. AudioBufferList* ioData) const
  25728. {
  25729. if (inBusNumber == 0
  25730. && currentBuffer != 0)
  25731. {
  25732. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25733. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25734. {
  25735. if (i < currentBuffer->getNumChannels())
  25736. {
  25737. memcpy (ioData->mBuffers[i].mData,
  25738. currentBuffer->getSampleData (i, 0),
  25739. sizeof (float) * inNumberFrames);
  25740. }
  25741. else
  25742. {
  25743. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25744. }
  25745. }
  25746. }
  25747. return noErr;
  25748. }
  25749. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25750. MidiBuffer& midiMessages)
  25751. {
  25752. const int numSamples = buffer.getNumSamples();
  25753. if (initialised)
  25754. {
  25755. AudioUnitRenderActionFlags flags = 0;
  25756. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25757. for (int i = getNumOutputChannels(); --i >= 0;)
  25758. {
  25759. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25760. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25761. }
  25762. currentBuffer = &buffer;
  25763. if (wantsMidiMessages)
  25764. {
  25765. const uint8* midiEventData;
  25766. int midiEventSize, midiEventPosition;
  25767. MidiBuffer::Iterator i (midiMessages);
  25768. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25769. {
  25770. if (midiEventSize <= 3)
  25771. MusicDeviceMIDIEvent (audioUnit,
  25772. midiEventData[0], midiEventData[1], midiEventData[2],
  25773. midiEventPosition);
  25774. else
  25775. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25776. }
  25777. midiMessages.clear();
  25778. }
  25779. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25780. 0, numSamples, outputBufferList);
  25781. timeStamp.mSampleTime += numSamples;
  25782. }
  25783. else
  25784. {
  25785. // Not initialised, so just bypass..
  25786. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25787. buffer.clear (i, 0, buffer.getNumSamples());
  25788. }
  25789. }
  25790. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25791. {
  25792. AudioPlayHead* const ph = getPlayHead();
  25793. AudioPlayHead::CurrentPositionInfo result;
  25794. if (ph != 0 && ph->getCurrentPosition (result))
  25795. {
  25796. if (outCurrentBeat != 0)
  25797. *outCurrentBeat = result.ppqPosition;
  25798. if (outCurrentTempo != 0)
  25799. *outCurrentTempo = result.bpm;
  25800. }
  25801. else
  25802. {
  25803. if (outCurrentBeat != 0)
  25804. *outCurrentBeat = 0;
  25805. if (outCurrentTempo != 0)
  25806. *outCurrentTempo = 120.0;
  25807. }
  25808. return noErr;
  25809. }
  25810. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25811. Float32* outTimeSig_Numerator,
  25812. UInt32* outTimeSig_Denominator,
  25813. Float64* outCurrentMeasureDownBeat) const
  25814. {
  25815. AudioPlayHead* const ph = getPlayHead();
  25816. AudioPlayHead::CurrentPositionInfo result;
  25817. if (ph != 0 && ph->getCurrentPosition (result))
  25818. {
  25819. if (outTimeSig_Numerator != 0)
  25820. *outTimeSig_Numerator = result.timeSigNumerator;
  25821. if (outTimeSig_Denominator != 0)
  25822. *outTimeSig_Denominator = result.timeSigDenominator;
  25823. if (outDeltaSampleOffsetToNextBeat != 0)
  25824. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25825. if (outCurrentMeasureDownBeat != 0)
  25826. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25827. }
  25828. else
  25829. {
  25830. if (outDeltaSampleOffsetToNextBeat != 0)
  25831. *outDeltaSampleOffsetToNextBeat = 0;
  25832. if (outTimeSig_Numerator != 0)
  25833. *outTimeSig_Numerator = 4;
  25834. if (outTimeSig_Denominator != 0)
  25835. *outTimeSig_Denominator = 4;
  25836. if (outCurrentMeasureDownBeat != 0)
  25837. *outCurrentMeasureDownBeat = 0;
  25838. }
  25839. return noErr;
  25840. }
  25841. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25842. Boolean* outTransportStateChanged,
  25843. Float64* outCurrentSampleInTimeLine,
  25844. Boolean* outIsCycling,
  25845. Float64* outCycleStartBeat,
  25846. Float64* outCycleEndBeat)
  25847. {
  25848. AudioPlayHead* const ph = getPlayHead();
  25849. AudioPlayHead::CurrentPositionInfo result;
  25850. if (ph != 0 && ph->getCurrentPosition (result))
  25851. {
  25852. if (outIsPlaying != 0)
  25853. *outIsPlaying = result.isPlaying;
  25854. if (outTransportStateChanged != 0)
  25855. {
  25856. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25857. wasPlaying = result.isPlaying;
  25858. }
  25859. if (outCurrentSampleInTimeLine != 0)
  25860. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25861. if (outIsCycling != 0)
  25862. *outIsCycling = false;
  25863. if (outCycleStartBeat != 0)
  25864. *outCycleStartBeat = 0;
  25865. if (outCycleEndBeat != 0)
  25866. *outCycleEndBeat = 0;
  25867. }
  25868. else
  25869. {
  25870. if (outIsPlaying != 0)
  25871. *outIsPlaying = false;
  25872. if (outTransportStateChanged != 0)
  25873. *outTransportStateChanged = false;
  25874. if (outCurrentSampleInTimeLine != 0)
  25875. *outCurrentSampleInTimeLine = 0;
  25876. if (outIsCycling != 0)
  25877. *outIsCycling = false;
  25878. if (outCycleStartBeat != 0)
  25879. *outCycleStartBeat = 0;
  25880. if (outCycleEndBeat != 0)
  25881. *outCycleEndBeat = 0;
  25882. }
  25883. return noErr;
  25884. }
  25885. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  25886. {
  25887. public:
  25888. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25889. : AudioProcessorEditor (&plugin_),
  25890. plugin (plugin_)
  25891. {
  25892. addAndMakeVisible (&wrapper);
  25893. setOpaque (true);
  25894. setVisible (true);
  25895. setSize (100, 100);
  25896. createView (createGenericViewIfNeeded);
  25897. }
  25898. ~AudioUnitPluginWindowCocoa()
  25899. {
  25900. const bool wasValid = isValid();
  25901. wrapper.setView (0);
  25902. if (wasValid)
  25903. plugin.editorBeingDeleted (this);
  25904. }
  25905. bool isValid() const { return wrapper.getView() != 0; }
  25906. void paint (Graphics& g)
  25907. {
  25908. g.fillAll (Colours::white);
  25909. }
  25910. void resized()
  25911. {
  25912. wrapper.setSize (getWidth(), getHeight());
  25913. }
  25914. private:
  25915. AudioUnitPluginInstance& plugin;
  25916. NSViewComponent wrapper;
  25917. bool createView (const bool createGenericViewIfNeeded)
  25918. {
  25919. NSView* pluginView = 0;
  25920. UInt32 dataSize = 0;
  25921. Boolean isWritable = false;
  25922. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25923. 0, &dataSize, &isWritable) == noErr
  25924. && dataSize != 0
  25925. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25926. 0, &dataSize, &isWritable) == noErr)
  25927. {
  25928. HeapBlock <AudioUnitCocoaViewInfo> info;
  25929. info.calloc (dataSize, 1);
  25930. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25931. 0, info, &dataSize) == noErr)
  25932. {
  25933. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25934. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25935. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25936. Class viewClass = [viewBundle classNamed: viewClassName];
  25937. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25938. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25939. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25940. {
  25941. id factory = [[[viewClass alloc] init] autorelease];
  25942. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25943. withSize: NSMakeSize (getWidth(), getHeight())];
  25944. }
  25945. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25946. {
  25947. CFRelease (info->mCocoaAUViewClass[i]);
  25948. CFRelease (info->mCocoaAUViewBundleLocation);
  25949. }
  25950. }
  25951. }
  25952. if (createGenericViewIfNeeded && (pluginView == 0))
  25953. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25954. wrapper.setView (pluginView);
  25955. if (pluginView != 0)
  25956. setSize ([pluginView frame].size.width,
  25957. [pluginView frame].size.height);
  25958. return pluginView != 0;
  25959. }
  25960. };
  25961. #if JUCE_SUPPORT_CARBON
  25962. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25963. {
  25964. public:
  25965. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25966. : AudioProcessorEditor (&plugin_),
  25967. plugin (plugin_),
  25968. viewComponent (0)
  25969. {
  25970. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25971. setOpaque (true);
  25972. setVisible (true);
  25973. setSize (400, 300);
  25974. ComponentDescription viewList [16];
  25975. UInt32 viewListSize = sizeof (viewList);
  25976. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25977. 0, &viewList, &viewListSize);
  25978. componentRecord = FindNextComponent (0, &viewList[0]);
  25979. }
  25980. ~AudioUnitPluginWindowCarbon()
  25981. {
  25982. innerWrapper = 0;
  25983. if (isValid())
  25984. plugin.editorBeingDeleted (this);
  25985. }
  25986. bool isValid() const throw() { return componentRecord != 0; }
  25987. void paint (Graphics& g)
  25988. {
  25989. g.fillAll (Colours::black);
  25990. }
  25991. void resized()
  25992. {
  25993. innerWrapper->setSize (getWidth(), getHeight());
  25994. }
  25995. bool keyStateChanged (bool)
  25996. {
  25997. return false;
  25998. }
  25999. bool keyPressed (const KeyPress&)
  26000. {
  26001. return false;
  26002. }
  26003. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  26004. AudioUnitCarbonView getViewComponent()
  26005. {
  26006. if (viewComponent == 0 && componentRecord != 0)
  26007. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  26008. return viewComponent;
  26009. }
  26010. void closeViewComponent()
  26011. {
  26012. if (viewComponent != 0)
  26013. {
  26014. log ("Closing AU GUI: " + plugin.getName());
  26015. CloseComponent (viewComponent);
  26016. viewComponent = 0;
  26017. }
  26018. }
  26019. juce_UseDebuggingNewOperator
  26020. private:
  26021. AudioUnitPluginInstance& plugin;
  26022. ComponentRecord* componentRecord;
  26023. AudioUnitCarbonView viewComponent;
  26024. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26025. {
  26026. public:
  26027. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  26028. : owner (owner_)
  26029. {
  26030. }
  26031. ~InnerWrapperComponent()
  26032. {
  26033. deleteWindow();
  26034. }
  26035. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26036. {
  26037. log ("Opening AU GUI: " + owner->plugin.getName());
  26038. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  26039. if (viewComponent == 0)
  26040. return 0;
  26041. Float32Point pos = { 0, 0 };
  26042. Float32Point size = { 250, 200 };
  26043. HIViewRef pluginView = 0;
  26044. AudioUnitCarbonViewCreate (viewComponent,
  26045. owner->getAudioUnit(),
  26046. windowRef,
  26047. rootView,
  26048. &pos,
  26049. &size,
  26050. (ControlRef*) &pluginView);
  26051. return pluginView;
  26052. }
  26053. void removeView (HIViewRef)
  26054. {
  26055. owner->closeViewComponent();
  26056. }
  26057. private:
  26058. AudioUnitPluginWindowCarbon* const owner;
  26059. };
  26060. friend class InnerWrapperComponent;
  26061. ScopedPointer<InnerWrapperComponent> innerWrapper;
  26062. };
  26063. #endif
  26064. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  26065. {
  26066. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  26067. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26068. w = 0;
  26069. #if JUCE_SUPPORT_CARBON
  26070. if (w == 0)
  26071. {
  26072. w = new AudioUnitPluginWindowCarbon (*this);
  26073. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26074. w = 0;
  26075. }
  26076. #endif
  26077. if (w == 0)
  26078. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  26079. return w.release();
  26080. }
  26081. const String AudioUnitPluginInstance::getCategory() const
  26082. {
  26083. const char* result = 0;
  26084. switch (componentDesc.componentType)
  26085. {
  26086. case kAudioUnitType_Effect:
  26087. case kAudioUnitType_MusicEffect:
  26088. result = "Effect";
  26089. break;
  26090. case kAudioUnitType_MusicDevice:
  26091. result = "Synth";
  26092. break;
  26093. case kAudioUnitType_Generator:
  26094. result = "Generator";
  26095. break;
  26096. case kAudioUnitType_Panner:
  26097. result = "Panner";
  26098. break;
  26099. default:
  26100. break;
  26101. }
  26102. return result;
  26103. }
  26104. int AudioUnitPluginInstance::getNumParameters()
  26105. {
  26106. return parameterIds.size();
  26107. }
  26108. float AudioUnitPluginInstance::getParameter (int index)
  26109. {
  26110. const ScopedLock sl (lock);
  26111. Float32 value = 0.0f;
  26112. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26113. {
  26114. AudioUnitGetParameter (audioUnit,
  26115. (UInt32) parameterIds.getUnchecked (index),
  26116. kAudioUnitScope_Global, 0,
  26117. &value);
  26118. }
  26119. return value;
  26120. }
  26121. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  26122. {
  26123. const ScopedLock sl (lock);
  26124. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26125. {
  26126. AudioUnitSetParameter (audioUnit,
  26127. (UInt32) parameterIds.getUnchecked (index),
  26128. kAudioUnitScope_Global, 0,
  26129. newValue, 0);
  26130. }
  26131. }
  26132. const String AudioUnitPluginInstance::getParameterName (int index)
  26133. {
  26134. AudioUnitParameterInfo info;
  26135. zerostruct (info);
  26136. UInt32 sz = sizeof (info);
  26137. String name;
  26138. if (AudioUnitGetProperty (audioUnit,
  26139. kAudioUnitProperty_ParameterInfo,
  26140. kAudioUnitScope_Global,
  26141. parameterIds [index], &info, &sz) == noErr)
  26142. {
  26143. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26144. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26145. else
  26146. name = String (info.name, sizeof (info.name));
  26147. }
  26148. return name;
  26149. }
  26150. const String AudioUnitPluginInstance::getParameterText (int index)
  26151. {
  26152. return String (getParameter (index));
  26153. }
  26154. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26155. {
  26156. AudioUnitParameterInfo info;
  26157. UInt32 sz = sizeof (info);
  26158. if (AudioUnitGetProperty (audioUnit,
  26159. kAudioUnitProperty_ParameterInfo,
  26160. kAudioUnitScope_Global,
  26161. parameterIds [index], &info, &sz) == noErr)
  26162. {
  26163. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26164. }
  26165. return true;
  26166. }
  26167. int AudioUnitPluginInstance::getNumPrograms()
  26168. {
  26169. CFArrayRef presets;
  26170. UInt32 sz = sizeof (CFArrayRef);
  26171. int num = 0;
  26172. if (AudioUnitGetProperty (audioUnit,
  26173. kAudioUnitProperty_FactoryPresets,
  26174. kAudioUnitScope_Global,
  26175. 0, &presets, &sz) == noErr)
  26176. {
  26177. num = (int) CFArrayGetCount (presets);
  26178. CFRelease (presets);
  26179. }
  26180. return num;
  26181. }
  26182. int AudioUnitPluginInstance::getCurrentProgram()
  26183. {
  26184. AUPreset current;
  26185. current.presetNumber = 0;
  26186. UInt32 sz = sizeof (AUPreset);
  26187. AudioUnitGetProperty (audioUnit,
  26188. kAudioUnitProperty_FactoryPresets,
  26189. kAudioUnitScope_Global,
  26190. 0, &current, &sz);
  26191. return current.presetNumber;
  26192. }
  26193. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26194. {
  26195. AUPreset current;
  26196. current.presetNumber = newIndex;
  26197. current.presetName = 0;
  26198. AudioUnitSetProperty (audioUnit,
  26199. kAudioUnitProperty_FactoryPresets,
  26200. kAudioUnitScope_Global,
  26201. 0, &current, sizeof (AUPreset));
  26202. }
  26203. const String AudioUnitPluginInstance::getProgramName (int index)
  26204. {
  26205. String s;
  26206. CFArrayRef presets;
  26207. UInt32 sz = sizeof (CFArrayRef);
  26208. if (AudioUnitGetProperty (audioUnit,
  26209. kAudioUnitProperty_FactoryPresets,
  26210. kAudioUnitScope_Global,
  26211. 0, &presets, &sz) == noErr)
  26212. {
  26213. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26214. {
  26215. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26216. if (p != 0 && p->presetNumber == index)
  26217. {
  26218. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26219. break;
  26220. }
  26221. }
  26222. CFRelease (presets);
  26223. }
  26224. return s;
  26225. }
  26226. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26227. {
  26228. jassertfalse; // xxx not implemented!
  26229. }
  26230. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26231. {
  26232. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26233. return "Input " + String (index + 1);
  26234. return String::empty;
  26235. }
  26236. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26237. {
  26238. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26239. return false;
  26240. return true;
  26241. }
  26242. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26243. {
  26244. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26245. return "Output " + String (index + 1);
  26246. return String::empty;
  26247. }
  26248. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26249. {
  26250. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26251. return false;
  26252. return true;
  26253. }
  26254. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26255. {
  26256. getCurrentProgramStateInformation (destData);
  26257. }
  26258. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26259. {
  26260. CFPropertyListRef propertyList = 0;
  26261. UInt32 sz = sizeof (CFPropertyListRef);
  26262. if (AudioUnitGetProperty (audioUnit,
  26263. kAudioUnitProperty_ClassInfo,
  26264. kAudioUnitScope_Global,
  26265. 0, &propertyList, &sz) == noErr)
  26266. {
  26267. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26268. CFWriteStreamOpen (stream);
  26269. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26270. CFWriteStreamClose (stream);
  26271. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26272. destData.setSize (bytesWritten);
  26273. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26274. CFRelease (data);
  26275. CFRelease (stream);
  26276. CFRelease (propertyList);
  26277. }
  26278. }
  26279. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26280. {
  26281. setCurrentProgramStateInformation (data, sizeInBytes);
  26282. }
  26283. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26284. {
  26285. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26286. (const UInt8*) data,
  26287. sizeInBytes,
  26288. kCFAllocatorNull);
  26289. CFReadStreamOpen (stream);
  26290. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26291. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26292. stream,
  26293. 0,
  26294. kCFPropertyListImmutable,
  26295. &format,
  26296. 0);
  26297. CFRelease (stream);
  26298. if (propertyList != 0)
  26299. AudioUnitSetProperty (audioUnit,
  26300. kAudioUnitProperty_ClassInfo,
  26301. kAudioUnitScope_Global,
  26302. 0, &propertyList, sizeof (propertyList));
  26303. }
  26304. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26305. {
  26306. }
  26307. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26308. {
  26309. }
  26310. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26311. const String& fileOrIdentifier)
  26312. {
  26313. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26314. return;
  26315. PluginDescription desc;
  26316. desc.fileOrIdentifier = fileOrIdentifier;
  26317. desc.uid = 0;
  26318. try
  26319. {
  26320. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26321. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26322. if (auInstance != 0)
  26323. {
  26324. auInstance->fillInPluginDescription (desc);
  26325. results.add (new PluginDescription (desc));
  26326. }
  26327. }
  26328. catch (...)
  26329. {
  26330. // crashed while loading...
  26331. }
  26332. }
  26333. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26334. {
  26335. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26336. {
  26337. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26338. if (result->audioUnit != 0)
  26339. {
  26340. result->initialise();
  26341. return result.release();
  26342. }
  26343. }
  26344. return 0;
  26345. }
  26346. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26347. const bool /*recursive*/)
  26348. {
  26349. StringArray result;
  26350. ComponentRecord* comp = 0;
  26351. ComponentDescription desc;
  26352. zerostruct (desc);
  26353. for (;;)
  26354. {
  26355. zerostruct (desc);
  26356. comp = FindNextComponent (comp, &desc);
  26357. if (comp == 0)
  26358. break;
  26359. GetComponentInfo (comp, &desc, 0, 0, 0);
  26360. if (desc.componentType == kAudioUnitType_MusicDevice
  26361. || desc.componentType == kAudioUnitType_MusicEffect
  26362. || desc.componentType == kAudioUnitType_Effect
  26363. || desc.componentType == kAudioUnitType_Generator
  26364. || desc.componentType == kAudioUnitType_Panner)
  26365. {
  26366. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26367. DBG (s);
  26368. result.add (s);
  26369. }
  26370. }
  26371. return result;
  26372. }
  26373. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26374. {
  26375. ComponentDescription desc;
  26376. String name, version, manufacturer;
  26377. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26378. return FindNextComponent (0, &desc) != 0;
  26379. const File f (fileOrIdentifier);
  26380. return f.hasFileExtension (".component")
  26381. && f.isDirectory();
  26382. }
  26383. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26384. {
  26385. ComponentDescription desc;
  26386. String name, version, manufacturer;
  26387. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26388. if (name.isEmpty())
  26389. name = fileOrIdentifier;
  26390. return name;
  26391. }
  26392. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26393. {
  26394. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26395. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26396. else
  26397. return File (desc.fileOrIdentifier).exists();
  26398. }
  26399. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26400. {
  26401. return FileSearchPath ("/(Default AudioUnit locations)");
  26402. }
  26403. #endif
  26404. END_JUCE_NAMESPACE
  26405. #undef log
  26406. #endif
  26407. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26408. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26409. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26410. #define JUCE_MAC_VST_INCLUDED 1
  26411. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26412. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26413. #if JUCE_WINDOWS
  26414. #undef _WIN32_WINNT
  26415. #define _WIN32_WINNT 0x500
  26416. #undef STRICT
  26417. #define STRICT
  26418. #include <windows.h>
  26419. #include <float.h>
  26420. #pragma warning (disable : 4312 4355)
  26421. #elif JUCE_LINUX
  26422. #include <float.h>
  26423. #include <sys/time.h>
  26424. #include <X11/Xlib.h>
  26425. #include <X11/Xutil.h>
  26426. #include <X11/Xatom.h>
  26427. #undef Font
  26428. #undef KeyPress
  26429. #undef Drawable
  26430. #undef Time
  26431. #else
  26432. #include <Cocoa/Cocoa.h>
  26433. #include <Carbon/Carbon.h>
  26434. #endif
  26435. #if ! (JUCE_MAC && JUCE_64BIT)
  26436. BEGIN_JUCE_NAMESPACE
  26437. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26438. #endif
  26439. #undef PRAGMA_ALIGN_SUPPORTED
  26440. #define VST_FORCE_DEPRECATED 0
  26441. #if JUCE_MSVC
  26442. #pragma warning (push)
  26443. #pragma warning (disable: 4996)
  26444. #endif
  26445. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26446. your include path if you want to add VST support.
  26447. If you're not interested in VSTs, you can disable them by changing the
  26448. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26449. */
  26450. #include "pluginterfaces/vst2.x/aeffectx.h"
  26451. #if JUCE_MSVC
  26452. #pragma warning (pop)
  26453. #endif
  26454. #if JUCE_LINUX
  26455. #define Font JUCE_NAMESPACE::Font
  26456. #define KeyPress JUCE_NAMESPACE::KeyPress
  26457. #define Drawable JUCE_NAMESPACE::Drawable
  26458. #define Time JUCE_NAMESPACE::Time
  26459. #endif
  26460. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26461. #ifdef __aeffect__
  26462. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26463. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26464. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26465. events to the list.
  26466. This is used by both the VST hosting code and the plugin wrapper.
  26467. */
  26468. class VSTMidiEventList
  26469. {
  26470. public:
  26471. VSTMidiEventList()
  26472. : numEventsUsed (0), numEventsAllocated (0)
  26473. {
  26474. }
  26475. ~VSTMidiEventList()
  26476. {
  26477. freeEvents();
  26478. }
  26479. void clear()
  26480. {
  26481. numEventsUsed = 0;
  26482. if (events != 0)
  26483. events->numEvents = 0;
  26484. }
  26485. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26486. {
  26487. ensureSize (numEventsUsed + 1);
  26488. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26489. events->numEvents = ++numEventsUsed;
  26490. if (numBytes <= 4)
  26491. {
  26492. if (e->type == kVstSysExType)
  26493. {
  26494. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26495. e->type = kVstMidiType;
  26496. e->byteSize = sizeof (VstMidiEvent);
  26497. e->noteLength = 0;
  26498. e->noteOffset = 0;
  26499. e->detune = 0;
  26500. e->noteOffVelocity = 0;
  26501. }
  26502. e->deltaFrames = frameOffset;
  26503. memcpy (e->midiData, midiData, numBytes);
  26504. }
  26505. else
  26506. {
  26507. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26508. if (se->type == kVstSysExType)
  26509. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26510. else
  26511. se->sysexDump = (char*) juce_malloc (numBytes);
  26512. memcpy (se->sysexDump, midiData, numBytes);
  26513. se->type = kVstSysExType;
  26514. se->byteSize = sizeof (VstMidiSysexEvent);
  26515. se->deltaFrames = frameOffset;
  26516. se->flags = 0;
  26517. se->dumpBytes = numBytes;
  26518. se->resvd1 = 0;
  26519. se->resvd2 = 0;
  26520. }
  26521. }
  26522. // Handy method to pull the events out of an event buffer supplied by the host
  26523. // or plugin.
  26524. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26525. {
  26526. for (int i = 0; i < events->numEvents; ++i)
  26527. {
  26528. const VstEvent* const e = events->events[i];
  26529. if (e != 0)
  26530. {
  26531. if (e->type == kVstMidiType)
  26532. {
  26533. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26534. 4, e->deltaFrames);
  26535. }
  26536. else if (e->type == kVstSysExType)
  26537. {
  26538. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26539. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26540. e->deltaFrames);
  26541. }
  26542. }
  26543. }
  26544. }
  26545. void ensureSize (int numEventsNeeded)
  26546. {
  26547. if (numEventsNeeded > numEventsAllocated)
  26548. {
  26549. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26550. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26551. if (events == 0)
  26552. events.calloc (size, 1);
  26553. else
  26554. events.realloc (size, 1);
  26555. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26556. {
  26557. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26558. (int) sizeof (VstMidiSysexEvent)));
  26559. e->type = kVstMidiType;
  26560. e->byteSize = sizeof (VstMidiEvent);
  26561. events->events[i] = (VstEvent*) e;
  26562. }
  26563. numEventsAllocated = numEventsNeeded;
  26564. }
  26565. }
  26566. void freeEvents()
  26567. {
  26568. if (events != 0)
  26569. {
  26570. for (int i = numEventsAllocated; --i >= 0;)
  26571. {
  26572. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26573. if (e->type == kVstSysExType)
  26574. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26575. juce_free (e);
  26576. }
  26577. events.free();
  26578. numEventsUsed = 0;
  26579. numEventsAllocated = 0;
  26580. }
  26581. }
  26582. HeapBlock <VstEvents> events;
  26583. private:
  26584. int numEventsUsed, numEventsAllocated;
  26585. };
  26586. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26587. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26588. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26589. #if ! JUCE_WINDOWS
  26590. static void _fpreset() {}
  26591. static void _clearfp() {}
  26592. #endif
  26593. extern void juce_callAnyTimersSynchronously();
  26594. const int fxbVersionNum = 1;
  26595. struct fxProgram
  26596. {
  26597. long chunkMagic; // 'CcnK'
  26598. long byteSize; // of this chunk, excl. magic + byteSize
  26599. long fxMagic; // 'FxCk'
  26600. long version;
  26601. long fxID; // fx unique id
  26602. long fxVersion;
  26603. long numParams;
  26604. char prgName[28];
  26605. float params[1]; // variable no. of parameters
  26606. };
  26607. struct fxSet
  26608. {
  26609. long chunkMagic; // 'CcnK'
  26610. long byteSize; // of this chunk, excl. magic + byteSize
  26611. long fxMagic; // 'FxBk'
  26612. long version;
  26613. long fxID; // fx unique id
  26614. long fxVersion;
  26615. long numPrograms;
  26616. char future[128];
  26617. fxProgram programs[1]; // variable no. of programs
  26618. };
  26619. struct fxChunkSet
  26620. {
  26621. long chunkMagic; // 'CcnK'
  26622. long byteSize; // of this chunk, excl. magic + byteSize
  26623. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26624. long version;
  26625. long fxID; // fx unique id
  26626. long fxVersion;
  26627. long numPrograms;
  26628. char future[128];
  26629. long chunkSize;
  26630. char chunk[8]; // variable
  26631. };
  26632. struct fxProgramSet
  26633. {
  26634. long chunkMagic; // 'CcnK'
  26635. long byteSize; // of this chunk, excl. magic + byteSize
  26636. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26637. long version;
  26638. long fxID; // fx unique id
  26639. long fxVersion;
  26640. long numPrograms;
  26641. char name[28];
  26642. long chunkSize;
  26643. char chunk[8]; // variable
  26644. };
  26645. static long vst_swap (const long x) throw()
  26646. {
  26647. #ifdef JUCE_LITTLE_ENDIAN
  26648. return (long) ByteOrder::swap ((uint32) x);
  26649. #else
  26650. return x;
  26651. #endif
  26652. }
  26653. static float vst_swapFloat (const float x) throw()
  26654. {
  26655. #ifdef JUCE_LITTLE_ENDIAN
  26656. union { uint32 asInt; float asFloat; } n;
  26657. n.asFloat = x;
  26658. n.asInt = ByteOrder::swap (n.asInt);
  26659. return n.asFloat;
  26660. #else
  26661. return x;
  26662. #endif
  26663. }
  26664. static double getVSTHostTimeNanoseconds()
  26665. {
  26666. #if JUCE_WINDOWS
  26667. return timeGetTime() * 1000000.0;
  26668. #elif JUCE_LINUX
  26669. timeval micro;
  26670. gettimeofday (&micro, 0);
  26671. return micro.tv_usec * 1000.0;
  26672. #elif JUCE_MAC
  26673. UnsignedWide micro;
  26674. Microseconds (&micro);
  26675. return micro.lo * 1000.0;
  26676. #endif
  26677. }
  26678. typedef AEffect* (*MainCall) (audioMasterCallback);
  26679. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26680. static int shellUIDToCreate = 0;
  26681. static int insideVSTCallback = 0;
  26682. class VSTPluginWindow;
  26683. // Change this to disable logging of various VST activities
  26684. #ifndef VST_LOGGING
  26685. #define VST_LOGGING 1
  26686. #endif
  26687. #if VST_LOGGING
  26688. #define log(a) Logger::writeToLog(a);
  26689. #else
  26690. #define log(a)
  26691. #endif
  26692. #if JUCE_MAC && JUCE_PPC
  26693. static void* NewCFMFromMachO (void* const machofp) throw()
  26694. {
  26695. void* result = juce_malloc (8);
  26696. ((void**) result)[0] = machofp;
  26697. ((void**) result)[1] = result;
  26698. return result;
  26699. }
  26700. #endif
  26701. #if JUCE_LINUX
  26702. extern Display* display;
  26703. extern XContext windowHandleXContext;
  26704. typedef void (*EventProcPtr) (XEvent* ev);
  26705. static bool xErrorTriggered;
  26706. static int temporaryErrorHandler (Display*, XErrorEvent*)
  26707. {
  26708. xErrorTriggered = true;
  26709. return 0;
  26710. }
  26711. static int getPropertyFromXWindow (Window handle, Atom atom)
  26712. {
  26713. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26714. xErrorTriggered = false;
  26715. int userSize;
  26716. unsigned long bytes, userCount;
  26717. unsigned char* data;
  26718. Atom userType;
  26719. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26720. &userType, &userSize, &userCount, &bytes, &data);
  26721. XSetErrorHandler (oldErrorHandler);
  26722. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26723. : 0;
  26724. }
  26725. static Window getChildWindow (Window windowToCheck)
  26726. {
  26727. Window rootWindow, parentWindow;
  26728. Window* childWindows;
  26729. unsigned int numChildren;
  26730. XQueryTree (display,
  26731. windowToCheck,
  26732. &rootWindow,
  26733. &parentWindow,
  26734. &childWindows,
  26735. &numChildren);
  26736. if (numChildren > 0)
  26737. return childWindows [0];
  26738. return 0;
  26739. }
  26740. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26741. {
  26742. if (e.mods.isLeftButtonDown())
  26743. {
  26744. ev.xbutton.button = Button1;
  26745. ev.xbutton.state |= Button1Mask;
  26746. }
  26747. else if (e.mods.isRightButtonDown())
  26748. {
  26749. ev.xbutton.button = Button3;
  26750. ev.xbutton.state |= Button3Mask;
  26751. }
  26752. else if (e.mods.isMiddleButtonDown())
  26753. {
  26754. ev.xbutton.button = Button2;
  26755. ev.xbutton.state |= Button2Mask;
  26756. }
  26757. }
  26758. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26759. {
  26760. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26761. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26762. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26763. }
  26764. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26765. {
  26766. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26767. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26768. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26769. }
  26770. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26771. {
  26772. if (increment < 0)
  26773. {
  26774. ev.xbutton.button = Button5;
  26775. ev.xbutton.state |= Button5Mask;
  26776. }
  26777. else if (increment > 0)
  26778. {
  26779. ev.xbutton.button = Button4;
  26780. ev.xbutton.state |= Button4Mask;
  26781. }
  26782. }
  26783. #endif
  26784. class ModuleHandle : public ReferenceCountedObject
  26785. {
  26786. public:
  26787. File file;
  26788. MainCall moduleMain;
  26789. String pluginName;
  26790. static Array <ModuleHandle*>& getActiveModules()
  26791. {
  26792. static Array <ModuleHandle*> activeModules;
  26793. return activeModules;
  26794. }
  26795. static ModuleHandle* findOrCreateModule (const File& file)
  26796. {
  26797. for (int i = getActiveModules().size(); --i >= 0;)
  26798. {
  26799. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26800. if (module->file == file)
  26801. return module;
  26802. }
  26803. _fpreset(); // (doesn't do any harm)
  26804. ++insideVSTCallback;
  26805. shellUIDToCreate = 0;
  26806. log ("Attempting to load VST: " + file.getFullPathName());
  26807. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26808. if (! m->open())
  26809. m = 0;
  26810. --insideVSTCallback;
  26811. _fpreset(); // (doesn't do any harm)
  26812. return m.release();
  26813. }
  26814. ModuleHandle (const File& file_)
  26815. : file (file_),
  26816. moduleMain (0),
  26817. #if JUCE_WINDOWS || JUCE_LINUX
  26818. hModule (0)
  26819. #elif JUCE_MAC
  26820. fragId (0),
  26821. resHandle (0),
  26822. bundleRef (0),
  26823. resFileId (0)
  26824. #endif
  26825. {
  26826. getActiveModules().add (this);
  26827. #if JUCE_WINDOWS || JUCE_LINUX
  26828. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26829. #elif JUCE_MAC
  26830. FSRef ref;
  26831. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26832. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26833. #endif
  26834. }
  26835. ~ModuleHandle()
  26836. {
  26837. getActiveModules().removeValue (this);
  26838. close();
  26839. }
  26840. juce_UseDebuggingNewOperator
  26841. #if JUCE_WINDOWS || JUCE_LINUX
  26842. void* hModule;
  26843. String fullParentDirectoryPathName;
  26844. bool open()
  26845. {
  26846. #if JUCE_WINDOWS
  26847. static bool timePeriodSet = false;
  26848. if (! timePeriodSet)
  26849. {
  26850. timePeriodSet = true;
  26851. timeBeginPeriod (2);
  26852. }
  26853. #endif
  26854. pluginName = file.getFileNameWithoutExtension();
  26855. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26856. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26857. if (moduleMain == 0)
  26858. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26859. return moduleMain != 0;
  26860. }
  26861. void close()
  26862. {
  26863. _fpreset(); // (doesn't do any harm)
  26864. PlatformUtilities::freeDynamicLibrary (hModule);
  26865. }
  26866. void closeEffect (AEffect* eff)
  26867. {
  26868. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26869. }
  26870. #else
  26871. CFragConnectionID fragId;
  26872. Handle resHandle;
  26873. CFBundleRef bundleRef;
  26874. FSSpec parentDirFSSpec;
  26875. short resFileId;
  26876. bool open()
  26877. {
  26878. bool ok = false;
  26879. const String filename (file.getFullPathName());
  26880. if (file.hasFileExtension (".vst"))
  26881. {
  26882. const char* const utf8 = filename.toUTF8();
  26883. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26884. strlen (utf8), file.isDirectory());
  26885. if (url != 0)
  26886. {
  26887. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26888. CFRelease (url);
  26889. if (bundleRef != 0)
  26890. {
  26891. if (CFBundleLoadExecutable (bundleRef))
  26892. {
  26893. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26894. if (moduleMain == 0)
  26895. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26896. if (moduleMain != 0)
  26897. {
  26898. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26899. if (name != 0)
  26900. {
  26901. if (CFGetTypeID (name) == CFStringGetTypeID())
  26902. {
  26903. char buffer[1024];
  26904. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26905. pluginName = buffer;
  26906. }
  26907. }
  26908. if (pluginName.isEmpty())
  26909. pluginName = file.getFileNameWithoutExtension();
  26910. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26911. ok = true;
  26912. }
  26913. }
  26914. if (! ok)
  26915. {
  26916. CFBundleUnloadExecutable (bundleRef);
  26917. CFRelease (bundleRef);
  26918. bundleRef = 0;
  26919. }
  26920. }
  26921. }
  26922. }
  26923. #if JUCE_PPC
  26924. else
  26925. {
  26926. FSRef fn;
  26927. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26928. {
  26929. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26930. if (resFileId != -1)
  26931. {
  26932. const int numEffs = Count1Resources ('aEff');
  26933. for (int i = 0; i < numEffs; ++i)
  26934. {
  26935. resHandle = Get1IndResource ('aEff', i + 1);
  26936. if (resHandle != 0)
  26937. {
  26938. OSType type;
  26939. Str255 name;
  26940. SInt16 id;
  26941. GetResInfo (resHandle, &id, &type, name);
  26942. pluginName = String ((const char*) name + 1, name[0]);
  26943. DetachResource (resHandle);
  26944. HLock (resHandle);
  26945. Ptr ptr;
  26946. Str255 errorText;
  26947. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26948. name, kPrivateCFragCopy,
  26949. &fragId, &ptr, errorText);
  26950. if (err == noErr)
  26951. {
  26952. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26953. ok = true;
  26954. }
  26955. else
  26956. {
  26957. HUnlock (resHandle);
  26958. }
  26959. break;
  26960. }
  26961. }
  26962. if (! ok)
  26963. CloseResFile (resFileId);
  26964. }
  26965. }
  26966. }
  26967. #endif
  26968. return ok;
  26969. }
  26970. void close()
  26971. {
  26972. #if JUCE_PPC
  26973. if (fragId != 0)
  26974. {
  26975. if (moduleMain != 0)
  26976. disposeMachOFromCFM ((void*) moduleMain);
  26977. CloseConnection (&fragId);
  26978. HUnlock (resHandle);
  26979. if (resFileId != 0)
  26980. CloseResFile (resFileId);
  26981. }
  26982. else
  26983. #endif
  26984. if (bundleRef != 0)
  26985. {
  26986. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26987. if (CFGetRetainCount (bundleRef) == 1)
  26988. CFBundleUnloadExecutable (bundleRef);
  26989. if (CFGetRetainCount (bundleRef) > 0)
  26990. CFRelease (bundleRef);
  26991. }
  26992. }
  26993. void closeEffect (AEffect* eff)
  26994. {
  26995. #if JUCE_PPC
  26996. if (fragId != 0)
  26997. {
  26998. Array<void*> thingsToDelete;
  26999. thingsToDelete.add ((void*) eff->dispatcher);
  27000. thingsToDelete.add ((void*) eff->process);
  27001. thingsToDelete.add ((void*) eff->setParameter);
  27002. thingsToDelete.add ((void*) eff->getParameter);
  27003. thingsToDelete.add ((void*) eff->processReplacing);
  27004. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  27005. for (int i = thingsToDelete.size(); --i >= 0;)
  27006. disposeMachOFromCFM (thingsToDelete[i]);
  27007. }
  27008. else
  27009. #endif
  27010. {
  27011. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  27012. }
  27013. }
  27014. #if JUCE_PPC
  27015. static void* newMachOFromCFM (void* cfmfp)
  27016. {
  27017. if (cfmfp == 0)
  27018. return 0;
  27019. UInt32* const mfp = new UInt32[6];
  27020. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  27021. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  27022. mfp[2] = 0x800c0000;
  27023. mfp[3] = 0x804c0004;
  27024. mfp[4] = 0x7c0903a6;
  27025. mfp[5] = 0x4e800420;
  27026. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  27027. return mfp;
  27028. }
  27029. static void disposeMachOFromCFM (void* ptr)
  27030. {
  27031. delete[] static_cast <UInt32*> (ptr);
  27032. }
  27033. void coerceAEffectFunctionCalls (AEffect* eff)
  27034. {
  27035. if (fragId != 0)
  27036. {
  27037. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  27038. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  27039. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  27040. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  27041. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  27042. }
  27043. }
  27044. #endif
  27045. #endif
  27046. };
  27047. /**
  27048. An instance of a plugin, created by a VSTPluginFormat.
  27049. */
  27050. class VSTPluginInstance : public AudioPluginInstance,
  27051. private Timer,
  27052. private AsyncUpdater
  27053. {
  27054. public:
  27055. ~VSTPluginInstance();
  27056. // AudioPluginInstance methods:
  27057. void fillInPluginDescription (PluginDescription& desc) const
  27058. {
  27059. desc.name = name;
  27060. desc.fileOrIdentifier = module->file.getFullPathName();
  27061. desc.uid = getUID();
  27062. desc.lastFileModTime = module->file.getLastModificationTime();
  27063. desc.pluginFormatName = "VST";
  27064. desc.category = getCategory();
  27065. {
  27066. char buffer [kVstMaxVendorStrLen + 8];
  27067. zerostruct (buffer);
  27068. dispatch (effGetVendorString, 0, 0, buffer, 0);
  27069. desc.manufacturerName = buffer;
  27070. }
  27071. desc.version = getVersion();
  27072. desc.numInputChannels = getNumInputChannels();
  27073. desc.numOutputChannels = getNumOutputChannels();
  27074. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  27075. }
  27076. const String getName() const { return name; }
  27077. int getUID() const;
  27078. bool acceptsMidi() const { return wantsMidiMessages; }
  27079. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  27080. // AudioProcessor methods:
  27081. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  27082. void releaseResources();
  27083. void processBlock (AudioSampleBuffer& buffer,
  27084. MidiBuffer& midiMessages);
  27085. AudioProcessorEditor* createEditor();
  27086. const String getInputChannelName (int index) const;
  27087. bool isInputChannelStereoPair (int index) const;
  27088. const String getOutputChannelName (int index) const;
  27089. bool isOutputChannelStereoPair (int index) const;
  27090. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  27091. float getParameter (int index);
  27092. void setParameter (int index, float newValue);
  27093. const String getParameterName (int index);
  27094. const String getParameterText (int index);
  27095. bool isParameterAutomatable (int index) const;
  27096. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  27097. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  27098. void setCurrentProgram (int index);
  27099. const String getProgramName (int index);
  27100. void changeProgramName (int index, const String& newName);
  27101. void getStateInformation (MemoryBlock& destData);
  27102. void getCurrentProgramStateInformation (MemoryBlock& destData);
  27103. void setStateInformation (const void* data, int sizeInBytes);
  27104. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27105. void timerCallback();
  27106. void handleAsyncUpdate();
  27107. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  27108. juce_UseDebuggingNewOperator
  27109. private:
  27110. friend class VSTPluginWindow;
  27111. friend class VSTPluginFormat;
  27112. AEffect* effect;
  27113. String name;
  27114. CriticalSection lock;
  27115. bool wantsMidiMessages, initialised, isPowerOn;
  27116. mutable StringArray programNames;
  27117. AudioSampleBuffer tempBuffer;
  27118. CriticalSection midiInLock;
  27119. MidiBuffer incomingMidi;
  27120. VSTMidiEventList midiEventsToSend;
  27121. VstTimeInfo vstHostTime;
  27122. ReferenceCountedObjectPtr <ModuleHandle> module;
  27123. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  27124. bool restoreProgramSettings (const fxProgram* const prog);
  27125. const String getCurrentProgramName();
  27126. void setParamsInProgramBlock (fxProgram* const prog);
  27127. void updateStoredProgramNames();
  27128. void initialise();
  27129. void handleMidiFromPlugin (const VstEvents* const events);
  27130. void createTempParameterStore (MemoryBlock& dest);
  27131. void restoreFromTempParameterStore (const MemoryBlock& mb);
  27132. const String getParameterLabel (int index) const;
  27133. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  27134. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  27135. void setChunkData (const char* data, int size, bool isPreset);
  27136. bool loadFromFXBFile (const void* data, int numBytes);
  27137. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  27138. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  27139. const String getVersion() const;
  27140. const String getCategory() const;
  27141. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  27142. void setPower (const bool on);
  27143. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27144. };
  27145. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27146. : effect (0),
  27147. wantsMidiMessages (false),
  27148. initialised (false),
  27149. isPowerOn (false),
  27150. tempBuffer (1, 1),
  27151. module (module_)
  27152. {
  27153. try
  27154. {
  27155. _fpreset();
  27156. ++insideVSTCallback;
  27157. name = module->pluginName;
  27158. log ("Creating VST instance: " + name);
  27159. #if JUCE_MAC
  27160. if (module->resFileId != 0)
  27161. UseResFile (module->resFileId);
  27162. #if JUCE_PPC
  27163. if (module->fragId != 0)
  27164. {
  27165. static void* audioMasterCoerced = 0;
  27166. if (audioMasterCoerced == 0)
  27167. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27168. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27169. }
  27170. else
  27171. #endif
  27172. #endif
  27173. {
  27174. effect = module->moduleMain (&audioMaster);
  27175. }
  27176. --insideVSTCallback;
  27177. if (effect != 0 && effect->magic == kEffectMagic)
  27178. {
  27179. #if JUCE_PPC
  27180. module->coerceAEffectFunctionCalls (effect);
  27181. #endif
  27182. jassert (effect->resvd2 == 0);
  27183. jassert (effect->object != 0);
  27184. _fpreset(); // some dodgy plugs fuck around with this
  27185. }
  27186. else
  27187. {
  27188. effect = 0;
  27189. }
  27190. }
  27191. catch (...)
  27192. {
  27193. --insideVSTCallback;
  27194. }
  27195. }
  27196. VSTPluginInstance::~VSTPluginInstance()
  27197. {
  27198. const ScopedLock sl (lock);
  27199. jassert (insideVSTCallback == 0);
  27200. if (effect != 0 && effect->magic == kEffectMagic)
  27201. {
  27202. try
  27203. {
  27204. #if JUCE_MAC
  27205. if (module->resFileId != 0)
  27206. UseResFile (module->resFileId);
  27207. #endif
  27208. // Must delete any editors before deleting the plugin instance!
  27209. jassert (getActiveEditor() == 0);
  27210. _fpreset(); // some dodgy plugs fuck around with this
  27211. module->closeEffect (effect);
  27212. }
  27213. catch (...)
  27214. {}
  27215. }
  27216. module = 0;
  27217. effect = 0;
  27218. }
  27219. void VSTPluginInstance::initialise()
  27220. {
  27221. if (initialised || effect == 0)
  27222. return;
  27223. log ("Initialising VST: " + module->pluginName);
  27224. initialised = true;
  27225. dispatch (effIdentify, 0, 0, 0, 0);
  27226. // this code would ask the plugin for its name, but so few plugins
  27227. // actually bother implementing this correctly, that it's better to
  27228. // just ignore it and use the file name instead.
  27229. /* {
  27230. char buffer [256];
  27231. zerostruct (buffer);
  27232. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27233. name = String (buffer).trim();
  27234. if (name.isEmpty())
  27235. name = module->pluginName;
  27236. }
  27237. */
  27238. if (getSampleRate() > 0)
  27239. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27240. if (getBlockSize() > 0)
  27241. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27242. dispatch (effOpen, 0, 0, 0, 0);
  27243. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27244. getSampleRate(), getBlockSize());
  27245. if (getNumPrograms() > 1)
  27246. setCurrentProgram (0);
  27247. else
  27248. dispatch (effSetProgram, 0, 0, 0, 0);
  27249. int i;
  27250. for (i = effect->numInputs; --i >= 0;)
  27251. dispatch (effConnectInput, i, 1, 0, 0);
  27252. for (i = effect->numOutputs; --i >= 0;)
  27253. dispatch (effConnectOutput, i, 1, 0, 0);
  27254. updateStoredProgramNames();
  27255. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27256. setLatencySamples (effect->initialDelay);
  27257. }
  27258. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27259. int samplesPerBlockExpected)
  27260. {
  27261. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27262. sampleRate_, samplesPerBlockExpected);
  27263. setLatencySamples (effect->initialDelay);
  27264. vstHostTime.tempo = 120.0;
  27265. vstHostTime.timeSigNumerator = 4;
  27266. vstHostTime.timeSigDenominator = 4;
  27267. vstHostTime.sampleRate = sampleRate_;
  27268. vstHostTime.samplePos = 0;
  27269. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27270. initialise();
  27271. if (initialised)
  27272. {
  27273. wantsMidiMessages = wantsMidiMessages
  27274. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27275. if (wantsMidiMessages)
  27276. midiEventsToSend.ensureSize (256);
  27277. else
  27278. midiEventsToSend.freeEvents();
  27279. incomingMidi.clear();
  27280. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27281. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27282. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27283. if (! isPowerOn)
  27284. setPower (true);
  27285. // dodgy hack to force some plugins to initialise the sample rate..
  27286. if ((! hasEditor()) && getNumParameters() > 0)
  27287. {
  27288. const float old = getParameter (0);
  27289. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27290. setParameter (0, old);
  27291. }
  27292. dispatch (effStartProcess, 0, 0, 0, 0);
  27293. }
  27294. }
  27295. void VSTPluginInstance::releaseResources()
  27296. {
  27297. if (initialised)
  27298. {
  27299. dispatch (effStopProcess, 0, 0, 0, 0);
  27300. setPower (false);
  27301. }
  27302. tempBuffer.setSize (1, 1);
  27303. incomingMidi.clear();
  27304. midiEventsToSend.freeEvents();
  27305. }
  27306. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27307. MidiBuffer& midiMessages)
  27308. {
  27309. const int numSamples = buffer.getNumSamples();
  27310. if (initialised)
  27311. {
  27312. AudioPlayHead* playHead = getPlayHead();
  27313. if (playHead != 0)
  27314. {
  27315. AudioPlayHead::CurrentPositionInfo position;
  27316. playHead->getCurrentPosition (position);
  27317. vstHostTime.tempo = position.bpm;
  27318. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27319. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27320. vstHostTime.ppqPos = position.ppqPosition;
  27321. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27322. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27323. if (position.isPlaying)
  27324. vstHostTime.flags |= kVstTransportPlaying;
  27325. else
  27326. vstHostTime.flags &= ~kVstTransportPlaying;
  27327. }
  27328. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27329. if (wantsMidiMessages)
  27330. {
  27331. midiEventsToSend.clear();
  27332. midiEventsToSend.ensureSize (1);
  27333. MidiBuffer::Iterator iter (midiMessages);
  27334. const uint8* midiData;
  27335. int numBytesOfMidiData, samplePosition;
  27336. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27337. {
  27338. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27339. jlimit (0, numSamples - 1, samplePosition));
  27340. }
  27341. try
  27342. {
  27343. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27344. }
  27345. catch (...)
  27346. {}
  27347. }
  27348. _clearfp();
  27349. if ((effect->flags & effFlagsCanReplacing) != 0)
  27350. {
  27351. try
  27352. {
  27353. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27354. }
  27355. catch (...)
  27356. {}
  27357. }
  27358. else
  27359. {
  27360. tempBuffer.setSize (effect->numOutputs, numSamples);
  27361. tempBuffer.clear();
  27362. try
  27363. {
  27364. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27365. }
  27366. catch (...)
  27367. {}
  27368. for (int i = effect->numOutputs; --i >= 0;)
  27369. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27370. }
  27371. }
  27372. else
  27373. {
  27374. // Not initialised, so just bypass..
  27375. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27376. buffer.clear (i, 0, buffer.getNumSamples());
  27377. }
  27378. {
  27379. // copy any incoming midi..
  27380. const ScopedLock sl (midiInLock);
  27381. midiMessages.swapWith (incomingMidi);
  27382. incomingMidi.clear();
  27383. }
  27384. }
  27385. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27386. {
  27387. if (events != 0)
  27388. {
  27389. const ScopedLock sl (midiInLock);
  27390. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27391. }
  27392. }
  27393. static Array <VSTPluginWindow*> activeVSTWindows;
  27394. class VSTPluginWindow : public AudioProcessorEditor,
  27395. #if ! JUCE_MAC
  27396. public ComponentMovementWatcher,
  27397. #endif
  27398. public Timer
  27399. {
  27400. public:
  27401. VSTPluginWindow (VSTPluginInstance& plugin_)
  27402. : AudioProcessorEditor (&plugin_),
  27403. #if ! JUCE_MAC
  27404. ComponentMovementWatcher (this),
  27405. #endif
  27406. plugin (plugin_),
  27407. isOpen (false),
  27408. wasShowing (false),
  27409. pluginRefusesToResize (false),
  27410. pluginWantsKeys (false),
  27411. alreadyInside (false),
  27412. recursiveResize (false)
  27413. {
  27414. #if JUCE_WINDOWS
  27415. sizeCheckCount = 0;
  27416. pluginHWND = 0;
  27417. #elif JUCE_LINUX
  27418. pluginWindow = None;
  27419. pluginProc = None;
  27420. #else
  27421. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27422. #endif
  27423. activeVSTWindows.add (this);
  27424. setSize (1, 1);
  27425. setOpaque (true);
  27426. setVisible (true);
  27427. }
  27428. ~VSTPluginWindow()
  27429. {
  27430. #if JUCE_MAC
  27431. innerWrapper = 0;
  27432. #else
  27433. closePluginWindow();
  27434. #endif
  27435. activeVSTWindows.removeValue (this);
  27436. plugin.editorBeingDeleted (this);
  27437. }
  27438. #if ! JUCE_MAC
  27439. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27440. {
  27441. if (recursiveResize)
  27442. return;
  27443. Component* const topComp = getTopLevelComponent();
  27444. if (topComp->getPeer() != 0)
  27445. {
  27446. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27447. recursiveResize = true;
  27448. #if JUCE_WINDOWS
  27449. if (pluginHWND != 0)
  27450. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27451. #elif JUCE_LINUX
  27452. if (pluginWindow != 0)
  27453. {
  27454. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27455. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27456. XMapRaised (display, pluginWindow);
  27457. }
  27458. #endif
  27459. recursiveResize = false;
  27460. }
  27461. }
  27462. void componentVisibilityChanged (Component&)
  27463. {
  27464. const bool isShowingNow = isShowing();
  27465. if (wasShowing != isShowingNow)
  27466. {
  27467. wasShowing = isShowingNow;
  27468. if (isShowingNow)
  27469. openPluginWindow();
  27470. else
  27471. closePluginWindow();
  27472. }
  27473. componentMovedOrResized (true, true);
  27474. }
  27475. void componentPeerChanged()
  27476. {
  27477. closePluginWindow();
  27478. openPluginWindow();
  27479. }
  27480. #endif
  27481. bool keyStateChanged (bool)
  27482. {
  27483. return pluginWantsKeys;
  27484. }
  27485. bool keyPressed (const KeyPress&)
  27486. {
  27487. return pluginWantsKeys;
  27488. }
  27489. #if JUCE_MAC
  27490. void paint (Graphics& g)
  27491. {
  27492. g.fillAll (Colours::black);
  27493. }
  27494. #else
  27495. void paint (Graphics& g)
  27496. {
  27497. if (isOpen)
  27498. {
  27499. ComponentPeer* const peer = getPeer();
  27500. if (peer != 0)
  27501. {
  27502. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27503. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27504. #if JUCE_LINUX
  27505. if (pluginWindow != 0)
  27506. {
  27507. const Rectangle<int> clip (g.getClipBounds());
  27508. XEvent ev;
  27509. zerostruct (ev);
  27510. ev.xexpose.type = Expose;
  27511. ev.xexpose.display = display;
  27512. ev.xexpose.window = pluginWindow;
  27513. ev.xexpose.x = clip.getX();
  27514. ev.xexpose.y = clip.getY();
  27515. ev.xexpose.width = clip.getWidth();
  27516. ev.xexpose.height = clip.getHeight();
  27517. sendEventToChild (&ev);
  27518. }
  27519. #endif
  27520. }
  27521. }
  27522. else
  27523. {
  27524. g.fillAll (Colours::black);
  27525. }
  27526. }
  27527. #endif
  27528. void timerCallback()
  27529. {
  27530. #if JUCE_WINDOWS
  27531. if (--sizeCheckCount <= 0)
  27532. {
  27533. sizeCheckCount = 10;
  27534. checkPluginWindowSize();
  27535. }
  27536. #endif
  27537. try
  27538. {
  27539. static bool reentrant = false;
  27540. if (! reentrant)
  27541. {
  27542. reentrant = true;
  27543. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27544. reentrant = false;
  27545. }
  27546. }
  27547. catch (...)
  27548. {}
  27549. }
  27550. void mouseDown (const MouseEvent& e)
  27551. {
  27552. #if JUCE_LINUX
  27553. if (pluginWindow == 0)
  27554. return;
  27555. toFront (true);
  27556. XEvent ev;
  27557. zerostruct (ev);
  27558. ev.xbutton.display = display;
  27559. ev.xbutton.type = ButtonPress;
  27560. ev.xbutton.window = pluginWindow;
  27561. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27562. ev.xbutton.time = CurrentTime;
  27563. ev.xbutton.x = e.x;
  27564. ev.xbutton.y = e.y;
  27565. ev.xbutton.x_root = e.getScreenX();
  27566. ev.xbutton.y_root = e.getScreenY();
  27567. translateJuceToXButtonModifiers (e, ev);
  27568. sendEventToChild (&ev);
  27569. #elif JUCE_WINDOWS
  27570. (void) e;
  27571. toFront (true);
  27572. #endif
  27573. }
  27574. void broughtToFront()
  27575. {
  27576. activeVSTWindows.removeValue (this);
  27577. activeVSTWindows.add (this);
  27578. #if JUCE_MAC
  27579. dispatch (effEditTop, 0, 0, 0, 0);
  27580. #endif
  27581. }
  27582. juce_UseDebuggingNewOperator
  27583. private:
  27584. VSTPluginInstance& plugin;
  27585. bool isOpen, wasShowing, recursiveResize;
  27586. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27587. #if JUCE_WINDOWS
  27588. HWND pluginHWND;
  27589. void* originalWndProc;
  27590. int sizeCheckCount;
  27591. #elif JUCE_LINUX
  27592. Window pluginWindow;
  27593. EventProcPtr pluginProc;
  27594. #endif
  27595. #if JUCE_MAC
  27596. void openPluginWindow (WindowRef parentWindow)
  27597. {
  27598. if (isOpen || parentWindow == 0)
  27599. return;
  27600. isOpen = true;
  27601. ERect* rect = 0;
  27602. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27603. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27604. // do this before and after like in the steinberg example
  27605. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27606. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27607. // Install keyboard hooks
  27608. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27609. // double-check it's not too tiny
  27610. int w = 250, h = 150;
  27611. if (rect != 0)
  27612. {
  27613. w = rect->right - rect->left;
  27614. h = rect->bottom - rect->top;
  27615. if (w == 0 || h == 0)
  27616. {
  27617. w = 250;
  27618. h = 150;
  27619. }
  27620. }
  27621. w = jmax (w, 32);
  27622. h = jmax (h, 32);
  27623. setSize (w, h);
  27624. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27625. repaint();
  27626. }
  27627. #else
  27628. void openPluginWindow()
  27629. {
  27630. if (isOpen || getWindowHandle() == 0)
  27631. return;
  27632. log ("Opening VST UI: " + plugin.name);
  27633. isOpen = true;
  27634. ERect* rect = 0;
  27635. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27636. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27637. // do this before and after like in the steinberg example
  27638. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27639. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27640. // Install keyboard hooks
  27641. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27642. #if JUCE_WINDOWS
  27643. originalWndProc = 0;
  27644. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27645. if (pluginHWND == 0)
  27646. {
  27647. isOpen = false;
  27648. setSize (300, 150);
  27649. return;
  27650. }
  27651. #pragma warning (push)
  27652. #pragma warning (disable: 4244)
  27653. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  27654. if (! pluginWantsKeys)
  27655. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27656. #pragma warning (pop)
  27657. int w, h;
  27658. RECT r;
  27659. GetWindowRect (pluginHWND, &r);
  27660. w = r.right - r.left;
  27661. h = r.bottom - r.top;
  27662. if (rect != 0)
  27663. {
  27664. const int rw = rect->right - rect->left;
  27665. const int rh = rect->bottom - rect->top;
  27666. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27667. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27668. {
  27669. // very dodgy logic to decide which size is right.
  27670. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27671. {
  27672. SetWindowPos (pluginHWND, 0,
  27673. 0, 0, rw, rh,
  27674. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27675. GetWindowRect (pluginHWND, &r);
  27676. w = r.right - r.left;
  27677. h = r.bottom - r.top;
  27678. pluginRefusesToResize = (w != rw) || (h != rh);
  27679. w = rw;
  27680. h = rh;
  27681. }
  27682. }
  27683. }
  27684. #elif JUCE_LINUX
  27685. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27686. if (pluginWindow != 0)
  27687. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27688. XInternAtom (display, "_XEventProc", False));
  27689. int w = 250, h = 150;
  27690. if (rect != 0)
  27691. {
  27692. w = rect->right - rect->left;
  27693. h = rect->bottom - rect->top;
  27694. if (w == 0 || h == 0)
  27695. {
  27696. w = 250;
  27697. h = 150;
  27698. }
  27699. }
  27700. if (pluginWindow != 0)
  27701. XMapRaised (display, pluginWindow);
  27702. #endif
  27703. // double-check it's not too tiny
  27704. w = jmax (w, 32);
  27705. h = jmax (h, 32);
  27706. setSize (w, h);
  27707. #if JUCE_WINDOWS
  27708. checkPluginWindowSize();
  27709. #endif
  27710. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27711. repaint();
  27712. }
  27713. #endif
  27714. #if ! JUCE_MAC
  27715. void closePluginWindow()
  27716. {
  27717. if (isOpen)
  27718. {
  27719. log ("Closing VST UI: " + plugin.getName());
  27720. isOpen = false;
  27721. dispatch (effEditClose, 0, 0, 0, 0);
  27722. #if JUCE_WINDOWS
  27723. #pragma warning (push)
  27724. #pragma warning (disable: 4244)
  27725. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27726. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27727. #pragma warning (pop)
  27728. stopTimer();
  27729. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27730. DestroyWindow (pluginHWND);
  27731. pluginHWND = 0;
  27732. #elif JUCE_LINUX
  27733. stopTimer();
  27734. pluginWindow = 0;
  27735. pluginProc = 0;
  27736. #endif
  27737. }
  27738. }
  27739. #endif
  27740. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27741. {
  27742. return plugin.dispatch (opcode, index, value, ptr, opt);
  27743. }
  27744. #if JUCE_WINDOWS
  27745. void checkPluginWindowSize()
  27746. {
  27747. RECT r;
  27748. GetWindowRect (pluginHWND, &r);
  27749. const int w = r.right - r.left;
  27750. const int h = r.bottom - r.top;
  27751. if (isShowing() && w > 0 && h > 0
  27752. && (w != getWidth() || h != getHeight())
  27753. && ! pluginRefusesToResize)
  27754. {
  27755. setSize (w, h);
  27756. sizeCheckCount = 0;
  27757. }
  27758. }
  27759. // hooks to get keyboard events from VST windows..
  27760. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27761. {
  27762. for (int i = activeVSTWindows.size(); --i >= 0;)
  27763. {
  27764. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27765. if (w->pluginHWND == hW)
  27766. {
  27767. if (message == WM_CHAR
  27768. || message == WM_KEYDOWN
  27769. || message == WM_SYSKEYDOWN
  27770. || message == WM_KEYUP
  27771. || message == WM_SYSKEYUP
  27772. || message == WM_APPCOMMAND)
  27773. {
  27774. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27775. message, wParam, lParam);
  27776. }
  27777. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27778. (HWND) w->pluginHWND,
  27779. message,
  27780. wParam,
  27781. lParam);
  27782. }
  27783. }
  27784. return DefWindowProc (hW, message, wParam, lParam);
  27785. }
  27786. #endif
  27787. #if JUCE_LINUX
  27788. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27789. void sendEventToChild (XEvent* event)
  27790. {
  27791. if (pluginProc != 0)
  27792. {
  27793. // if the plugin publishes an event procedure, pass the event directly..
  27794. pluginProc (event);
  27795. }
  27796. else if (pluginWindow != 0)
  27797. {
  27798. // if the plugin has a window, then send the event to the window so that
  27799. // its message thread will pick it up..
  27800. XSendEvent (display, pluginWindow, False, 0L, event);
  27801. XFlush (display);
  27802. }
  27803. }
  27804. void mouseEnter (const MouseEvent& e)
  27805. {
  27806. if (pluginWindow != 0)
  27807. {
  27808. XEvent ev;
  27809. zerostruct (ev);
  27810. ev.xcrossing.display = display;
  27811. ev.xcrossing.type = EnterNotify;
  27812. ev.xcrossing.window = pluginWindow;
  27813. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27814. ev.xcrossing.time = CurrentTime;
  27815. ev.xcrossing.x = e.x;
  27816. ev.xcrossing.y = e.y;
  27817. ev.xcrossing.x_root = e.getScreenX();
  27818. ev.xcrossing.y_root = e.getScreenY();
  27819. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27820. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27821. translateJuceToXCrossingModifiers (e, ev);
  27822. sendEventToChild (&ev);
  27823. }
  27824. }
  27825. void mouseExit (const MouseEvent& e)
  27826. {
  27827. if (pluginWindow != 0)
  27828. {
  27829. XEvent ev;
  27830. zerostruct (ev);
  27831. ev.xcrossing.display = display;
  27832. ev.xcrossing.type = LeaveNotify;
  27833. ev.xcrossing.window = pluginWindow;
  27834. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27835. ev.xcrossing.time = CurrentTime;
  27836. ev.xcrossing.x = e.x;
  27837. ev.xcrossing.y = e.y;
  27838. ev.xcrossing.x_root = e.getScreenX();
  27839. ev.xcrossing.y_root = e.getScreenY();
  27840. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27841. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27842. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27843. translateJuceToXCrossingModifiers (e, ev);
  27844. sendEventToChild (&ev);
  27845. }
  27846. }
  27847. void mouseMove (const MouseEvent& e)
  27848. {
  27849. if (pluginWindow != 0)
  27850. {
  27851. XEvent ev;
  27852. zerostruct (ev);
  27853. ev.xmotion.display = display;
  27854. ev.xmotion.type = MotionNotify;
  27855. ev.xmotion.window = pluginWindow;
  27856. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27857. ev.xmotion.time = CurrentTime;
  27858. ev.xmotion.is_hint = NotifyNormal;
  27859. ev.xmotion.x = e.x;
  27860. ev.xmotion.y = e.y;
  27861. ev.xmotion.x_root = e.getScreenX();
  27862. ev.xmotion.y_root = e.getScreenY();
  27863. sendEventToChild (&ev);
  27864. }
  27865. }
  27866. void mouseDrag (const MouseEvent& e)
  27867. {
  27868. if (pluginWindow != 0)
  27869. {
  27870. XEvent ev;
  27871. zerostruct (ev);
  27872. ev.xmotion.display = display;
  27873. ev.xmotion.type = MotionNotify;
  27874. ev.xmotion.window = pluginWindow;
  27875. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27876. ev.xmotion.time = CurrentTime;
  27877. ev.xmotion.x = e.x ;
  27878. ev.xmotion.y = e.y;
  27879. ev.xmotion.x_root = e.getScreenX();
  27880. ev.xmotion.y_root = e.getScreenY();
  27881. ev.xmotion.is_hint = NotifyNormal;
  27882. translateJuceToXMotionModifiers (e, ev);
  27883. sendEventToChild (&ev);
  27884. }
  27885. }
  27886. void mouseUp (const MouseEvent& e)
  27887. {
  27888. if (pluginWindow != 0)
  27889. {
  27890. XEvent ev;
  27891. zerostruct (ev);
  27892. ev.xbutton.display = display;
  27893. ev.xbutton.type = ButtonRelease;
  27894. ev.xbutton.window = pluginWindow;
  27895. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27896. ev.xbutton.time = CurrentTime;
  27897. ev.xbutton.x = e.x;
  27898. ev.xbutton.y = e.y;
  27899. ev.xbutton.x_root = e.getScreenX();
  27900. ev.xbutton.y_root = e.getScreenY();
  27901. translateJuceToXButtonModifiers (e, ev);
  27902. sendEventToChild (&ev);
  27903. }
  27904. }
  27905. void mouseWheelMove (const MouseEvent& e,
  27906. float incrementX,
  27907. float incrementY)
  27908. {
  27909. if (pluginWindow != 0)
  27910. {
  27911. XEvent ev;
  27912. zerostruct (ev);
  27913. ev.xbutton.display = display;
  27914. ev.xbutton.type = ButtonPress;
  27915. ev.xbutton.window = pluginWindow;
  27916. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27917. ev.xbutton.time = CurrentTime;
  27918. ev.xbutton.x = e.x;
  27919. ev.xbutton.y = e.y;
  27920. ev.xbutton.x_root = e.getScreenX();
  27921. ev.xbutton.y_root = e.getScreenY();
  27922. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27923. sendEventToChild (&ev);
  27924. // TODO - put a usleep here ?
  27925. ev.xbutton.type = ButtonRelease;
  27926. sendEventToChild (&ev);
  27927. }
  27928. }
  27929. #endif
  27930. #if JUCE_MAC
  27931. #if ! JUCE_SUPPORT_CARBON
  27932. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27933. #endif
  27934. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27935. {
  27936. public:
  27937. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27938. : owner (owner_),
  27939. alreadyInside (false)
  27940. {
  27941. }
  27942. ~InnerWrapperComponent()
  27943. {
  27944. deleteWindow();
  27945. }
  27946. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27947. {
  27948. owner->openPluginWindow (windowRef);
  27949. return 0;
  27950. }
  27951. void removeView (HIViewRef)
  27952. {
  27953. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27954. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27955. }
  27956. bool getEmbeddedViewSize (int& w, int& h)
  27957. {
  27958. ERect* rect = 0;
  27959. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27960. w = rect->right - rect->left;
  27961. h = rect->bottom - rect->top;
  27962. return true;
  27963. }
  27964. void mouseDown (int x, int y)
  27965. {
  27966. if (! alreadyInside)
  27967. {
  27968. alreadyInside = true;
  27969. getTopLevelComponent()->toFront (true);
  27970. owner->dispatch (effEditMouse, x, y, 0, 0);
  27971. alreadyInside = false;
  27972. }
  27973. else
  27974. {
  27975. PostEvent (::mouseDown, 0);
  27976. }
  27977. }
  27978. void paint()
  27979. {
  27980. ComponentPeer* const peer = getPeer();
  27981. if (peer != 0)
  27982. {
  27983. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27984. ERect r;
  27985. r.left = pos.getX();
  27986. r.right = r.left + getWidth();
  27987. r.top = pos.getY();
  27988. r.bottom = r.top + getHeight();
  27989. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27990. }
  27991. }
  27992. private:
  27993. VSTPluginWindow* const owner;
  27994. bool alreadyInside;
  27995. };
  27996. friend class InnerWrapperComponent;
  27997. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27998. void resized()
  27999. {
  28000. innerWrapper->setSize (getWidth(), getHeight());
  28001. }
  28002. #endif
  28003. };
  28004. AudioProcessorEditor* VSTPluginInstance::createEditor()
  28005. {
  28006. if (hasEditor())
  28007. return new VSTPluginWindow (*this);
  28008. return 0;
  28009. }
  28010. void VSTPluginInstance::handleAsyncUpdate()
  28011. {
  28012. // indicates that something about the plugin has changed..
  28013. updateHostDisplay();
  28014. }
  28015. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  28016. {
  28017. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  28018. {
  28019. changeProgramName (getCurrentProgram(), prog->prgName);
  28020. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  28021. setParameter (i, vst_swapFloat (prog->params[i]));
  28022. return true;
  28023. }
  28024. return false;
  28025. }
  28026. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  28027. const int dataSize)
  28028. {
  28029. if (dataSize < 28)
  28030. return false;
  28031. const fxSet* const set = (const fxSet*) data;
  28032. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  28033. || vst_swap (set->version) > fxbVersionNum)
  28034. return false;
  28035. if (vst_swap (set->fxMagic) == 'FxBk')
  28036. {
  28037. // bank of programs
  28038. if (vst_swap (set->numPrograms) >= 0)
  28039. {
  28040. const int oldProg = getCurrentProgram();
  28041. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  28042. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28043. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  28044. {
  28045. if (i != oldProg)
  28046. {
  28047. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  28048. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28049. return false;
  28050. if (vst_swap (set->numPrograms) > 0)
  28051. setCurrentProgram (i);
  28052. if (! restoreProgramSettings (prog))
  28053. return false;
  28054. }
  28055. }
  28056. if (vst_swap (set->numPrograms) > 0)
  28057. setCurrentProgram (oldProg);
  28058. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  28059. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28060. return false;
  28061. if (! restoreProgramSettings (prog))
  28062. return false;
  28063. }
  28064. }
  28065. else if (vst_swap (set->fxMagic) == 'FxCk')
  28066. {
  28067. // single program
  28068. const fxProgram* const prog = (const fxProgram*) data;
  28069. if (vst_swap (prog->chunkMagic) != 'CcnK')
  28070. return false;
  28071. changeProgramName (getCurrentProgram(), prog->prgName);
  28072. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  28073. setParameter (i, vst_swapFloat (prog->params[i]));
  28074. }
  28075. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  28076. {
  28077. // non-preset chunk
  28078. const fxChunkSet* const cset = (const fxChunkSet*) data;
  28079. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  28080. return false;
  28081. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  28082. }
  28083. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  28084. {
  28085. // preset chunk
  28086. const fxProgramSet* const cset = (const fxProgramSet*) data;
  28087. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  28088. return false;
  28089. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  28090. changeProgramName (getCurrentProgram(), cset->name);
  28091. }
  28092. else
  28093. {
  28094. return false;
  28095. }
  28096. return true;
  28097. }
  28098. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  28099. {
  28100. const int numParams = getNumParameters();
  28101. prog->chunkMagic = vst_swap ('CcnK');
  28102. prog->byteSize = 0;
  28103. prog->fxMagic = vst_swap ('FxCk');
  28104. prog->version = vst_swap (fxbVersionNum);
  28105. prog->fxID = vst_swap (getUID());
  28106. prog->fxVersion = vst_swap (getVersionNumber());
  28107. prog->numParams = vst_swap (numParams);
  28108. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  28109. for (int i = 0; i < numParams; ++i)
  28110. prog->params[i] = vst_swapFloat (getParameter (i));
  28111. }
  28112. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  28113. {
  28114. const int numPrograms = getNumPrograms();
  28115. const int numParams = getNumParameters();
  28116. if (usesChunks())
  28117. {
  28118. if (isFXB)
  28119. {
  28120. MemoryBlock chunk;
  28121. getChunkData (chunk, false, maxSizeMB);
  28122. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  28123. dest.setSize (totalLen, true);
  28124. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  28125. set->chunkMagic = vst_swap ('CcnK');
  28126. set->byteSize = 0;
  28127. set->fxMagic = vst_swap ('FBCh');
  28128. set->version = vst_swap (fxbVersionNum);
  28129. set->fxID = vst_swap (getUID());
  28130. set->fxVersion = vst_swap (getVersionNumber());
  28131. set->numPrograms = vst_swap (numPrograms);
  28132. set->chunkSize = vst_swap ((long) chunk.getSize());
  28133. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28134. }
  28135. else
  28136. {
  28137. MemoryBlock chunk;
  28138. getChunkData (chunk, true, maxSizeMB);
  28139. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  28140. dest.setSize (totalLen, true);
  28141. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28142. set->chunkMagic = vst_swap ('CcnK');
  28143. set->byteSize = 0;
  28144. set->fxMagic = vst_swap ('FPCh');
  28145. set->version = vst_swap (fxbVersionNum);
  28146. set->fxID = vst_swap (getUID());
  28147. set->fxVersion = vst_swap (getVersionNumber());
  28148. set->numPrograms = vst_swap (numPrograms);
  28149. set->chunkSize = vst_swap ((long) chunk.getSize());
  28150. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28151. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28152. }
  28153. }
  28154. else
  28155. {
  28156. if (isFXB)
  28157. {
  28158. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28159. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28160. dest.setSize (len, true);
  28161. fxSet* const set = (fxSet*) dest.getData();
  28162. set->chunkMagic = vst_swap ('CcnK');
  28163. set->byteSize = 0;
  28164. set->fxMagic = vst_swap ('FxBk');
  28165. set->version = vst_swap (fxbVersionNum);
  28166. set->fxID = vst_swap (getUID());
  28167. set->fxVersion = vst_swap (getVersionNumber());
  28168. set->numPrograms = vst_swap (numPrograms);
  28169. const int oldProgram = getCurrentProgram();
  28170. MemoryBlock oldSettings;
  28171. createTempParameterStore (oldSettings);
  28172. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28173. for (int i = 0; i < numPrograms; ++i)
  28174. {
  28175. if (i != oldProgram)
  28176. {
  28177. setCurrentProgram (i);
  28178. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28179. }
  28180. }
  28181. setCurrentProgram (oldProgram);
  28182. restoreFromTempParameterStore (oldSettings);
  28183. }
  28184. else
  28185. {
  28186. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28187. dest.setSize (totalLen, true);
  28188. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28189. }
  28190. }
  28191. return true;
  28192. }
  28193. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28194. {
  28195. if (usesChunks())
  28196. {
  28197. void* data = 0;
  28198. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28199. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28200. {
  28201. mb.setSize (bytes);
  28202. mb.copyFrom (data, 0, bytes);
  28203. }
  28204. }
  28205. }
  28206. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28207. {
  28208. if (size > 0 && usesChunks())
  28209. {
  28210. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28211. if (! isPreset)
  28212. updateStoredProgramNames();
  28213. }
  28214. }
  28215. void VSTPluginInstance::timerCallback()
  28216. {
  28217. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28218. stopTimer();
  28219. }
  28220. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28221. {
  28222. const ScopedLock sl (lock);
  28223. ++insideVSTCallback;
  28224. int result = 0;
  28225. try
  28226. {
  28227. if (effect != 0)
  28228. {
  28229. #if JUCE_MAC
  28230. if (module->resFileId != 0)
  28231. UseResFile (module->resFileId);
  28232. #endif
  28233. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28234. #if JUCE_MAC
  28235. module->resFileId = CurResFile();
  28236. #endif
  28237. --insideVSTCallback;
  28238. return result;
  28239. }
  28240. }
  28241. catch (...)
  28242. {
  28243. }
  28244. --insideVSTCallback;
  28245. return result;
  28246. }
  28247. // handles non plugin-specific callbacks..
  28248. static const int defaultVSTSampleRateValue = 16384;
  28249. static const int defaultVSTBlockSizeValue = 512;
  28250. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28251. {
  28252. (void) index;
  28253. (void) value;
  28254. (void) opt;
  28255. switch (opcode)
  28256. {
  28257. case audioMasterCanDo:
  28258. {
  28259. static const char* canDos[] = { "supplyIdle",
  28260. "sendVstEvents",
  28261. "sendVstMidiEvent",
  28262. "sendVstTimeInfo",
  28263. "receiveVstEvents",
  28264. "receiveVstMidiEvent",
  28265. "supportShell",
  28266. "shellCategory" };
  28267. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28268. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28269. return 1;
  28270. return 0;
  28271. }
  28272. case audioMasterVersion: return 0x2400;
  28273. case audioMasterCurrentId: return shellUIDToCreate;
  28274. case audioMasterGetNumAutomatableParameters: return 0;
  28275. case audioMasterGetAutomationState: return 1;
  28276. case audioMasterGetVendorVersion: return 0x0101;
  28277. case audioMasterGetVendorString:
  28278. case audioMasterGetProductString:
  28279. {
  28280. String hostName ("Juce VST Host");
  28281. if (JUCEApplication::getInstance() != 0)
  28282. hostName = JUCEApplication::getInstance()->getApplicationName();
  28283. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28284. break;
  28285. }
  28286. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28287. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28288. case audioMasterSetOutputSampleRate: return 0;
  28289. default:
  28290. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28291. break;
  28292. }
  28293. return 0;
  28294. }
  28295. // handles callbacks for a specific plugin
  28296. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28297. {
  28298. switch (opcode)
  28299. {
  28300. case audioMasterAutomate:
  28301. sendParamChangeMessageToListeners (index, opt);
  28302. break;
  28303. case audioMasterProcessEvents:
  28304. handleMidiFromPlugin ((const VstEvents*) ptr);
  28305. break;
  28306. case audioMasterGetTime:
  28307. #if JUCE_MSVC
  28308. #pragma warning (push)
  28309. #pragma warning (disable: 4311)
  28310. #endif
  28311. return (VstIntPtr) &vstHostTime;
  28312. #if JUCE_MSVC
  28313. #pragma warning (pop)
  28314. #endif
  28315. break;
  28316. case audioMasterIdle:
  28317. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28318. {
  28319. ++insideVSTCallback;
  28320. #if JUCE_MAC
  28321. if (getActiveEditor() != 0)
  28322. dispatch (effEditIdle, 0, 0, 0, 0);
  28323. #endif
  28324. juce_callAnyTimersSynchronously();
  28325. handleUpdateNowIfNeeded();
  28326. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28327. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28328. --insideVSTCallback;
  28329. }
  28330. break;
  28331. case audioMasterUpdateDisplay:
  28332. triggerAsyncUpdate();
  28333. break;
  28334. case audioMasterTempoAt:
  28335. // returns (10000 * bpm)
  28336. break;
  28337. case audioMasterNeedIdle:
  28338. startTimer (50);
  28339. break;
  28340. case audioMasterSizeWindow:
  28341. if (getActiveEditor() != 0)
  28342. getActiveEditor()->setSize (index, value);
  28343. return 1;
  28344. case audioMasterGetSampleRate:
  28345. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28346. case audioMasterGetBlockSize:
  28347. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28348. case audioMasterWantMidi:
  28349. wantsMidiMessages = true;
  28350. break;
  28351. case audioMasterGetDirectory:
  28352. #if JUCE_MAC
  28353. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28354. #else
  28355. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28356. #endif
  28357. case audioMasterGetAutomationState:
  28358. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28359. break;
  28360. // none of these are handled (yet)..
  28361. case audioMasterBeginEdit:
  28362. case audioMasterEndEdit:
  28363. case audioMasterSetTime:
  28364. case audioMasterPinConnected:
  28365. case audioMasterGetParameterQuantization:
  28366. case audioMasterIOChanged:
  28367. case audioMasterGetInputLatency:
  28368. case audioMasterGetOutputLatency:
  28369. case audioMasterGetPreviousPlug:
  28370. case audioMasterGetNextPlug:
  28371. case audioMasterWillReplaceOrAccumulate:
  28372. case audioMasterGetCurrentProcessLevel:
  28373. case audioMasterOfflineStart:
  28374. case audioMasterOfflineRead:
  28375. case audioMasterOfflineWrite:
  28376. case audioMasterOfflineGetCurrentPass:
  28377. case audioMasterOfflineGetCurrentMetaPass:
  28378. case audioMasterVendorSpecific:
  28379. case audioMasterSetIcon:
  28380. case audioMasterGetLanguage:
  28381. case audioMasterOpenWindow:
  28382. case audioMasterCloseWindow:
  28383. break;
  28384. default:
  28385. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28386. }
  28387. return 0;
  28388. }
  28389. // entry point for all callbacks from the plugin
  28390. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28391. {
  28392. try
  28393. {
  28394. if (effect != 0 && effect->resvd2 != 0)
  28395. {
  28396. return ((VSTPluginInstance*)(effect->resvd2))
  28397. ->handleCallback (opcode, index, value, ptr, opt);
  28398. }
  28399. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28400. }
  28401. catch (...)
  28402. {
  28403. return 0;
  28404. }
  28405. }
  28406. const String VSTPluginInstance::getVersion() const
  28407. {
  28408. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28409. String s;
  28410. if (v == 0 || v == -1)
  28411. v = getVersionNumber();
  28412. if (v != 0)
  28413. {
  28414. int versionBits[4];
  28415. int n = 0;
  28416. while (v != 0)
  28417. {
  28418. versionBits [n++] = (v & 0xff);
  28419. v >>= 8;
  28420. }
  28421. s << 'V';
  28422. while (n > 0)
  28423. {
  28424. s << versionBits [--n];
  28425. if (n > 0)
  28426. s << '.';
  28427. }
  28428. }
  28429. return s;
  28430. }
  28431. int VSTPluginInstance::getUID() const
  28432. {
  28433. int uid = effect != 0 ? effect->uniqueID : 0;
  28434. if (uid == 0)
  28435. uid = module->file.hashCode();
  28436. return uid;
  28437. }
  28438. const String VSTPluginInstance::getCategory() const
  28439. {
  28440. const char* result = 0;
  28441. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28442. {
  28443. case kPlugCategEffect: result = "Effect"; break;
  28444. case kPlugCategSynth: result = "Synth"; break;
  28445. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28446. case kPlugCategMastering: result = "Mastering"; break;
  28447. case kPlugCategSpacializer: result = "Spacial"; break;
  28448. case kPlugCategRoomFx: result = "Reverb"; break;
  28449. case kPlugSurroundFx: result = "Surround"; break;
  28450. case kPlugCategRestoration: result = "Restoration"; break;
  28451. case kPlugCategGenerator: result = "Tone generation"; break;
  28452. default: break;
  28453. }
  28454. return result;
  28455. }
  28456. float VSTPluginInstance::getParameter (int index)
  28457. {
  28458. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28459. {
  28460. try
  28461. {
  28462. const ScopedLock sl (lock);
  28463. return effect->getParameter (effect, index);
  28464. }
  28465. catch (...)
  28466. {
  28467. }
  28468. }
  28469. return 0.0f;
  28470. }
  28471. void VSTPluginInstance::setParameter (int index, float newValue)
  28472. {
  28473. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28474. {
  28475. try
  28476. {
  28477. const ScopedLock sl (lock);
  28478. if (effect->getParameter (effect, index) != newValue)
  28479. effect->setParameter (effect, index, newValue);
  28480. }
  28481. catch (...)
  28482. {
  28483. }
  28484. }
  28485. }
  28486. const String VSTPluginInstance::getParameterName (int index)
  28487. {
  28488. if (effect != 0)
  28489. {
  28490. jassert (index >= 0 && index < effect->numParams);
  28491. char nm [256];
  28492. zerostruct (nm);
  28493. dispatch (effGetParamName, index, 0, nm, 0);
  28494. return String (nm).trim();
  28495. }
  28496. return String::empty;
  28497. }
  28498. const String VSTPluginInstance::getParameterLabel (int index) const
  28499. {
  28500. if (effect != 0)
  28501. {
  28502. jassert (index >= 0 && index < effect->numParams);
  28503. char nm [256];
  28504. zerostruct (nm);
  28505. dispatch (effGetParamLabel, index, 0, nm, 0);
  28506. return String (nm).trim();
  28507. }
  28508. return String::empty;
  28509. }
  28510. const String VSTPluginInstance::getParameterText (int index)
  28511. {
  28512. if (effect != 0)
  28513. {
  28514. jassert (index >= 0 && index < effect->numParams);
  28515. char nm [256];
  28516. zerostruct (nm);
  28517. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28518. return String (nm).trim();
  28519. }
  28520. return String::empty;
  28521. }
  28522. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28523. {
  28524. if (effect != 0)
  28525. {
  28526. jassert (index >= 0 && index < effect->numParams);
  28527. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28528. }
  28529. return false;
  28530. }
  28531. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28532. {
  28533. dest.setSize (64 + 4 * getNumParameters());
  28534. dest.fillWith (0);
  28535. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28536. float* const p = (float*) (((char*) dest.getData()) + 64);
  28537. for (int i = 0; i < getNumParameters(); ++i)
  28538. p[i] = getParameter(i);
  28539. }
  28540. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28541. {
  28542. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28543. float* p = (float*) (((char*) m.getData()) + 64);
  28544. for (int i = 0; i < getNumParameters(); ++i)
  28545. setParameter (i, p[i]);
  28546. }
  28547. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28548. {
  28549. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28550. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28551. }
  28552. const String VSTPluginInstance::getProgramName (int index)
  28553. {
  28554. if (index == getCurrentProgram())
  28555. {
  28556. return getCurrentProgramName();
  28557. }
  28558. else if (effect != 0)
  28559. {
  28560. char nm [256];
  28561. zerostruct (nm);
  28562. if (dispatch (effGetProgramNameIndexed,
  28563. jlimit (0, getNumPrograms(), index),
  28564. -1, nm, 0) != 0)
  28565. {
  28566. return String (nm).trim();
  28567. }
  28568. }
  28569. return programNames [index];
  28570. }
  28571. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28572. {
  28573. if (index == getCurrentProgram())
  28574. {
  28575. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28576. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28577. }
  28578. else
  28579. {
  28580. jassertfalse; // xxx not implemented!
  28581. }
  28582. }
  28583. void VSTPluginInstance::updateStoredProgramNames()
  28584. {
  28585. if (effect != 0 && getNumPrograms() > 0)
  28586. {
  28587. char nm [256];
  28588. zerostruct (nm);
  28589. // only do this if the plugin can't use indexed names..
  28590. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28591. {
  28592. const int oldProgram = getCurrentProgram();
  28593. MemoryBlock oldSettings;
  28594. createTempParameterStore (oldSettings);
  28595. for (int i = 0; i < getNumPrograms(); ++i)
  28596. {
  28597. setCurrentProgram (i);
  28598. getCurrentProgramName(); // (this updates the list)
  28599. }
  28600. setCurrentProgram (oldProgram);
  28601. restoreFromTempParameterStore (oldSettings);
  28602. }
  28603. }
  28604. }
  28605. const String VSTPluginInstance::getCurrentProgramName()
  28606. {
  28607. if (effect != 0)
  28608. {
  28609. char nm [256];
  28610. zerostruct (nm);
  28611. dispatch (effGetProgramName, 0, 0, nm, 0);
  28612. const int index = getCurrentProgram();
  28613. if (programNames[index].isEmpty())
  28614. {
  28615. while (programNames.size() < index)
  28616. programNames.add (String::empty);
  28617. programNames.set (index, String (nm).trim());
  28618. }
  28619. return String (nm).trim();
  28620. }
  28621. return String::empty;
  28622. }
  28623. const String VSTPluginInstance::getInputChannelName (int index) const
  28624. {
  28625. if (index >= 0 && index < getNumInputChannels())
  28626. {
  28627. VstPinProperties pinProps;
  28628. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28629. return String (pinProps.label, sizeof (pinProps.label));
  28630. }
  28631. return String::empty;
  28632. }
  28633. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28634. {
  28635. if (index < 0 || index >= getNumInputChannels())
  28636. return false;
  28637. VstPinProperties pinProps;
  28638. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28639. return (pinProps.flags & kVstPinIsStereo) != 0;
  28640. return true;
  28641. }
  28642. const String VSTPluginInstance::getOutputChannelName (int index) const
  28643. {
  28644. if (index >= 0 && index < getNumOutputChannels())
  28645. {
  28646. VstPinProperties pinProps;
  28647. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28648. return String (pinProps.label, sizeof (pinProps.label));
  28649. }
  28650. return String::empty;
  28651. }
  28652. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28653. {
  28654. if (index < 0 || index >= getNumOutputChannels())
  28655. return false;
  28656. VstPinProperties pinProps;
  28657. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28658. return (pinProps.flags & kVstPinIsStereo) != 0;
  28659. return true;
  28660. }
  28661. void VSTPluginInstance::setPower (const bool on)
  28662. {
  28663. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28664. isPowerOn = on;
  28665. }
  28666. const int defaultMaxSizeMB = 64;
  28667. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28668. {
  28669. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28670. }
  28671. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28672. {
  28673. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28674. }
  28675. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28676. {
  28677. loadFromFXBFile (data, sizeInBytes);
  28678. }
  28679. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28680. {
  28681. loadFromFXBFile (data, sizeInBytes);
  28682. }
  28683. VSTPluginFormat::VSTPluginFormat()
  28684. {
  28685. }
  28686. VSTPluginFormat::~VSTPluginFormat()
  28687. {
  28688. }
  28689. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28690. const String& fileOrIdentifier)
  28691. {
  28692. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28693. return;
  28694. PluginDescription desc;
  28695. desc.fileOrIdentifier = fileOrIdentifier;
  28696. desc.uid = 0;
  28697. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28698. if (instance == 0)
  28699. return;
  28700. try
  28701. {
  28702. #if JUCE_MAC
  28703. if (instance->module->resFileId != 0)
  28704. UseResFile (instance->module->resFileId);
  28705. #endif
  28706. instance->fillInPluginDescription (desc);
  28707. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28708. if (category != kPlugCategShell)
  28709. {
  28710. // Normal plugin...
  28711. results.add (new PluginDescription (desc));
  28712. ++insideVSTCallback;
  28713. instance->dispatch (effOpen, 0, 0, 0, 0);
  28714. --insideVSTCallback;
  28715. }
  28716. else
  28717. {
  28718. // It's a shell plugin, so iterate all the subtypes...
  28719. char shellEffectName [64];
  28720. for (;;)
  28721. {
  28722. zerostruct (shellEffectName);
  28723. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28724. if (uid == 0)
  28725. {
  28726. break;
  28727. }
  28728. else
  28729. {
  28730. desc.uid = uid;
  28731. desc.name = shellEffectName;
  28732. bool alreadyThere = false;
  28733. for (int i = results.size(); --i >= 0;)
  28734. {
  28735. PluginDescription* const d = results.getUnchecked(i);
  28736. if (d->isDuplicateOf (desc))
  28737. {
  28738. alreadyThere = true;
  28739. break;
  28740. }
  28741. }
  28742. if (! alreadyThere)
  28743. results.add (new PluginDescription (desc));
  28744. }
  28745. }
  28746. }
  28747. }
  28748. catch (...)
  28749. {
  28750. // crashed while loading...
  28751. }
  28752. }
  28753. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28754. {
  28755. ScopedPointer <VSTPluginInstance> result;
  28756. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28757. {
  28758. File file (desc.fileOrIdentifier);
  28759. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28760. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28761. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28762. if (module != 0)
  28763. {
  28764. shellUIDToCreate = desc.uid;
  28765. result = new VSTPluginInstance (module);
  28766. if (result->effect != 0)
  28767. {
  28768. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28769. result->initialise();
  28770. }
  28771. else
  28772. {
  28773. result = 0;
  28774. }
  28775. }
  28776. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28777. }
  28778. return result.release();
  28779. }
  28780. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28781. {
  28782. const File f (fileOrIdentifier);
  28783. #if JUCE_MAC
  28784. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28785. return true;
  28786. #if JUCE_PPC
  28787. FSRef fileRef;
  28788. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28789. {
  28790. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28791. if (resFileId != -1)
  28792. {
  28793. const int numEffects = Count1Resources ('aEff');
  28794. CloseResFile (resFileId);
  28795. if (numEffects > 0)
  28796. return true;
  28797. }
  28798. }
  28799. #endif
  28800. return false;
  28801. #elif JUCE_WINDOWS
  28802. return f.existsAsFile() && f.hasFileExtension (".dll");
  28803. #elif JUCE_LINUX
  28804. return f.existsAsFile() && f.hasFileExtension (".so");
  28805. #endif
  28806. }
  28807. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28808. {
  28809. return fileOrIdentifier;
  28810. }
  28811. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28812. {
  28813. return File (desc.fileOrIdentifier).exists();
  28814. }
  28815. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28816. {
  28817. StringArray results;
  28818. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28819. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28820. return results;
  28821. }
  28822. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28823. {
  28824. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28825. // .component or .vst directories.
  28826. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28827. while (iter.next())
  28828. {
  28829. const File f (iter.getFile());
  28830. bool isPlugin = false;
  28831. if (fileMightContainThisPluginType (f.getFullPathName()))
  28832. {
  28833. isPlugin = true;
  28834. results.add (f.getFullPathName());
  28835. }
  28836. if (recursive && (! isPlugin) && f.isDirectory())
  28837. recursiveFileSearch (results, f, true);
  28838. }
  28839. }
  28840. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28841. {
  28842. #if JUCE_MAC
  28843. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28844. #elif JUCE_WINDOWS
  28845. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28846. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28847. #elif JUCE_LINUX
  28848. return FileSearchPath ("/usr/lib/vst");
  28849. #endif
  28850. }
  28851. END_JUCE_NAMESPACE
  28852. #endif
  28853. #undef log
  28854. #endif
  28855. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28856. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28857. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28858. BEGIN_JUCE_NAMESPACE
  28859. AudioProcessor::AudioProcessor()
  28860. : playHead (0),
  28861. activeEditor (0),
  28862. sampleRate (0),
  28863. blockSize (0),
  28864. numInputChannels (0),
  28865. numOutputChannels (0),
  28866. latencySamples (0),
  28867. suspended (false),
  28868. nonRealtime (false)
  28869. {
  28870. }
  28871. AudioProcessor::~AudioProcessor()
  28872. {
  28873. // ooh, nasty - the editor should have been deleted before the filter
  28874. // that it refers to is deleted..
  28875. jassert (activeEditor == 0);
  28876. #if JUCE_DEBUG
  28877. // This will fail if you've called beginParameterChangeGesture() for one
  28878. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28879. jassert (changingParams.countNumberOfSetBits() == 0);
  28880. #endif
  28881. }
  28882. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28883. {
  28884. playHead = newPlayHead;
  28885. }
  28886. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28887. {
  28888. const ScopedLock sl (listenerLock);
  28889. listeners.addIfNotAlreadyThere (newListener);
  28890. }
  28891. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28892. {
  28893. const ScopedLock sl (listenerLock);
  28894. listeners.removeValue (listenerToRemove);
  28895. }
  28896. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28897. const int numOuts,
  28898. const double sampleRate_,
  28899. const int blockSize_) throw()
  28900. {
  28901. numInputChannels = numIns;
  28902. numOutputChannels = numOuts;
  28903. sampleRate = sampleRate_;
  28904. blockSize = blockSize_;
  28905. }
  28906. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28907. {
  28908. nonRealtime = nonRealtime_;
  28909. }
  28910. void AudioProcessor::setLatencySamples (const int newLatency)
  28911. {
  28912. if (latencySamples != newLatency)
  28913. {
  28914. latencySamples = newLatency;
  28915. updateHostDisplay();
  28916. }
  28917. }
  28918. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28919. const float newValue)
  28920. {
  28921. setParameter (parameterIndex, newValue);
  28922. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28923. }
  28924. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28925. {
  28926. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28927. for (int i = listeners.size(); --i >= 0;)
  28928. {
  28929. AudioProcessorListener* l;
  28930. {
  28931. const ScopedLock sl (listenerLock);
  28932. l = listeners [i];
  28933. }
  28934. if (l != 0)
  28935. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28936. }
  28937. }
  28938. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28939. {
  28940. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28941. #if JUCE_DEBUG
  28942. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28943. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28944. jassert (! changingParams [parameterIndex]);
  28945. changingParams.setBit (parameterIndex);
  28946. #endif
  28947. for (int i = listeners.size(); --i >= 0;)
  28948. {
  28949. AudioProcessorListener* l;
  28950. {
  28951. const ScopedLock sl (listenerLock);
  28952. l = listeners [i];
  28953. }
  28954. if (l != 0)
  28955. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28956. }
  28957. }
  28958. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28959. {
  28960. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28961. #if JUCE_DEBUG
  28962. // This means you've called endParameterChangeGesture without having previously called
  28963. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28964. // calls matched correctly.
  28965. jassert (changingParams [parameterIndex]);
  28966. changingParams.clearBit (parameterIndex);
  28967. #endif
  28968. for (int i = listeners.size(); --i >= 0;)
  28969. {
  28970. AudioProcessorListener* l;
  28971. {
  28972. const ScopedLock sl (listenerLock);
  28973. l = listeners [i];
  28974. }
  28975. if (l != 0)
  28976. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28977. }
  28978. }
  28979. void AudioProcessor::updateHostDisplay()
  28980. {
  28981. for (int i = listeners.size(); --i >= 0;)
  28982. {
  28983. AudioProcessorListener* l;
  28984. {
  28985. const ScopedLock sl (listenerLock);
  28986. l = listeners [i];
  28987. }
  28988. if (l != 0)
  28989. l->audioProcessorChanged (this);
  28990. }
  28991. }
  28992. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28993. {
  28994. return true;
  28995. }
  28996. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28997. {
  28998. return false;
  28999. }
  29000. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  29001. {
  29002. const ScopedLock sl (callbackLock);
  29003. suspended = shouldBeSuspended;
  29004. }
  29005. void AudioProcessor::reset()
  29006. {
  29007. }
  29008. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  29009. {
  29010. const ScopedLock sl (callbackLock);
  29011. jassert (activeEditor == editor);
  29012. if (activeEditor == editor)
  29013. activeEditor = 0;
  29014. }
  29015. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  29016. {
  29017. if (activeEditor != 0)
  29018. return activeEditor;
  29019. AudioProcessorEditor* const ed = createEditor();
  29020. if (ed != 0)
  29021. {
  29022. // you must give your editor comp a size before returning it..
  29023. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  29024. const ScopedLock sl (callbackLock);
  29025. activeEditor = ed;
  29026. }
  29027. return ed;
  29028. }
  29029. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  29030. {
  29031. getStateInformation (destData);
  29032. }
  29033. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  29034. {
  29035. setStateInformation (data, sizeInBytes);
  29036. }
  29037. // magic number to identify memory blocks that we've stored as XML
  29038. const uint32 magicXmlNumber = 0x21324356;
  29039. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  29040. JUCE_NAMESPACE::MemoryBlock& destData)
  29041. {
  29042. const String xmlString (xml.createDocument (String::empty, true, false));
  29043. const int stringLength = xmlString.getNumBytesAsUTF8();
  29044. destData.setSize (stringLength + 10);
  29045. char* const d = static_cast<char*> (destData.getData());
  29046. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  29047. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  29048. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  29049. }
  29050. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  29051. const int sizeInBytes)
  29052. {
  29053. if (sizeInBytes > 8
  29054. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  29055. {
  29056. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  29057. if (stringLength > 0)
  29058. {
  29059. XmlDocument doc (String::fromUTF8 (static_cast<const char*> (data) + 8,
  29060. jmin ((sizeInBytes - 8), stringLength)));
  29061. return doc.getDocumentElement();
  29062. }
  29063. }
  29064. return 0;
  29065. }
  29066. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  29067. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  29068. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  29069. {
  29070. return timeInSeconds == other.timeInSeconds
  29071. && ppqPosition == other.ppqPosition
  29072. && editOriginTime == other.editOriginTime
  29073. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  29074. && frameRate == other.frameRate
  29075. && isPlaying == other.isPlaying
  29076. && isRecording == other.isRecording
  29077. && bpm == other.bpm
  29078. && timeSigNumerator == other.timeSigNumerator
  29079. && timeSigDenominator == other.timeSigDenominator;
  29080. }
  29081. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  29082. {
  29083. return ! operator== (other);
  29084. }
  29085. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  29086. {
  29087. zerostruct (*this);
  29088. timeSigNumerator = 4;
  29089. timeSigDenominator = 4;
  29090. bpm = 120;
  29091. }
  29092. END_JUCE_NAMESPACE
  29093. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  29094. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  29095. BEGIN_JUCE_NAMESPACE
  29096. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  29097. : owner (owner_)
  29098. {
  29099. // the filter must be valid..
  29100. jassert (owner != 0);
  29101. }
  29102. AudioProcessorEditor::~AudioProcessorEditor()
  29103. {
  29104. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  29105. // filter for some reason..
  29106. jassert (owner->getActiveEditor() != this);
  29107. }
  29108. END_JUCE_NAMESPACE
  29109. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  29110. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  29111. BEGIN_JUCE_NAMESPACE
  29112. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  29113. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  29114. : id (id_),
  29115. processor (processor_),
  29116. isPrepared (false)
  29117. {
  29118. jassert (processor_ != 0);
  29119. }
  29120. AudioProcessorGraph::Node::~Node()
  29121. {
  29122. }
  29123. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  29124. AudioProcessorGraph* const graph)
  29125. {
  29126. if (! isPrepared)
  29127. {
  29128. isPrepared = true;
  29129. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29130. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  29131. if (ioProc != 0)
  29132. ioProc->setParentGraph (graph);
  29133. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  29134. processor->getNumOutputChannels(),
  29135. sampleRate, blockSize);
  29136. processor->prepareToPlay (sampleRate, blockSize);
  29137. }
  29138. }
  29139. void AudioProcessorGraph::Node::unprepare()
  29140. {
  29141. if (isPrepared)
  29142. {
  29143. isPrepared = false;
  29144. processor->releaseResources();
  29145. }
  29146. }
  29147. AudioProcessorGraph::AudioProcessorGraph()
  29148. : lastNodeId (0),
  29149. renderingBuffers (1, 1),
  29150. currentAudioOutputBuffer (1, 1)
  29151. {
  29152. }
  29153. AudioProcessorGraph::~AudioProcessorGraph()
  29154. {
  29155. clearRenderingSequence();
  29156. clear();
  29157. }
  29158. const String AudioProcessorGraph::getName() const
  29159. {
  29160. return "Audio Graph";
  29161. }
  29162. void AudioProcessorGraph::clear()
  29163. {
  29164. nodes.clear();
  29165. connections.clear();
  29166. triggerAsyncUpdate();
  29167. }
  29168. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29169. {
  29170. for (int i = nodes.size(); --i >= 0;)
  29171. if (nodes.getUnchecked(i)->id == nodeId)
  29172. return nodes.getUnchecked(i);
  29173. return 0;
  29174. }
  29175. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29176. uint32 nodeId)
  29177. {
  29178. if (newProcessor == 0)
  29179. {
  29180. jassertfalse;
  29181. return 0;
  29182. }
  29183. if (nodeId == 0)
  29184. {
  29185. nodeId = ++lastNodeId;
  29186. }
  29187. else
  29188. {
  29189. // you can't add a node with an id that already exists in the graph..
  29190. jassert (getNodeForId (nodeId) == 0);
  29191. removeNode (nodeId);
  29192. }
  29193. lastNodeId = nodeId;
  29194. Node* const n = new Node (nodeId, newProcessor);
  29195. nodes.add (n);
  29196. triggerAsyncUpdate();
  29197. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29198. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29199. if (ioProc != 0)
  29200. ioProc->setParentGraph (this);
  29201. return n;
  29202. }
  29203. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29204. {
  29205. disconnectNode (nodeId);
  29206. for (int i = nodes.size(); --i >= 0;)
  29207. {
  29208. if (nodes.getUnchecked(i)->id == nodeId)
  29209. {
  29210. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29211. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29212. if (ioProc != 0)
  29213. ioProc->setParentGraph (0);
  29214. nodes.remove (i);
  29215. triggerAsyncUpdate();
  29216. return true;
  29217. }
  29218. }
  29219. return false;
  29220. }
  29221. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29222. const int sourceChannelIndex,
  29223. const uint32 destNodeId,
  29224. const int destChannelIndex) const
  29225. {
  29226. for (int i = connections.size(); --i >= 0;)
  29227. {
  29228. const Connection* const c = connections.getUnchecked(i);
  29229. if (c->sourceNodeId == sourceNodeId
  29230. && c->destNodeId == destNodeId
  29231. && c->sourceChannelIndex == sourceChannelIndex
  29232. && c->destChannelIndex == destChannelIndex)
  29233. {
  29234. return c;
  29235. }
  29236. }
  29237. return 0;
  29238. }
  29239. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29240. const uint32 possibleDestNodeId) const
  29241. {
  29242. for (int i = connections.size(); --i >= 0;)
  29243. {
  29244. const Connection* const c = connections.getUnchecked(i);
  29245. if (c->sourceNodeId == possibleSourceNodeId
  29246. && c->destNodeId == possibleDestNodeId)
  29247. {
  29248. return true;
  29249. }
  29250. }
  29251. return false;
  29252. }
  29253. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29254. const int sourceChannelIndex,
  29255. const uint32 destNodeId,
  29256. const int destChannelIndex) const
  29257. {
  29258. if (sourceChannelIndex < 0
  29259. || destChannelIndex < 0
  29260. || sourceNodeId == destNodeId
  29261. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29262. return false;
  29263. const Node* const source = getNodeForId (sourceNodeId);
  29264. if (source == 0
  29265. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29266. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29267. return false;
  29268. const Node* const dest = getNodeForId (destNodeId);
  29269. if (dest == 0
  29270. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29271. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29272. return false;
  29273. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29274. destNodeId, destChannelIndex) == 0;
  29275. }
  29276. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29277. const int sourceChannelIndex,
  29278. const uint32 destNodeId,
  29279. const int destChannelIndex)
  29280. {
  29281. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29282. return false;
  29283. Connection* const c = new Connection();
  29284. c->sourceNodeId = sourceNodeId;
  29285. c->sourceChannelIndex = sourceChannelIndex;
  29286. c->destNodeId = destNodeId;
  29287. c->destChannelIndex = destChannelIndex;
  29288. connections.add (c);
  29289. triggerAsyncUpdate();
  29290. return true;
  29291. }
  29292. void AudioProcessorGraph::removeConnection (const int index)
  29293. {
  29294. connections.remove (index);
  29295. triggerAsyncUpdate();
  29296. }
  29297. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29298. const uint32 destNodeId, const int destChannelIndex)
  29299. {
  29300. bool doneAnything = false;
  29301. for (int i = connections.size(); --i >= 0;)
  29302. {
  29303. const Connection* const c = connections.getUnchecked(i);
  29304. if (c->sourceNodeId == sourceNodeId
  29305. && c->destNodeId == destNodeId
  29306. && c->sourceChannelIndex == sourceChannelIndex
  29307. && c->destChannelIndex == destChannelIndex)
  29308. {
  29309. removeConnection (i);
  29310. doneAnything = true;
  29311. triggerAsyncUpdate();
  29312. }
  29313. }
  29314. return doneAnything;
  29315. }
  29316. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29317. {
  29318. bool doneAnything = false;
  29319. for (int i = connections.size(); --i >= 0;)
  29320. {
  29321. const Connection* const c = connections.getUnchecked(i);
  29322. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29323. {
  29324. removeConnection (i);
  29325. doneAnything = true;
  29326. triggerAsyncUpdate();
  29327. }
  29328. }
  29329. return doneAnything;
  29330. }
  29331. bool AudioProcessorGraph::removeIllegalConnections()
  29332. {
  29333. bool doneAnything = false;
  29334. for (int i = connections.size(); --i >= 0;)
  29335. {
  29336. const Connection* const c = connections.getUnchecked(i);
  29337. const Node* const source = getNodeForId (c->sourceNodeId);
  29338. const Node* const dest = getNodeForId (c->destNodeId);
  29339. if (source == 0 || dest == 0
  29340. || (c->sourceChannelIndex != midiChannelIndex
  29341. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29342. || (c->sourceChannelIndex == midiChannelIndex
  29343. && ! source->processor->producesMidi())
  29344. || (c->destChannelIndex != midiChannelIndex
  29345. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29346. || (c->destChannelIndex == midiChannelIndex
  29347. && ! dest->processor->acceptsMidi()))
  29348. {
  29349. removeConnection (i);
  29350. doneAnything = true;
  29351. triggerAsyncUpdate();
  29352. }
  29353. }
  29354. return doneAnything;
  29355. }
  29356. namespace GraphRenderingOps
  29357. {
  29358. class AudioGraphRenderingOp
  29359. {
  29360. public:
  29361. AudioGraphRenderingOp() {}
  29362. virtual ~AudioGraphRenderingOp() {}
  29363. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29364. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29365. const int numSamples) = 0;
  29366. juce_UseDebuggingNewOperator
  29367. };
  29368. class ClearChannelOp : public AudioGraphRenderingOp
  29369. {
  29370. public:
  29371. ClearChannelOp (const int channelNum_)
  29372. : channelNum (channelNum_)
  29373. {}
  29374. ~ClearChannelOp() {}
  29375. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29376. {
  29377. sharedBufferChans.clear (channelNum, 0, numSamples);
  29378. }
  29379. private:
  29380. const int channelNum;
  29381. ClearChannelOp (const ClearChannelOp&);
  29382. ClearChannelOp& operator= (const ClearChannelOp&);
  29383. };
  29384. class CopyChannelOp : public AudioGraphRenderingOp
  29385. {
  29386. public:
  29387. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29388. : srcChannelNum (srcChannelNum_),
  29389. dstChannelNum (dstChannelNum_)
  29390. {}
  29391. ~CopyChannelOp() {}
  29392. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29393. {
  29394. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29395. }
  29396. private:
  29397. const int srcChannelNum, dstChannelNum;
  29398. CopyChannelOp (const CopyChannelOp&);
  29399. CopyChannelOp& operator= (const CopyChannelOp&);
  29400. };
  29401. class AddChannelOp : public AudioGraphRenderingOp
  29402. {
  29403. public:
  29404. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29405. : srcChannelNum (srcChannelNum_),
  29406. dstChannelNum (dstChannelNum_)
  29407. {}
  29408. ~AddChannelOp() {}
  29409. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29410. {
  29411. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29412. }
  29413. private:
  29414. const int srcChannelNum, dstChannelNum;
  29415. AddChannelOp (const AddChannelOp&);
  29416. AddChannelOp& operator= (const AddChannelOp&);
  29417. };
  29418. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29419. {
  29420. public:
  29421. ClearMidiBufferOp (const int bufferNum_)
  29422. : bufferNum (bufferNum_)
  29423. {}
  29424. ~ClearMidiBufferOp() {}
  29425. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29426. {
  29427. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29428. }
  29429. private:
  29430. const int bufferNum;
  29431. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29432. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29433. };
  29434. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29435. {
  29436. public:
  29437. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29438. : srcBufferNum (srcBufferNum_),
  29439. dstBufferNum (dstBufferNum_)
  29440. {}
  29441. ~CopyMidiBufferOp() {}
  29442. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29443. {
  29444. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29445. }
  29446. private:
  29447. const int srcBufferNum, dstBufferNum;
  29448. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29449. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29450. };
  29451. class AddMidiBufferOp : public AudioGraphRenderingOp
  29452. {
  29453. public:
  29454. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29455. : srcBufferNum (srcBufferNum_),
  29456. dstBufferNum (dstBufferNum_)
  29457. {}
  29458. ~AddMidiBufferOp() {}
  29459. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29460. {
  29461. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29462. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29463. }
  29464. private:
  29465. const int srcBufferNum, dstBufferNum;
  29466. AddMidiBufferOp (const AddMidiBufferOp&);
  29467. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29468. };
  29469. class ProcessBufferOp : public AudioGraphRenderingOp
  29470. {
  29471. public:
  29472. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29473. const Array <int>& audioChannelsToUse_,
  29474. const int totalChans_,
  29475. const int midiBufferToUse_)
  29476. : node (node_),
  29477. processor (node_->getProcessor()),
  29478. audioChannelsToUse (audioChannelsToUse_),
  29479. totalChans (jmax (1, totalChans_)),
  29480. midiBufferToUse (midiBufferToUse_)
  29481. {
  29482. channels.calloc (totalChans);
  29483. while (audioChannelsToUse.size() < totalChans)
  29484. audioChannelsToUse.add (0);
  29485. }
  29486. ~ProcessBufferOp()
  29487. {
  29488. }
  29489. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29490. {
  29491. for (int i = totalChans; --i >= 0;)
  29492. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29493. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29494. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29495. }
  29496. const AudioProcessorGraph::Node::Ptr node;
  29497. AudioProcessor* const processor;
  29498. private:
  29499. Array <int> audioChannelsToUse;
  29500. HeapBlock <float*> channels;
  29501. int totalChans;
  29502. int midiBufferToUse;
  29503. ProcessBufferOp (const ProcessBufferOp&);
  29504. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29505. };
  29506. /** Used to calculate the correct sequence of rendering ops needed, based on
  29507. the best re-use of shared buffers at each stage.
  29508. */
  29509. class RenderingOpSequenceCalculator
  29510. {
  29511. public:
  29512. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29513. const Array<void*>& orderedNodes_,
  29514. Array<void*>& renderingOps)
  29515. : graph (graph_),
  29516. orderedNodes (orderedNodes_)
  29517. {
  29518. nodeIds.add (-2); // first buffer is read-only zeros
  29519. channels.add (0);
  29520. midiNodeIds.add (-2);
  29521. for (int i = 0; i < orderedNodes.size(); ++i)
  29522. {
  29523. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29524. renderingOps, i);
  29525. markAnyUnusedBuffersAsFree (i);
  29526. }
  29527. }
  29528. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29529. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29530. juce_UseDebuggingNewOperator
  29531. private:
  29532. AudioProcessorGraph& graph;
  29533. const Array<void*>& orderedNodes;
  29534. Array <int> nodeIds, channels, midiNodeIds;
  29535. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29536. Array<void*>& renderingOps,
  29537. const int ourRenderingIndex)
  29538. {
  29539. const int numIns = node->getProcessor()->getNumInputChannels();
  29540. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29541. const int totalChans = jmax (numIns, numOuts);
  29542. Array <int> audioChannelsToUse;
  29543. int midiBufferToUse = -1;
  29544. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29545. {
  29546. // get a list of all the inputs to this node
  29547. Array <int> sourceNodes, sourceOutputChans;
  29548. for (int i = graph.getNumConnections(); --i >= 0;)
  29549. {
  29550. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29551. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29552. {
  29553. sourceNodes.add (c->sourceNodeId);
  29554. sourceOutputChans.add (c->sourceChannelIndex);
  29555. }
  29556. }
  29557. int bufIndex = -1;
  29558. if (sourceNodes.size() == 0)
  29559. {
  29560. // unconnected input channel
  29561. if (inputChan >= numOuts)
  29562. {
  29563. bufIndex = getReadOnlyEmptyBuffer();
  29564. jassert (bufIndex >= 0);
  29565. }
  29566. else
  29567. {
  29568. bufIndex = getFreeBuffer (false);
  29569. renderingOps.add (new ClearChannelOp (bufIndex));
  29570. }
  29571. }
  29572. else if (sourceNodes.size() == 1)
  29573. {
  29574. // channel with a straightforward single input..
  29575. const int srcNode = sourceNodes.getUnchecked(0);
  29576. const int srcChan = sourceOutputChans.getUnchecked(0);
  29577. bufIndex = getBufferContaining (srcNode, srcChan);
  29578. if (bufIndex < 0)
  29579. {
  29580. // if not found, this is probably a feedback loop
  29581. bufIndex = getReadOnlyEmptyBuffer();
  29582. jassert (bufIndex >= 0);
  29583. }
  29584. if (inputChan < numOuts
  29585. && isBufferNeededLater (ourRenderingIndex,
  29586. inputChan,
  29587. srcNode, srcChan))
  29588. {
  29589. // can't mess up this channel because it's needed later by another node, so we
  29590. // need to use a copy of it..
  29591. const int newFreeBuffer = getFreeBuffer (false);
  29592. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29593. bufIndex = newFreeBuffer;
  29594. }
  29595. }
  29596. else
  29597. {
  29598. // channel with a mix of several inputs..
  29599. // try to find a re-usable channel from our inputs..
  29600. int reusableInputIndex = -1;
  29601. for (int i = 0; i < sourceNodes.size(); ++i)
  29602. {
  29603. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29604. sourceOutputChans.getUnchecked(i));
  29605. if (sourceBufIndex >= 0
  29606. && ! isBufferNeededLater (ourRenderingIndex,
  29607. inputChan,
  29608. sourceNodes.getUnchecked(i),
  29609. sourceOutputChans.getUnchecked(i)))
  29610. {
  29611. // we've found one of our input chans that can be re-used..
  29612. reusableInputIndex = i;
  29613. bufIndex = sourceBufIndex;
  29614. break;
  29615. }
  29616. }
  29617. if (reusableInputIndex < 0)
  29618. {
  29619. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29620. bufIndex = getFreeBuffer (false);
  29621. jassert (bufIndex != 0);
  29622. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29623. sourceOutputChans.getUnchecked (0));
  29624. if (srcIndex < 0)
  29625. {
  29626. // if not found, this is probably a feedback loop
  29627. renderingOps.add (new ClearChannelOp (bufIndex));
  29628. }
  29629. else
  29630. {
  29631. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29632. }
  29633. reusableInputIndex = 0;
  29634. }
  29635. for (int j = 0; j < sourceNodes.size(); ++j)
  29636. {
  29637. if (j != reusableInputIndex)
  29638. {
  29639. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29640. sourceOutputChans.getUnchecked(j));
  29641. if (srcIndex >= 0)
  29642. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29643. }
  29644. }
  29645. }
  29646. jassert (bufIndex >= 0);
  29647. audioChannelsToUse.add (bufIndex);
  29648. if (inputChan < numOuts)
  29649. markBufferAsContaining (bufIndex, node->id, inputChan);
  29650. }
  29651. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29652. {
  29653. const int bufIndex = getFreeBuffer (false);
  29654. jassert (bufIndex != 0);
  29655. audioChannelsToUse.add (bufIndex);
  29656. markBufferAsContaining (bufIndex, node->id, outputChan);
  29657. }
  29658. // Now the same thing for midi..
  29659. Array <int> midiSourceNodes;
  29660. for (int i = graph.getNumConnections(); --i >= 0;)
  29661. {
  29662. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29663. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29664. midiSourceNodes.add (c->sourceNodeId);
  29665. }
  29666. if (midiSourceNodes.size() == 0)
  29667. {
  29668. // No midi inputs..
  29669. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29670. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29671. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29672. }
  29673. else if (midiSourceNodes.size() == 1)
  29674. {
  29675. // One midi input..
  29676. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29677. AudioProcessorGraph::midiChannelIndex);
  29678. if (midiBufferToUse >= 0)
  29679. {
  29680. if (isBufferNeededLater (ourRenderingIndex,
  29681. AudioProcessorGraph::midiChannelIndex,
  29682. midiSourceNodes.getUnchecked(0),
  29683. AudioProcessorGraph::midiChannelIndex))
  29684. {
  29685. // can't mess up this channel because it's needed later by another node, so we
  29686. // need to use a copy of it..
  29687. const int newFreeBuffer = getFreeBuffer (true);
  29688. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29689. midiBufferToUse = newFreeBuffer;
  29690. }
  29691. }
  29692. else
  29693. {
  29694. // probably a feedback loop, so just use an empty one..
  29695. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29696. }
  29697. }
  29698. else
  29699. {
  29700. // More than one midi input being mixed..
  29701. int reusableInputIndex = -1;
  29702. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29703. {
  29704. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29705. AudioProcessorGraph::midiChannelIndex);
  29706. if (sourceBufIndex >= 0
  29707. && ! isBufferNeededLater (ourRenderingIndex,
  29708. AudioProcessorGraph::midiChannelIndex,
  29709. midiSourceNodes.getUnchecked(i),
  29710. AudioProcessorGraph::midiChannelIndex))
  29711. {
  29712. // we've found one of our input buffers that can be re-used..
  29713. reusableInputIndex = i;
  29714. midiBufferToUse = sourceBufIndex;
  29715. break;
  29716. }
  29717. }
  29718. if (reusableInputIndex < 0)
  29719. {
  29720. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29721. midiBufferToUse = getFreeBuffer (true);
  29722. jassert (midiBufferToUse >= 0);
  29723. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29724. AudioProcessorGraph::midiChannelIndex);
  29725. if (srcIndex >= 0)
  29726. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29727. else
  29728. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29729. reusableInputIndex = 0;
  29730. }
  29731. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29732. {
  29733. if (j != reusableInputIndex)
  29734. {
  29735. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29736. AudioProcessorGraph::midiChannelIndex);
  29737. if (srcIndex >= 0)
  29738. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29739. }
  29740. }
  29741. }
  29742. if (node->getProcessor()->producesMidi())
  29743. markBufferAsContaining (midiBufferToUse, node->id,
  29744. AudioProcessorGraph::midiChannelIndex);
  29745. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29746. totalChans, midiBufferToUse));
  29747. }
  29748. int getFreeBuffer (const bool forMidi)
  29749. {
  29750. if (forMidi)
  29751. {
  29752. for (int i = 1; i < midiNodeIds.size(); ++i)
  29753. if (midiNodeIds.getUnchecked(i) < 0)
  29754. return i;
  29755. midiNodeIds.add (-1);
  29756. return midiNodeIds.size() - 1;
  29757. }
  29758. else
  29759. {
  29760. for (int i = 1; i < nodeIds.size(); ++i)
  29761. if (nodeIds.getUnchecked(i) < 0)
  29762. return i;
  29763. nodeIds.add (-1);
  29764. channels.add (0);
  29765. return nodeIds.size() - 1;
  29766. }
  29767. }
  29768. int getReadOnlyEmptyBuffer() const
  29769. {
  29770. return 0;
  29771. }
  29772. int getBufferContaining (const int nodeId, const int outputChannel) const
  29773. {
  29774. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29775. {
  29776. for (int i = midiNodeIds.size(); --i >= 0;)
  29777. if (midiNodeIds.getUnchecked(i) == nodeId)
  29778. return i;
  29779. }
  29780. else
  29781. {
  29782. for (int i = nodeIds.size(); --i >= 0;)
  29783. if (nodeIds.getUnchecked(i) == nodeId
  29784. && channels.getUnchecked(i) == outputChannel)
  29785. return i;
  29786. }
  29787. return -1;
  29788. }
  29789. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29790. {
  29791. int i;
  29792. for (i = 0; i < nodeIds.size(); ++i)
  29793. {
  29794. if (nodeIds.getUnchecked(i) >= 0
  29795. && ! isBufferNeededLater (stepIndex, -1,
  29796. nodeIds.getUnchecked(i),
  29797. channels.getUnchecked(i)))
  29798. {
  29799. nodeIds.set (i, -1);
  29800. }
  29801. }
  29802. for (i = 0; i < midiNodeIds.size(); ++i)
  29803. {
  29804. if (midiNodeIds.getUnchecked(i) >= 0
  29805. && ! isBufferNeededLater (stepIndex, -1,
  29806. midiNodeIds.getUnchecked(i),
  29807. AudioProcessorGraph::midiChannelIndex))
  29808. {
  29809. midiNodeIds.set (i, -1);
  29810. }
  29811. }
  29812. }
  29813. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29814. int inputChannelOfIndexToIgnore,
  29815. const int nodeId,
  29816. const int outputChanIndex) const
  29817. {
  29818. while (stepIndexToSearchFrom < orderedNodes.size())
  29819. {
  29820. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29821. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29822. {
  29823. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29824. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29825. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29826. return true;
  29827. }
  29828. else
  29829. {
  29830. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29831. if (i != inputChannelOfIndexToIgnore
  29832. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29833. node->id, i) != 0)
  29834. return true;
  29835. }
  29836. inputChannelOfIndexToIgnore = -1;
  29837. ++stepIndexToSearchFrom;
  29838. }
  29839. return false;
  29840. }
  29841. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29842. {
  29843. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29844. {
  29845. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29846. midiNodeIds.set (bufferNum, nodeId);
  29847. }
  29848. else
  29849. {
  29850. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29851. nodeIds.set (bufferNum, nodeId);
  29852. channels.set (bufferNum, outputIndex);
  29853. }
  29854. }
  29855. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29856. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29857. };
  29858. }
  29859. void AudioProcessorGraph::clearRenderingSequence()
  29860. {
  29861. const ScopedLock sl (renderLock);
  29862. for (int i = renderingOps.size(); --i >= 0;)
  29863. {
  29864. GraphRenderingOps::AudioGraphRenderingOp* const r
  29865. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29866. renderingOps.remove (i);
  29867. delete r;
  29868. }
  29869. }
  29870. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29871. const uint32 possibleDestinationId,
  29872. const int recursionCheck) const
  29873. {
  29874. if (recursionCheck > 0)
  29875. {
  29876. for (int i = connections.size(); --i >= 0;)
  29877. {
  29878. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29879. if (c->destNodeId == possibleDestinationId
  29880. && (c->sourceNodeId == possibleInputId
  29881. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29882. return true;
  29883. }
  29884. }
  29885. return false;
  29886. }
  29887. void AudioProcessorGraph::buildRenderingSequence()
  29888. {
  29889. Array<void*> newRenderingOps;
  29890. int numRenderingBuffersNeeded = 2;
  29891. int numMidiBuffersNeeded = 1;
  29892. {
  29893. MessageManagerLock mml;
  29894. Array<void*> orderedNodes;
  29895. int i;
  29896. for (i = 0; i < nodes.size(); ++i)
  29897. {
  29898. Node* const node = nodes.getUnchecked(i);
  29899. node->prepare (getSampleRate(), getBlockSize(), this);
  29900. int j = 0;
  29901. for (; j < orderedNodes.size(); ++j)
  29902. if (isAnInputTo (node->id,
  29903. ((Node*) orderedNodes.getUnchecked (j))->id,
  29904. nodes.size() + 1))
  29905. break;
  29906. orderedNodes.insert (j, node);
  29907. }
  29908. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29909. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29910. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29911. }
  29912. Array<void*> oldRenderingOps (renderingOps);
  29913. {
  29914. // swap over to the new rendering sequence..
  29915. const ScopedLock sl (renderLock);
  29916. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29917. renderingBuffers.clear();
  29918. for (int i = midiBuffers.size(); --i >= 0;)
  29919. midiBuffers.getUnchecked(i)->clear();
  29920. while (midiBuffers.size() < numMidiBuffersNeeded)
  29921. midiBuffers.add (new MidiBuffer());
  29922. renderingOps = newRenderingOps;
  29923. }
  29924. for (int i = oldRenderingOps.size(); --i >= 0;)
  29925. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29926. }
  29927. void AudioProcessorGraph::handleAsyncUpdate()
  29928. {
  29929. buildRenderingSequence();
  29930. }
  29931. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29932. {
  29933. currentAudioInputBuffer = 0;
  29934. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29935. currentMidiInputBuffer = 0;
  29936. currentMidiOutputBuffer.clear();
  29937. clearRenderingSequence();
  29938. buildRenderingSequence();
  29939. }
  29940. void AudioProcessorGraph::releaseResources()
  29941. {
  29942. for (int i = 0; i < nodes.size(); ++i)
  29943. nodes.getUnchecked(i)->unprepare();
  29944. renderingBuffers.setSize (1, 1);
  29945. midiBuffers.clear();
  29946. currentAudioInputBuffer = 0;
  29947. currentAudioOutputBuffer.setSize (1, 1);
  29948. currentMidiInputBuffer = 0;
  29949. currentMidiOutputBuffer.clear();
  29950. }
  29951. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29952. {
  29953. const int numSamples = buffer.getNumSamples();
  29954. const ScopedLock sl (renderLock);
  29955. currentAudioInputBuffer = &buffer;
  29956. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29957. currentAudioOutputBuffer.clear();
  29958. currentMidiInputBuffer = &midiMessages;
  29959. currentMidiOutputBuffer.clear();
  29960. int i;
  29961. for (i = 0; i < renderingOps.size(); ++i)
  29962. {
  29963. GraphRenderingOps::AudioGraphRenderingOp* const op
  29964. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29965. op->perform (renderingBuffers, midiBuffers, numSamples);
  29966. }
  29967. for (i = 0; i < buffer.getNumChannels(); ++i)
  29968. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29969. midiMessages.clear();
  29970. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29971. }
  29972. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29973. {
  29974. return "Input " + String (channelIndex + 1);
  29975. }
  29976. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29977. {
  29978. return "Output " + String (channelIndex + 1);
  29979. }
  29980. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29981. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29982. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29983. bool AudioProcessorGraph::producesMidi() const { return true; }
  29984. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29985. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29986. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29987. : type (type_),
  29988. graph (0)
  29989. {
  29990. }
  29991. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29992. {
  29993. }
  29994. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29995. {
  29996. switch (type)
  29997. {
  29998. case audioOutputNode: return "Audio Output";
  29999. case audioInputNode: return "Audio Input";
  30000. case midiOutputNode: return "Midi Output";
  30001. case midiInputNode: return "Midi Input";
  30002. default: break;
  30003. }
  30004. return String::empty;
  30005. }
  30006. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  30007. {
  30008. d.name = getName();
  30009. d.uid = d.name.hashCode();
  30010. d.category = "I/O devices";
  30011. d.pluginFormatName = "Internal";
  30012. d.manufacturerName = "Raw Material Software";
  30013. d.version = "1.0";
  30014. d.isInstrument = false;
  30015. d.numInputChannels = getNumInputChannels();
  30016. if (type == audioOutputNode && graph != 0)
  30017. d.numInputChannels = graph->getNumInputChannels();
  30018. d.numOutputChannels = getNumOutputChannels();
  30019. if (type == audioInputNode && graph != 0)
  30020. d.numOutputChannels = graph->getNumOutputChannels();
  30021. }
  30022. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  30023. {
  30024. jassert (graph != 0);
  30025. }
  30026. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  30027. {
  30028. }
  30029. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  30030. MidiBuffer& midiMessages)
  30031. {
  30032. jassert (graph != 0);
  30033. switch (type)
  30034. {
  30035. case audioOutputNode:
  30036. {
  30037. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  30038. buffer.getNumChannels()); --i >= 0;)
  30039. {
  30040. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  30041. }
  30042. break;
  30043. }
  30044. case audioInputNode:
  30045. {
  30046. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  30047. buffer.getNumChannels()); --i >= 0;)
  30048. {
  30049. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  30050. }
  30051. break;
  30052. }
  30053. case midiOutputNode:
  30054. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  30055. break;
  30056. case midiInputNode:
  30057. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  30058. break;
  30059. default:
  30060. break;
  30061. }
  30062. }
  30063. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  30064. {
  30065. return type == midiOutputNode;
  30066. }
  30067. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  30068. {
  30069. return type == midiInputNode;
  30070. }
  30071. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  30072. {
  30073. switch (type)
  30074. {
  30075. case audioOutputNode: return "Output " + String (channelIndex + 1);
  30076. case midiOutputNode: return "Midi Output";
  30077. default: break;
  30078. }
  30079. return String::empty;
  30080. }
  30081. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  30082. {
  30083. switch (type)
  30084. {
  30085. case audioInputNode: return "Input " + String (channelIndex + 1);
  30086. case midiInputNode: return "Midi Input";
  30087. default: break;
  30088. }
  30089. return String::empty;
  30090. }
  30091. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  30092. {
  30093. return type == audioInputNode || type == audioOutputNode;
  30094. }
  30095. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  30096. {
  30097. return isInputChannelStereoPair (index);
  30098. }
  30099. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  30100. {
  30101. return type == audioInputNode || type == midiInputNode;
  30102. }
  30103. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  30104. {
  30105. return type == audioOutputNode || type == midiOutputNode;
  30106. }
  30107. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  30108. {
  30109. return 0;
  30110. }
  30111. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  30112. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  30113. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  30114. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  30115. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  30116. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  30117. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  30118. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  30119. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  30120. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  30121. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  30122. {
  30123. }
  30124. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  30125. {
  30126. }
  30127. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  30128. {
  30129. graph = newGraph;
  30130. if (graph != 0)
  30131. {
  30132. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  30133. type == audioInputNode ? graph->getNumInputChannels() : 0,
  30134. getSampleRate(),
  30135. getBlockSize());
  30136. updateHostDisplay();
  30137. }
  30138. }
  30139. END_JUCE_NAMESPACE
  30140. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30141. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30142. BEGIN_JUCE_NAMESPACE
  30143. AudioProcessorPlayer::AudioProcessorPlayer()
  30144. : processor (0),
  30145. sampleRate (0),
  30146. blockSize (0),
  30147. isPrepared (false),
  30148. numInputChans (0),
  30149. numOutputChans (0),
  30150. tempBuffer (1, 1)
  30151. {
  30152. }
  30153. AudioProcessorPlayer::~AudioProcessorPlayer()
  30154. {
  30155. setProcessor (0);
  30156. }
  30157. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30158. {
  30159. if (processor != processorToPlay)
  30160. {
  30161. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30162. {
  30163. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30164. sampleRate, blockSize);
  30165. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30166. }
  30167. AudioProcessor* oldOne;
  30168. {
  30169. const ScopedLock sl (lock);
  30170. oldOne = isPrepared ? processor : 0;
  30171. processor = processorToPlay;
  30172. isPrepared = true;
  30173. }
  30174. if (oldOne != 0)
  30175. oldOne->releaseResources();
  30176. }
  30177. }
  30178. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30179. const int numInputChannels,
  30180. float** const outputChannelData,
  30181. const int numOutputChannels,
  30182. const int numSamples)
  30183. {
  30184. // these should have been prepared by audioDeviceAboutToStart()...
  30185. jassert (sampleRate > 0 && blockSize > 0);
  30186. incomingMidi.clear();
  30187. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30188. int i, totalNumChans = 0;
  30189. if (numInputChannels > numOutputChannels)
  30190. {
  30191. // if there aren't enough output channels for the number of
  30192. // inputs, we need to create some temporary extra ones (can't
  30193. // use the input data in case it gets written to)
  30194. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30195. false, false, true);
  30196. for (i = 0; i < numOutputChannels; ++i)
  30197. {
  30198. channels[totalNumChans] = outputChannelData[i];
  30199. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30200. ++totalNumChans;
  30201. }
  30202. for (i = numOutputChannels; i < numInputChannels; ++i)
  30203. {
  30204. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30205. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30206. ++totalNumChans;
  30207. }
  30208. }
  30209. else
  30210. {
  30211. for (i = 0; i < numInputChannels; ++i)
  30212. {
  30213. channels[totalNumChans] = outputChannelData[i];
  30214. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30215. ++totalNumChans;
  30216. }
  30217. for (i = numInputChannels; i < numOutputChannels; ++i)
  30218. {
  30219. channels[totalNumChans] = outputChannelData[i];
  30220. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30221. ++totalNumChans;
  30222. }
  30223. }
  30224. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30225. const ScopedLock sl (lock);
  30226. if (processor != 0)
  30227. {
  30228. const ScopedLock sl (processor->getCallbackLock());
  30229. if (processor->isSuspended())
  30230. {
  30231. for (i = 0; i < numOutputChannels; ++i)
  30232. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30233. }
  30234. else
  30235. {
  30236. processor->processBlock (buffer, incomingMidi);
  30237. }
  30238. }
  30239. }
  30240. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30241. {
  30242. const ScopedLock sl (lock);
  30243. sampleRate = device->getCurrentSampleRate();
  30244. blockSize = device->getCurrentBufferSizeSamples();
  30245. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30246. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30247. messageCollector.reset (sampleRate);
  30248. zeromem (channels, sizeof (channels));
  30249. if (processor != 0)
  30250. {
  30251. if (isPrepared)
  30252. processor->releaseResources();
  30253. AudioProcessor* const oldProcessor = processor;
  30254. setProcessor (0);
  30255. setProcessor (oldProcessor);
  30256. }
  30257. }
  30258. void AudioProcessorPlayer::audioDeviceStopped()
  30259. {
  30260. const ScopedLock sl (lock);
  30261. if (processor != 0 && isPrepared)
  30262. processor->releaseResources();
  30263. sampleRate = 0.0;
  30264. blockSize = 0;
  30265. isPrepared = false;
  30266. tempBuffer.setSize (1, 1);
  30267. }
  30268. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30269. {
  30270. messageCollector.addMessageToQueue (message);
  30271. }
  30272. END_JUCE_NAMESPACE
  30273. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30274. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30275. BEGIN_JUCE_NAMESPACE
  30276. class ProcessorParameterPropertyComp : public PropertyComponent,
  30277. public AudioProcessorListener,
  30278. public AsyncUpdater
  30279. {
  30280. public:
  30281. ProcessorParameterPropertyComp (const String& name,
  30282. AudioProcessor* const owner_,
  30283. const int index_)
  30284. : PropertyComponent (name),
  30285. owner (owner_),
  30286. index (index_)
  30287. {
  30288. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  30289. owner_->addListener (this);
  30290. }
  30291. ~ProcessorParameterPropertyComp()
  30292. {
  30293. owner->removeListener (this);
  30294. deleteAllChildren();
  30295. }
  30296. void refresh()
  30297. {
  30298. slider->setValue (owner->getParameter (index), false);
  30299. }
  30300. void audioProcessorChanged (AudioProcessor*) {}
  30301. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30302. {
  30303. if (parameterIndex == index)
  30304. triggerAsyncUpdate();
  30305. }
  30306. void handleAsyncUpdate()
  30307. {
  30308. refresh();
  30309. }
  30310. juce_UseDebuggingNewOperator
  30311. private:
  30312. AudioProcessor* const owner;
  30313. const int index;
  30314. Slider* slider;
  30315. class ParamSlider : public Slider
  30316. {
  30317. public:
  30318. ParamSlider (AudioProcessor* const owner_, const int index_)
  30319. : Slider (String::empty),
  30320. owner (owner_),
  30321. index (index_)
  30322. {
  30323. setRange (0.0, 1.0, 0.0);
  30324. setSliderStyle (Slider::LinearBar);
  30325. setTextBoxIsEditable (false);
  30326. setScrollWheelEnabled (false);
  30327. }
  30328. ~ParamSlider()
  30329. {
  30330. }
  30331. void valueChanged()
  30332. {
  30333. const float newVal = (float) getValue();
  30334. if (owner->getParameter (index) != newVal)
  30335. owner->setParameter (index, newVal);
  30336. }
  30337. const String getTextFromValue (double /*value*/)
  30338. {
  30339. return owner->getParameterText (index);
  30340. }
  30341. juce_UseDebuggingNewOperator
  30342. private:
  30343. AudioProcessor* const owner;
  30344. const int index;
  30345. ParamSlider (const ParamSlider&);
  30346. ParamSlider& operator= (const ParamSlider&);
  30347. };
  30348. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30349. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30350. };
  30351. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30352. : AudioProcessorEditor (owner_)
  30353. {
  30354. setOpaque (true);
  30355. addAndMakeVisible (panel = new PropertyPanel());
  30356. Array <PropertyComponent*> params;
  30357. const int numParams = owner_->getNumParameters();
  30358. int totalHeight = 0;
  30359. for (int i = 0; i < numParams; ++i)
  30360. {
  30361. String name (owner_->getParameterName (i));
  30362. if (name.trim().isEmpty())
  30363. name = "Unnamed";
  30364. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  30365. params.add (pc);
  30366. totalHeight += pc->getPreferredHeight();
  30367. }
  30368. panel->addProperties (params);
  30369. setSize (400, jlimit (25, 400, totalHeight));
  30370. }
  30371. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30372. {
  30373. deleteAllChildren();
  30374. }
  30375. void GenericAudioProcessorEditor::paint (Graphics& g)
  30376. {
  30377. g.fillAll (Colours::white);
  30378. }
  30379. void GenericAudioProcessorEditor::resized()
  30380. {
  30381. panel->setSize (getWidth(), getHeight());
  30382. }
  30383. END_JUCE_NAMESPACE
  30384. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30385. /*** Start of inlined file: juce_Sampler.cpp ***/
  30386. BEGIN_JUCE_NAMESPACE
  30387. SamplerSound::SamplerSound (const String& name_,
  30388. AudioFormatReader& source,
  30389. const BigInteger& midiNotes_,
  30390. const int midiNoteForNormalPitch,
  30391. const double attackTimeSecs,
  30392. const double releaseTimeSecs,
  30393. const double maxSampleLengthSeconds)
  30394. : name (name_),
  30395. midiNotes (midiNotes_),
  30396. midiRootNote (midiNoteForNormalPitch)
  30397. {
  30398. sourceSampleRate = source.sampleRate;
  30399. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30400. {
  30401. length = 0;
  30402. attackSamples = 0;
  30403. releaseSamples = 0;
  30404. }
  30405. else
  30406. {
  30407. length = jmin ((int) source.lengthInSamples,
  30408. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30409. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30410. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30411. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30412. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30413. }
  30414. }
  30415. SamplerSound::~SamplerSound()
  30416. {
  30417. }
  30418. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30419. {
  30420. return midiNotes [midiNoteNumber];
  30421. }
  30422. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30423. {
  30424. return true;
  30425. }
  30426. SamplerVoice::SamplerVoice()
  30427. : pitchRatio (0.0),
  30428. sourceSamplePosition (0.0),
  30429. lgain (0.0f),
  30430. rgain (0.0f),
  30431. isInAttack (false),
  30432. isInRelease (false)
  30433. {
  30434. }
  30435. SamplerVoice::~SamplerVoice()
  30436. {
  30437. }
  30438. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30439. {
  30440. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30441. }
  30442. void SamplerVoice::startNote (const int midiNoteNumber,
  30443. const float velocity,
  30444. SynthesiserSound* s,
  30445. const int /*currentPitchWheelPosition*/)
  30446. {
  30447. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30448. jassert (sound != 0); // this object can only play SamplerSounds!
  30449. if (sound != 0)
  30450. {
  30451. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30452. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30453. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30454. sourceSamplePosition = 0.0;
  30455. lgain = velocity;
  30456. rgain = velocity;
  30457. isInAttack = (sound->attackSamples > 0);
  30458. isInRelease = false;
  30459. if (isInAttack)
  30460. {
  30461. attackReleaseLevel = 0.0f;
  30462. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30463. }
  30464. else
  30465. {
  30466. attackReleaseLevel = 1.0f;
  30467. attackDelta = 0.0f;
  30468. }
  30469. if (sound->releaseSamples > 0)
  30470. {
  30471. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30472. }
  30473. else
  30474. {
  30475. releaseDelta = 0.0f;
  30476. }
  30477. }
  30478. }
  30479. void SamplerVoice::stopNote (const bool allowTailOff)
  30480. {
  30481. if (allowTailOff)
  30482. {
  30483. isInAttack = false;
  30484. isInRelease = true;
  30485. }
  30486. else
  30487. {
  30488. clearCurrentNote();
  30489. }
  30490. }
  30491. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30492. {
  30493. }
  30494. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30495. const int /*newValue*/)
  30496. {
  30497. }
  30498. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30499. {
  30500. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30501. if (playingSound != 0)
  30502. {
  30503. const float* const inL = playingSound->data->getSampleData (0, 0);
  30504. const float* const inR = playingSound->data->getNumChannels() > 1
  30505. ? playingSound->data->getSampleData (1, 0) : 0;
  30506. float* outL = outputBuffer.getSampleData (0, startSample);
  30507. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30508. while (--numSamples >= 0)
  30509. {
  30510. const int pos = (int) sourceSamplePosition;
  30511. const float alpha = (float) (sourceSamplePosition - pos);
  30512. const float invAlpha = 1.0f - alpha;
  30513. // just using a very simple linear interpolation here..
  30514. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30515. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30516. : l;
  30517. l *= lgain;
  30518. r *= rgain;
  30519. if (isInAttack)
  30520. {
  30521. l *= attackReleaseLevel;
  30522. r *= attackReleaseLevel;
  30523. attackReleaseLevel += attackDelta;
  30524. if (attackReleaseLevel >= 1.0f)
  30525. {
  30526. attackReleaseLevel = 1.0f;
  30527. isInAttack = false;
  30528. }
  30529. }
  30530. else if (isInRelease)
  30531. {
  30532. l *= attackReleaseLevel;
  30533. r *= attackReleaseLevel;
  30534. attackReleaseLevel += releaseDelta;
  30535. if (attackReleaseLevel <= 0.0f)
  30536. {
  30537. stopNote (false);
  30538. break;
  30539. }
  30540. }
  30541. if (outR != 0)
  30542. {
  30543. *outL++ += l;
  30544. *outR++ += r;
  30545. }
  30546. else
  30547. {
  30548. *outL++ += (l + r) * 0.5f;
  30549. }
  30550. sourceSamplePosition += pitchRatio;
  30551. if (sourceSamplePosition > playingSound->length)
  30552. {
  30553. stopNote (false);
  30554. break;
  30555. }
  30556. }
  30557. }
  30558. }
  30559. END_JUCE_NAMESPACE
  30560. /*** End of inlined file: juce_Sampler.cpp ***/
  30561. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30562. BEGIN_JUCE_NAMESPACE
  30563. SynthesiserSound::SynthesiserSound()
  30564. {
  30565. }
  30566. SynthesiserSound::~SynthesiserSound()
  30567. {
  30568. }
  30569. SynthesiserVoice::SynthesiserVoice()
  30570. : currentSampleRate (44100.0),
  30571. currentlyPlayingNote (-1),
  30572. noteOnTime (0),
  30573. currentlyPlayingSound (0)
  30574. {
  30575. }
  30576. SynthesiserVoice::~SynthesiserVoice()
  30577. {
  30578. }
  30579. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30580. {
  30581. return currentlyPlayingSound != 0
  30582. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30583. }
  30584. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30585. {
  30586. currentSampleRate = newRate;
  30587. }
  30588. void SynthesiserVoice::clearCurrentNote()
  30589. {
  30590. currentlyPlayingNote = -1;
  30591. currentlyPlayingSound = 0;
  30592. }
  30593. Synthesiser::Synthesiser()
  30594. : sampleRate (0),
  30595. lastNoteOnCounter (0),
  30596. shouldStealNotes (true)
  30597. {
  30598. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30599. lastPitchWheelValues[i] = 0x2000;
  30600. }
  30601. Synthesiser::~Synthesiser()
  30602. {
  30603. }
  30604. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30605. {
  30606. const ScopedLock sl (lock);
  30607. return voices [index];
  30608. }
  30609. void Synthesiser::clearVoices()
  30610. {
  30611. const ScopedLock sl (lock);
  30612. voices.clear();
  30613. }
  30614. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30615. {
  30616. const ScopedLock sl (lock);
  30617. voices.add (newVoice);
  30618. }
  30619. void Synthesiser::removeVoice (const int index)
  30620. {
  30621. const ScopedLock sl (lock);
  30622. voices.remove (index);
  30623. }
  30624. void Synthesiser::clearSounds()
  30625. {
  30626. const ScopedLock sl (lock);
  30627. sounds.clear();
  30628. }
  30629. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30630. {
  30631. const ScopedLock sl (lock);
  30632. sounds.add (newSound);
  30633. }
  30634. void Synthesiser::removeSound (const int index)
  30635. {
  30636. const ScopedLock sl (lock);
  30637. sounds.remove (index);
  30638. }
  30639. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30640. {
  30641. shouldStealNotes = shouldStealNotes_;
  30642. }
  30643. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30644. {
  30645. if (sampleRate != newRate)
  30646. {
  30647. const ScopedLock sl (lock);
  30648. allNotesOff (0, false);
  30649. sampleRate = newRate;
  30650. for (int i = voices.size(); --i >= 0;)
  30651. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30652. }
  30653. }
  30654. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30655. const MidiBuffer& midiData,
  30656. int startSample,
  30657. int numSamples)
  30658. {
  30659. // must set the sample rate before using this!
  30660. jassert (sampleRate != 0);
  30661. const ScopedLock sl (lock);
  30662. MidiBuffer::Iterator midiIterator (midiData);
  30663. midiIterator.setNextSamplePosition (startSample);
  30664. MidiMessage m (0xf4, 0.0);
  30665. while (numSamples > 0)
  30666. {
  30667. int midiEventPos;
  30668. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30669. && midiEventPos < startSample + numSamples;
  30670. const int numThisTime = useEvent ? midiEventPos - startSample
  30671. : numSamples;
  30672. if (numThisTime > 0)
  30673. {
  30674. for (int i = voices.size(); --i >= 0;)
  30675. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30676. }
  30677. if (useEvent)
  30678. {
  30679. if (m.isNoteOn())
  30680. {
  30681. const int channel = m.getChannel();
  30682. noteOn (channel,
  30683. m.getNoteNumber(),
  30684. m.getFloatVelocity());
  30685. }
  30686. else if (m.isNoteOff())
  30687. {
  30688. noteOff (m.getChannel(),
  30689. m.getNoteNumber(),
  30690. true);
  30691. }
  30692. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30693. {
  30694. allNotesOff (m.getChannel(), true);
  30695. }
  30696. else if (m.isPitchWheel())
  30697. {
  30698. const int channel = m.getChannel();
  30699. const int wheelPos = m.getPitchWheelValue();
  30700. lastPitchWheelValues [channel - 1] = wheelPos;
  30701. handlePitchWheel (channel, wheelPos);
  30702. }
  30703. else if (m.isController())
  30704. {
  30705. handleController (m.getChannel(),
  30706. m.getControllerNumber(),
  30707. m.getControllerValue());
  30708. }
  30709. }
  30710. startSample += numThisTime;
  30711. numSamples -= numThisTime;
  30712. }
  30713. }
  30714. void Synthesiser::noteOn (const int midiChannel,
  30715. const int midiNoteNumber,
  30716. const float velocity)
  30717. {
  30718. const ScopedLock sl (lock);
  30719. for (int i = sounds.size(); --i >= 0;)
  30720. {
  30721. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30722. if (sound->appliesToNote (midiNoteNumber)
  30723. && sound->appliesToChannel (midiChannel))
  30724. {
  30725. startVoice (findFreeVoice (sound, shouldStealNotes),
  30726. sound, midiChannel, midiNoteNumber, velocity);
  30727. }
  30728. }
  30729. }
  30730. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30731. SynthesiserSound* const sound,
  30732. const int midiChannel,
  30733. const int midiNoteNumber,
  30734. const float velocity)
  30735. {
  30736. if (voice != 0 && sound != 0)
  30737. {
  30738. if (voice->currentlyPlayingSound != 0)
  30739. voice->stopNote (false);
  30740. voice->startNote (midiNoteNumber,
  30741. velocity,
  30742. sound,
  30743. lastPitchWheelValues [midiChannel - 1]);
  30744. voice->currentlyPlayingNote = midiNoteNumber;
  30745. voice->noteOnTime = ++lastNoteOnCounter;
  30746. voice->currentlyPlayingSound = sound;
  30747. }
  30748. }
  30749. void Synthesiser::noteOff (const int midiChannel,
  30750. const int midiNoteNumber,
  30751. const bool allowTailOff)
  30752. {
  30753. const ScopedLock sl (lock);
  30754. for (int i = voices.size(); --i >= 0;)
  30755. {
  30756. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30757. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30758. {
  30759. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30760. if (sound != 0
  30761. && sound->appliesToNote (midiNoteNumber)
  30762. && sound->appliesToChannel (midiChannel))
  30763. {
  30764. voice->stopNote (allowTailOff);
  30765. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30766. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30767. }
  30768. }
  30769. }
  30770. }
  30771. void Synthesiser::allNotesOff (const int midiChannel,
  30772. const bool allowTailOff)
  30773. {
  30774. const ScopedLock sl (lock);
  30775. for (int i = voices.size(); --i >= 0;)
  30776. {
  30777. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30778. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30779. voice->stopNote (allowTailOff);
  30780. }
  30781. }
  30782. void Synthesiser::handlePitchWheel (const int midiChannel,
  30783. const int wheelValue)
  30784. {
  30785. const ScopedLock sl (lock);
  30786. for (int i = voices.size(); --i >= 0;)
  30787. {
  30788. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30789. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30790. {
  30791. voice->pitchWheelMoved (wheelValue);
  30792. }
  30793. }
  30794. }
  30795. void Synthesiser::handleController (const int midiChannel,
  30796. const int controllerNumber,
  30797. const int controllerValue)
  30798. {
  30799. const ScopedLock sl (lock);
  30800. for (int i = voices.size(); --i >= 0;)
  30801. {
  30802. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30803. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30804. voice->controllerMoved (controllerNumber, controllerValue);
  30805. }
  30806. }
  30807. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30808. const bool stealIfNoneAvailable) const
  30809. {
  30810. const ScopedLock sl (lock);
  30811. for (int i = voices.size(); --i >= 0;)
  30812. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30813. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30814. return voices.getUnchecked (i);
  30815. if (stealIfNoneAvailable)
  30816. {
  30817. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30818. SynthesiserVoice* oldest = 0;
  30819. for (int i = voices.size(); --i >= 0;)
  30820. {
  30821. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30822. if (voice->canPlaySound (soundToPlay)
  30823. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30824. oldest = voice;
  30825. }
  30826. jassert (oldest != 0);
  30827. return oldest;
  30828. }
  30829. return 0;
  30830. }
  30831. END_JUCE_NAMESPACE
  30832. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30833. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30834. BEGIN_JUCE_NAMESPACE
  30835. ActionBroadcaster::ActionBroadcaster() throw()
  30836. {
  30837. // are you trying to create this object before or after juce has been intialised??
  30838. jassert (MessageManager::instance != 0);
  30839. }
  30840. ActionBroadcaster::~ActionBroadcaster()
  30841. {
  30842. // all event-based objects must be deleted BEFORE juce is shut down!
  30843. jassert (MessageManager::instance != 0);
  30844. }
  30845. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30846. {
  30847. actionListenerList.addActionListener (listener);
  30848. }
  30849. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30850. {
  30851. jassert (actionListenerList.isValidMessageListener());
  30852. if (actionListenerList.isValidMessageListener())
  30853. actionListenerList.removeActionListener (listener);
  30854. }
  30855. void ActionBroadcaster::removeAllActionListeners()
  30856. {
  30857. actionListenerList.removeAllActionListeners();
  30858. }
  30859. void ActionBroadcaster::sendActionMessage (const String& message) const
  30860. {
  30861. actionListenerList.sendActionMessage (message);
  30862. }
  30863. END_JUCE_NAMESPACE
  30864. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30865. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30866. BEGIN_JUCE_NAMESPACE
  30867. // special message of our own with a string in it
  30868. class ActionMessage : public Message
  30869. {
  30870. public:
  30871. const String message;
  30872. ActionMessage (const String& messageText, void* const listener_) throw()
  30873. : message (messageText)
  30874. {
  30875. pointerParameter = listener_;
  30876. }
  30877. ~ActionMessage() throw()
  30878. {
  30879. }
  30880. private:
  30881. ActionMessage (const ActionMessage&);
  30882. ActionMessage& operator= (const ActionMessage&);
  30883. };
  30884. ActionListenerList::ActionListenerList()
  30885. {
  30886. }
  30887. ActionListenerList::~ActionListenerList()
  30888. {
  30889. }
  30890. void ActionListenerList::addActionListener (ActionListener* const listener)
  30891. {
  30892. const ScopedLock sl (actionListenerLock_);
  30893. jassert (listener != 0);
  30894. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30895. if (listener != 0)
  30896. actionListeners_.add (listener);
  30897. }
  30898. void ActionListenerList::removeActionListener (ActionListener* const listener)
  30899. {
  30900. const ScopedLock sl (actionListenerLock_);
  30901. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30902. actionListeners_.removeValue (listener);
  30903. }
  30904. void ActionListenerList::removeAllActionListeners()
  30905. {
  30906. const ScopedLock sl (actionListenerLock_);
  30907. actionListeners_.clear();
  30908. }
  30909. void ActionListenerList::sendActionMessage (const String& message) const
  30910. {
  30911. const ScopedLock sl (actionListenerLock_);
  30912. for (int i = actionListeners_.size(); --i >= 0;)
  30913. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30914. }
  30915. void ActionListenerList::handleMessage (const Message& message)
  30916. {
  30917. const ActionMessage& am = (const ActionMessage&) message;
  30918. if (actionListeners_.contains (am.pointerParameter))
  30919. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30920. }
  30921. END_JUCE_NAMESPACE
  30922. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30923. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30924. BEGIN_JUCE_NAMESPACE
  30925. AsyncUpdater::AsyncUpdater() throw()
  30926. : asyncMessagePending (false)
  30927. {
  30928. internalAsyncHandler.owner = this;
  30929. }
  30930. AsyncUpdater::~AsyncUpdater()
  30931. {
  30932. }
  30933. void AsyncUpdater::triggerAsyncUpdate()
  30934. {
  30935. if (! asyncMessagePending)
  30936. {
  30937. asyncMessagePending = true;
  30938. internalAsyncHandler.postMessage (new Message());
  30939. }
  30940. }
  30941. void AsyncUpdater::cancelPendingUpdate() throw()
  30942. {
  30943. asyncMessagePending = false;
  30944. }
  30945. void AsyncUpdater::handleUpdateNowIfNeeded()
  30946. {
  30947. if (asyncMessagePending)
  30948. {
  30949. asyncMessagePending = false;
  30950. handleAsyncUpdate();
  30951. }
  30952. }
  30953. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30954. {
  30955. owner->handleUpdateNowIfNeeded();
  30956. }
  30957. END_JUCE_NAMESPACE
  30958. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30959. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30960. BEGIN_JUCE_NAMESPACE
  30961. ChangeBroadcaster::ChangeBroadcaster() throw()
  30962. {
  30963. // are you trying to create this object before or after juce has been intialised??
  30964. jassert (MessageManager::instance != 0);
  30965. }
  30966. ChangeBroadcaster::~ChangeBroadcaster()
  30967. {
  30968. // all event-based objects must be deleted BEFORE juce is shut down!
  30969. jassert (MessageManager::instance != 0);
  30970. }
  30971. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30972. {
  30973. changeListenerList.addChangeListener (listener);
  30974. }
  30975. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30976. {
  30977. jassert (changeListenerList.isValidMessageListener());
  30978. if (changeListenerList.isValidMessageListener())
  30979. changeListenerList.removeChangeListener (listener);
  30980. }
  30981. void ChangeBroadcaster::removeAllChangeListeners()
  30982. {
  30983. changeListenerList.removeAllChangeListeners();
  30984. }
  30985. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  30986. {
  30987. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30988. }
  30989. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30990. {
  30991. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30992. }
  30993. void ChangeBroadcaster::dispatchPendingMessages()
  30994. {
  30995. changeListenerList.dispatchPendingMessages();
  30996. }
  30997. END_JUCE_NAMESPACE
  30998. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30999. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  31000. BEGIN_JUCE_NAMESPACE
  31001. ChangeListenerList::ChangeListenerList()
  31002. : lastChangedObject (0),
  31003. messagePending (false)
  31004. {
  31005. }
  31006. ChangeListenerList::~ChangeListenerList()
  31007. {
  31008. }
  31009. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  31010. {
  31011. const ScopedLock sl (lock);
  31012. jassert (listener != 0);
  31013. if (listener != 0)
  31014. listeners.add (listener);
  31015. }
  31016. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  31017. {
  31018. const ScopedLock sl (lock);
  31019. listeners.removeValue (listener);
  31020. }
  31021. void ChangeListenerList::removeAllChangeListeners()
  31022. {
  31023. const ScopedLock sl (lock);
  31024. listeners.clear();
  31025. }
  31026. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  31027. {
  31028. const ScopedLock sl (lock);
  31029. if ((! messagePending) && (listeners.size() > 0))
  31030. {
  31031. lastChangedObject = objectThatHasChanged;
  31032. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  31033. messagePending = true;
  31034. }
  31035. }
  31036. void ChangeListenerList::handleMessage (const Message& message)
  31037. {
  31038. sendSynchronousChangeMessage (message.pointerParameter);
  31039. }
  31040. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  31041. {
  31042. const ScopedLock sl (lock);
  31043. messagePending = false;
  31044. for (int i = listeners.size(); --i >= 0;)
  31045. {
  31046. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  31047. {
  31048. const ScopedUnlock tempUnlocker (lock);
  31049. l->changeListenerCallback (objectThatHasChanged);
  31050. }
  31051. i = jmin (i, listeners.size());
  31052. }
  31053. }
  31054. void ChangeListenerList::dispatchPendingMessages()
  31055. {
  31056. if (messagePending)
  31057. sendSynchronousChangeMessage (lastChangedObject);
  31058. }
  31059. END_JUCE_NAMESPACE
  31060. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  31061. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  31062. BEGIN_JUCE_NAMESPACE
  31063. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  31064. const uint32 magicMessageHeaderNumber)
  31065. : Thread ("Juce IPC connection"),
  31066. callbackConnectionState (false),
  31067. useMessageThread (callbacksOnMessageThread),
  31068. magicMessageHeader (magicMessageHeaderNumber),
  31069. pipeReceiveMessageTimeout (-1)
  31070. {
  31071. }
  31072. InterprocessConnection::~InterprocessConnection()
  31073. {
  31074. callbackConnectionState = false;
  31075. disconnect();
  31076. }
  31077. bool InterprocessConnection::connectToSocket (const String& hostName,
  31078. const int portNumber,
  31079. const int timeOutMillisecs)
  31080. {
  31081. disconnect();
  31082. const ScopedLock sl (pipeAndSocketLock);
  31083. socket = new StreamingSocket();
  31084. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  31085. {
  31086. connectionMadeInt();
  31087. startThread();
  31088. return true;
  31089. }
  31090. else
  31091. {
  31092. socket = 0;
  31093. return false;
  31094. }
  31095. }
  31096. bool InterprocessConnection::connectToPipe (const String& pipeName,
  31097. const int pipeReceiveMessageTimeoutMs)
  31098. {
  31099. disconnect();
  31100. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31101. if (newPipe->openExisting (pipeName))
  31102. {
  31103. const ScopedLock sl (pipeAndSocketLock);
  31104. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31105. initialiseWithPipe (newPipe.release());
  31106. return true;
  31107. }
  31108. return false;
  31109. }
  31110. bool InterprocessConnection::createPipe (const String& pipeName,
  31111. const int pipeReceiveMessageTimeoutMs)
  31112. {
  31113. disconnect();
  31114. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31115. if (newPipe->createNewPipe (pipeName))
  31116. {
  31117. const ScopedLock sl (pipeAndSocketLock);
  31118. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31119. initialiseWithPipe (newPipe.release());
  31120. return true;
  31121. }
  31122. return false;
  31123. }
  31124. void InterprocessConnection::disconnect()
  31125. {
  31126. if (socket != 0)
  31127. socket->close();
  31128. if (pipe != 0)
  31129. {
  31130. pipe->cancelPendingReads();
  31131. pipe->close();
  31132. }
  31133. stopThread (4000);
  31134. {
  31135. const ScopedLock sl (pipeAndSocketLock);
  31136. socket = 0;
  31137. pipe = 0;
  31138. }
  31139. connectionLostInt();
  31140. }
  31141. bool InterprocessConnection::isConnected() const
  31142. {
  31143. const ScopedLock sl (pipeAndSocketLock);
  31144. return ((socket != 0 && socket->isConnected())
  31145. || (pipe != 0 && pipe->isOpen()))
  31146. && isThreadRunning();
  31147. }
  31148. const String InterprocessConnection::getConnectedHostName() const
  31149. {
  31150. if (pipe != 0)
  31151. {
  31152. return "localhost";
  31153. }
  31154. else if (socket != 0)
  31155. {
  31156. if (! socket->isLocal())
  31157. return socket->getHostName();
  31158. return "localhost";
  31159. }
  31160. return String::empty;
  31161. }
  31162. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31163. {
  31164. uint32 messageHeader[2];
  31165. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31166. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31167. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31168. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31169. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31170. size_t bytesWritten = 0;
  31171. const ScopedLock sl (pipeAndSocketLock);
  31172. if (socket != 0)
  31173. {
  31174. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31175. }
  31176. else if (pipe != 0)
  31177. {
  31178. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31179. }
  31180. if (bytesWritten < 0)
  31181. {
  31182. // error..
  31183. return false;
  31184. }
  31185. return (bytesWritten == messageData.getSize());
  31186. }
  31187. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31188. {
  31189. jassert (socket == 0);
  31190. socket = socket_;
  31191. connectionMadeInt();
  31192. startThread();
  31193. }
  31194. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31195. {
  31196. jassert (pipe == 0);
  31197. pipe = pipe_;
  31198. connectionMadeInt();
  31199. startThread();
  31200. }
  31201. const int messageMagicNumber = 0xb734128b;
  31202. void InterprocessConnection::handleMessage (const Message& message)
  31203. {
  31204. if (message.intParameter1 == messageMagicNumber)
  31205. {
  31206. switch (message.intParameter2)
  31207. {
  31208. case 0:
  31209. {
  31210. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31211. messageReceived (*data);
  31212. break;
  31213. }
  31214. case 1:
  31215. connectionMade();
  31216. break;
  31217. case 2:
  31218. connectionLost();
  31219. break;
  31220. }
  31221. }
  31222. }
  31223. void InterprocessConnection::connectionMadeInt()
  31224. {
  31225. if (! callbackConnectionState)
  31226. {
  31227. callbackConnectionState = true;
  31228. if (useMessageThread)
  31229. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31230. else
  31231. connectionMade();
  31232. }
  31233. }
  31234. void InterprocessConnection::connectionLostInt()
  31235. {
  31236. if (callbackConnectionState)
  31237. {
  31238. callbackConnectionState = false;
  31239. if (useMessageThread)
  31240. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31241. else
  31242. connectionLost();
  31243. }
  31244. }
  31245. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31246. {
  31247. jassert (callbackConnectionState);
  31248. if (useMessageThread)
  31249. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31250. else
  31251. messageReceived (data);
  31252. }
  31253. bool InterprocessConnection::readNextMessageInt()
  31254. {
  31255. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31256. uint32 messageHeader[2];
  31257. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31258. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31259. if (bytes == sizeof (messageHeader)
  31260. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31261. {
  31262. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31263. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31264. {
  31265. MemoryBlock messageData (bytesInMessage, true);
  31266. int bytesRead = 0;
  31267. while (bytesInMessage > 0)
  31268. {
  31269. if (threadShouldExit())
  31270. return false;
  31271. const int numThisTime = jmin (bytesInMessage, 65536);
  31272. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31273. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31274. if (bytesIn <= 0)
  31275. break;
  31276. bytesRead += bytesIn;
  31277. bytesInMessage -= bytesIn;
  31278. }
  31279. if (bytesRead >= 0)
  31280. deliverDataInt (messageData);
  31281. }
  31282. }
  31283. else if (bytes < 0)
  31284. {
  31285. {
  31286. const ScopedLock sl (pipeAndSocketLock);
  31287. socket = 0;
  31288. }
  31289. connectionLostInt();
  31290. return false;
  31291. }
  31292. return true;
  31293. }
  31294. void InterprocessConnection::run()
  31295. {
  31296. while (! threadShouldExit())
  31297. {
  31298. if (socket != 0)
  31299. {
  31300. const int ready = socket->waitUntilReady (true, 0);
  31301. if (ready < 0)
  31302. {
  31303. {
  31304. const ScopedLock sl (pipeAndSocketLock);
  31305. socket = 0;
  31306. }
  31307. connectionLostInt();
  31308. break;
  31309. }
  31310. else if (ready > 0)
  31311. {
  31312. if (! readNextMessageInt())
  31313. break;
  31314. }
  31315. else
  31316. {
  31317. Thread::sleep (2);
  31318. }
  31319. }
  31320. else if (pipe != 0)
  31321. {
  31322. if (! pipe->isOpen())
  31323. {
  31324. {
  31325. const ScopedLock sl (pipeAndSocketLock);
  31326. pipe = 0;
  31327. }
  31328. connectionLostInt();
  31329. break;
  31330. }
  31331. else
  31332. {
  31333. if (! readNextMessageInt())
  31334. break;
  31335. }
  31336. }
  31337. else
  31338. {
  31339. break;
  31340. }
  31341. }
  31342. }
  31343. END_JUCE_NAMESPACE
  31344. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31345. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31346. BEGIN_JUCE_NAMESPACE
  31347. InterprocessConnectionServer::InterprocessConnectionServer()
  31348. : Thread ("Juce IPC server")
  31349. {
  31350. }
  31351. InterprocessConnectionServer::~InterprocessConnectionServer()
  31352. {
  31353. stop();
  31354. }
  31355. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31356. {
  31357. stop();
  31358. socket = new StreamingSocket();
  31359. if (socket->createListener (portNumber))
  31360. {
  31361. startThread();
  31362. return true;
  31363. }
  31364. socket = 0;
  31365. return false;
  31366. }
  31367. void InterprocessConnectionServer::stop()
  31368. {
  31369. signalThreadShouldExit();
  31370. if (socket != 0)
  31371. socket->close();
  31372. stopThread (4000);
  31373. socket = 0;
  31374. }
  31375. void InterprocessConnectionServer::run()
  31376. {
  31377. while ((! threadShouldExit()) && socket != 0)
  31378. {
  31379. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31380. if (clientSocket != 0)
  31381. {
  31382. InterprocessConnection* newConnection = createConnectionObject();
  31383. if (newConnection != 0)
  31384. newConnection->initialiseWithSocket (clientSocket.release());
  31385. }
  31386. }
  31387. }
  31388. END_JUCE_NAMESPACE
  31389. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31390. /*** Start of inlined file: juce_Message.cpp ***/
  31391. BEGIN_JUCE_NAMESPACE
  31392. Message::Message() throw()
  31393. : intParameter1 (0),
  31394. intParameter2 (0),
  31395. intParameter3 (0),
  31396. pointerParameter (0)
  31397. {
  31398. }
  31399. Message::Message (const int intParameter1_,
  31400. const int intParameter2_,
  31401. const int intParameter3_,
  31402. void* const pointerParameter_) throw()
  31403. : intParameter1 (intParameter1_),
  31404. intParameter2 (intParameter2_),
  31405. intParameter3 (intParameter3_),
  31406. pointerParameter (pointerParameter_)
  31407. {
  31408. }
  31409. Message::~Message() throw()
  31410. {
  31411. }
  31412. END_JUCE_NAMESPACE
  31413. /*** End of inlined file: juce_Message.cpp ***/
  31414. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31415. BEGIN_JUCE_NAMESPACE
  31416. MessageListener::MessageListener() throw()
  31417. {
  31418. // are you trying to create a messagelistener before or after juce has been intialised??
  31419. jassert (MessageManager::instance != 0);
  31420. if (MessageManager::instance != 0)
  31421. MessageManager::instance->messageListeners.add (this);
  31422. }
  31423. MessageListener::~MessageListener()
  31424. {
  31425. if (MessageManager::instance != 0)
  31426. MessageManager::instance->messageListeners.removeValue (this);
  31427. }
  31428. void MessageListener::postMessage (Message* const message) const throw()
  31429. {
  31430. message->messageRecipient = const_cast <MessageListener*> (this);
  31431. if (MessageManager::instance == 0)
  31432. MessageManager::getInstance();
  31433. MessageManager::instance->postMessageToQueue (message);
  31434. }
  31435. bool MessageListener::isValidMessageListener() const throw()
  31436. {
  31437. return (MessageManager::instance != 0)
  31438. && MessageManager::instance->messageListeners.contains (this);
  31439. }
  31440. END_JUCE_NAMESPACE
  31441. /*** End of inlined file: juce_MessageListener.cpp ***/
  31442. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31443. BEGIN_JUCE_NAMESPACE
  31444. // platform-specific functions..
  31445. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31446. bool juce_postMessageToSystemQueue (Message* message);
  31447. MessageManager* MessageManager::instance = 0;
  31448. static const int quitMessageId = 0xfffff321;
  31449. MessageManager::MessageManager() throw()
  31450. : quitMessagePosted (false),
  31451. quitMessageReceived (false),
  31452. threadWithLock (0)
  31453. {
  31454. messageThreadId = Thread::getCurrentThreadId();
  31455. }
  31456. MessageManager::~MessageManager() throw()
  31457. {
  31458. broadcastListeners = 0;
  31459. doPlatformSpecificShutdown();
  31460. // If you hit this assertion, then you've probably leaked a Component or some other
  31461. // kind of MessageListener object...
  31462. jassert (messageListeners.size() == 0);
  31463. jassert (instance == this);
  31464. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31465. }
  31466. MessageManager* MessageManager::getInstance() throw()
  31467. {
  31468. if (instance == 0)
  31469. {
  31470. instance = new MessageManager();
  31471. doPlatformSpecificInitialisation();
  31472. }
  31473. return instance;
  31474. }
  31475. void MessageManager::postMessageToQueue (Message* const message)
  31476. {
  31477. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31478. delete message;
  31479. }
  31480. CallbackMessage::CallbackMessage() throw() {}
  31481. CallbackMessage::~CallbackMessage() throw() {}
  31482. void CallbackMessage::post()
  31483. {
  31484. if (MessageManager::instance != 0)
  31485. MessageManager::instance->postCallbackMessage (this);
  31486. }
  31487. void MessageManager::postCallbackMessage (Message* const message)
  31488. {
  31489. message->messageRecipient = 0;
  31490. postMessageToQueue (message);
  31491. }
  31492. // not for public use..
  31493. void MessageManager::deliverMessage (Message* const message)
  31494. {
  31495. const ScopedPointer <Message> messageDeleter (message);
  31496. MessageListener* const recipient = message->messageRecipient;
  31497. JUCE_TRY
  31498. {
  31499. if (messageListeners.contains (recipient))
  31500. {
  31501. recipient->handleMessage (*message);
  31502. }
  31503. else if (recipient == 0)
  31504. {
  31505. if (message->intParameter1 == quitMessageId)
  31506. {
  31507. quitMessageReceived = true;
  31508. }
  31509. else
  31510. {
  31511. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31512. if (cm != 0)
  31513. cm->messageCallback();
  31514. }
  31515. }
  31516. }
  31517. JUCE_CATCH_EXCEPTION
  31518. }
  31519. #if ! (JUCE_MAC || JUCE_IOS)
  31520. void MessageManager::runDispatchLoop()
  31521. {
  31522. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31523. runDispatchLoopUntil (-1);
  31524. }
  31525. void MessageManager::stopDispatchLoop()
  31526. {
  31527. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31528. m->messageRecipient = 0;
  31529. postMessageToQueue (m);
  31530. quitMessagePosted = true;
  31531. }
  31532. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31533. {
  31534. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31535. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31536. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31537. && ! quitMessageReceived)
  31538. {
  31539. JUCE_TRY
  31540. {
  31541. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31542. {
  31543. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31544. if (msToWait > 0)
  31545. Thread::sleep (jmin (5, msToWait));
  31546. }
  31547. }
  31548. JUCE_CATCH_EXCEPTION
  31549. }
  31550. return ! quitMessageReceived;
  31551. }
  31552. #endif
  31553. void MessageManager::deliverBroadcastMessage (const String& value)
  31554. {
  31555. if (broadcastListeners != 0)
  31556. broadcastListeners->sendActionMessage (value);
  31557. }
  31558. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31559. {
  31560. if (broadcastListeners == 0)
  31561. broadcastListeners = new ActionListenerList();
  31562. broadcastListeners->addActionListener (listener);
  31563. }
  31564. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31565. {
  31566. if (broadcastListeners != 0)
  31567. broadcastListeners->removeActionListener (listener);
  31568. }
  31569. bool MessageManager::isThisTheMessageThread() const throw()
  31570. {
  31571. return Thread::getCurrentThreadId() == messageThreadId;
  31572. }
  31573. void MessageManager::setCurrentThreadAsMessageThread()
  31574. {
  31575. if (messageThreadId != Thread::getCurrentThreadId())
  31576. {
  31577. messageThreadId = Thread::getCurrentThreadId();
  31578. // This is needed on windows to make sure the message window is created by this thread
  31579. doPlatformSpecificShutdown();
  31580. doPlatformSpecificInitialisation();
  31581. }
  31582. }
  31583. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31584. {
  31585. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31586. return thisThread == messageThreadId || thisThread == threadWithLock;
  31587. }
  31588. /* The only safe way to lock the message thread while another thread does
  31589. some work is by posting a special message, whose purpose is to tie up the event
  31590. loop until the other thread has finished its business.
  31591. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31592. get locked before making an event callback, because if the same OS lock gets indirectly
  31593. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31594. in Cocoa).
  31595. */
  31596. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31597. {
  31598. public:
  31599. SharedEvents() {}
  31600. ~SharedEvents() {}
  31601. /* This class just holds a couple of events to communicate between the BlockingMessage
  31602. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31603. this shared data must be kept in a separate, ref-counted container. */
  31604. WaitableEvent lockedEvent, releaseEvent;
  31605. private:
  31606. SharedEvents (const SharedEvents&);
  31607. SharedEvents& operator= (const SharedEvents&);
  31608. };
  31609. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31610. {
  31611. public:
  31612. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31613. ~BlockingMessage() throw() {}
  31614. void messageCallback()
  31615. {
  31616. events->lockedEvent.signal();
  31617. events->releaseEvent.wait();
  31618. }
  31619. juce_UseDebuggingNewOperator
  31620. private:
  31621. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31622. BlockingMessage (const BlockingMessage&);
  31623. BlockingMessage& operator= (const BlockingMessage&);
  31624. };
  31625. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31626. : sharedEvents (0),
  31627. locked (false)
  31628. {
  31629. init (threadToCheck, 0);
  31630. }
  31631. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31632. : sharedEvents (0),
  31633. locked (false)
  31634. {
  31635. init (0, jobToCheckForExitSignal);
  31636. }
  31637. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31638. {
  31639. if (MessageManager::instance != 0)
  31640. {
  31641. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31642. {
  31643. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31644. }
  31645. else
  31646. {
  31647. if (threadToCheck == 0 && job == 0)
  31648. {
  31649. MessageManager::instance->lockingLock.enter();
  31650. }
  31651. else
  31652. {
  31653. while (! MessageManager::instance->lockingLock.tryEnter())
  31654. {
  31655. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31656. || (job != 0 && job->shouldExit()))
  31657. return;
  31658. Thread::sleep (1);
  31659. }
  31660. }
  31661. sharedEvents = new SharedEvents();
  31662. sharedEvents->incReferenceCount();
  31663. (new BlockingMessage (sharedEvents))->post();
  31664. while (! sharedEvents->lockedEvent.wait (50))
  31665. {
  31666. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31667. || (job != 0 && job->shouldExit()))
  31668. {
  31669. sharedEvents->releaseEvent.signal();
  31670. sharedEvents->decReferenceCount();
  31671. sharedEvents = 0;
  31672. MessageManager::instance->lockingLock.exit();
  31673. return;
  31674. }
  31675. }
  31676. jassert (MessageManager::instance->threadWithLock == 0);
  31677. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31678. locked = true;
  31679. }
  31680. }
  31681. }
  31682. MessageManagerLock::~MessageManagerLock() throw()
  31683. {
  31684. if (sharedEvents != 0)
  31685. {
  31686. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31687. sharedEvents->releaseEvent.signal();
  31688. sharedEvents->decReferenceCount();
  31689. if (MessageManager::instance != 0)
  31690. {
  31691. MessageManager::instance->threadWithLock = 0;
  31692. MessageManager::instance->lockingLock.exit();
  31693. }
  31694. }
  31695. }
  31696. END_JUCE_NAMESPACE
  31697. /*** End of inlined file: juce_MessageManager.cpp ***/
  31698. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31699. BEGIN_JUCE_NAMESPACE
  31700. class MultiTimer::MultiTimerCallback : public Timer
  31701. {
  31702. public:
  31703. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31704. : timerId (timerId_),
  31705. owner (owner_)
  31706. {
  31707. }
  31708. ~MultiTimerCallback()
  31709. {
  31710. }
  31711. void timerCallback()
  31712. {
  31713. owner.timerCallback (timerId);
  31714. }
  31715. const int timerId;
  31716. private:
  31717. MultiTimer& owner;
  31718. };
  31719. MultiTimer::MultiTimer() throw()
  31720. {
  31721. }
  31722. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31723. {
  31724. }
  31725. MultiTimer::~MultiTimer()
  31726. {
  31727. const ScopedLock sl (timerListLock);
  31728. timers.clear();
  31729. }
  31730. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31731. {
  31732. const ScopedLock sl (timerListLock);
  31733. for (int i = timers.size(); --i >= 0;)
  31734. {
  31735. MultiTimerCallback* const t = timers.getUnchecked(i);
  31736. if (t->timerId == timerId)
  31737. {
  31738. t->startTimer (intervalInMilliseconds);
  31739. return;
  31740. }
  31741. }
  31742. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31743. timers.add (newTimer);
  31744. newTimer->startTimer (intervalInMilliseconds);
  31745. }
  31746. void MultiTimer::stopTimer (const int timerId) throw()
  31747. {
  31748. const ScopedLock sl (timerListLock);
  31749. for (int i = timers.size(); --i >= 0;)
  31750. {
  31751. MultiTimerCallback* const t = timers.getUnchecked(i);
  31752. if (t->timerId == timerId)
  31753. t->stopTimer();
  31754. }
  31755. }
  31756. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31757. {
  31758. const ScopedLock sl (timerListLock);
  31759. for (int i = timers.size(); --i >= 0;)
  31760. {
  31761. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31762. if (t->timerId == timerId)
  31763. return t->isTimerRunning();
  31764. }
  31765. return false;
  31766. }
  31767. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31768. {
  31769. const ScopedLock sl (timerListLock);
  31770. for (int i = timers.size(); --i >= 0;)
  31771. {
  31772. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31773. if (t->timerId == timerId)
  31774. return t->getTimerInterval();
  31775. }
  31776. return 0;
  31777. }
  31778. END_JUCE_NAMESPACE
  31779. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31780. /*** Start of inlined file: juce_Timer.cpp ***/
  31781. BEGIN_JUCE_NAMESPACE
  31782. class InternalTimerThread : private Thread,
  31783. private MessageListener,
  31784. private DeletedAtShutdown,
  31785. private AsyncUpdater
  31786. {
  31787. public:
  31788. InternalTimerThread()
  31789. : Thread ("Juce Timer"),
  31790. firstTimer (0),
  31791. callbackNeeded (0)
  31792. {
  31793. triggerAsyncUpdate();
  31794. }
  31795. ~InternalTimerThread() throw()
  31796. {
  31797. stopThread (4000);
  31798. jassert (instance == this || instance == 0);
  31799. if (instance == this)
  31800. instance = 0;
  31801. }
  31802. void run()
  31803. {
  31804. uint32 lastTime = Time::getMillisecondCounter();
  31805. while (! threadShouldExit())
  31806. {
  31807. const uint32 now = Time::getMillisecondCounter();
  31808. if (now <= lastTime)
  31809. {
  31810. wait (2);
  31811. continue;
  31812. }
  31813. const int elapsed = now - lastTime;
  31814. lastTime = now;
  31815. int timeUntilFirstTimer = 1000;
  31816. {
  31817. const ScopedLock sl (lock);
  31818. decrementAllCounters (elapsed);
  31819. if (firstTimer != 0)
  31820. timeUntilFirstTimer = firstTimer->countdownMs;
  31821. }
  31822. if (timeUntilFirstTimer <= 0)
  31823. {
  31824. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31825. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31826. but if it fails it means the message-thread changed the value from under us so at least
  31827. some processing is happenening and we can just loop around and try again
  31828. */
  31829. if (callbackNeeded.compareAndSetBool (1, 0))
  31830. {
  31831. postMessage (new Message());
  31832. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31833. when the app has a modal loop), so this is how long to wait before assuming the
  31834. message has been lost and trying again.
  31835. */
  31836. const uint32 messageDeliveryTimeout = now + 2000;
  31837. while (callbackNeeded.get() != 0)
  31838. {
  31839. wait (4);
  31840. if (threadShouldExit())
  31841. return;
  31842. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31843. break;
  31844. }
  31845. }
  31846. }
  31847. else
  31848. {
  31849. // don't wait for too long because running this loop also helps keep the
  31850. // Time::getApproximateMillisecondTimer value stay up-to-date
  31851. wait (jlimit (1, 50, timeUntilFirstTimer));
  31852. }
  31853. }
  31854. }
  31855. void callTimers()
  31856. {
  31857. const ScopedLock sl (lock);
  31858. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31859. {
  31860. Timer* const t = firstTimer;
  31861. t->countdownMs = t->periodMs;
  31862. removeTimer (t);
  31863. addTimer (t);
  31864. const ScopedUnlock ul (lock);
  31865. JUCE_TRY
  31866. {
  31867. t->timerCallback();
  31868. }
  31869. JUCE_CATCH_EXCEPTION
  31870. }
  31871. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31872. before the boolean is set. This set should never fail since if it was false in the first place,
  31873. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31874. get a message then the value is true and the other thread can only set it to true again and
  31875. we will get another callback to set it to false.
  31876. */
  31877. callbackNeeded.set (0);
  31878. }
  31879. void handleMessage (const Message&)
  31880. {
  31881. callTimers();
  31882. }
  31883. void callTimersSynchronously()
  31884. {
  31885. if (! isThreadRunning())
  31886. {
  31887. // (This is relied on by some plugins in cases where the MM has
  31888. // had to restart and the async callback never started)
  31889. cancelPendingUpdate();
  31890. triggerAsyncUpdate();
  31891. }
  31892. callTimers();
  31893. }
  31894. static void callAnyTimersSynchronously()
  31895. {
  31896. if (InternalTimerThread::instance != 0)
  31897. InternalTimerThread::instance->callTimersSynchronously();
  31898. }
  31899. static inline void add (Timer* const tim) throw()
  31900. {
  31901. if (instance == 0)
  31902. instance = new InternalTimerThread();
  31903. const ScopedLock sl (instance->lock);
  31904. instance->addTimer (tim);
  31905. }
  31906. static inline void remove (Timer* const tim) throw()
  31907. {
  31908. if (instance != 0)
  31909. {
  31910. const ScopedLock sl (instance->lock);
  31911. instance->removeTimer (tim);
  31912. }
  31913. }
  31914. static inline void resetCounter (Timer* const tim,
  31915. const int newCounter) throw()
  31916. {
  31917. if (instance != 0)
  31918. {
  31919. tim->countdownMs = newCounter;
  31920. tim->periodMs = newCounter;
  31921. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31922. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31923. {
  31924. const ScopedLock sl (instance->lock);
  31925. instance->removeTimer (tim);
  31926. instance->addTimer (tim);
  31927. }
  31928. }
  31929. }
  31930. private:
  31931. friend class Timer;
  31932. static InternalTimerThread* instance;
  31933. static CriticalSection lock;
  31934. Timer* volatile firstTimer;
  31935. Atomic <int> callbackNeeded;
  31936. void addTimer (Timer* const t) throw()
  31937. {
  31938. #if JUCE_DEBUG
  31939. Timer* tt = firstTimer;
  31940. while (tt != 0)
  31941. {
  31942. // trying to add a timer that's already here - shouldn't get to this point,
  31943. // so if you get this assertion, let me know!
  31944. jassert (tt != t);
  31945. tt = tt->next;
  31946. }
  31947. jassert (t->previous == 0 && t->next == 0);
  31948. #endif
  31949. Timer* i = firstTimer;
  31950. if (i == 0 || i->countdownMs > t->countdownMs)
  31951. {
  31952. t->next = firstTimer;
  31953. firstTimer = t;
  31954. }
  31955. else
  31956. {
  31957. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31958. i = i->next;
  31959. jassert (i != 0);
  31960. t->next = i->next;
  31961. t->previous = i;
  31962. i->next = t;
  31963. }
  31964. if (t->next != 0)
  31965. t->next->previous = t;
  31966. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31967. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31968. notify();
  31969. }
  31970. void removeTimer (Timer* const t) throw()
  31971. {
  31972. #if JUCE_DEBUG
  31973. Timer* tt = firstTimer;
  31974. bool found = false;
  31975. while (tt != 0)
  31976. {
  31977. if (tt == t)
  31978. {
  31979. found = true;
  31980. break;
  31981. }
  31982. tt = tt->next;
  31983. }
  31984. // trying to remove a timer that's not here - shouldn't get to this point,
  31985. // so if you get this assertion, let me know!
  31986. jassert (found);
  31987. #endif
  31988. if (t->previous != 0)
  31989. {
  31990. jassert (firstTimer != t);
  31991. t->previous->next = t->next;
  31992. }
  31993. else
  31994. {
  31995. jassert (firstTimer == t);
  31996. firstTimer = t->next;
  31997. }
  31998. if (t->next != 0)
  31999. t->next->previous = t->previous;
  32000. t->next = 0;
  32001. t->previous = 0;
  32002. }
  32003. void decrementAllCounters (const int numMillisecs) const
  32004. {
  32005. Timer* t = firstTimer;
  32006. while (t != 0)
  32007. {
  32008. t->countdownMs -= numMillisecs;
  32009. t = t->next;
  32010. }
  32011. }
  32012. void handleAsyncUpdate()
  32013. {
  32014. startThread (7);
  32015. }
  32016. InternalTimerThread (const InternalTimerThread&);
  32017. InternalTimerThread& operator= (const InternalTimerThread&);
  32018. };
  32019. InternalTimerThread* InternalTimerThread::instance = 0;
  32020. CriticalSection InternalTimerThread::lock;
  32021. void juce_callAnyTimersSynchronously()
  32022. {
  32023. InternalTimerThread::callAnyTimersSynchronously();
  32024. }
  32025. #if JUCE_DEBUG
  32026. static SortedSet <Timer*> activeTimers;
  32027. #endif
  32028. Timer::Timer() throw()
  32029. : countdownMs (0),
  32030. periodMs (0),
  32031. previous (0),
  32032. next (0)
  32033. {
  32034. #if JUCE_DEBUG
  32035. activeTimers.add (this);
  32036. #endif
  32037. }
  32038. Timer::Timer (const Timer&) throw()
  32039. : countdownMs (0),
  32040. periodMs (0),
  32041. previous (0),
  32042. next (0)
  32043. {
  32044. #if JUCE_DEBUG
  32045. activeTimers.add (this);
  32046. #endif
  32047. }
  32048. Timer::~Timer()
  32049. {
  32050. stopTimer();
  32051. #if JUCE_DEBUG
  32052. activeTimers.removeValue (this);
  32053. #endif
  32054. }
  32055. void Timer::startTimer (const int interval) throw()
  32056. {
  32057. const ScopedLock sl (InternalTimerThread::lock);
  32058. #if JUCE_DEBUG
  32059. // this isn't a valid object! Your timer might be a dangling pointer or something..
  32060. jassert (activeTimers.contains (this));
  32061. #endif
  32062. if (periodMs == 0)
  32063. {
  32064. countdownMs = interval;
  32065. periodMs = jmax (1, interval);
  32066. InternalTimerThread::add (this);
  32067. }
  32068. else
  32069. {
  32070. InternalTimerThread::resetCounter (this, interval);
  32071. }
  32072. }
  32073. void Timer::stopTimer() throw()
  32074. {
  32075. const ScopedLock sl (InternalTimerThread::lock);
  32076. #if JUCE_DEBUG
  32077. // this isn't a valid object! Your timer might be a dangling pointer or something..
  32078. jassert (activeTimers.contains (this));
  32079. #endif
  32080. if (periodMs > 0)
  32081. {
  32082. InternalTimerThread::remove (this);
  32083. periodMs = 0;
  32084. }
  32085. }
  32086. END_JUCE_NAMESPACE
  32087. /*** End of inlined file: juce_Timer.cpp ***/
  32088. #endif
  32089. #if JUCE_BUILD_GUI
  32090. /*** Start of inlined file: juce_Component.cpp ***/
  32091. BEGIN_JUCE_NAMESPACE
  32092. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  32093. enum ComponentMessageNumbers
  32094. {
  32095. customCommandMessage = 0x7fff0001,
  32096. exitModalStateMessage = 0x7fff0002
  32097. };
  32098. static uint32 nextComponentUID = 0;
  32099. Component* Component::currentlyFocusedComponent = 0;
  32100. Component::Component()
  32101. : parentComponent_ (0),
  32102. componentUID (++nextComponentUID),
  32103. numDeepMouseListeners (0),
  32104. lookAndFeel_ (0),
  32105. effect_ (0),
  32106. bufferedImage_ (0),
  32107. mouseListeners_ (0),
  32108. keyListeners_ (0),
  32109. componentFlags_ (0)
  32110. {
  32111. }
  32112. Component::Component (const String& name)
  32113. : componentName_ (name),
  32114. parentComponent_ (0),
  32115. componentUID (++nextComponentUID),
  32116. numDeepMouseListeners (0),
  32117. lookAndFeel_ (0),
  32118. effect_ (0),
  32119. bufferedImage_ (0),
  32120. mouseListeners_ (0),
  32121. keyListeners_ (0),
  32122. componentFlags_ (0)
  32123. {
  32124. }
  32125. Component::~Component()
  32126. {
  32127. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32128. if (parentComponent_ != 0)
  32129. {
  32130. parentComponent_->removeChildComponent (this);
  32131. }
  32132. else if ((currentlyFocusedComponent == this)
  32133. || isParentOf (currentlyFocusedComponent))
  32134. {
  32135. giveAwayFocus();
  32136. }
  32137. if (flags.hasHeavyweightPeerFlag)
  32138. removeFromDesktop();
  32139. for (int i = childComponentList_.size(); --i >= 0;)
  32140. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  32141. delete mouseListeners_;
  32142. delete keyListeners_;
  32143. }
  32144. void Component::setName (const String& name)
  32145. {
  32146. // if component methods are being called from threads other than the message
  32147. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32148. checkMessageManagerIsLocked
  32149. if (componentName_ != name)
  32150. {
  32151. componentName_ = name;
  32152. if (flags.hasHeavyweightPeerFlag)
  32153. {
  32154. ComponentPeer* const peer = getPeer();
  32155. jassert (peer != 0);
  32156. if (peer != 0)
  32157. peer->setTitle (name);
  32158. }
  32159. BailOutChecker checker (this);
  32160. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32161. }
  32162. }
  32163. void Component::setVisible (bool shouldBeVisible)
  32164. {
  32165. if (flags.visibleFlag != shouldBeVisible)
  32166. {
  32167. // if component methods are being called from threads other than the message
  32168. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32169. checkMessageManagerIsLocked
  32170. SafePointer<Component> safePointer (this);
  32171. flags.visibleFlag = shouldBeVisible;
  32172. internalRepaint (0, 0, getWidth(), getHeight());
  32173. sendFakeMouseMove();
  32174. if (! shouldBeVisible)
  32175. {
  32176. if (currentlyFocusedComponent == this
  32177. || isParentOf (currentlyFocusedComponent))
  32178. {
  32179. if (parentComponent_ != 0)
  32180. parentComponent_->grabKeyboardFocus();
  32181. else
  32182. giveAwayFocus();
  32183. }
  32184. }
  32185. if (safePointer != 0)
  32186. {
  32187. sendVisibilityChangeMessage();
  32188. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32189. {
  32190. ComponentPeer* const peer = getPeer();
  32191. jassert (peer != 0);
  32192. if (peer != 0)
  32193. {
  32194. peer->setVisible (shouldBeVisible);
  32195. internalHierarchyChanged();
  32196. }
  32197. }
  32198. }
  32199. }
  32200. }
  32201. void Component::visibilityChanged()
  32202. {
  32203. }
  32204. void Component::sendVisibilityChangeMessage()
  32205. {
  32206. BailOutChecker checker (this);
  32207. visibilityChanged();
  32208. if (! checker.shouldBailOut())
  32209. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32210. }
  32211. bool Component::isShowing() const
  32212. {
  32213. if (flags.visibleFlag)
  32214. {
  32215. if (parentComponent_ != 0)
  32216. {
  32217. return parentComponent_->isShowing();
  32218. }
  32219. else
  32220. {
  32221. const ComponentPeer* const peer = getPeer();
  32222. return peer != 0 && ! peer->isMinimised();
  32223. }
  32224. }
  32225. return false;
  32226. }
  32227. class FadeOutProxyComponent : public Component,
  32228. public Timer
  32229. {
  32230. public:
  32231. FadeOutProxyComponent (Component* comp,
  32232. const int fadeLengthMs,
  32233. const int deltaXToMove,
  32234. const int deltaYToMove,
  32235. const float scaleFactorAtEnd)
  32236. : lastTime (0),
  32237. alpha (1.0f),
  32238. scale (1.0f)
  32239. {
  32240. image = comp->createComponentSnapshot (comp->getLocalBounds());
  32241. setBounds (comp->getBounds());
  32242. comp->getParentComponent()->addAndMakeVisible (this);
  32243. toBehind (comp);
  32244. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  32245. centreX = comp->getX() + comp->getWidth() * 0.5f;
  32246. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  32247. centreY = comp->getY() + comp->getHeight() * 0.5f;
  32248. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  32249. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  32250. setInterceptsMouseClicks (false, false);
  32251. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  32252. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  32253. }
  32254. ~FadeOutProxyComponent()
  32255. {
  32256. }
  32257. void paint (Graphics& g)
  32258. {
  32259. g.setOpacity (alpha);
  32260. g.drawImage (image,
  32261. 0, 0, getWidth(), getHeight(),
  32262. 0, 0, image.getWidth(), image.getHeight());
  32263. }
  32264. void timerCallback()
  32265. {
  32266. const uint32 now = Time::getMillisecondCounter();
  32267. if (lastTime == 0)
  32268. lastTime = now;
  32269. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  32270. lastTime = now;
  32271. alpha += alphaChangePerMs * msPassed;
  32272. if (alpha > 0)
  32273. {
  32274. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  32275. {
  32276. centreX += xChangePerMs * msPassed;
  32277. centreY += yChangePerMs * msPassed;
  32278. scale += scaleChangePerMs * msPassed;
  32279. const int w = roundToInt (image.getWidth() * scale);
  32280. const int h = roundToInt (image.getHeight() * scale);
  32281. setBounds (roundToInt (centreX) - w / 2,
  32282. roundToInt (centreY) - h / 2,
  32283. w, h);
  32284. }
  32285. repaint();
  32286. }
  32287. else
  32288. {
  32289. delete this;
  32290. }
  32291. }
  32292. juce_UseDebuggingNewOperator
  32293. private:
  32294. Image image;
  32295. uint32 lastTime;
  32296. float alpha, alphaChangePerMs;
  32297. float centreX, xChangePerMs;
  32298. float centreY, yChangePerMs;
  32299. float scale, scaleChangePerMs;
  32300. FadeOutProxyComponent (const FadeOutProxyComponent&);
  32301. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  32302. };
  32303. void Component::fadeOutComponent (const int millisecondsToFade,
  32304. const int deltaXToMove,
  32305. const int deltaYToMove,
  32306. const float scaleFactorAtEnd)
  32307. {
  32308. //xxx won't work for comps without parents
  32309. if (isShowing() && millisecondsToFade > 0)
  32310. new FadeOutProxyComponent (this, millisecondsToFade,
  32311. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  32312. setVisible (false);
  32313. }
  32314. bool Component::isValidComponent() const
  32315. {
  32316. return (this != 0) && isValidMessageListener();
  32317. }
  32318. void* Component::getWindowHandle() const
  32319. {
  32320. const ComponentPeer* const peer = getPeer();
  32321. if (peer != 0)
  32322. return peer->getNativeHandle();
  32323. return 0;
  32324. }
  32325. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32326. {
  32327. // if component methods are being called from threads other than the message
  32328. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32329. checkMessageManagerIsLocked
  32330. if (isOpaque())
  32331. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32332. else
  32333. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32334. int currentStyleFlags = 0;
  32335. // don't use getPeer(), so that we only get the peer that's specifically
  32336. // for this comp, and not for one of its parents.
  32337. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32338. if (peer != 0)
  32339. currentStyleFlags = peer->getStyleFlags();
  32340. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32341. {
  32342. SafePointer<Component> safePointer (this);
  32343. #if JUCE_LINUX
  32344. // it's wise to give the component a non-zero size before
  32345. // putting it on the desktop, as X windows get confused by this, and
  32346. // a (1, 1) minimum size is enforced here.
  32347. setSize (jmax (1, getWidth()),
  32348. jmax (1, getHeight()));
  32349. #endif
  32350. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32351. bool wasFullscreen = false;
  32352. bool wasMinimised = false;
  32353. ComponentBoundsConstrainer* currentConstainer = 0;
  32354. Rectangle<int> oldNonFullScreenBounds;
  32355. if (peer != 0)
  32356. {
  32357. wasFullscreen = peer->isFullScreen();
  32358. wasMinimised = peer->isMinimised();
  32359. currentConstainer = peer->getConstrainer();
  32360. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32361. removeFromDesktop();
  32362. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32363. }
  32364. if (parentComponent_ != 0)
  32365. parentComponent_->removeChildComponent (this);
  32366. if (safePointer != 0)
  32367. {
  32368. flags.hasHeavyweightPeerFlag = true;
  32369. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32370. Desktop::getInstance().addDesktopComponent (this);
  32371. bounds_.setPosition (topLeft);
  32372. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32373. peer->setVisible (isVisible());
  32374. if (wasFullscreen)
  32375. {
  32376. peer->setFullScreen (true);
  32377. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32378. }
  32379. if (wasMinimised)
  32380. peer->setMinimised (true);
  32381. if (isAlwaysOnTop())
  32382. peer->setAlwaysOnTop (true);
  32383. peer->setConstrainer (currentConstainer);
  32384. repaint();
  32385. }
  32386. internalHierarchyChanged();
  32387. }
  32388. }
  32389. void Component::removeFromDesktop()
  32390. {
  32391. // if component methods are being called from threads other than the message
  32392. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32393. checkMessageManagerIsLocked
  32394. if (flags.hasHeavyweightPeerFlag)
  32395. {
  32396. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32397. flags.hasHeavyweightPeerFlag = false;
  32398. jassert (peer != 0);
  32399. delete peer;
  32400. Desktop::getInstance().removeDesktopComponent (this);
  32401. }
  32402. }
  32403. bool Component::isOnDesktop() const throw()
  32404. {
  32405. return flags.hasHeavyweightPeerFlag;
  32406. }
  32407. void Component::userTriedToCloseWindow()
  32408. {
  32409. /* This means that the user's trying to get rid of your window with the 'close window' system
  32410. menu option (on windows) or possibly the task manager - you should really handle this
  32411. and delete or hide your component in an appropriate way.
  32412. If you want to ignore the event and don't want to trigger this assertion, just override
  32413. this method and do nothing.
  32414. */
  32415. jassertfalse;
  32416. }
  32417. void Component::minimisationStateChanged (bool)
  32418. {
  32419. }
  32420. void Component::setOpaque (const bool shouldBeOpaque)
  32421. {
  32422. if (shouldBeOpaque != flags.opaqueFlag)
  32423. {
  32424. flags.opaqueFlag = shouldBeOpaque;
  32425. if (flags.hasHeavyweightPeerFlag)
  32426. {
  32427. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32428. if (peer != 0)
  32429. {
  32430. // to make it recreate the heavyweight window
  32431. addToDesktop (peer->getStyleFlags());
  32432. }
  32433. }
  32434. repaint();
  32435. }
  32436. }
  32437. bool Component::isOpaque() const throw()
  32438. {
  32439. return flags.opaqueFlag;
  32440. }
  32441. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32442. {
  32443. if (shouldBeBuffered != flags.bufferToImageFlag)
  32444. {
  32445. bufferedImage_ = Image::null;
  32446. flags.bufferToImageFlag = shouldBeBuffered;
  32447. }
  32448. }
  32449. void Component::toFront (const bool setAsForeground)
  32450. {
  32451. // if component methods are being called from threads other than the message
  32452. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32453. checkMessageManagerIsLocked
  32454. if (flags.hasHeavyweightPeerFlag)
  32455. {
  32456. ComponentPeer* const peer = getPeer();
  32457. if (peer != 0)
  32458. {
  32459. peer->toFront (setAsForeground);
  32460. if (setAsForeground && ! hasKeyboardFocus (true))
  32461. grabKeyboardFocus();
  32462. }
  32463. }
  32464. else if (parentComponent_ != 0)
  32465. {
  32466. Array<Component*>& childList = parentComponent_->childComponentList_;
  32467. if (childList.getLast() != this)
  32468. {
  32469. const int index = childList.indexOf (this);
  32470. if (index >= 0)
  32471. {
  32472. int insertIndex = -1;
  32473. if (! flags.alwaysOnTopFlag)
  32474. {
  32475. insertIndex = childList.size() - 1;
  32476. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32477. --insertIndex;
  32478. }
  32479. if (index != insertIndex)
  32480. {
  32481. childList.move (index, insertIndex);
  32482. sendFakeMouseMove();
  32483. repaintParent();
  32484. }
  32485. }
  32486. }
  32487. if (setAsForeground)
  32488. {
  32489. internalBroughtToFront();
  32490. grabKeyboardFocus();
  32491. }
  32492. }
  32493. }
  32494. void Component::toBehind (Component* const other)
  32495. {
  32496. if (other != 0 && other != this)
  32497. {
  32498. // the two components must belong to the same parent..
  32499. jassert (parentComponent_ == other->parentComponent_);
  32500. if (parentComponent_ != 0)
  32501. {
  32502. Array<Component*>& childList = parentComponent_->childComponentList_;
  32503. const int index = childList.indexOf (this);
  32504. if (index >= 0 && childList [index + 1] != other)
  32505. {
  32506. int otherIndex = childList.indexOf (other);
  32507. if (otherIndex >= 0)
  32508. {
  32509. if (index < otherIndex)
  32510. --otherIndex;
  32511. childList.move (index, otherIndex);
  32512. sendFakeMouseMove();
  32513. repaintParent();
  32514. }
  32515. }
  32516. }
  32517. else if (isOnDesktop())
  32518. {
  32519. jassert (other->isOnDesktop());
  32520. if (other->isOnDesktop())
  32521. {
  32522. ComponentPeer* const us = getPeer();
  32523. ComponentPeer* const them = other->getPeer();
  32524. jassert (us != 0 && them != 0);
  32525. if (us != 0 && them != 0)
  32526. us->toBehind (them);
  32527. }
  32528. }
  32529. }
  32530. }
  32531. void Component::toBack()
  32532. {
  32533. Array<Component*>& childList = parentComponent_->childComponentList_;
  32534. if (isOnDesktop())
  32535. {
  32536. jassertfalse; //xxx need to add this to native window
  32537. }
  32538. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32539. {
  32540. const int index = childList.indexOf (this);
  32541. if (index > 0)
  32542. {
  32543. int insertIndex = 0;
  32544. if (flags.alwaysOnTopFlag)
  32545. {
  32546. while (insertIndex < childList.size()
  32547. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32548. {
  32549. ++insertIndex;
  32550. }
  32551. }
  32552. if (index != insertIndex)
  32553. {
  32554. childList.move (index, insertIndex);
  32555. sendFakeMouseMove();
  32556. repaintParent();
  32557. }
  32558. }
  32559. }
  32560. }
  32561. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32562. {
  32563. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32564. {
  32565. flags.alwaysOnTopFlag = shouldStayOnTop;
  32566. if (isOnDesktop())
  32567. {
  32568. ComponentPeer* const peer = getPeer();
  32569. jassert (peer != 0);
  32570. if (peer != 0)
  32571. {
  32572. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32573. {
  32574. // some kinds of peer can't change their always-on-top status, so
  32575. // for these, we'll need to create a new window
  32576. const int oldFlags = peer->getStyleFlags();
  32577. removeFromDesktop();
  32578. addToDesktop (oldFlags);
  32579. }
  32580. }
  32581. }
  32582. if (shouldStayOnTop)
  32583. toFront (false);
  32584. internalHierarchyChanged();
  32585. }
  32586. }
  32587. bool Component::isAlwaysOnTop() const throw()
  32588. {
  32589. return flags.alwaysOnTopFlag;
  32590. }
  32591. int Component::proportionOfWidth (const float proportion) const throw()
  32592. {
  32593. return roundToInt (proportion * bounds_.getWidth());
  32594. }
  32595. int Component::proportionOfHeight (const float proportion) const throw()
  32596. {
  32597. return roundToInt (proportion * bounds_.getHeight());
  32598. }
  32599. int Component::getParentWidth() const throw()
  32600. {
  32601. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32602. : getParentMonitorArea().getWidth();
  32603. }
  32604. int Component::getParentHeight() const throw()
  32605. {
  32606. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32607. : getParentMonitorArea().getHeight();
  32608. }
  32609. int Component::getScreenX() const
  32610. {
  32611. return getScreenPosition().getX();
  32612. }
  32613. int Component::getScreenY() const
  32614. {
  32615. return getScreenPosition().getY();
  32616. }
  32617. const Point<int> Component::getScreenPosition() const
  32618. {
  32619. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32620. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32621. : getPosition());
  32622. }
  32623. const Rectangle<int> Component::getScreenBounds() const
  32624. {
  32625. return bounds_.withPosition (getScreenPosition());
  32626. }
  32627. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32628. {
  32629. const Component* c = this;
  32630. Point<int> p (relativePosition);
  32631. do
  32632. {
  32633. if (c->flags.hasHeavyweightPeerFlag)
  32634. return c->getPeer()->relativePositionToGlobal (p);
  32635. p += c->getPosition();
  32636. c = c->parentComponent_;
  32637. }
  32638. while (c != 0);
  32639. return p;
  32640. }
  32641. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32642. {
  32643. if (flags.hasHeavyweightPeerFlag)
  32644. {
  32645. return getPeer()->globalPositionToRelative (screenPosition);
  32646. }
  32647. else
  32648. {
  32649. if (parentComponent_ != 0)
  32650. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32651. return screenPosition - getPosition();
  32652. }
  32653. }
  32654. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32655. {
  32656. Point<int> p (positionRelativeToThis);
  32657. if (targetComponent != 0)
  32658. {
  32659. const Component* c = this;
  32660. do
  32661. {
  32662. if (c == targetComponent)
  32663. return p;
  32664. if (c->flags.hasHeavyweightPeerFlag)
  32665. {
  32666. p = c->getPeer()->relativePositionToGlobal (p);
  32667. break;
  32668. }
  32669. p += c->getPosition();
  32670. c = c->parentComponent_;
  32671. }
  32672. while (c != 0);
  32673. p = targetComponent->globalPositionToRelative (p);
  32674. }
  32675. return p;
  32676. }
  32677. void Component::setBounds (const int x, const int y, int w, int h)
  32678. {
  32679. // if component methods are being called from threads other than the message
  32680. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32681. checkMessageManagerIsLocked
  32682. if (w < 0) w = 0;
  32683. if (h < 0) h = 0;
  32684. const bool wasResized = (getWidth() != w || getHeight() != h);
  32685. const bool wasMoved = (getX() != x || getY() != y);
  32686. #if JUCE_DEBUG
  32687. // It's a very bad idea to try to resize a window during its paint() method!
  32688. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32689. #endif
  32690. if (wasMoved || wasResized)
  32691. {
  32692. if (flags.visibleFlag)
  32693. {
  32694. // send a fake mouse move to trigger enter/exit messages if needed..
  32695. sendFakeMouseMove();
  32696. if (! flags.hasHeavyweightPeerFlag)
  32697. repaintParent();
  32698. }
  32699. bounds_.setBounds (x, y, w, h);
  32700. if (wasResized)
  32701. repaint();
  32702. else if (! flags.hasHeavyweightPeerFlag)
  32703. repaintParent();
  32704. if (flags.hasHeavyweightPeerFlag)
  32705. {
  32706. ComponentPeer* const peer = getPeer();
  32707. if (peer != 0)
  32708. {
  32709. if (wasMoved && wasResized)
  32710. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32711. else if (wasMoved)
  32712. peer->setPosition (getX(), getY());
  32713. else if (wasResized)
  32714. peer->setSize (getWidth(), getHeight());
  32715. }
  32716. }
  32717. sendMovedResizedMessages (wasMoved, wasResized);
  32718. }
  32719. }
  32720. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32721. {
  32722. JUCE_TRY
  32723. {
  32724. if (wasMoved)
  32725. moved();
  32726. if (wasResized)
  32727. {
  32728. resized();
  32729. for (int i = childComponentList_.size(); --i >= 0;)
  32730. {
  32731. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32732. i = jmin (i, childComponentList_.size());
  32733. }
  32734. }
  32735. BailOutChecker checker (this);
  32736. if (parentComponent_ != 0)
  32737. parentComponent_->childBoundsChanged (this);
  32738. if (! checker.shouldBailOut())
  32739. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32740. *this, wasMoved, wasResized);
  32741. }
  32742. JUCE_CATCH_EXCEPTION
  32743. }
  32744. void Component::setSize (const int w, const int h)
  32745. {
  32746. setBounds (getX(), getY(), w, h);
  32747. }
  32748. void Component::setTopLeftPosition (const int x, const int y)
  32749. {
  32750. setBounds (x, y, getWidth(), getHeight());
  32751. }
  32752. void Component::setTopRightPosition (const int x, const int y)
  32753. {
  32754. setTopLeftPosition (x - getWidth(), y);
  32755. }
  32756. void Component::setBounds (const Rectangle<int>& r)
  32757. {
  32758. setBounds (r.getX(),
  32759. r.getY(),
  32760. r.getWidth(),
  32761. r.getHeight());
  32762. }
  32763. void Component::setBoundsRelative (const float x, const float y,
  32764. const float w, const float h)
  32765. {
  32766. const int pw = getParentWidth();
  32767. const int ph = getParentHeight();
  32768. setBounds (roundToInt (x * pw),
  32769. roundToInt (y * ph),
  32770. roundToInt (w * pw),
  32771. roundToInt (h * ph));
  32772. }
  32773. void Component::setCentrePosition (const int x, const int y)
  32774. {
  32775. setTopLeftPosition (x - getWidth() / 2,
  32776. y - getHeight() / 2);
  32777. }
  32778. void Component::setCentreRelative (const float x, const float y)
  32779. {
  32780. setCentrePosition (roundToInt (getParentWidth() * x),
  32781. roundToInt (getParentHeight() * y));
  32782. }
  32783. void Component::centreWithSize (const int width, const int height)
  32784. {
  32785. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32786. setBounds (parentArea.getCentreX() - width / 2,
  32787. parentArea.getCentreY() - height / 2,
  32788. width, height);
  32789. }
  32790. void Component::setBoundsInset (const BorderSize& borders)
  32791. {
  32792. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32793. }
  32794. void Component::setBoundsToFit (int x, int y, int width, int height,
  32795. const Justification& justification,
  32796. const bool onlyReduceInSize)
  32797. {
  32798. // it's no good calling this method unless both the component and
  32799. // target rectangle have a finite size.
  32800. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32801. if (getWidth() > 0 && getHeight() > 0
  32802. && width > 0 && height > 0)
  32803. {
  32804. int newW, newH;
  32805. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32806. {
  32807. newW = getWidth();
  32808. newH = getHeight();
  32809. }
  32810. else
  32811. {
  32812. const double imageRatio = getHeight() / (double) getWidth();
  32813. const double targetRatio = height / (double) width;
  32814. if (imageRatio <= targetRatio)
  32815. {
  32816. newW = width;
  32817. newH = jmin (height, roundToInt (newW * imageRatio));
  32818. }
  32819. else
  32820. {
  32821. newH = height;
  32822. newW = jmin (width, roundToInt (newH / imageRatio));
  32823. }
  32824. }
  32825. if (newW > 0 && newH > 0)
  32826. {
  32827. int newX, newY;
  32828. justification.applyToRectangle (newX, newY, newW, newH,
  32829. x, y, width, height);
  32830. setBounds (newX, newY, newW, newH);
  32831. }
  32832. }
  32833. }
  32834. bool Component::hitTest (int x, int y)
  32835. {
  32836. if (! flags.ignoresMouseClicksFlag)
  32837. return true;
  32838. if (flags.allowChildMouseClicksFlag)
  32839. {
  32840. for (int i = getNumChildComponents(); --i >= 0;)
  32841. {
  32842. Component* const c = getChildComponent (i);
  32843. if (c->isVisible()
  32844. && c->bounds_.contains (x, y)
  32845. && c->hitTest (x - c->getX(),
  32846. y - c->getY()))
  32847. {
  32848. return true;
  32849. }
  32850. }
  32851. }
  32852. return false;
  32853. }
  32854. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32855. const bool allowClicksOnChildComponents) throw()
  32856. {
  32857. flags.ignoresMouseClicksFlag = ! allowClicks;
  32858. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32859. }
  32860. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32861. bool& allowsClicksOnChildComponents) const throw()
  32862. {
  32863. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32864. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32865. }
  32866. bool Component::contains (const int x, const int y)
  32867. {
  32868. if (((unsigned int) x) < (unsigned int) getWidth()
  32869. && ((unsigned int) y) < (unsigned int) getHeight()
  32870. && hitTest (x, y))
  32871. {
  32872. if (parentComponent_ != 0)
  32873. {
  32874. return parentComponent_->contains (x + getX(),
  32875. y + getY());
  32876. }
  32877. else if (flags.hasHeavyweightPeerFlag)
  32878. {
  32879. const ComponentPeer* const peer = getPeer();
  32880. if (peer != 0)
  32881. return peer->contains (Point<int> (x, y), true);
  32882. }
  32883. }
  32884. return false;
  32885. }
  32886. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32887. {
  32888. if (! contains (x, y))
  32889. return false;
  32890. Component* p = this;
  32891. while (p->parentComponent_ != 0)
  32892. {
  32893. x += p->getX();
  32894. y += p->getY();
  32895. p = p->parentComponent_;
  32896. }
  32897. const Component* const c = p->getComponentAt (x, y);
  32898. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32899. }
  32900. Component* Component::getComponentAt (const Point<int>& position)
  32901. {
  32902. return getComponentAt (position.getX(), position.getY());
  32903. }
  32904. Component* Component::getComponentAt (const int x, const int y)
  32905. {
  32906. if (flags.visibleFlag
  32907. && ((unsigned int) x) < (unsigned int) getWidth()
  32908. && ((unsigned int) y) < (unsigned int) getHeight()
  32909. && hitTest (x, y))
  32910. {
  32911. for (int i = childComponentList_.size(); --i >= 0;)
  32912. {
  32913. Component* const child = childComponentList_.getUnchecked(i);
  32914. Component* const c = child->getComponentAt (x - child->getX(),
  32915. y - child->getY());
  32916. if (c != 0)
  32917. return c;
  32918. }
  32919. return this;
  32920. }
  32921. return 0;
  32922. }
  32923. void Component::addChildComponent (Component* const child, int zOrder)
  32924. {
  32925. // if component methods are being called from threads other than the message
  32926. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32927. checkMessageManagerIsLocked
  32928. if (child != 0 && child->parentComponent_ != this)
  32929. {
  32930. if (child->parentComponent_ != 0)
  32931. child->parentComponent_->removeChildComponent (child);
  32932. else
  32933. child->removeFromDesktop();
  32934. child->parentComponent_ = this;
  32935. if (child->isVisible())
  32936. child->repaintParent();
  32937. if (! child->isAlwaysOnTop())
  32938. {
  32939. if (zOrder < 0 || zOrder > childComponentList_.size())
  32940. zOrder = childComponentList_.size();
  32941. while (zOrder > 0)
  32942. {
  32943. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32944. break;
  32945. --zOrder;
  32946. }
  32947. }
  32948. childComponentList_.insert (zOrder, child);
  32949. child->internalHierarchyChanged();
  32950. internalChildrenChanged();
  32951. }
  32952. }
  32953. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32954. {
  32955. if (child != 0)
  32956. {
  32957. child->setVisible (true);
  32958. addChildComponent (child, zOrder);
  32959. }
  32960. }
  32961. void Component::removeChildComponent (Component* const child)
  32962. {
  32963. removeChildComponent (childComponentList_.indexOf (child));
  32964. }
  32965. Component* Component::removeChildComponent (const int index)
  32966. {
  32967. // if component methods are being called from threads other than the message
  32968. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32969. checkMessageManagerIsLocked
  32970. Component* const child = childComponentList_ [index];
  32971. if (child != 0)
  32972. {
  32973. sendFakeMouseMove();
  32974. child->repaintParent();
  32975. childComponentList_.remove (index);
  32976. child->parentComponent_ = 0;
  32977. JUCE_TRY
  32978. {
  32979. if ((currentlyFocusedComponent == child)
  32980. || child->isParentOf (currentlyFocusedComponent))
  32981. {
  32982. // get rid first to force the grabKeyboardFocus to change to us.
  32983. giveAwayFocus();
  32984. grabKeyboardFocus();
  32985. }
  32986. }
  32987. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32988. catch (const std::exception& e)
  32989. {
  32990. currentlyFocusedComponent = 0;
  32991. Desktop::getInstance().triggerFocusCallback();
  32992. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32993. }
  32994. catch (...)
  32995. {
  32996. currentlyFocusedComponent = 0;
  32997. Desktop::getInstance().triggerFocusCallback();
  32998. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32999. }
  33000. #endif
  33001. child->internalHierarchyChanged();
  33002. internalChildrenChanged();
  33003. }
  33004. return child;
  33005. }
  33006. void Component::removeAllChildren()
  33007. {
  33008. while (childComponentList_.size() > 0)
  33009. removeChildComponent (childComponentList_.size() - 1);
  33010. }
  33011. void Component::deleteAllChildren()
  33012. {
  33013. while (childComponentList_.size() > 0)
  33014. delete (removeChildComponent (childComponentList_.size() - 1));
  33015. }
  33016. int Component::getNumChildComponents() const throw()
  33017. {
  33018. return childComponentList_.size();
  33019. }
  33020. Component* Component::getChildComponent (const int index) const throw()
  33021. {
  33022. return childComponentList_ [index];
  33023. }
  33024. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  33025. {
  33026. return childComponentList_.indexOf (const_cast <Component*> (child));
  33027. }
  33028. Component* Component::getTopLevelComponent() const throw()
  33029. {
  33030. const Component* comp = this;
  33031. while (comp->parentComponent_ != 0)
  33032. comp = comp->parentComponent_;
  33033. return const_cast <Component*> (comp);
  33034. }
  33035. bool Component::isParentOf (const Component* possibleChild) const throw()
  33036. {
  33037. if (! possibleChild->isValidComponent())
  33038. {
  33039. jassert (possibleChild == 0);
  33040. return false;
  33041. }
  33042. while (possibleChild != 0)
  33043. {
  33044. possibleChild = possibleChild->parentComponent_;
  33045. if (possibleChild == this)
  33046. return true;
  33047. }
  33048. return false;
  33049. }
  33050. void Component::parentHierarchyChanged()
  33051. {
  33052. }
  33053. void Component::childrenChanged()
  33054. {
  33055. }
  33056. void Component::internalChildrenChanged()
  33057. {
  33058. if (componentListeners.isEmpty())
  33059. {
  33060. childrenChanged();
  33061. }
  33062. else
  33063. {
  33064. BailOutChecker checker (this);
  33065. childrenChanged();
  33066. if (! checker.shouldBailOut())
  33067. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  33068. }
  33069. }
  33070. void Component::internalHierarchyChanged()
  33071. {
  33072. BailOutChecker checker (this);
  33073. parentHierarchyChanged();
  33074. if (checker.shouldBailOut())
  33075. return;
  33076. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  33077. if (checker.shouldBailOut())
  33078. return;
  33079. for (int i = childComponentList_.size(); --i >= 0;)
  33080. {
  33081. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  33082. if (checker.shouldBailOut())
  33083. {
  33084. // you really shouldn't delete the parent component during a callback telling you
  33085. // that it's changed..
  33086. jassertfalse;
  33087. return;
  33088. }
  33089. i = jmin (i, childComponentList_.size());
  33090. }
  33091. }
  33092. void* Component::runModalLoopCallback (void* userData)
  33093. {
  33094. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  33095. }
  33096. int Component::runModalLoop()
  33097. {
  33098. if (! MessageManager::getInstance()->isThisTheMessageThread())
  33099. {
  33100. // use a callback so this can be called from non-gui threads
  33101. return (int) (pointer_sized_int) MessageManager::getInstance()
  33102. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  33103. }
  33104. if (! isCurrentlyModal())
  33105. enterModalState (true);
  33106. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  33107. }
  33108. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  33109. {
  33110. // if component methods are being called from threads other than the message
  33111. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33112. checkMessageManagerIsLocked
  33113. // Check for an attempt to make a component modal when it already is!
  33114. // This can cause nasty problems..
  33115. jassert (! flags.currentlyModalFlag);
  33116. if (! isCurrentlyModal())
  33117. {
  33118. ModalComponentManager::getInstance()->startModal (this, callback);
  33119. flags.currentlyModalFlag = true;
  33120. setVisible (true);
  33121. if (takeKeyboardFocus_)
  33122. grabKeyboardFocus();
  33123. }
  33124. }
  33125. void Component::exitModalState (const int returnValue)
  33126. {
  33127. if (isCurrentlyModal())
  33128. {
  33129. if (MessageManager::getInstance()->isThisTheMessageThread())
  33130. {
  33131. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33132. flags.currentlyModalFlag = false;
  33133. bringModalComponentToFront();
  33134. }
  33135. else
  33136. {
  33137. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  33138. }
  33139. }
  33140. }
  33141. bool Component::isCurrentlyModal() const throw()
  33142. {
  33143. return flags.currentlyModalFlag
  33144. && getCurrentlyModalComponent() == this;
  33145. }
  33146. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33147. {
  33148. Component* const mc = getCurrentlyModalComponent();
  33149. return mc != 0
  33150. && mc != this
  33151. && (! mc->isParentOf (this))
  33152. && ! mc->canModalEventBeSentToComponent (this);
  33153. }
  33154. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33155. {
  33156. return ModalComponentManager::getInstance()->getNumModalComponents();
  33157. }
  33158. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33159. {
  33160. return ModalComponentManager::getInstance()->getModalComponent (index);
  33161. }
  33162. void Component::bringModalComponentToFront()
  33163. {
  33164. ComponentPeer* lastOne = 0;
  33165. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  33166. {
  33167. Component* const c = getCurrentlyModalComponent (i);
  33168. if (c == 0)
  33169. break;
  33170. ComponentPeer* peer = c->getPeer();
  33171. if (peer != 0 && peer != lastOne)
  33172. {
  33173. if (lastOne == 0)
  33174. {
  33175. peer->toFront (true);
  33176. peer->grabFocus();
  33177. }
  33178. else
  33179. peer->toBehind (lastOne);
  33180. lastOne = peer;
  33181. }
  33182. }
  33183. }
  33184. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33185. {
  33186. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33187. }
  33188. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33189. {
  33190. return flags.bringToFrontOnClickFlag;
  33191. }
  33192. void Component::setMouseCursor (const MouseCursor& cursor)
  33193. {
  33194. if (cursor_ != cursor)
  33195. {
  33196. cursor_ = cursor;
  33197. if (flags.visibleFlag)
  33198. updateMouseCursor();
  33199. }
  33200. }
  33201. const MouseCursor Component::getMouseCursor()
  33202. {
  33203. return cursor_;
  33204. }
  33205. void Component::updateMouseCursor() const
  33206. {
  33207. sendFakeMouseMove();
  33208. }
  33209. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33210. {
  33211. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33212. }
  33213. void Component::repaintParent()
  33214. {
  33215. if (flags.visibleFlag)
  33216. internalRepaint (0, 0, getWidth(), getHeight());
  33217. }
  33218. void Component::repaint()
  33219. {
  33220. repaint (0, 0, getWidth(), getHeight());
  33221. }
  33222. void Component::repaint (const int x, const int y,
  33223. const int w, const int h)
  33224. {
  33225. bufferedImage_ = Image::null;
  33226. if (flags.visibleFlag)
  33227. internalRepaint (x, y, w, h);
  33228. }
  33229. void Component::repaint (const Rectangle<int>& area)
  33230. {
  33231. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33232. }
  33233. void Component::internalRepaint (int x, int y, int w, int h)
  33234. {
  33235. // if component methods are being called from threads other than the message
  33236. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33237. checkMessageManagerIsLocked
  33238. if (x < 0)
  33239. {
  33240. w += x;
  33241. x = 0;
  33242. }
  33243. if (x + w > getWidth())
  33244. w = getWidth() - x;
  33245. if (w > 0)
  33246. {
  33247. if (y < 0)
  33248. {
  33249. h += y;
  33250. y = 0;
  33251. }
  33252. if (y + h > getHeight())
  33253. h = getHeight() - y;
  33254. if (h > 0)
  33255. {
  33256. if (parentComponent_ != 0)
  33257. {
  33258. x += getX();
  33259. y += getY();
  33260. if (parentComponent_->flags.visibleFlag)
  33261. parentComponent_->internalRepaint (x, y, w, h);
  33262. }
  33263. else if (flags.hasHeavyweightPeerFlag)
  33264. {
  33265. ComponentPeer* const peer = getPeer();
  33266. if (peer != 0)
  33267. peer->repaint (Rectangle<int> (x, y, w, h));
  33268. }
  33269. }
  33270. }
  33271. }
  33272. void Component::renderComponent (Graphics& g)
  33273. {
  33274. const Rectangle<int> clipBounds (g.getClipBounds());
  33275. g.saveState();
  33276. clipObscuredRegions (g, clipBounds, 0, 0);
  33277. if (! g.isClipEmpty())
  33278. {
  33279. if (flags.bufferToImageFlag)
  33280. {
  33281. if (bufferedImage_.isNull())
  33282. {
  33283. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33284. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33285. Graphics imG (bufferedImage_);
  33286. paint (imG);
  33287. }
  33288. g.setColour (Colours::black);
  33289. g.drawImageAt (bufferedImage_, 0, 0);
  33290. }
  33291. else
  33292. {
  33293. paint (g);
  33294. }
  33295. }
  33296. g.restoreState();
  33297. for (int i = 0; i < childComponentList_.size(); ++i)
  33298. {
  33299. Component* const child = childComponentList_.getUnchecked (i);
  33300. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33301. {
  33302. g.saveState();
  33303. if (g.reduceClipRegion (child->getX(), child->getY(),
  33304. child->getWidth(), child->getHeight()))
  33305. {
  33306. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33307. {
  33308. const Component* const sibling = childComponentList_.getUnchecked (j);
  33309. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33310. g.excludeClipRegion (sibling->getBounds());
  33311. }
  33312. if (! g.isClipEmpty())
  33313. {
  33314. g.setOrigin (child->getX(), child->getY());
  33315. child->paintEntireComponent (g);
  33316. }
  33317. }
  33318. g.restoreState();
  33319. }
  33320. }
  33321. g.saveState();
  33322. paintOverChildren (g);
  33323. g.restoreState();
  33324. }
  33325. void Component::paintEntireComponent (Graphics& g)
  33326. {
  33327. jassert (! g.isClipEmpty());
  33328. #if JUCE_DEBUG
  33329. flags.isInsidePaintCall = true;
  33330. #endif
  33331. if (effect_ != 0)
  33332. {
  33333. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33334. getWidth(), getHeight(),
  33335. ! flags.opaqueFlag, Image::NativeImage);
  33336. {
  33337. Graphics g2 (effectImage);
  33338. renderComponent (g2);
  33339. }
  33340. effect_->applyEffect (effectImage, g);
  33341. }
  33342. else
  33343. {
  33344. renderComponent (g);
  33345. }
  33346. #if JUCE_DEBUG
  33347. flags.isInsidePaintCall = false;
  33348. #endif
  33349. }
  33350. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33351. const bool clipImageToComponentBounds)
  33352. {
  33353. Rectangle<int> r (areaToGrab);
  33354. if (clipImageToComponentBounds)
  33355. r = r.getIntersection (getLocalBounds());
  33356. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33357. jmax (1, r.getWidth()),
  33358. jmax (1, r.getHeight()),
  33359. true);
  33360. Graphics imageContext (componentImage);
  33361. imageContext.setOrigin (-r.getX(), -r.getY());
  33362. paintEntireComponent (imageContext);
  33363. return componentImage;
  33364. }
  33365. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33366. {
  33367. if (effect_ != effect)
  33368. {
  33369. effect_ = effect;
  33370. repaint();
  33371. }
  33372. }
  33373. LookAndFeel& Component::getLookAndFeel() const throw()
  33374. {
  33375. const Component* c = this;
  33376. do
  33377. {
  33378. if (c->lookAndFeel_ != 0)
  33379. return *(c->lookAndFeel_);
  33380. c = c->parentComponent_;
  33381. }
  33382. while (c != 0);
  33383. return LookAndFeel::getDefaultLookAndFeel();
  33384. }
  33385. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33386. {
  33387. if (lookAndFeel_ != newLookAndFeel)
  33388. {
  33389. lookAndFeel_ = newLookAndFeel;
  33390. sendLookAndFeelChange();
  33391. }
  33392. }
  33393. void Component::lookAndFeelChanged()
  33394. {
  33395. }
  33396. void Component::sendLookAndFeelChange()
  33397. {
  33398. repaint();
  33399. lookAndFeelChanged();
  33400. // (it's not a great idea to do anything that would delete this component
  33401. // during the lookAndFeelChanged() callback)
  33402. jassert (isValidComponent());
  33403. SafePointer<Component> safePointer (this);
  33404. for (int i = childComponentList_.size(); --i >= 0;)
  33405. {
  33406. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33407. if (safePointer == 0)
  33408. return;
  33409. i = jmin (i, childComponentList_.size());
  33410. }
  33411. }
  33412. static const Identifier getColourPropertyId (const int colourId)
  33413. {
  33414. String s;
  33415. s.preallocateStorage (18);
  33416. s << "jcclr_" << String::toHexString (colourId);
  33417. return s;
  33418. }
  33419. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33420. {
  33421. var* v = properties.getItem (getColourPropertyId (colourId));
  33422. if (v != 0)
  33423. return Colour ((int) *v);
  33424. if (inheritFromParent && parentComponent_ != 0)
  33425. return parentComponent_->findColour (colourId, true);
  33426. return getLookAndFeel().findColour (colourId);
  33427. }
  33428. bool Component::isColourSpecified (const int colourId) const
  33429. {
  33430. return properties.contains (getColourPropertyId (colourId));
  33431. }
  33432. void Component::removeColour (const int colourId)
  33433. {
  33434. if (properties.remove (getColourPropertyId (colourId)))
  33435. colourChanged();
  33436. }
  33437. void Component::setColour (const int colourId, const Colour& colour)
  33438. {
  33439. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  33440. colourChanged();
  33441. }
  33442. void Component::copyAllExplicitColoursTo (Component& target) const
  33443. {
  33444. bool changed = false;
  33445. for (int i = properties.size(); --i >= 0;)
  33446. {
  33447. const Identifier name (properties.getName(i));
  33448. if (name.toString().startsWith ("jcclr_"))
  33449. if (target.properties.set (name, properties [name]))
  33450. changed = true;
  33451. }
  33452. if (changed)
  33453. target.colourChanged();
  33454. }
  33455. void Component::colourChanged()
  33456. {
  33457. }
  33458. const Rectangle<int> Component::getLocalBounds() const throw()
  33459. {
  33460. return Rectangle<int> (getWidth(), getHeight());
  33461. }
  33462. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33463. {
  33464. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33465. : Desktop::getInstance().getMainMonitorArea();
  33466. }
  33467. const Rectangle<int> Component::getUnclippedArea() const
  33468. {
  33469. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33470. Component* p = parentComponent_;
  33471. int px = getX();
  33472. int py = getY();
  33473. while (p != 0)
  33474. {
  33475. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33476. return Rectangle<int>();
  33477. px += p->getX();
  33478. py += p->getY();
  33479. p = p->parentComponent_;
  33480. }
  33481. return Rectangle<int> (x, y, w, h);
  33482. }
  33483. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33484. const int deltaX, const int deltaY) const
  33485. {
  33486. for (int i = childComponentList_.size(); --i >= 0;)
  33487. {
  33488. const Component* const c = childComponentList_.getUnchecked(i);
  33489. if (c->isVisible())
  33490. {
  33491. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33492. if (! newClip.isEmpty())
  33493. {
  33494. if (c->isOpaque())
  33495. {
  33496. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33497. }
  33498. else
  33499. {
  33500. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33501. c->getX() + deltaX,
  33502. c->getY() + deltaY);
  33503. }
  33504. }
  33505. }
  33506. }
  33507. }
  33508. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33509. {
  33510. result.clear();
  33511. const Rectangle<int> unclipped (getUnclippedArea());
  33512. if (! unclipped.isEmpty())
  33513. {
  33514. result.add (unclipped);
  33515. if (includeSiblings)
  33516. {
  33517. const Component* const c = getTopLevelComponent();
  33518. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33519. c->getLocalBounds(), this);
  33520. }
  33521. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33522. result.consolidate();
  33523. }
  33524. }
  33525. void Component::subtractObscuredRegions (RectangleList& result,
  33526. const Point<int>& delta,
  33527. const Rectangle<int>& clipRect,
  33528. const Component* const compToAvoid) const
  33529. {
  33530. for (int i = childComponentList_.size(); --i >= 0;)
  33531. {
  33532. const Component* const c = childComponentList_.getUnchecked(i);
  33533. if (c != compToAvoid && c->isVisible())
  33534. {
  33535. if (c->isOpaque())
  33536. {
  33537. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33538. childBounds.translate (delta.getX(), delta.getY());
  33539. result.subtract (childBounds);
  33540. }
  33541. else
  33542. {
  33543. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33544. newClip.translate (-c->getX(), -c->getY());
  33545. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33546. newClip, compToAvoid);
  33547. }
  33548. }
  33549. }
  33550. }
  33551. void Component::mouseEnter (const MouseEvent&)
  33552. {
  33553. // base class does nothing
  33554. }
  33555. void Component::mouseExit (const MouseEvent&)
  33556. {
  33557. // base class does nothing
  33558. }
  33559. void Component::mouseDown (const MouseEvent&)
  33560. {
  33561. // base class does nothing
  33562. }
  33563. void Component::mouseUp (const MouseEvent&)
  33564. {
  33565. // base class does nothing
  33566. }
  33567. void Component::mouseDrag (const MouseEvent&)
  33568. {
  33569. // base class does nothing
  33570. }
  33571. void Component::mouseMove (const MouseEvent&)
  33572. {
  33573. // base class does nothing
  33574. }
  33575. void Component::mouseDoubleClick (const MouseEvent&)
  33576. {
  33577. // base class does nothing
  33578. }
  33579. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33580. {
  33581. // the base class just passes this event up to its parent..
  33582. if (parentComponent_ != 0)
  33583. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33584. wheelIncrementX, wheelIncrementY);
  33585. }
  33586. void Component::resized()
  33587. {
  33588. // base class does nothing
  33589. }
  33590. void Component::moved()
  33591. {
  33592. // base class does nothing
  33593. }
  33594. void Component::childBoundsChanged (Component*)
  33595. {
  33596. // base class does nothing
  33597. }
  33598. void Component::parentSizeChanged()
  33599. {
  33600. // base class does nothing
  33601. }
  33602. void Component::addComponentListener (ComponentListener* const newListener)
  33603. {
  33604. jassert (isValidComponent());
  33605. componentListeners.add (newListener);
  33606. }
  33607. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33608. {
  33609. jassert (isValidComponent());
  33610. componentListeners.remove (listenerToRemove);
  33611. }
  33612. void Component::inputAttemptWhenModal()
  33613. {
  33614. bringModalComponentToFront();
  33615. getLookAndFeel().playAlertSound();
  33616. }
  33617. bool Component::canModalEventBeSentToComponent (const Component*)
  33618. {
  33619. return false;
  33620. }
  33621. void Component::internalModalInputAttempt()
  33622. {
  33623. Component* const current = getCurrentlyModalComponent();
  33624. if (current != 0)
  33625. current->inputAttemptWhenModal();
  33626. }
  33627. void Component::paint (Graphics&)
  33628. {
  33629. // all painting is done in the subclasses
  33630. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33631. }
  33632. void Component::paintOverChildren (Graphics&)
  33633. {
  33634. // all painting is done in the subclasses
  33635. }
  33636. void Component::handleMessage (const Message& message)
  33637. {
  33638. if (message.intParameter1 == exitModalStateMessage)
  33639. {
  33640. exitModalState (message.intParameter2);
  33641. }
  33642. else if (message.intParameter1 == customCommandMessage)
  33643. {
  33644. handleCommandMessage (message.intParameter2);
  33645. }
  33646. }
  33647. void Component::postCommandMessage (const int commandId)
  33648. {
  33649. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33650. }
  33651. void Component::handleCommandMessage (int)
  33652. {
  33653. // used by subclasses
  33654. }
  33655. void Component::addMouseListener (MouseListener* const newListener,
  33656. const bool wantsEventsForAllNestedChildComponents)
  33657. {
  33658. // if component methods are being called from threads other than the message
  33659. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33660. checkMessageManagerIsLocked
  33661. if (mouseListeners_ == 0)
  33662. mouseListeners_ = new Array<MouseListener*>();
  33663. if (! mouseListeners_->contains (newListener))
  33664. {
  33665. if (wantsEventsForAllNestedChildComponents)
  33666. {
  33667. mouseListeners_->insert (0, newListener);
  33668. ++numDeepMouseListeners;
  33669. }
  33670. else
  33671. {
  33672. mouseListeners_->add (newListener);
  33673. }
  33674. }
  33675. }
  33676. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33677. {
  33678. // if component methods are being called from threads other than the message
  33679. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33680. checkMessageManagerIsLocked
  33681. if (mouseListeners_ != 0)
  33682. {
  33683. const int index = mouseListeners_->indexOf (listenerToRemove);
  33684. if (index >= 0)
  33685. {
  33686. if (index < numDeepMouseListeners)
  33687. --numDeepMouseListeners;
  33688. mouseListeners_->remove (index);
  33689. }
  33690. }
  33691. }
  33692. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33693. {
  33694. if (isCurrentlyBlockedByAnotherModalComponent())
  33695. {
  33696. // if something else is modal, always just show a normal mouse cursor
  33697. source.showMouseCursor (MouseCursor::NormalCursor);
  33698. return;
  33699. }
  33700. if (! flags.mouseInsideFlag)
  33701. {
  33702. flags.mouseInsideFlag = true;
  33703. flags.mouseOverFlag = true;
  33704. flags.draggingFlag = false;
  33705. BailOutChecker checker (this);
  33706. if (flags.repaintOnMouseActivityFlag)
  33707. repaint();
  33708. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33709. this, this, time, relativePos,
  33710. time, 0, false);
  33711. mouseEnter (me);
  33712. if (checker.shouldBailOut())
  33713. return;
  33714. Desktop::getInstance().resetTimer();
  33715. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33716. if (checker.shouldBailOut())
  33717. return;
  33718. if (mouseListeners_ != 0)
  33719. {
  33720. for (int i = mouseListeners_->size(); --i >= 0;)
  33721. {
  33722. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33723. if (checker.shouldBailOut())
  33724. return;
  33725. i = jmin (i, mouseListeners_->size());
  33726. }
  33727. }
  33728. Component* p = parentComponent_;
  33729. while (p != 0)
  33730. {
  33731. if (p->numDeepMouseListeners > 0)
  33732. {
  33733. BailOutChecker checker2 (this, p);
  33734. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33735. {
  33736. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33737. if (checker2.shouldBailOut())
  33738. return;
  33739. i = jmin (i, p->numDeepMouseListeners);
  33740. }
  33741. }
  33742. p = p->parentComponent_;
  33743. }
  33744. }
  33745. }
  33746. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33747. {
  33748. BailOutChecker checker (this);
  33749. if (flags.draggingFlag)
  33750. {
  33751. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33752. if (checker.shouldBailOut())
  33753. return;
  33754. }
  33755. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33756. {
  33757. flags.mouseInsideFlag = false;
  33758. flags.mouseOverFlag = false;
  33759. flags.draggingFlag = false;
  33760. if (flags.repaintOnMouseActivityFlag)
  33761. repaint();
  33762. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33763. this, this, time, relativePos,
  33764. time, 0, false);
  33765. mouseExit (me);
  33766. if (checker.shouldBailOut())
  33767. return;
  33768. Desktop::getInstance().resetTimer();
  33769. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33770. if (checker.shouldBailOut())
  33771. return;
  33772. if (mouseListeners_ != 0)
  33773. {
  33774. for (int i = mouseListeners_->size(); --i >= 0;)
  33775. {
  33776. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33777. if (checker.shouldBailOut())
  33778. return;
  33779. i = jmin (i, mouseListeners_->size());
  33780. }
  33781. }
  33782. Component* p = parentComponent_;
  33783. while (p != 0)
  33784. {
  33785. if (p->numDeepMouseListeners > 0)
  33786. {
  33787. BailOutChecker checker2 (this, p);
  33788. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33789. {
  33790. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33791. if (checker2.shouldBailOut())
  33792. return;
  33793. i = jmin (i, p->numDeepMouseListeners);
  33794. }
  33795. }
  33796. p = p->parentComponent_;
  33797. }
  33798. }
  33799. }
  33800. class InternalDragRepeater : public Timer
  33801. {
  33802. public:
  33803. InternalDragRepeater()
  33804. {}
  33805. ~InternalDragRepeater()
  33806. {
  33807. clearSingletonInstance();
  33808. }
  33809. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33810. void timerCallback()
  33811. {
  33812. Desktop& desktop = Desktop::getInstance();
  33813. int numMiceDown = 0;
  33814. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33815. {
  33816. MouseInputSource* const source = desktop.getMouseSource(i);
  33817. if (source->isDragging())
  33818. {
  33819. source->triggerFakeMove();
  33820. ++numMiceDown;
  33821. }
  33822. }
  33823. if (numMiceDown == 0)
  33824. deleteInstance();
  33825. }
  33826. juce_UseDebuggingNewOperator
  33827. private:
  33828. InternalDragRepeater (const InternalDragRepeater&);
  33829. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33830. };
  33831. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33832. void Component::beginDragAutoRepeat (const int interval)
  33833. {
  33834. if (interval > 0)
  33835. {
  33836. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33837. InternalDragRepeater::getInstance()->startTimer (interval);
  33838. }
  33839. else
  33840. {
  33841. InternalDragRepeater::deleteInstance();
  33842. }
  33843. }
  33844. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33845. {
  33846. Desktop& desktop = Desktop::getInstance();
  33847. BailOutChecker checker (this);
  33848. if (isCurrentlyBlockedByAnotherModalComponent())
  33849. {
  33850. internalModalInputAttempt();
  33851. if (checker.shouldBailOut())
  33852. return;
  33853. // If processing the input attempt has exited the modal loop, we'll allow the event
  33854. // to be delivered..
  33855. if (isCurrentlyBlockedByAnotherModalComponent())
  33856. {
  33857. // allow blocked mouse-events to go to global listeners..
  33858. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33859. this, this, time, relativePos, time,
  33860. source.getNumberOfMultipleClicks(), false);
  33861. desktop.resetTimer();
  33862. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33863. return;
  33864. }
  33865. }
  33866. {
  33867. Component* c = this;
  33868. while (c != 0)
  33869. {
  33870. if (c->isBroughtToFrontOnMouseClick())
  33871. {
  33872. c->toFront (true);
  33873. if (checker.shouldBailOut())
  33874. return;
  33875. }
  33876. c = c->parentComponent_;
  33877. }
  33878. }
  33879. if (! flags.dontFocusOnMouseClickFlag)
  33880. {
  33881. grabFocusInternal (focusChangedByMouseClick);
  33882. if (checker.shouldBailOut())
  33883. return;
  33884. }
  33885. flags.draggingFlag = true;
  33886. flags.mouseOverFlag = true;
  33887. if (flags.repaintOnMouseActivityFlag)
  33888. repaint();
  33889. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33890. this, this, time, relativePos, time,
  33891. source.getNumberOfMultipleClicks(), false);
  33892. mouseDown (me);
  33893. if (checker.shouldBailOut())
  33894. return;
  33895. desktop.resetTimer();
  33896. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33897. if (checker.shouldBailOut())
  33898. return;
  33899. if (mouseListeners_ != 0)
  33900. {
  33901. for (int i = mouseListeners_->size(); --i >= 0;)
  33902. {
  33903. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  33904. if (checker.shouldBailOut())
  33905. return;
  33906. i = jmin (i, mouseListeners_->size());
  33907. }
  33908. }
  33909. Component* p = parentComponent_;
  33910. while (p != 0)
  33911. {
  33912. if (p->numDeepMouseListeners > 0)
  33913. {
  33914. BailOutChecker checker2 (this, p);
  33915. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33916. {
  33917. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  33918. if (checker2.shouldBailOut())
  33919. return;
  33920. i = jmin (i, p->numDeepMouseListeners);
  33921. }
  33922. }
  33923. p = p->parentComponent_;
  33924. }
  33925. }
  33926. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33927. {
  33928. if (flags.draggingFlag)
  33929. {
  33930. Desktop& desktop = Desktop::getInstance();
  33931. flags.draggingFlag = false;
  33932. BailOutChecker checker (this);
  33933. if (flags.repaintOnMouseActivityFlag)
  33934. repaint();
  33935. const MouseEvent me (source, relativePos,
  33936. oldModifiers, this, this, time,
  33937. globalPositionToRelative (source.getLastMouseDownPosition()),
  33938. source.getLastMouseDownTime(),
  33939. source.getNumberOfMultipleClicks(),
  33940. source.hasMouseMovedSignificantlySincePressed());
  33941. mouseUp (me);
  33942. if (checker.shouldBailOut())
  33943. return;
  33944. desktop.resetTimer();
  33945. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33946. if (checker.shouldBailOut())
  33947. return;
  33948. if (mouseListeners_ != 0)
  33949. {
  33950. for (int i = mouseListeners_->size(); --i >= 0;)
  33951. {
  33952. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  33953. if (checker.shouldBailOut())
  33954. return;
  33955. i = jmin (i, mouseListeners_->size());
  33956. }
  33957. }
  33958. {
  33959. Component* p = parentComponent_;
  33960. while (p != 0)
  33961. {
  33962. if (p->numDeepMouseListeners > 0)
  33963. {
  33964. BailOutChecker checker2 (this, p);
  33965. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33966. {
  33967. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  33968. if (checker2.shouldBailOut())
  33969. return;
  33970. i = jmin (i, p->numDeepMouseListeners);
  33971. }
  33972. }
  33973. p = p->parentComponent_;
  33974. }
  33975. }
  33976. // check for double-click
  33977. if (me.getNumberOfClicks() >= 2)
  33978. {
  33979. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33980. mouseDoubleClick (me);
  33981. if (checker.shouldBailOut())
  33982. return;
  33983. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33984. if (checker.shouldBailOut())
  33985. return;
  33986. for (int i = numListeners; --i >= 0;)
  33987. {
  33988. if (checker.shouldBailOut())
  33989. return;
  33990. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33991. if (ml != 0)
  33992. ml->mouseDoubleClick (me);
  33993. }
  33994. if (checker.shouldBailOut())
  33995. return;
  33996. Component* p = parentComponent_;
  33997. while (p != 0)
  33998. {
  33999. if (p->numDeepMouseListeners > 0)
  34000. {
  34001. BailOutChecker checker2 (this, p);
  34002. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34003. {
  34004. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  34005. if (checker2.shouldBailOut())
  34006. return;
  34007. i = jmin (i, p->numDeepMouseListeners);
  34008. }
  34009. }
  34010. p = p->parentComponent_;
  34011. }
  34012. }
  34013. }
  34014. }
  34015. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  34016. {
  34017. if (flags.draggingFlag)
  34018. {
  34019. Desktop& desktop = Desktop::getInstance();
  34020. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  34021. BailOutChecker checker (this);
  34022. const MouseEvent me (source, relativePos,
  34023. source.getCurrentModifiers(), this, this, time,
  34024. globalPositionToRelative (source.getLastMouseDownPosition()),
  34025. source.getLastMouseDownTime(),
  34026. source.getNumberOfMultipleClicks(),
  34027. source.hasMouseMovedSignificantlySincePressed());
  34028. mouseDrag (me);
  34029. if (checker.shouldBailOut())
  34030. return;
  34031. desktop.resetTimer();
  34032. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34033. if (checker.shouldBailOut())
  34034. return;
  34035. if (mouseListeners_ != 0)
  34036. {
  34037. for (int i = mouseListeners_->size(); --i >= 0;)
  34038. {
  34039. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  34040. if (checker.shouldBailOut())
  34041. return;
  34042. i = jmin (i, mouseListeners_->size());
  34043. }
  34044. }
  34045. Component* p = parentComponent_;
  34046. while (p != 0)
  34047. {
  34048. if (p->numDeepMouseListeners > 0)
  34049. {
  34050. BailOutChecker checker2 (this, p);
  34051. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34052. {
  34053. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  34054. if (checker2.shouldBailOut())
  34055. return;
  34056. i = jmin (i, p->numDeepMouseListeners);
  34057. }
  34058. }
  34059. p = p->parentComponent_;
  34060. }
  34061. }
  34062. }
  34063. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  34064. {
  34065. Desktop& desktop = Desktop::getInstance();
  34066. BailOutChecker checker (this);
  34067. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  34068. this, this, time, relativePos,
  34069. time, 0, false);
  34070. if (isCurrentlyBlockedByAnotherModalComponent())
  34071. {
  34072. // allow blocked mouse-events to go to global listeners..
  34073. desktop.sendMouseMove();
  34074. }
  34075. else
  34076. {
  34077. flags.mouseOverFlag = true;
  34078. mouseMove (me);
  34079. if (checker.shouldBailOut())
  34080. return;
  34081. desktop.resetTimer();
  34082. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34083. if (checker.shouldBailOut())
  34084. return;
  34085. if (mouseListeners_ != 0)
  34086. {
  34087. for (int i = mouseListeners_->size(); --i >= 0;)
  34088. {
  34089. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  34090. if (checker.shouldBailOut())
  34091. return;
  34092. i = jmin (i, mouseListeners_->size());
  34093. }
  34094. }
  34095. Component* p = parentComponent_;
  34096. while (p != 0)
  34097. {
  34098. if (p->numDeepMouseListeners > 0)
  34099. {
  34100. BailOutChecker checker2 (this, p);
  34101. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34102. {
  34103. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  34104. if (checker2.shouldBailOut())
  34105. return;
  34106. i = jmin (i, p->numDeepMouseListeners);
  34107. }
  34108. }
  34109. p = p->parentComponent_;
  34110. }
  34111. }
  34112. }
  34113. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  34114. const Time& time, const float amountX, const float amountY)
  34115. {
  34116. Desktop& desktop = Desktop::getInstance();
  34117. BailOutChecker checker (this);
  34118. const float wheelIncrementX = amountX / 256.0f;
  34119. const float wheelIncrementY = amountY / 256.0f;
  34120. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  34121. this, this, time, relativePos, time, 0, false);
  34122. if (isCurrentlyBlockedByAnotherModalComponent())
  34123. {
  34124. // allow blocked mouse-events to go to global listeners..
  34125. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  34126. }
  34127. else
  34128. {
  34129. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34130. if (checker.shouldBailOut())
  34131. return;
  34132. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  34133. if (checker.shouldBailOut())
  34134. return;
  34135. if (mouseListeners_ != 0)
  34136. {
  34137. for (int i = mouseListeners_->size(); --i >= 0;)
  34138. {
  34139. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34140. if (checker.shouldBailOut())
  34141. return;
  34142. i = jmin (i, mouseListeners_->size());
  34143. }
  34144. }
  34145. Component* p = parentComponent_;
  34146. while (p != 0)
  34147. {
  34148. if (p->numDeepMouseListeners > 0)
  34149. {
  34150. BailOutChecker checker2 (this, p);
  34151. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34152. {
  34153. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34154. if (checker2.shouldBailOut())
  34155. return;
  34156. i = jmin (i, p->numDeepMouseListeners);
  34157. }
  34158. }
  34159. p = p->parentComponent_;
  34160. }
  34161. }
  34162. }
  34163. void Component::sendFakeMouseMove() const
  34164. {
  34165. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  34166. }
  34167. void Component::broughtToFront()
  34168. {
  34169. }
  34170. void Component::internalBroughtToFront()
  34171. {
  34172. if (! isValidComponent())
  34173. return;
  34174. if (flags.hasHeavyweightPeerFlag)
  34175. Desktop::getInstance().componentBroughtToFront (this);
  34176. BailOutChecker checker (this);
  34177. broughtToFront();
  34178. if (checker.shouldBailOut())
  34179. return;
  34180. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  34181. if (checker.shouldBailOut())
  34182. return;
  34183. // When brought to the front and there's a modal component blocking this one,
  34184. // we need to bring the modal one to the front instead..
  34185. Component* const cm = getCurrentlyModalComponent();
  34186. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  34187. bringModalComponentToFront();
  34188. }
  34189. void Component::focusGained (FocusChangeType)
  34190. {
  34191. // base class does nothing
  34192. }
  34193. void Component::internalFocusGain (const FocusChangeType cause)
  34194. {
  34195. SafePointer<Component> safePointer (this);
  34196. focusGained (cause);
  34197. if (safePointer != 0)
  34198. internalChildFocusChange (cause);
  34199. }
  34200. void Component::focusLost (FocusChangeType)
  34201. {
  34202. // base class does nothing
  34203. }
  34204. void Component::internalFocusLoss (const FocusChangeType cause)
  34205. {
  34206. SafePointer<Component> safePointer (this);
  34207. focusLost (focusChangedDirectly);
  34208. if (safePointer != 0)
  34209. internalChildFocusChange (cause);
  34210. }
  34211. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  34212. {
  34213. // base class does nothing
  34214. }
  34215. void Component::internalChildFocusChange (FocusChangeType cause)
  34216. {
  34217. const bool childIsNowFocused = hasKeyboardFocus (true);
  34218. if (flags.childCompFocusedFlag != childIsNowFocused)
  34219. {
  34220. flags.childCompFocusedFlag = childIsNowFocused;
  34221. SafePointer<Component> safePointer (this);
  34222. focusOfChildComponentChanged (cause);
  34223. if (safePointer == 0)
  34224. return;
  34225. }
  34226. if (parentComponent_ != 0)
  34227. parentComponent_->internalChildFocusChange (cause);
  34228. }
  34229. bool Component::isEnabled() const throw()
  34230. {
  34231. return (! flags.isDisabledFlag)
  34232. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34233. }
  34234. void Component::setEnabled (const bool shouldBeEnabled)
  34235. {
  34236. if (flags.isDisabledFlag == shouldBeEnabled)
  34237. {
  34238. flags.isDisabledFlag = ! shouldBeEnabled;
  34239. // if any parent components are disabled, setting our flag won't make a difference,
  34240. // so no need to send a change message
  34241. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34242. sendEnablementChangeMessage();
  34243. }
  34244. }
  34245. void Component::sendEnablementChangeMessage()
  34246. {
  34247. SafePointer<Component> safePointer (this);
  34248. enablementChanged();
  34249. if (safePointer == 0)
  34250. return;
  34251. for (int i = getNumChildComponents(); --i >= 0;)
  34252. {
  34253. Component* const c = getChildComponent (i);
  34254. if (c != 0)
  34255. {
  34256. c->sendEnablementChangeMessage();
  34257. if (safePointer == 0)
  34258. return;
  34259. }
  34260. }
  34261. }
  34262. void Component::enablementChanged()
  34263. {
  34264. }
  34265. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34266. {
  34267. flags.wantsFocusFlag = wantsFocus;
  34268. }
  34269. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34270. {
  34271. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34272. }
  34273. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34274. {
  34275. return ! flags.dontFocusOnMouseClickFlag;
  34276. }
  34277. bool Component::getWantsKeyboardFocus() const throw()
  34278. {
  34279. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34280. }
  34281. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34282. {
  34283. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34284. }
  34285. bool Component::isFocusContainer() const throw()
  34286. {
  34287. return flags.isFocusContainerFlag;
  34288. }
  34289. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34290. int Component::getExplicitFocusOrder() const
  34291. {
  34292. return properties [juce_explicitFocusOrderId];
  34293. }
  34294. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34295. {
  34296. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34297. }
  34298. KeyboardFocusTraverser* Component::createFocusTraverser()
  34299. {
  34300. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34301. return new KeyboardFocusTraverser();
  34302. return parentComponent_->createFocusTraverser();
  34303. }
  34304. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34305. {
  34306. // give the focus to this component
  34307. if (currentlyFocusedComponent != this)
  34308. {
  34309. JUCE_TRY
  34310. {
  34311. // get the focus onto our desktop window
  34312. ComponentPeer* const peer = getPeer();
  34313. if (peer != 0)
  34314. {
  34315. SafePointer<Component> safePointer (this);
  34316. peer->grabFocus();
  34317. if (peer->isFocused() && currentlyFocusedComponent != this)
  34318. {
  34319. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34320. currentlyFocusedComponent = this;
  34321. Desktop::getInstance().triggerFocusCallback();
  34322. // call this after setting currentlyFocusedComponent so that the one that's
  34323. // losing it has a chance to see where focus is going
  34324. if (componentLosingFocus != 0)
  34325. componentLosingFocus->internalFocusLoss (cause);
  34326. if (currentlyFocusedComponent == this)
  34327. {
  34328. focusGained (cause);
  34329. if (safePointer != 0)
  34330. internalChildFocusChange (cause);
  34331. }
  34332. }
  34333. }
  34334. }
  34335. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34336. catch (const std::exception& e)
  34337. {
  34338. currentlyFocusedComponent = 0;
  34339. Desktop::getInstance().triggerFocusCallback();
  34340. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34341. }
  34342. catch (...)
  34343. {
  34344. currentlyFocusedComponent = 0;
  34345. Desktop::getInstance().triggerFocusCallback();
  34346. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34347. }
  34348. #endif
  34349. }
  34350. }
  34351. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34352. {
  34353. if (isShowing())
  34354. {
  34355. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34356. {
  34357. takeKeyboardFocus (cause);
  34358. }
  34359. else
  34360. {
  34361. if (isParentOf (currentlyFocusedComponent)
  34362. && currentlyFocusedComponent->isShowing())
  34363. {
  34364. // do nothing if the focused component is actually a child of ours..
  34365. }
  34366. else
  34367. {
  34368. // find the default child component..
  34369. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34370. if (traverser != 0)
  34371. {
  34372. Component* const defaultComp = traverser->getDefaultComponent (this);
  34373. traverser = 0;
  34374. if (defaultComp != 0)
  34375. {
  34376. defaultComp->grabFocusInternal (cause, false);
  34377. return;
  34378. }
  34379. }
  34380. if (canTryParent && parentComponent_ != 0)
  34381. {
  34382. // if no children want it and we're allowed to try our parent comp,
  34383. // then pass up to parent, which will try our siblings.
  34384. parentComponent_->grabFocusInternal (cause, true);
  34385. }
  34386. }
  34387. }
  34388. }
  34389. }
  34390. void Component::grabKeyboardFocus()
  34391. {
  34392. // if component methods are being called from threads other than the message
  34393. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34394. checkMessageManagerIsLocked
  34395. grabFocusInternal (focusChangedDirectly);
  34396. }
  34397. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34398. {
  34399. // if component methods are being called from threads other than the message
  34400. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34401. checkMessageManagerIsLocked
  34402. if (parentComponent_ != 0)
  34403. {
  34404. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34405. if (traverser != 0)
  34406. {
  34407. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34408. : traverser->getPreviousComponent (this);
  34409. traverser = 0;
  34410. if (nextComp != 0)
  34411. {
  34412. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34413. {
  34414. SafePointer<Component> nextCompPointer (nextComp);
  34415. internalModalInputAttempt();
  34416. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34417. return;
  34418. }
  34419. nextComp->grabFocusInternal (focusChangedByTabKey);
  34420. return;
  34421. }
  34422. }
  34423. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34424. }
  34425. }
  34426. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34427. {
  34428. return (currentlyFocusedComponent == this)
  34429. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34430. }
  34431. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34432. {
  34433. return currentlyFocusedComponent;
  34434. }
  34435. void Component::giveAwayFocus()
  34436. {
  34437. // use a copy so we can clear the value before the call
  34438. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34439. currentlyFocusedComponent = 0;
  34440. Desktop::getInstance().triggerFocusCallback();
  34441. if (componentLosingFocus != 0)
  34442. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34443. }
  34444. bool Component::isMouseOver() const throw()
  34445. {
  34446. return flags.mouseOverFlag;
  34447. }
  34448. bool Component::isMouseButtonDown() const throw()
  34449. {
  34450. return flags.draggingFlag;
  34451. }
  34452. bool Component::isMouseOverOrDragging() const throw()
  34453. {
  34454. return flags.mouseOverFlag || flags.draggingFlag;
  34455. }
  34456. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34457. {
  34458. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34459. }
  34460. const Point<int> Component::getMouseXYRelative() const
  34461. {
  34462. return globalPositionToRelative (Desktop::getMousePosition());
  34463. }
  34464. const Rectangle<int> Component::getParentMonitorArea() const
  34465. {
  34466. return Desktop::getInstance()
  34467. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34468. }
  34469. void Component::addKeyListener (KeyListener* const newListener)
  34470. {
  34471. if (keyListeners_ == 0)
  34472. keyListeners_ = new Array <KeyListener*>();
  34473. keyListeners_->addIfNotAlreadyThere (newListener);
  34474. }
  34475. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34476. {
  34477. if (keyListeners_ != 0)
  34478. keyListeners_->removeValue (listenerToRemove);
  34479. }
  34480. bool Component::keyPressed (const KeyPress&)
  34481. {
  34482. return false;
  34483. }
  34484. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34485. {
  34486. return false;
  34487. }
  34488. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34489. {
  34490. if (parentComponent_ != 0)
  34491. parentComponent_->modifierKeysChanged (modifiers);
  34492. }
  34493. void Component::internalModifierKeysChanged()
  34494. {
  34495. sendFakeMouseMove();
  34496. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34497. }
  34498. ComponentPeer* Component::getPeer() const
  34499. {
  34500. if (flags.hasHeavyweightPeerFlag)
  34501. return ComponentPeer::getPeerFor (this);
  34502. else if (parentComponent_ != 0)
  34503. return parentComponent_->getPeer();
  34504. else
  34505. return 0;
  34506. }
  34507. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34508. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34509. {
  34510. jassert (component1 != 0);
  34511. }
  34512. bool Component::BailOutChecker::shouldBailOut() const throw()
  34513. {
  34514. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34515. }
  34516. END_JUCE_NAMESPACE
  34517. /*** End of inlined file: juce_Component.cpp ***/
  34518. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34519. BEGIN_JUCE_NAMESPACE
  34520. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34521. void ComponentListener::componentBroughtToFront (Component&) {}
  34522. void ComponentListener::componentVisibilityChanged (Component&) {}
  34523. void ComponentListener::componentChildrenChanged (Component&) {}
  34524. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34525. void ComponentListener::componentNameChanged (Component&) {}
  34526. void ComponentListener::componentBeingDeleted (Component&) {}
  34527. END_JUCE_NAMESPACE
  34528. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34529. /*** Start of inlined file: juce_Desktop.cpp ***/
  34530. BEGIN_JUCE_NAMESPACE
  34531. Desktop::Desktop()
  34532. : mouseClickCounter (0),
  34533. kioskModeComponent (0)
  34534. {
  34535. createMouseInputSources();
  34536. refreshMonitorSizes();
  34537. }
  34538. Desktop::~Desktop()
  34539. {
  34540. jassert (instance == this);
  34541. instance = 0;
  34542. // doh! If you don't delete all your windows before exiting, you're going to
  34543. // be leaking memory!
  34544. jassert (desktopComponents.size() == 0);
  34545. }
  34546. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34547. {
  34548. if (instance == 0)
  34549. instance = new Desktop();
  34550. return *instance;
  34551. }
  34552. Desktop* Desktop::instance = 0;
  34553. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34554. const bool clipToWorkArea);
  34555. void Desktop::refreshMonitorSizes()
  34556. {
  34557. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34558. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34559. monitorCoordsClipped.clear();
  34560. monitorCoordsUnclipped.clear();
  34561. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34562. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34563. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34564. if (oldClipped != monitorCoordsClipped
  34565. || oldUnclipped != monitorCoordsUnclipped)
  34566. {
  34567. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34568. {
  34569. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34570. if (p != 0)
  34571. p->handleScreenSizeChange();
  34572. }
  34573. }
  34574. }
  34575. int Desktop::getNumDisplayMonitors() const throw()
  34576. {
  34577. return monitorCoordsClipped.size();
  34578. }
  34579. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34580. {
  34581. return clippedToWorkArea ? monitorCoordsClipped [index]
  34582. : monitorCoordsUnclipped [index];
  34583. }
  34584. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34585. {
  34586. RectangleList rl;
  34587. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34588. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34589. return rl;
  34590. }
  34591. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34592. {
  34593. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34594. }
  34595. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34596. {
  34597. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34598. double bestDistance = 1.0e10;
  34599. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34600. {
  34601. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34602. if (rect.contains (position))
  34603. return rect;
  34604. const double distance = rect.getCentre().getDistanceFrom (position);
  34605. if (distance < bestDistance)
  34606. {
  34607. bestDistance = distance;
  34608. best = rect;
  34609. }
  34610. }
  34611. return best;
  34612. }
  34613. int Desktop::getNumComponents() const throw()
  34614. {
  34615. return desktopComponents.size();
  34616. }
  34617. Component* Desktop::getComponent (const int index) const throw()
  34618. {
  34619. return desktopComponents [index];
  34620. }
  34621. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34622. {
  34623. for (int i = desktopComponents.size(); --i >= 0;)
  34624. {
  34625. Component* const c = desktopComponents.getUnchecked(i);
  34626. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34627. if (c->contains (relative.getX(), relative.getY()))
  34628. return c->getComponentAt (relative.getX(), relative.getY());
  34629. }
  34630. return 0;
  34631. }
  34632. void Desktop::addDesktopComponent (Component* const c)
  34633. {
  34634. jassert (c != 0);
  34635. jassert (! desktopComponents.contains (c));
  34636. desktopComponents.addIfNotAlreadyThere (c);
  34637. }
  34638. void Desktop::removeDesktopComponent (Component* const c)
  34639. {
  34640. desktopComponents.removeValue (c);
  34641. }
  34642. void Desktop::componentBroughtToFront (Component* const c)
  34643. {
  34644. const int index = desktopComponents.indexOf (c);
  34645. jassert (index >= 0);
  34646. if (index >= 0)
  34647. {
  34648. int newIndex = -1;
  34649. if (! c->isAlwaysOnTop())
  34650. {
  34651. newIndex = desktopComponents.size();
  34652. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34653. --newIndex;
  34654. --newIndex;
  34655. }
  34656. desktopComponents.move (index, newIndex);
  34657. }
  34658. }
  34659. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34660. {
  34661. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34662. }
  34663. int Desktop::getMouseButtonClickCounter() throw()
  34664. {
  34665. return getInstance().mouseClickCounter;
  34666. }
  34667. void Desktop::incrementMouseClickCounter() throw()
  34668. {
  34669. ++mouseClickCounter;
  34670. }
  34671. int Desktop::getNumDraggingMouseSources() const throw()
  34672. {
  34673. int num = 0;
  34674. for (int i = mouseSources.size(); --i >= 0;)
  34675. if (mouseSources.getUnchecked(i)->isDragging())
  34676. ++num;
  34677. return num;
  34678. }
  34679. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34680. {
  34681. int num = 0;
  34682. for (int i = mouseSources.size(); --i >= 0;)
  34683. {
  34684. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34685. if (mi->isDragging())
  34686. {
  34687. if (index == num)
  34688. return mi;
  34689. ++num;
  34690. }
  34691. }
  34692. return 0;
  34693. }
  34694. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34695. {
  34696. focusListeners.add (listener);
  34697. }
  34698. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34699. {
  34700. focusListeners.remove (listener);
  34701. }
  34702. void Desktop::triggerFocusCallback()
  34703. {
  34704. triggerAsyncUpdate();
  34705. }
  34706. void Desktop::handleAsyncUpdate()
  34707. {
  34708. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34709. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34710. }
  34711. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34712. {
  34713. mouseListeners.add (listener);
  34714. resetTimer();
  34715. }
  34716. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34717. {
  34718. mouseListeners.remove (listener);
  34719. resetTimer();
  34720. }
  34721. void Desktop::timerCallback()
  34722. {
  34723. if (lastFakeMouseMove != getMousePosition())
  34724. sendMouseMove();
  34725. }
  34726. void Desktop::sendMouseMove()
  34727. {
  34728. if (! mouseListeners.isEmpty())
  34729. {
  34730. startTimer (20);
  34731. lastFakeMouseMove = getMousePosition();
  34732. Component* const target = findComponentAt (lastFakeMouseMove);
  34733. if (target != 0)
  34734. {
  34735. Component::BailOutChecker checker (target);
  34736. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34737. const Time now (Time::getCurrentTime());
  34738. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34739. target, target, now, pos, now, 0, false);
  34740. if (me.mods.isAnyMouseButtonDown())
  34741. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34742. else
  34743. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34744. }
  34745. }
  34746. }
  34747. void Desktop::resetTimer()
  34748. {
  34749. if (mouseListeners.size() == 0)
  34750. stopTimer();
  34751. else
  34752. startTimer (100);
  34753. lastFakeMouseMove = getMousePosition();
  34754. }
  34755. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34756. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34757. {
  34758. if (kioskModeComponent != componentToUse)
  34759. {
  34760. // agh! Don't delete a component without first stopping it being the kiosk comp
  34761. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34762. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34763. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34764. if (kioskModeComponent->isValidComponent())
  34765. {
  34766. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34767. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34768. }
  34769. kioskModeComponent = componentToUse;
  34770. if (kioskModeComponent != 0)
  34771. {
  34772. jassert (kioskModeComponent->isValidComponent());
  34773. // Only components that are already on the desktop can be put into kiosk mode!
  34774. jassert (kioskModeComponent->isOnDesktop());
  34775. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34776. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34777. }
  34778. }
  34779. }
  34780. END_JUCE_NAMESPACE
  34781. /*** End of inlined file: juce_Desktop.cpp ***/
  34782. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34783. BEGIN_JUCE_NAMESPACE
  34784. class ModalComponentManager::ModalItem : public ComponentListener
  34785. {
  34786. public:
  34787. ModalItem (Component* const comp, Callback* const callback)
  34788. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34789. {
  34790. if (callback != 0)
  34791. callbacks.add (callback);
  34792. jassert (comp != 0);
  34793. component->addComponentListener (this);
  34794. }
  34795. ~ModalItem()
  34796. {
  34797. if (! isDeleted)
  34798. component->removeComponentListener (this);
  34799. }
  34800. void componentBeingDeleted (Component&)
  34801. {
  34802. isDeleted = true;
  34803. cancel();
  34804. }
  34805. void componentVisibilityChanged (Component&)
  34806. {
  34807. if (! component->isShowing())
  34808. cancel();
  34809. }
  34810. void componentParentHierarchyChanged (Component&)
  34811. {
  34812. if (! component->isShowing())
  34813. cancel();
  34814. }
  34815. void cancel()
  34816. {
  34817. if (isActive)
  34818. {
  34819. isActive = false;
  34820. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34821. }
  34822. }
  34823. Component* component;
  34824. OwnedArray<Callback> callbacks;
  34825. int returnValue;
  34826. bool isActive, isDeleted;
  34827. private:
  34828. ModalItem (const ModalItem&);
  34829. ModalItem& operator= (const ModalItem&);
  34830. };
  34831. ModalComponentManager::ModalComponentManager()
  34832. {
  34833. }
  34834. ModalComponentManager::~ModalComponentManager()
  34835. {
  34836. clearSingletonInstance();
  34837. }
  34838. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34839. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34840. {
  34841. if (component != 0)
  34842. stack.add (new ModalItem (component, callback));
  34843. }
  34844. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34845. {
  34846. if (callback != 0)
  34847. {
  34848. ScopedPointer<Callback> callbackDeleter (callback);
  34849. for (int i = stack.size(); --i >= 0;)
  34850. {
  34851. ModalItem* const item = stack.getUnchecked(i);
  34852. if (item->component == component)
  34853. {
  34854. item->callbacks.add (callback);
  34855. callbackDeleter.release();
  34856. break;
  34857. }
  34858. }
  34859. }
  34860. }
  34861. void ModalComponentManager::endModal (Component* component)
  34862. {
  34863. for (int i = stack.size(); --i >= 0;)
  34864. {
  34865. ModalItem* const item = stack.getUnchecked(i);
  34866. if (item->component == component)
  34867. item->cancel();
  34868. }
  34869. }
  34870. void ModalComponentManager::endModal (Component* component, int returnValue)
  34871. {
  34872. for (int i = stack.size(); --i >= 0;)
  34873. {
  34874. ModalItem* const item = stack.getUnchecked(i);
  34875. if (item->component == component)
  34876. {
  34877. item->returnValue = returnValue;
  34878. item->cancel();
  34879. }
  34880. }
  34881. }
  34882. int ModalComponentManager::getNumModalComponents() const
  34883. {
  34884. int n = 0;
  34885. for (int i = 0; i < stack.size(); ++i)
  34886. if (stack.getUnchecked(i)->isActive)
  34887. ++n;
  34888. return n;
  34889. }
  34890. Component* ModalComponentManager::getModalComponent (const int index) const
  34891. {
  34892. int n = 0;
  34893. for (int i = stack.size(); --i >= 0;)
  34894. {
  34895. const ModalItem* const item = stack.getUnchecked(i);
  34896. if (item->isActive)
  34897. if (n++ == index)
  34898. return item->component;
  34899. }
  34900. return 0;
  34901. }
  34902. bool ModalComponentManager::isModal (Component* const comp) const
  34903. {
  34904. for (int i = stack.size(); --i >= 0;)
  34905. {
  34906. const ModalItem* const item = stack.getUnchecked(i);
  34907. if (item->isActive && item->component == comp)
  34908. return true;
  34909. }
  34910. return false;
  34911. }
  34912. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34913. {
  34914. return comp == getModalComponent (0);
  34915. }
  34916. void ModalComponentManager::handleAsyncUpdate()
  34917. {
  34918. for (int i = stack.size(); --i >= 0;)
  34919. {
  34920. const ModalItem* const item = stack.getUnchecked(i);
  34921. if (! item->isActive)
  34922. {
  34923. for (int j = item->callbacks.size(); --j >= 0;)
  34924. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34925. stack.remove (i);
  34926. }
  34927. }
  34928. }
  34929. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34930. {
  34931. public:
  34932. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34933. ~ReturnValueRetriever() {}
  34934. void modalStateFinished (int returnValue)
  34935. {
  34936. finished = true;
  34937. value = returnValue;
  34938. }
  34939. private:
  34940. int& value;
  34941. bool& finished;
  34942. ReturnValueRetriever (const ReturnValueRetriever&);
  34943. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34944. };
  34945. int ModalComponentManager::runEventLoopForCurrentComponent()
  34946. {
  34947. // This can only be run from the message thread!
  34948. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34949. Component* currentlyModal = getModalComponent (0);
  34950. if (currentlyModal == 0)
  34951. return 0;
  34952. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34953. int returnValue = 0;
  34954. bool finished = false;
  34955. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34956. JUCE_TRY
  34957. {
  34958. while (! finished)
  34959. {
  34960. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34961. break;
  34962. }
  34963. }
  34964. JUCE_CATCH_EXCEPTION
  34965. if (prevFocused != 0)
  34966. prevFocused->grabKeyboardFocus();
  34967. return returnValue;
  34968. }
  34969. END_JUCE_NAMESPACE
  34970. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34971. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34972. BEGIN_JUCE_NAMESPACE
  34973. ArrowButton::ArrowButton (const String& name,
  34974. float arrowDirectionInRadians,
  34975. const Colour& arrowColour)
  34976. : Button (name),
  34977. colour (arrowColour)
  34978. {
  34979. path.lineTo (0.0f, 1.0f);
  34980. path.lineTo (1.0f, 0.5f);
  34981. path.closeSubPath();
  34982. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34983. 0.5f, 0.5f));
  34984. setComponentEffect (&shadow);
  34985. buttonStateChanged();
  34986. }
  34987. ArrowButton::~ArrowButton()
  34988. {
  34989. }
  34990. void ArrowButton::paintButton (Graphics& g,
  34991. bool /*isMouseOverButton*/,
  34992. bool /*isButtonDown*/)
  34993. {
  34994. g.setColour (colour);
  34995. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34996. (float) offset,
  34997. (float) (getWidth() - 3),
  34998. (float) (getHeight() - 3),
  34999. false));
  35000. }
  35001. void ArrowButton::buttonStateChanged()
  35002. {
  35003. offset = (isDown()) ? 1 : 0;
  35004. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  35005. 0.3f, -1, 0);
  35006. }
  35007. END_JUCE_NAMESPACE
  35008. /*** End of inlined file: juce_ArrowButton.cpp ***/
  35009. /*** Start of inlined file: juce_Button.cpp ***/
  35010. BEGIN_JUCE_NAMESPACE
  35011. class Button::RepeatTimer : public Timer
  35012. {
  35013. public:
  35014. RepeatTimer (Button& owner_) : owner (owner_) {}
  35015. void timerCallback() { owner.repeatTimerCallback(); }
  35016. juce_UseDebuggingNewOperator
  35017. private:
  35018. Button& owner;
  35019. RepeatTimer (const RepeatTimer&);
  35020. RepeatTimer& operator= (const RepeatTimer&);
  35021. };
  35022. Button::Button (const String& name)
  35023. : Component (name),
  35024. text (name),
  35025. buttonPressTime (0),
  35026. lastTimeCallbackTime (0),
  35027. commandManagerToUse (0),
  35028. autoRepeatDelay (-1),
  35029. autoRepeatSpeed (0),
  35030. autoRepeatMinimumDelay (-1),
  35031. radioGroupId (0),
  35032. commandID (0),
  35033. connectedEdgeFlags (0),
  35034. buttonState (buttonNormal),
  35035. lastToggleState (false),
  35036. clickTogglesState (false),
  35037. needsToRelease (false),
  35038. needsRepainting (false),
  35039. isKeyDown (false),
  35040. triggerOnMouseDown (false),
  35041. generateTooltip (false)
  35042. {
  35043. setWantsKeyboardFocus (true);
  35044. isOn.addListener (this);
  35045. }
  35046. Button::~Button()
  35047. {
  35048. isOn.removeListener (this);
  35049. if (commandManagerToUse != 0)
  35050. commandManagerToUse->removeListener (this);
  35051. repeatTimer = 0;
  35052. clearShortcuts();
  35053. }
  35054. void Button::setButtonText (const String& newText)
  35055. {
  35056. if (text != newText)
  35057. {
  35058. text = newText;
  35059. repaint();
  35060. }
  35061. }
  35062. void Button::setTooltip (const String& newTooltip)
  35063. {
  35064. SettableTooltipClient::setTooltip (newTooltip);
  35065. generateTooltip = false;
  35066. }
  35067. const String Button::getTooltip()
  35068. {
  35069. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  35070. {
  35071. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  35072. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  35073. for (int i = 0; i < keyPresses.size(); ++i)
  35074. {
  35075. const String key (keyPresses.getReference(i).getTextDescription());
  35076. tt << " [";
  35077. if (key.length() == 1)
  35078. tt << TRANS("shortcut") << ": '" << key << "']";
  35079. else
  35080. tt << key << ']';
  35081. }
  35082. return tt;
  35083. }
  35084. return SettableTooltipClient::getTooltip();
  35085. }
  35086. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  35087. {
  35088. if (connectedEdgeFlags != connectedEdgeFlags_)
  35089. {
  35090. connectedEdgeFlags = connectedEdgeFlags_;
  35091. repaint();
  35092. }
  35093. }
  35094. void Button::setToggleState (const bool shouldBeOn,
  35095. const bool sendChangeNotification)
  35096. {
  35097. if (shouldBeOn != lastToggleState)
  35098. {
  35099. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  35100. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  35101. lastToggleState = shouldBeOn;
  35102. repaint();
  35103. if (sendChangeNotification)
  35104. {
  35105. Component::SafePointer<Component> deletionWatcher (this);
  35106. sendClickMessage (ModifierKeys());
  35107. if (deletionWatcher == 0)
  35108. return;
  35109. }
  35110. if (lastToggleState)
  35111. turnOffOtherButtonsInGroup (sendChangeNotification);
  35112. }
  35113. }
  35114. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  35115. {
  35116. clickTogglesState = shouldToggle;
  35117. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35118. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35119. // it is that this button represents, and the button will update its state to reflect this
  35120. // in the applicationCommandListChanged() method.
  35121. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35122. }
  35123. bool Button::getClickingTogglesState() const throw()
  35124. {
  35125. return clickTogglesState;
  35126. }
  35127. void Button::valueChanged (Value& value)
  35128. {
  35129. if (value.refersToSameSourceAs (isOn))
  35130. setToggleState (isOn.getValue(), true);
  35131. }
  35132. void Button::setRadioGroupId (const int newGroupId)
  35133. {
  35134. if (radioGroupId != newGroupId)
  35135. {
  35136. radioGroupId = newGroupId;
  35137. if (lastToggleState)
  35138. turnOffOtherButtonsInGroup (true);
  35139. }
  35140. }
  35141. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  35142. {
  35143. Component* const p = getParentComponent();
  35144. if (p != 0 && radioGroupId != 0)
  35145. {
  35146. Component::SafePointer<Component> deletionWatcher (this);
  35147. for (int i = p->getNumChildComponents(); --i >= 0;)
  35148. {
  35149. Component* const c = p->getChildComponent (i);
  35150. if (c != this)
  35151. {
  35152. Button* const b = dynamic_cast <Button*> (c);
  35153. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  35154. {
  35155. b->setToggleState (false, sendChangeNotification);
  35156. if (deletionWatcher == 0)
  35157. return;
  35158. }
  35159. }
  35160. }
  35161. }
  35162. }
  35163. void Button::enablementChanged()
  35164. {
  35165. updateState (0);
  35166. repaint();
  35167. }
  35168. Button::ButtonState Button::updateState (const MouseEvent* const e)
  35169. {
  35170. ButtonState state = buttonNormal;
  35171. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  35172. {
  35173. Point<int> mousePos;
  35174. if (e == 0)
  35175. mousePos = getMouseXYRelative();
  35176. else
  35177. mousePos = e->getEventRelativeTo (this).getPosition();
  35178. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  35179. const bool down = isMouseButtonDown();
  35180. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  35181. state = buttonDown;
  35182. else if (over)
  35183. state = buttonOver;
  35184. }
  35185. setState (state);
  35186. return state;
  35187. }
  35188. void Button::setState (const ButtonState newState)
  35189. {
  35190. if (buttonState != newState)
  35191. {
  35192. buttonState = newState;
  35193. repaint();
  35194. if (buttonState == buttonDown)
  35195. {
  35196. buttonPressTime = Time::getApproximateMillisecondCounter();
  35197. lastTimeCallbackTime = buttonPressTime;
  35198. }
  35199. sendStateMessage();
  35200. }
  35201. }
  35202. bool Button::isDown() const throw()
  35203. {
  35204. return buttonState == buttonDown;
  35205. }
  35206. bool Button::isOver() const throw()
  35207. {
  35208. return buttonState != buttonNormal;
  35209. }
  35210. void Button::buttonStateChanged()
  35211. {
  35212. }
  35213. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35214. {
  35215. const uint32 now = Time::getApproximateMillisecondCounter();
  35216. return now > buttonPressTime ? now - buttonPressTime : 0;
  35217. }
  35218. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35219. {
  35220. triggerOnMouseDown = isTriggeredOnMouseDown;
  35221. }
  35222. void Button::clicked()
  35223. {
  35224. }
  35225. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35226. {
  35227. clicked();
  35228. }
  35229. static const int clickMessageId = 0x2f3f4f99;
  35230. void Button::triggerClick()
  35231. {
  35232. postCommandMessage (clickMessageId);
  35233. }
  35234. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35235. {
  35236. if (clickTogglesState)
  35237. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35238. sendClickMessage (modifiers);
  35239. }
  35240. void Button::flashButtonState()
  35241. {
  35242. if (isEnabled())
  35243. {
  35244. needsToRelease = true;
  35245. setState (buttonDown);
  35246. getRepeatTimer().startTimer (100);
  35247. }
  35248. }
  35249. void Button::handleCommandMessage (int commandId)
  35250. {
  35251. if (commandId == clickMessageId)
  35252. {
  35253. if (isEnabled())
  35254. {
  35255. flashButtonState();
  35256. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35257. }
  35258. }
  35259. else
  35260. {
  35261. Component::handleCommandMessage (commandId);
  35262. }
  35263. }
  35264. void Button::addButtonListener (Listener* const newListener)
  35265. {
  35266. buttonListeners.add (newListener);
  35267. }
  35268. void Button::removeButtonListener (Listener* const listener)
  35269. {
  35270. buttonListeners.remove (listener);
  35271. }
  35272. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35273. {
  35274. Component::BailOutChecker checker (this);
  35275. if (commandManagerToUse != 0 && commandID != 0)
  35276. {
  35277. ApplicationCommandTarget::InvocationInfo info (commandID);
  35278. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35279. info.originatingComponent = this;
  35280. commandManagerToUse->invoke (info, true);
  35281. }
  35282. clicked (modifiers);
  35283. if (! checker.shouldBailOut())
  35284. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35285. }
  35286. void Button::sendStateMessage()
  35287. {
  35288. Component::BailOutChecker checker (this);
  35289. buttonStateChanged();
  35290. if (! checker.shouldBailOut())
  35291. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35292. }
  35293. void Button::paint (Graphics& g)
  35294. {
  35295. if (needsToRelease && isEnabled())
  35296. {
  35297. needsToRelease = false;
  35298. needsRepainting = true;
  35299. }
  35300. paintButton (g, isOver(), isDown());
  35301. }
  35302. void Button::mouseEnter (const MouseEvent& e)
  35303. {
  35304. updateState (&e);
  35305. }
  35306. void Button::mouseExit (const MouseEvent& e)
  35307. {
  35308. updateState (&e);
  35309. }
  35310. void Button::mouseDown (const MouseEvent& e)
  35311. {
  35312. updateState (&e);
  35313. if (isDown())
  35314. {
  35315. if (autoRepeatDelay >= 0)
  35316. getRepeatTimer().startTimer (autoRepeatDelay);
  35317. if (triggerOnMouseDown)
  35318. internalClickCallback (e.mods);
  35319. }
  35320. }
  35321. void Button::mouseUp (const MouseEvent& e)
  35322. {
  35323. const bool wasDown = isDown();
  35324. updateState (&e);
  35325. if (wasDown && isOver() && ! triggerOnMouseDown)
  35326. internalClickCallback (e.mods);
  35327. }
  35328. void Button::mouseDrag (const MouseEvent& e)
  35329. {
  35330. const ButtonState oldState = buttonState;
  35331. updateState (&e);
  35332. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35333. getRepeatTimer().startTimer (autoRepeatSpeed);
  35334. }
  35335. void Button::focusGained (FocusChangeType)
  35336. {
  35337. updateState (0);
  35338. repaint();
  35339. }
  35340. void Button::focusLost (FocusChangeType)
  35341. {
  35342. updateState (0);
  35343. repaint();
  35344. }
  35345. void Button::setVisible (bool shouldBeVisible)
  35346. {
  35347. if (shouldBeVisible != isVisible())
  35348. {
  35349. Component::setVisible (shouldBeVisible);
  35350. if (! shouldBeVisible)
  35351. needsToRelease = false;
  35352. updateState (0);
  35353. }
  35354. else
  35355. {
  35356. Component::setVisible (shouldBeVisible);
  35357. }
  35358. }
  35359. void Button::parentHierarchyChanged()
  35360. {
  35361. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35362. if (newKeySource != keySource.getComponent())
  35363. {
  35364. if (keySource != 0)
  35365. keySource->removeKeyListener (this);
  35366. keySource = newKeySource;
  35367. if (keySource != 0)
  35368. keySource->addKeyListener (this);
  35369. }
  35370. }
  35371. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35372. const int commandID_,
  35373. const bool generateTooltip_)
  35374. {
  35375. commandID = commandID_;
  35376. generateTooltip = generateTooltip_;
  35377. if (commandManagerToUse != commandManagerToUse_)
  35378. {
  35379. if (commandManagerToUse != 0)
  35380. commandManagerToUse->removeListener (this);
  35381. commandManagerToUse = commandManagerToUse_;
  35382. if (commandManagerToUse != 0)
  35383. commandManagerToUse->addListener (this);
  35384. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35385. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35386. // it is that this button represents, and the button will update its state to reflect this
  35387. // in the applicationCommandListChanged() method.
  35388. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35389. }
  35390. if (commandManagerToUse != 0)
  35391. applicationCommandListChanged();
  35392. else
  35393. setEnabled (true);
  35394. }
  35395. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35396. {
  35397. if (info.commandID == commandID
  35398. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35399. {
  35400. flashButtonState();
  35401. }
  35402. }
  35403. void Button::applicationCommandListChanged()
  35404. {
  35405. if (commandManagerToUse != 0)
  35406. {
  35407. ApplicationCommandInfo info (0);
  35408. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35409. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35410. if (target != 0)
  35411. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35412. }
  35413. }
  35414. void Button::addShortcut (const KeyPress& key)
  35415. {
  35416. if (key.isValid())
  35417. {
  35418. jassert (! isRegisteredForShortcut (key)); // already registered!
  35419. shortcuts.add (key);
  35420. parentHierarchyChanged();
  35421. }
  35422. }
  35423. void Button::clearShortcuts()
  35424. {
  35425. shortcuts.clear();
  35426. parentHierarchyChanged();
  35427. }
  35428. bool Button::isShortcutPressed() const
  35429. {
  35430. if (! isCurrentlyBlockedByAnotherModalComponent())
  35431. {
  35432. for (int i = shortcuts.size(); --i >= 0;)
  35433. if (shortcuts.getReference(i).isCurrentlyDown())
  35434. return true;
  35435. }
  35436. return false;
  35437. }
  35438. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35439. {
  35440. for (int i = shortcuts.size(); --i >= 0;)
  35441. if (key == shortcuts.getReference(i))
  35442. return true;
  35443. return false;
  35444. }
  35445. bool Button::keyStateChanged (const bool, Component*)
  35446. {
  35447. if (! isEnabled())
  35448. return false;
  35449. const bool wasDown = isKeyDown;
  35450. isKeyDown = isShortcutPressed();
  35451. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35452. getRepeatTimer().startTimer (autoRepeatDelay);
  35453. updateState (0);
  35454. if (isEnabled() && wasDown && ! isKeyDown)
  35455. {
  35456. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35457. // (return immediately - this button may now have been deleted)
  35458. return true;
  35459. }
  35460. return wasDown || isKeyDown;
  35461. }
  35462. bool Button::keyPressed (const KeyPress&, Component*)
  35463. {
  35464. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35465. return isShortcutPressed();
  35466. }
  35467. bool Button::keyPressed (const KeyPress& key)
  35468. {
  35469. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35470. {
  35471. triggerClick();
  35472. return true;
  35473. }
  35474. return false;
  35475. }
  35476. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35477. const int repeatMillisecs,
  35478. const int minimumDelayInMillisecs) throw()
  35479. {
  35480. autoRepeatDelay = initialDelayMillisecs;
  35481. autoRepeatSpeed = repeatMillisecs;
  35482. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35483. }
  35484. void Button::repeatTimerCallback()
  35485. {
  35486. if (needsRepainting)
  35487. {
  35488. getRepeatTimer().stopTimer();
  35489. updateState (0);
  35490. needsRepainting = false;
  35491. }
  35492. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35493. {
  35494. int repeatSpeed = autoRepeatSpeed;
  35495. if (autoRepeatMinimumDelay >= 0)
  35496. {
  35497. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35498. timeHeldDown *= timeHeldDown;
  35499. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35500. }
  35501. repeatSpeed = jmax (1, repeatSpeed);
  35502. getRepeatTimer().startTimer (repeatSpeed);
  35503. const uint32 now = Time::getApproximateMillisecondCounter();
  35504. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35505. lastTimeCallbackTime = now;
  35506. Component::SafePointer<Component> deletionWatcher (this);
  35507. for (int i = numTimesToCallback; --i >= 0;)
  35508. {
  35509. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35510. if (deletionWatcher == 0 || ! isDown())
  35511. return;
  35512. }
  35513. }
  35514. else if (! needsToRelease)
  35515. {
  35516. getRepeatTimer().stopTimer();
  35517. }
  35518. }
  35519. Button::RepeatTimer& Button::getRepeatTimer()
  35520. {
  35521. if (repeatTimer == 0)
  35522. repeatTimer = new RepeatTimer (*this);
  35523. return *repeatTimer;
  35524. }
  35525. END_JUCE_NAMESPACE
  35526. /*** End of inlined file: juce_Button.cpp ***/
  35527. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35528. BEGIN_JUCE_NAMESPACE
  35529. DrawableButton::DrawableButton (const String& name,
  35530. const DrawableButton::ButtonStyle buttonStyle)
  35531. : Button (name),
  35532. style (buttonStyle),
  35533. edgeIndent (3)
  35534. {
  35535. if (buttonStyle == ImageOnButtonBackground)
  35536. {
  35537. backgroundOff = Colour (0xffbbbbff);
  35538. backgroundOn = Colour (0xff3333ff);
  35539. }
  35540. else
  35541. {
  35542. backgroundOff = Colours::transparentBlack;
  35543. backgroundOn = Colour (0xaabbbbff);
  35544. }
  35545. }
  35546. DrawableButton::~DrawableButton()
  35547. {
  35548. deleteImages();
  35549. }
  35550. void DrawableButton::deleteImages()
  35551. {
  35552. }
  35553. void DrawableButton::setImages (const Drawable* normal,
  35554. const Drawable* over,
  35555. const Drawable* down,
  35556. const Drawable* disabled,
  35557. const Drawable* normalOn,
  35558. const Drawable* overOn,
  35559. const Drawable* downOn,
  35560. const Drawable* disabledOn)
  35561. {
  35562. deleteImages();
  35563. jassert (normal != 0); // you really need to give it at least a normal image..
  35564. if (normal != 0)
  35565. normalImage = normal->createCopy();
  35566. if (over != 0)
  35567. overImage = over->createCopy();
  35568. if (down != 0)
  35569. downImage = down->createCopy();
  35570. if (disabled != 0)
  35571. disabledImage = disabled->createCopy();
  35572. if (normalOn != 0)
  35573. normalImageOn = normalOn->createCopy();
  35574. if (overOn != 0)
  35575. overImageOn = overOn->createCopy();
  35576. if (downOn != 0)
  35577. downImageOn = downOn->createCopy();
  35578. if (disabledOn != 0)
  35579. disabledImageOn = disabledOn->createCopy();
  35580. repaint();
  35581. }
  35582. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35583. {
  35584. if (style != newStyle)
  35585. {
  35586. style = newStyle;
  35587. repaint();
  35588. }
  35589. }
  35590. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35591. const Colour& toggledOnColour)
  35592. {
  35593. if (backgroundOff != toggledOffColour
  35594. || backgroundOn != toggledOnColour)
  35595. {
  35596. backgroundOff = toggledOffColour;
  35597. backgroundOn = toggledOnColour;
  35598. repaint();
  35599. }
  35600. }
  35601. const Colour& DrawableButton::getBackgroundColour() const throw()
  35602. {
  35603. return getToggleState() ? backgroundOn
  35604. : backgroundOff;
  35605. }
  35606. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35607. {
  35608. edgeIndent = numPixelsIndent;
  35609. repaint();
  35610. }
  35611. void DrawableButton::paintButton (Graphics& g,
  35612. bool isMouseOverButton,
  35613. bool isButtonDown)
  35614. {
  35615. Rectangle<int> imageSpace;
  35616. if (style == ImageOnButtonBackground)
  35617. {
  35618. const int insetX = getWidth() / 4;
  35619. const int insetY = getHeight() / 4;
  35620. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35621. getLookAndFeel().drawButtonBackground (g, *this,
  35622. getBackgroundColour(),
  35623. isMouseOverButton,
  35624. isButtonDown);
  35625. }
  35626. else
  35627. {
  35628. g.fillAll (getBackgroundColour());
  35629. const int textH = (style == ImageAboveTextLabel)
  35630. ? jmin (16, proportionOfHeight (0.25f))
  35631. : 0;
  35632. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35633. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35634. imageSpace.setBounds (indentX, indentY,
  35635. getWidth() - indentX * 2,
  35636. getHeight() - indentY * 2 - textH);
  35637. if (textH > 0)
  35638. {
  35639. g.setFont ((float) textH);
  35640. g.setColour (findColour (DrawableButton::textColourId)
  35641. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35642. g.drawFittedText (getButtonText(),
  35643. 2, getHeight() - textH - 1,
  35644. getWidth() - 4, textH,
  35645. Justification::centred, 1);
  35646. }
  35647. }
  35648. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35649. g.setOpacity (1.0f);
  35650. const Drawable* imageToDraw = 0;
  35651. if (isEnabled())
  35652. {
  35653. imageToDraw = getCurrentImage();
  35654. }
  35655. else
  35656. {
  35657. imageToDraw = getToggleState() ? disabledImageOn
  35658. : disabledImage;
  35659. if (imageToDraw == 0)
  35660. {
  35661. g.setOpacity (0.4f);
  35662. imageToDraw = getNormalImage();
  35663. }
  35664. }
  35665. if (imageToDraw != 0)
  35666. {
  35667. if (style == ImageRaw)
  35668. {
  35669. imageToDraw->draw (g, 1.0f);
  35670. }
  35671. else
  35672. {
  35673. imageToDraw->drawWithin (g,
  35674. imageSpace.getX(),
  35675. imageSpace.getY(),
  35676. imageSpace.getWidth(),
  35677. imageSpace.getHeight(),
  35678. RectanglePlacement::centred,
  35679. 1.0f);
  35680. }
  35681. }
  35682. }
  35683. const Drawable* DrawableButton::getCurrentImage() const throw()
  35684. {
  35685. if (isDown())
  35686. return getDownImage();
  35687. if (isOver())
  35688. return getOverImage();
  35689. return getNormalImage();
  35690. }
  35691. const Drawable* DrawableButton::getNormalImage() const throw()
  35692. {
  35693. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35694. : normalImage;
  35695. }
  35696. const Drawable* DrawableButton::getOverImage() const throw()
  35697. {
  35698. const Drawable* d = normalImage;
  35699. if (getToggleState())
  35700. {
  35701. if (overImageOn != 0)
  35702. d = overImageOn;
  35703. else if (normalImageOn != 0)
  35704. d = normalImageOn;
  35705. else if (overImage != 0)
  35706. d = overImage;
  35707. }
  35708. else
  35709. {
  35710. if (overImage != 0)
  35711. d = overImage;
  35712. }
  35713. return d;
  35714. }
  35715. const Drawable* DrawableButton::getDownImage() const throw()
  35716. {
  35717. const Drawable* d = normalImage;
  35718. if (getToggleState())
  35719. {
  35720. if (downImageOn != 0)
  35721. d = downImageOn;
  35722. else if (overImageOn != 0)
  35723. d = overImageOn;
  35724. else if (normalImageOn != 0)
  35725. d = normalImageOn;
  35726. else if (downImage != 0)
  35727. d = downImage;
  35728. else
  35729. d = getOverImage();
  35730. }
  35731. else
  35732. {
  35733. if (downImage != 0)
  35734. d = downImage;
  35735. else
  35736. d = getOverImage();
  35737. }
  35738. return d;
  35739. }
  35740. END_JUCE_NAMESPACE
  35741. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35742. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35743. BEGIN_JUCE_NAMESPACE
  35744. HyperlinkButton::HyperlinkButton (const String& linkText,
  35745. const URL& linkURL)
  35746. : Button (linkText),
  35747. url (linkURL),
  35748. font (14.0f, Font::underlined),
  35749. resizeFont (true),
  35750. justification (Justification::centred)
  35751. {
  35752. setMouseCursor (MouseCursor::PointingHandCursor);
  35753. setTooltip (linkURL.toString (false));
  35754. }
  35755. HyperlinkButton::~HyperlinkButton()
  35756. {
  35757. }
  35758. void HyperlinkButton::setFont (const Font& newFont,
  35759. const bool resizeToMatchComponentHeight,
  35760. const Justification& justificationType)
  35761. {
  35762. font = newFont;
  35763. resizeFont = resizeToMatchComponentHeight;
  35764. justification = justificationType;
  35765. repaint();
  35766. }
  35767. void HyperlinkButton::setURL (const URL& newURL) throw()
  35768. {
  35769. url = newURL;
  35770. setTooltip (newURL.toString (false));
  35771. }
  35772. const Font HyperlinkButton::getFontToUse() const
  35773. {
  35774. Font f (font);
  35775. if (resizeFont)
  35776. f.setHeight (getHeight() * 0.7f);
  35777. return f;
  35778. }
  35779. void HyperlinkButton::changeWidthToFitText()
  35780. {
  35781. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35782. }
  35783. void HyperlinkButton::colourChanged()
  35784. {
  35785. repaint();
  35786. }
  35787. void HyperlinkButton::clicked()
  35788. {
  35789. if (url.isWellFormed())
  35790. url.launchInDefaultBrowser();
  35791. }
  35792. void HyperlinkButton::paintButton (Graphics& g,
  35793. bool isMouseOverButton,
  35794. bool isButtonDown)
  35795. {
  35796. const Colour textColour (findColour (textColourId));
  35797. if (isEnabled())
  35798. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35799. : textColour);
  35800. else
  35801. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35802. g.setFont (getFontToUse());
  35803. g.drawText (getButtonText(),
  35804. 2, 0, getWidth() - 2, getHeight(),
  35805. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35806. true);
  35807. }
  35808. END_JUCE_NAMESPACE
  35809. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35810. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35811. BEGIN_JUCE_NAMESPACE
  35812. ImageButton::ImageButton (const String& text_)
  35813. : Button (text_),
  35814. scaleImageToFit (true),
  35815. preserveProportions (true),
  35816. alphaThreshold (0),
  35817. imageX (0),
  35818. imageY (0),
  35819. imageW (0),
  35820. imageH (0),
  35821. normalImage (0),
  35822. overImage (0),
  35823. downImage (0)
  35824. {
  35825. }
  35826. ImageButton::~ImageButton()
  35827. {
  35828. }
  35829. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35830. const bool rescaleImagesWhenButtonSizeChanges,
  35831. const bool preserveImageProportions,
  35832. const Image& normalImage_,
  35833. const float imageOpacityWhenNormal,
  35834. const Colour& overlayColourWhenNormal,
  35835. const Image& overImage_,
  35836. const float imageOpacityWhenOver,
  35837. const Colour& overlayColourWhenOver,
  35838. const Image& downImage_,
  35839. const float imageOpacityWhenDown,
  35840. const Colour& overlayColourWhenDown,
  35841. const float hitTestAlphaThreshold)
  35842. {
  35843. normalImage = normalImage_;
  35844. overImage = overImage_;
  35845. downImage = downImage_;
  35846. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35847. {
  35848. imageW = normalImage.getWidth();
  35849. imageH = normalImage.getHeight();
  35850. setSize (imageW, imageH);
  35851. }
  35852. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35853. preserveProportions = preserveImageProportions;
  35854. normalOpacity = imageOpacityWhenNormal;
  35855. normalOverlay = overlayColourWhenNormal;
  35856. overOpacity = imageOpacityWhenOver;
  35857. overOverlay = overlayColourWhenOver;
  35858. downOpacity = imageOpacityWhenDown;
  35859. downOverlay = overlayColourWhenDown;
  35860. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35861. repaint();
  35862. }
  35863. const Image ImageButton::getCurrentImage() const
  35864. {
  35865. if (isDown() || getToggleState())
  35866. return getDownImage();
  35867. if (isOver())
  35868. return getOverImage();
  35869. return getNormalImage();
  35870. }
  35871. const Image ImageButton::getNormalImage() const
  35872. {
  35873. return normalImage;
  35874. }
  35875. const Image ImageButton::getOverImage() const
  35876. {
  35877. return overImage.isValid() ? overImage
  35878. : normalImage;
  35879. }
  35880. const Image ImageButton::getDownImage() const
  35881. {
  35882. return downImage.isValid() ? downImage
  35883. : getOverImage();
  35884. }
  35885. void ImageButton::paintButton (Graphics& g,
  35886. bool isMouseOverButton,
  35887. bool isButtonDown)
  35888. {
  35889. if (! isEnabled())
  35890. {
  35891. isMouseOverButton = false;
  35892. isButtonDown = false;
  35893. }
  35894. Image im (getCurrentImage());
  35895. if (im.isValid())
  35896. {
  35897. const int iw = im.getWidth();
  35898. const int ih = im.getHeight();
  35899. imageW = getWidth();
  35900. imageH = getHeight();
  35901. imageX = (imageW - iw) >> 1;
  35902. imageY = (imageH - ih) >> 1;
  35903. if (scaleImageToFit)
  35904. {
  35905. if (preserveProportions)
  35906. {
  35907. int newW, newH;
  35908. const float imRatio = ih / (float)iw;
  35909. const float destRatio = imageH / (float)imageW;
  35910. if (imRatio > destRatio)
  35911. {
  35912. newW = roundToInt (imageH / imRatio);
  35913. newH = imageH;
  35914. }
  35915. else
  35916. {
  35917. newW = imageW;
  35918. newH = roundToInt (imageW * imRatio);
  35919. }
  35920. imageX = (imageW - newW) / 2;
  35921. imageY = (imageH - newH) / 2;
  35922. imageW = newW;
  35923. imageH = newH;
  35924. }
  35925. else
  35926. {
  35927. imageX = 0;
  35928. imageY = 0;
  35929. }
  35930. }
  35931. if (! scaleImageToFit)
  35932. {
  35933. imageW = iw;
  35934. imageH = ih;
  35935. }
  35936. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35937. isButtonDown ? downOverlay
  35938. : (isMouseOverButton ? overOverlay
  35939. : normalOverlay),
  35940. isButtonDown ? downOpacity
  35941. : (isMouseOverButton ? overOpacity
  35942. : normalOpacity),
  35943. *this);
  35944. }
  35945. }
  35946. bool ImageButton::hitTest (int x, int y)
  35947. {
  35948. if (alphaThreshold == 0)
  35949. return true;
  35950. Image im (getCurrentImage());
  35951. return im.isNull() || (imageW > 0 && imageH > 0
  35952. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35953. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35954. }
  35955. END_JUCE_NAMESPACE
  35956. /*** End of inlined file: juce_ImageButton.cpp ***/
  35957. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35958. BEGIN_JUCE_NAMESPACE
  35959. ShapeButton::ShapeButton (const String& text_,
  35960. const Colour& normalColour_,
  35961. const Colour& overColour_,
  35962. const Colour& downColour_)
  35963. : Button (text_),
  35964. normalColour (normalColour_),
  35965. overColour (overColour_),
  35966. downColour (downColour_),
  35967. maintainShapeProportions (false),
  35968. outlineWidth (0.0f)
  35969. {
  35970. }
  35971. ShapeButton::~ShapeButton()
  35972. {
  35973. }
  35974. void ShapeButton::setColours (const Colour& newNormalColour,
  35975. const Colour& newOverColour,
  35976. const Colour& newDownColour)
  35977. {
  35978. normalColour = newNormalColour;
  35979. overColour = newOverColour;
  35980. downColour = newDownColour;
  35981. }
  35982. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35983. const float newOutlineWidth)
  35984. {
  35985. outlineColour = newOutlineColour;
  35986. outlineWidth = newOutlineWidth;
  35987. }
  35988. void ShapeButton::setShape (const Path& newShape,
  35989. const bool resizeNowToFitThisShape,
  35990. const bool maintainShapeProportions_,
  35991. const bool hasShadow)
  35992. {
  35993. shape = newShape;
  35994. maintainShapeProportions = maintainShapeProportions_;
  35995. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35996. setComponentEffect ((hasShadow) ? &shadow : 0);
  35997. if (resizeNowToFitThisShape)
  35998. {
  35999. Rectangle<float> bounds (shape.getBounds());
  36000. if (hasShadow)
  36001. bounds.expand (4.0f, 4.0f);
  36002. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  36003. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  36004. 1 + (int) (bounds.getHeight() + outlineWidth));
  36005. }
  36006. }
  36007. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  36008. {
  36009. if (! isEnabled())
  36010. {
  36011. isMouseOverButton = false;
  36012. isButtonDown = false;
  36013. }
  36014. g.setColour ((isButtonDown) ? downColour
  36015. : (isMouseOverButton) ? overColour
  36016. : normalColour);
  36017. int w = getWidth();
  36018. int h = getHeight();
  36019. if (getComponentEffect() != 0)
  36020. {
  36021. w -= 4;
  36022. h -= 4;
  36023. }
  36024. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  36025. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  36026. w - offset - outlineWidth,
  36027. h - offset - outlineWidth,
  36028. maintainShapeProportions));
  36029. g.fillPath (shape, trans);
  36030. if (outlineWidth > 0.0f)
  36031. {
  36032. g.setColour (outlineColour);
  36033. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  36034. }
  36035. }
  36036. END_JUCE_NAMESPACE
  36037. /*** End of inlined file: juce_ShapeButton.cpp ***/
  36038. /*** Start of inlined file: juce_TextButton.cpp ***/
  36039. BEGIN_JUCE_NAMESPACE
  36040. TextButton::TextButton (const String& name,
  36041. const String& toolTip)
  36042. : Button (name)
  36043. {
  36044. setTooltip (toolTip);
  36045. }
  36046. TextButton::~TextButton()
  36047. {
  36048. }
  36049. void TextButton::paintButton (Graphics& g,
  36050. bool isMouseOverButton,
  36051. bool isButtonDown)
  36052. {
  36053. getLookAndFeel().drawButtonBackground (g, *this,
  36054. findColour (getToggleState() ? buttonOnColourId
  36055. : buttonColourId),
  36056. isMouseOverButton,
  36057. isButtonDown);
  36058. getLookAndFeel().drawButtonText (g, *this,
  36059. isMouseOverButton,
  36060. isButtonDown);
  36061. }
  36062. void TextButton::colourChanged()
  36063. {
  36064. repaint();
  36065. }
  36066. const Font TextButton::getFont()
  36067. {
  36068. return Font (jmin (15.0f, getHeight() * 0.6f));
  36069. }
  36070. void TextButton::changeWidthToFitText (const int newHeight)
  36071. {
  36072. if (newHeight >= 0)
  36073. setSize (jmax (1, getWidth()), newHeight);
  36074. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  36075. getHeight());
  36076. }
  36077. END_JUCE_NAMESPACE
  36078. /*** End of inlined file: juce_TextButton.cpp ***/
  36079. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  36080. BEGIN_JUCE_NAMESPACE
  36081. ToggleButton::ToggleButton (const String& buttonText)
  36082. : Button (buttonText)
  36083. {
  36084. setClickingTogglesState (true);
  36085. }
  36086. ToggleButton::~ToggleButton()
  36087. {
  36088. }
  36089. void ToggleButton::paintButton (Graphics& g,
  36090. bool isMouseOverButton,
  36091. bool isButtonDown)
  36092. {
  36093. getLookAndFeel().drawToggleButton (g, *this,
  36094. isMouseOverButton,
  36095. isButtonDown);
  36096. }
  36097. void ToggleButton::changeWidthToFitText()
  36098. {
  36099. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  36100. }
  36101. void ToggleButton::colourChanged()
  36102. {
  36103. repaint();
  36104. }
  36105. END_JUCE_NAMESPACE
  36106. /*** End of inlined file: juce_ToggleButton.cpp ***/
  36107. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  36108. BEGIN_JUCE_NAMESPACE
  36109. ToolbarButton::ToolbarButton (const int itemId_,
  36110. const String& buttonText,
  36111. Drawable* const normalImage_,
  36112. Drawable* const toggledOnImage_)
  36113. : ToolbarItemComponent (itemId_, buttonText, true),
  36114. normalImage (normalImage_),
  36115. toggledOnImage (toggledOnImage_)
  36116. {
  36117. jassert (normalImage_ != 0);
  36118. }
  36119. ToolbarButton::~ToolbarButton()
  36120. {
  36121. }
  36122. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  36123. bool /*isToolbarVertical*/,
  36124. int& preferredSize,
  36125. int& minSize, int& maxSize)
  36126. {
  36127. preferredSize = minSize = maxSize = toolbarDepth;
  36128. return true;
  36129. }
  36130. void ToolbarButton::paintButtonArea (Graphics& g,
  36131. int width, int height,
  36132. bool /*isMouseOver*/,
  36133. bool /*isMouseDown*/)
  36134. {
  36135. Drawable* d = normalImage;
  36136. if (getToggleState() && toggledOnImage != 0)
  36137. d = toggledOnImage;
  36138. if (! isEnabled())
  36139. {
  36140. Image im (Image::ARGB, width, height, true);
  36141. {
  36142. Graphics g2 (im);
  36143. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  36144. }
  36145. im.desaturate();
  36146. g.drawImageAt (im, 0, 0);
  36147. }
  36148. else
  36149. {
  36150. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  36151. }
  36152. }
  36153. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  36154. {
  36155. }
  36156. END_JUCE_NAMESPACE
  36157. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  36158. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  36159. BEGIN_JUCE_NAMESPACE
  36160. class CodeDocumentLine
  36161. {
  36162. public:
  36163. CodeDocumentLine (const juce_wchar* const line_,
  36164. const int lineLength_,
  36165. const int numNewLineChars,
  36166. const int lineStartInFile_)
  36167. : line (line_, lineLength_),
  36168. lineStartInFile (lineStartInFile_),
  36169. lineLength (lineLength_),
  36170. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  36171. {
  36172. }
  36173. ~CodeDocumentLine()
  36174. {
  36175. }
  36176. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  36177. {
  36178. const juce_wchar* const t = text;
  36179. int pos = 0;
  36180. while (t [pos] != 0)
  36181. {
  36182. const int startOfLine = pos;
  36183. int numNewLineChars = 0;
  36184. while (t[pos] != 0)
  36185. {
  36186. if (t[pos] == '\r')
  36187. {
  36188. ++numNewLineChars;
  36189. ++pos;
  36190. if (t[pos] == '\n')
  36191. {
  36192. ++numNewLineChars;
  36193. ++pos;
  36194. }
  36195. break;
  36196. }
  36197. if (t[pos] == '\n')
  36198. {
  36199. ++numNewLineChars;
  36200. ++pos;
  36201. break;
  36202. }
  36203. ++pos;
  36204. }
  36205. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36206. numNewLineChars, startOfLine));
  36207. }
  36208. jassert (pos == text.length());
  36209. }
  36210. bool endsWithLineBreak() const throw()
  36211. {
  36212. return lineLengthWithoutNewLines != lineLength;
  36213. }
  36214. void updateLength() throw()
  36215. {
  36216. lineLengthWithoutNewLines = lineLength = line.length();
  36217. while (lineLengthWithoutNewLines > 0
  36218. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36219. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36220. {
  36221. --lineLengthWithoutNewLines;
  36222. }
  36223. }
  36224. String line;
  36225. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36226. };
  36227. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36228. : document (document_),
  36229. currentLine (document_->lines[0]),
  36230. line (0),
  36231. position (0)
  36232. {
  36233. }
  36234. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36235. : document (other.document),
  36236. currentLine (other.currentLine),
  36237. line (other.line),
  36238. position (other.position)
  36239. {
  36240. }
  36241. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36242. {
  36243. document = other.document;
  36244. currentLine = other.currentLine;
  36245. line = other.line;
  36246. position = other.position;
  36247. return *this;
  36248. }
  36249. CodeDocument::Iterator::~Iterator() throw()
  36250. {
  36251. }
  36252. juce_wchar CodeDocument::Iterator::nextChar()
  36253. {
  36254. if (currentLine == 0)
  36255. return 0;
  36256. jassert (currentLine == document->lines.getUnchecked (line));
  36257. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36258. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36259. {
  36260. ++line;
  36261. currentLine = document->lines [line];
  36262. }
  36263. return result;
  36264. }
  36265. void CodeDocument::Iterator::skip()
  36266. {
  36267. if (currentLine != 0)
  36268. {
  36269. jassert (currentLine == document->lines.getUnchecked (line));
  36270. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36271. {
  36272. ++line;
  36273. currentLine = document->lines [line];
  36274. }
  36275. }
  36276. }
  36277. void CodeDocument::Iterator::skipToEndOfLine()
  36278. {
  36279. if (currentLine != 0)
  36280. {
  36281. jassert (currentLine == document->lines.getUnchecked (line));
  36282. ++line;
  36283. currentLine = document->lines [line];
  36284. if (currentLine != 0)
  36285. position = currentLine->lineStartInFile;
  36286. else
  36287. position = document->getNumCharacters();
  36288. }
  36289. }
  36290. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36291. {
  36292. if (currentLine == 0)
  36293. return 0;
  36294. jassert (currentLine == document->lines.getUnchecked (line));
  36295. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36296. }
  36297. void CodeDocument::Iterator::skipWhitespace()
  36298. {
  36299. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36300. skip();
  36301. }
  36302. bool CodeDocument::Iterator::isEOF() const throw()
  36303. {
  36304. return currentLine == 0;
  36305. }
  36306. CodeDocument::Position::Position() throw()
  36307. : owner (0), characterPos (0), line (0),
  36308. indexInLine (0), positionMaintained (false)
  36309. {
  36310. }
  36311. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36312. const int line_, const int indexInLine_) throw()
  36313. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36314. characterPos (0), line (line_),
  36315. indexInLine (indexInLine_), positionMaintained (false)
  36316. {
  36317. setLineAndIndex (line_, indexInLine_);
  36318. }
  36319. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36320. const int characterPos_) throw()
  36321. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36322. positionMaintained (false)
  36323. {
  36324. setPosition (characterPos_);
  36325. }
  36326. CodeDocument::Position::Position (const Position& other) throw()
  36327. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36328. indexInLine (other.indexInLine), positionMaintained (false)
  36329. {
  36330. jassert (*this == other);
  36331. }
  36332. CodeDocument::Position::~Position()
  36333. {
  36334. setPositionMaintained (false);
  36335. }
  36336. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36337. {
  36338. if (this != &other)
  36339. {
  36340. const bool wasPositionMaintained = positionMaintained;
  36341. if (owner != other.owner)
  36342. setPositionMaintained (false);
  36343. owner = other.owner;
  36344. line = other.line;
  36345. indexInLine = other.indexInLine;
  36346. characterPos = other.characterPos;
  36347. setPositionMaintained (wasPositionMaintained);
  36348. jassert (*this == other);
  36349. }
  36350. return *this;
  36351. }
  36352. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36353. {
  36354. jassert ((characterPos == other.characterPos)
  36355. == (line == other.line && indexInLine == other.indexInLine));
  36356. return characterPos == other.characterPos
  36357. && line == other.line
  36358. && indexInLine == other.indexInLine
  36359. && owner == other.owner;
  36360. }
  36361. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36362. {
  36363. return ! operator== (other);
  36364. }
  36365. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36366. {
  36367. jassert (owner != 0);
  36368. if (owner->lines.size() == 0)
  36369. {
  36370. line = 0;
  36371. indexInLine = 0;
  36372. characterPos = 0;
  36373. }
  36374. else
  36375. {
  36376. if (newLine >= owner->lines.size())
  36377. {
  36378. line = owner->lines.size() - 1;
  36379. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36380. jassert (l != 0);
  36381. indexInLine = l->lineLengthWithoutNewLines;
  36382. characterPos = l->lineStartInFile + indexInLine;
  36383. }
  36384. else
  36385. {
  36386. line = jmax (0, newLine);
  36387. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36388. jassert (l != 0);
  36389. if (l->lineLengthWithoutNewLines > 0)
  36390. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36391. else
  36392. indexInLine = 0;
  36393. characterPos = l->lineStartInFile + indexInLine;
  36394. }
  36395. }
  36396. }
  36397. void CodeDocument::Position::setPosition (const int newPosition)
  36398. {
  36399. jassert (owner != 0);
  36400. line = 0;
  36401. indexInLine = 0;
  36402. characterPos = 0;
  36403. if (newPosition > 0)
  36404. {
  36405. int lineStart = 0;
  36406. int lineEnd = owner->lines.size();
  36407. for (;;)
  36408. {
  36409. if (lineEnd - lineStart < 4)
  36410. {
  36411. for (int i = lineStart; i < lineEnd; ++i)
  36412. {
  36413. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36414. int index = newPosition - l->lineStartInFile;
  36415. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36416. {
  36417. line = i;
  36418. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36419. characterPos = l->lineStartInFile + indexInLine;
  36420. }
  36421. }
  36422. break;
  36423. }
  36424. else
  36425. {
  36426. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36427. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36428. if (newPosition >= mid->lineStartInFile)
  36429. lineStart = midIndex;
  36430. else
  36431. lineEnd = midIndex;
  36432. }
  36433. }
  36434. }
  36435. }
  36436. void CodeDocument::Position::moveBy (int characterDelta)
  36437. {
  36438. jassert (owner != 0);
  36439. if (characterDelta == 1)
  36440. {
  36441. setPosition (getPosition());
  36442. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36443. if (line < owner->lines.size())
  36444. {
  36445. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36446. if (indexInLine + characterDelta < l->lineLength
  36447. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36448. ++characterDelta;
  36449. }
  36450. }
  36451. setPosition (characterPos + characterDelta);
  36452. }
  36453. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36454. {
  36455. CodeDocument::Position p (*this);
  36456. p.moveBy (characterDelta);
  36457. return p;
  36458. }
  36459. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36460. {
  36461. CodeDocument::Position p (*this);
  36462. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36463. return p;
  36464. }
  36465. const juce_wchar CodeDocument::Position::getCharacter() const
  36466. {
  36467. const CodeDocumentLine* const l = owner->lines [line];
  36468. return l == 0 ? 0 : l->line [getIndexInLine()];
  36469. }
  36470. const String CodeDocument::Position::getLineText() const
  36471. {
  36472. const CodeDocumentLine* const l = owner->lines [line];
  36473. return l == 0 ? String::empty : l->line;
  36474. }
  36475. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36476. {
  36477. if (isMaintained != positionMaintained)
  36478. {
  36479. positionMaintained = isMaintained;
  36480. if (owner != 0)
  36481. {
  36482. if (isMaintained)
  36483. {
  36484. jassert (! owner->positionsToMaintain.contains (this));
  36485. owner->positionsToMaintain.add (this);
  36486. }
  36487. else
  36488. {
  36489. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36490. jassert (owner->positionsToMaintain.contains (this));
  36491. owner->positionsToMaintain.removeValue (this);
  36492. }
  36493. }
  36494. }
  36495. }
  36496. CodeDocument::CodeDocument()
  36497. : undoManager (std::numeric_limits<int>::max(), 10000),
  36498. currentActionIndex (0),
  36499. indexOfSavedState (-1),
  36500. maximumLineLength (-1),
  36501. newLineChars ("\r\n")
  36502. {
  36503. }
  36504. CodeDocument::~CodeDocument()
  36505. {
  36506. }
  36507. const String CodeDocument::getAllContent() const
  36508. {
  36509. return getTextBetween (Position (this, 0),
  36510. Position (this, lines.size(), 0));
  36511. }
  36512. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36513. {
  36514. if (end.getPosition() <= start.getPosition())
  36515. return String::empty;
  36516. const int startLine = start.getLineNumber();
  36517. const int endLine = end.getLineNumber();
  36518. if (startLine == endLine)
  36519. {
  36520. CodeDocumentLine* const line = lines [startLine];
  36521. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36522. }
  36523. String result;
  36524. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36525. String::Concatenator concatenator (result);
  36526. const int maxLine = jmin (lines.size() - 1, endLine);
  36527. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36528. {
  36529. const CodeDocumentLine* line = lines.getUnchecked(i);
  36530. int len = line->lineLength;
  36531. if (i == startLine)
  36532. {
  36533. const int index = start.getIndexInLine();
  36534. concatenator.append (line->line.substring (index, len));
  36535. }
  36536. else if (i == endLine)
  36537. {
  36538. len = end.getIndexInLine();
  36539. concatenator.append (line->line.substring (0, len));
  36540. }
  36541. else
  36542. {
  36543. concatenator.append (line->line);
  36544. }
  36545. }
  36546. return result;
  36547. }
  36548. int CodeDocument::getNumCharacters() const throw()
  36549. {
  36550. const CodeDocumentLine* const lastLine = lines.getLast();
  36551. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36552. }
  36553. const String CodeDocument::getLine (const int lineIndex) const throw()
  36554. {
  36555. const CodeDocumentLine* const line = lines [lineIndex];
  36556. return (line == 0) ? String::empty : line->line;
  36557. }
  36558. int CodeDocument::getMaximumLineLength() throw()
  36559. {
  36560. if (maximumLineLength < 0)
  36561. {
  36562. maximumLineLength = 0;
  36563. for (int i = lines.size(); --i >= 0;)
  36564. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36565. }
  36566. return maximumLineLength;
  36567. }
  36568. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36569. {
  36570. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36571. }
  36572. void CodeDocument::insertText (const Position& position, const String& text)
  36573. {
  36574. insert (text, position.getPosition(), true);
  36575. }
  36576. void CodeDocument::replaceAllContent (const String& newContent)
  36577. {
  36578. remove (0, getNumCharacters(), true);
  36579. insert (newContent, 0, true);
  36580. }
  36581. bool CodeDocument::loadFromStream (InputStream& stream)
  36582. {
  36583. replaceAllContent (stream.readEntireStreamAsString());
  36584. setSavePoint();
  36585. clearUndoHistory();
  36586. return true;
  36587. }
  36588. bool CodeDocument::writeToStream (OutputStream& stream)
  36589. {
  36590. for (int i = 0; i < lines.size(); ++i)
  36591. {
  36592. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36593. const char* utf8 = temp.toUTF8();
  36594. if (! stream.write (utf8, (int) strlen (utf8)))
  36595. return false;
  36596. }
  36597. return true;
  36598. }
  36599. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36600. {
  36601. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36602. newLineChars = newLine;
  36603. }
  36604. void CodeDocument::newTransaction()
  36605. {
  36606. undoManager.beginNewTransaction (String::empty);
  36607. }
  36608. void CodeDocument::undo()
  36609. {
  36610. newTransaction();
  36611. undoManager.undo();
  36612. }
  36613. void CodeDocument::redo()
  36614. {
  36615. undoManager.redo();
  36616. }
  36617. void CodeDocument::clearUndoHistory()
  36618. {
  36619. undoManager.clearUndoHistory();
  36620. }
  36621. void CodeDocument::setSavePoint() throw()
  36622. {
  36623. indexOfSavedState = currentActionIndex;
  36624. }
  36625. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36626. {
  36627. return currentActionIndex != indexOfSavedState;
  36628. }
  36629. static int getCodeCharacterCategory (const juce_wchar character) throw()
  36630. {
  36631. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36632. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36633. }
  36634. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36635. {
  36636. Position p (position);
  36637. const int maxDistance = 256;
  36638. int i = 0;
  36639. while (i < maxDistance
  36640. && CharacterFunctions::isWhitespace (p.getCharacter())
  36641. && (i == 0 || (p.getCharacter() != '\n'
  36642. && p.getCharacter() != '\r')))
  36643. {
  36644. ++i;
  36645. p.moveBy (1);
  36646. }
  36647. if (i == 0)
  36648. {
  36649. const int type = getCodeCharacterCategory (p.getCharacter());
  36650. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  36651. {
  36652. ++i;
  36653. p.moveBy (1);
  36654. }
  36655. while (i < maxDistance
  36656. && CharacterFunctions::isWhitespace (p.getCharacter())
  36657. && (i == 0 || (p.getCharacter() != '\n'
  36658. && p.getCharacter() != '\r')))
  36659. {
  36660. ++i;
  36661. p.moveBy (1);
  36662. }
  36663. }
  36664. return p;
  36665. }
  36666. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36667. {
  36668. Position p (position);
  36669. const int maxDistance = 256;
  36670. int i = 0;
  36671. bool stoppedAtLineStart = false;
  36672. while (i < maxDistance)
  36673. {
  36674. const juce_wchar c = p.movedBy (-1).getCharacter();
  36675. if (c == '\r' || c == '\n')
  36676. {
  36677. stoppedAtLineStart = true;
  36678. if (i > 0)
  36679. break;
  36680. }
  36681. if (! CharacterFunctions::isWhitespace (c))
  36682. break;
  36683. p.moveBy (-1);
  36684. ++i;
  36685. }
  36686. if (i < maxDistance && ! stoppedAtLineStart)
  36687. {
  36688. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  36689. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  36690. {
  36691. p.moveBy (-1);
  36692. ++i;
  36693. }
  36694. }
  36695. return p;
  36696. }
  36697. void CodeDocument::checkLastLineStatus()
  36698. {
  36699. while (lines.size() > 0
  36700. && lines.getLast()->lineLength == 0
  36701. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36702. {
  36703. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36704. lines.removeLast();
  36705. }
  36706. const CodeDocumentLine* const lastLine = lines.getLast();
  36707. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36708. {
  36709. // check that there's an empty line at the end if the preceding one ends in a newline..
  36710. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36711. }
  36712. }
  36713. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36714. {
  36715. listeners.add (listener);
  36716. }
  36717. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36718. {
  36719. listeners.remove (listener);
  36720. }
  36721. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36722. {
  36723. Position startPos (this, startLine, 0);
  36724. Position endPos (this, endLine, 0);
  36725. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36726. }
  36727. class CodeDocumentInsertAction : public UndoableAction
  36728. {
  36729. CodeDocument& owner;
  36730. const String text;
  36731. int insertPos;
  36732. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36733. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36734. public:
  36735. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36736. : owner (owner_),
  36737. text (text_),
  36738. insertPos (insertPos_)
  36739. {
  36740. }
  36741. ~CodeDocumentInsertAction() {}
  36742. bool perform()
  36743. {
  36744. owner.currentActionIndex++;
  36745. owner.insert (text, insertPos, false);
  36746. return true;
  36747. }
  36748. bool undo()
  36749. {
  36750. owner.currentActionIndex--;
  36751. owner.remove (insertPos, insertPos + text.length(), false);
  36752. return true;
  36753. }
  36754. int getSizeInUnits() { return text.length() + 32; }
  36755. };
  36756. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36757. {
  36758. if (text.isEmpty())
  36759. return;
  36760. if (undoable)
  36761. {
  36762. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36763. }
  36764. else
  36765. {
  36766. Position pos (this, insertPos);
  36767. const int firstAffectedLine = pos.getLineNumber();
  36768. int lastAffectedLine = firstAffectedLine + 1;
  36769. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36770. String textInsideOriginalLine (text);
  36771. if (firstLine != 0)
  36772. {
  36773. const int index = pos.getIndexInLine();
  36774. textInsideOriginalLine = firstLine->line.substring (0, index)
  36775. + textInsideOriginalLine
  36776. + firstLine->line.substring (index);
  36777. }
  36778. maximumLineLength = -1;
  36779. Array <CodeDocumentLine*> newLines;
  36780. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36781. jassert (newLines.size() > 0);
  36782. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36783. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36784. lines.set (firstAffectedLine, newFirstLine);
  36785. if (newLines.size() > 1)
  36786. {
  36787. for (int i = 1; i < newLines.size(); ++i)
  36788. {
  36789. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36790. lines.insert (firstAffectedLine + i, l);
  36791. }
  36792. lastAffectedLine = lines.size();
  36793. }
  36794. int i, lineStart = newFirstLine->lineStartInFile;
  36795. for (i = firstAffectedLine; i < lines.size(); ++i)
  36796. {
  36797. CodeDocumentLine* const l = lines.getUnchecked (i);
  36798. l->lineStartInFile = lineStart;
  36799. lineStart += l->lineLength;
  36800. }
  36801. checkLastLineStatus();
  36802. const int newTextLength = text.length();
  36803. for (i = 0; i < positionsToMaintain.size(); ++i)
  36804. {
  36805. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36806. if (p->getPosition() >= insertPos)
  36807. p->setPosition (p->getPosition() + newTextLength);
  36808. }
  36809. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36810. }
  36811. }
  36812. class CodeDocumentDeleteAction : public UndoableAction
  36813. {
  36814. CodeDocument& owner;
  36815. int startPos, endPos;
  36816. String removedText;
  36817. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36818. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36819. public:
  36820. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36821. : owner (owner_),
  36822. startPos (startPos_),
  36823. endPos (endPos_)
  36824. {
  36825. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36826. CodeDocument::Position (&owner, endPos));
  36827. }
  36828. ~CodeDocumentDeleteAction() {}
  36829. bool perform()
  36830. {
  36831. owner.currentActionIndex++;
  36832. owner.remove (startPos, endPos, false);
  36833. return true;
  36834. }
  36835. bool undo()
  36836. {
  36837. owner.currentActionIndex--;
  36838. owner.insert (removedText, startPos, false);
  36839. return true;
  36840. }
  36841. int getSizeInUnits() { return removedText.length() + 32; }
  36842. };
  36843. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36844. {
  36845. if (endPos <= startPos)
  36846. return;
  36847. if (undoable)
  36848. {
  36849. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36850. }
  36851. else
  36852. {
  36853. Position startPosition (this, startPos);
  36854. Position endPosition (this, endPos);
  36855. maximumLineLength = -1;
  36856. const int firstAffectedLine = startPosition.getLineNumber();
  36857. const int endLine = endPosition.getLineNumber();
  36858. int lastAffectedLine = firstAffectedLine + 1;
  36859. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36860. if (firstAffectedLine == endLine)
  36861. {
  36862. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36863. + firstLine->line.substring (endPosition.getIndexInLine());
  36864. firstLine->updateLength();
  36865. }
  36866. else
  36867. {
  36868. lastAffectedLine = lines.size();
  36869. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36870. jassert (lastLine != 0);
  36871. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36872. + lastLine->line.substring (endPosition.getIndexInLine());
  36873. firstLine->updateLength();
  36874. int numLinesToRemove = endLine - firstAffectedLine;
  36875. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36876. }
  36877. int i;
  36878. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36879. {
  36880. CodeDocumentLine* const l = lines.getUnchecked (i);
  36881. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36882. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36883. }
  36884. checkLastLineStatus();
  36885. const int totalChars = getNumCharacters();
  36886. for (i = 0; i < positionsToMaintain.size(); ++i)
  36887. {
  36888. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36889. if (p->getPosition() > startPosition.getPosition())
  36890. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36891. if (p->getPosition() > totalChars)
  36892. p->setPosition (totalChars);
  36893. }
  36894. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36895. }
  36896. }
  36897. END_JUCE_NAMESPACE
  36898. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36899. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36900. BEGIN_JUCE_NAMESPACE
  36901. class CodeEditorComponent::CaretComponent : public Component,
  36902. public Timer
  36903. {
  36904. public:
  36905. CaretComponent (CodeEditorComponent& owner_)
  36906. : owner (owner_)
  36907. {
  36908. setAlwaysOnTop (true);
  36909. setInterceptsMouseClicks (false, false);
  36910. }
  36911. ~CaretComponent()
  36912. {
  36913. }
  36914. void paint (Graphics& g)
  36915. {
  36916. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36917. }
  36918. void timerCallback()
  36919. {
  36920. setVisible (shouldBeShown() && ! isVisible());
  36921. }
  36922. void updatePosition()
  36923. {
  36924. startTimer (400);
  36925. setVisible (shouldBeShown());
  36926. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36927. }
  36928. private:
  36929. CodeEditorComponent& owner;
  36930. CaretComponent (const CaretComponent&);
  36931. CaretComponent& operator= (const CaretComponent&);
  36932. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36933. };
  36934. class CodeEditorComponent::CodeEditorLine
  36935. {
  36936. public:
  36937. CodeEditorLine() throw()
  36938. : highlightColumnStart (0), highlightColumnEnd (0)
  36939. {
  36940. }
  36941. ~CodeEditorLine() throw()
  36942. {
  36943. }
  36944. bool update (CodeDocument& document, int lineNum,
  36945. CodeDocument::Iterator& source,
  36946. CodeTokeniser* analyser, const int spacesPerTab,
  36947. const CodeDocument::Position& selectionStart,
  36948. const CodeDocument::Position& selectionEnd)
  36949. {
  36950. Array <SyntaxToken> newTokens;
  36951. newTokens.ensureStorageAllocated (8);
  36952. if (analyser == 0)
  36953. {
  36954. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36955. }
  36956. else if (lineNum < document.getNumLines())
  36957. {
  36958. const CodeDocument::Position pos (&document, lineNum, 0);
  36959. createTokens (pos.getPosition(), pos.getLineText(),
  36960. source, analyser, newTokens);
  36961. }
  36962. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36963. int newHighlightStart = 0;
  36964. int newHighlightEnd = 0;
  36965. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36966. {
  36967. const String line (document.getLine (lineNum));
  36968. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36969. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36970. line, spacesPerTab);
  36971. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36972. line, spacesPerTab);
  36973. }
  36974. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36975. {
  36976. highlightColumnStart = newHighlightStart;
  36977. highlightColumnEnd = newHighlightEnd;
  36978. }
  36979. else
  36980. {
  36981. if (tokens.size() == newTokens.size())
  36982. {
  36983. bool allTheSame = true;
  36984. for (int i = newTokens.size(); --i >= 0;)
  36985. {
  36986. if (tokens.getReference(i) != newTokens.getReference(i))
  36987. {
  36988. allTheSame = false;
  36989. break;
  36990. }
  36991. }
  36992. if (allTheSame)
  36993. return false;
  36994. }
  36995. }
  36996. tokens.swapWithArray (newTokens);
  36997. return true;
  36998. }
  36999. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  37000. float x, const int y, const int baselineOffset, const int lineHeight,
  37001. const Colour& highlightColour) const
  37002. {
  37003. if (highlightColumnStart < highlightColumnEnd)
  37004. {
  37005. g.setColour (highlightColour);
  37006. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  37007. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  37008. }
  37009. int lastType = std::numeric_limits<int>::min();
  37010. for (int i = 0; i < tokens.size(); ++i)
  37011. {
  37012. SyntaxToken& token = tokens.getReference(i);
  37013. if (lastType != token.tokenType)
  37014. {
  37015. lastType = token.tokenType;
  37016. g.setColour (owner.getColourForTokenType (lastType));
  37017. }
  37018. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  37019. if (i < tokens.size() - 1)
  37020. {
  37021. if (token.width < 0)
  37022. token.width = font.getStringWidthFloat (token.text);
  37023. x += token.width;
  37024. }
  37025. }
  37026. }
  37027. private:
  37028. struct SyntaxToken
  37029. {
  37030. String text;
  37031. int tokenType;
  37032. float width;
  37033. SyntaxToken (const String& text_, const int type) throw()
  37034. : text (text_), tokenType (type), width (-1.0f)
  37035. {
  37036. }
  37037. bool operator!= (const SyntaxToken& other) const throw()
  37038. {
  37039. return text != other.text || tokenType != other.tokenType;
  37040. }
  37041. };
  37042. Array <SyntaxToken> tokens;
  37043. int highlightColumnStart, highlightColumnEnd;
  37044. static void createTokens (int startPosition, const String& lineText,
  37045. CodeDocument::Iterator& source,
  37046. CodeTokeniser* analyser,
  37047. Array <SyntaxToken>& newTokens)
  37048. {
  37049. CodeDocument::Iterator lastIterator (source);
  37050. const int lineLength = lineText.length();
  37051. for (;;)
  37052. {
  37053. int tokenType = analyser->readNextToken (source);
  37054. int tokenStart = lastIterator.getPosition();
  37055. int tokenEnd = source.getPosition();
  37056. if (tokenEnd <= tokenStart)
  37057. break;
  37058. tokenEnd -= startPosition;
  37059. if (tokenEnd > 0)
  37060. {
  37061. tokenStart -= startPosition;
  37062. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  37063. tokenType));
  37064. if (tokenEnd >= lineLength)
  37065. break;
  37066. }
  37067. lastIterator = source;
  37068. }
  37069. source = lastIterator;
  37070. }
  37071. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  37072. {
  37073. int x = 0;
  37074. for (int i = 0; i < tokens.size(); ++i)
  37075. {
  37076. SyntaxToken& t = tokens.getReference(i);
  37077. for (;;)
  37078. {
  37079. int tabPos = t.text.indexOfChar ('\t');
  37080. if (tabPos < 0)
  37081. break;
  37082. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  37083. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  37084. }
  37085. x += t.text.length();
  37086. }
  37087. }
  37088. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  37089. {
  37090. jassert (index <= line.length());
  37091. int col = 0;
  37092. for (int i = 0; i < index; ++i)
  37093. {
  37094. if (line[i] != '\t')
  37095. ++col;
  37096. else
  37097. col += spacesPerTab - (col % spacesPerTab);
  37098. }
  37099. return col;
  37100. }
  37101. };
  37102. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  37103. CodeTokeniser* const codeTokeniser_)
  37104. : document (document_),
  37105. firstLineOnScreen (0),
  37106. gutter (5),
  37107. spacesPerTab (4),
  37108. lineHeight (0),
  37109. linesOnScreen (0),
  37110. columnsOnScreen (0),
  37111. scrollbarThickness (16),
  37112. columnToTryToMaintain (-1),
  37113. useSpacesForTabs (false),
  37114. xOffset (0),
  37115. codeTokeniser (codeTokeniser_)
  37116. {
  37117. caretPos = CodeDocument::Position (&document_, 0, 0);
  37118. caretPos.setPositionMaintained (true);
  37119. selectionStart = CodeDocument::Position (&document_, 0, 0);
  37120. selectionStart.setPositionMaintained (true);
  37121. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  37122. selectionEnd.setPositionMaintained (true);
  37123. setOpaque (true);
  37124. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  37125. setWantsKeyboardFocus (true);
  37126. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  37127. verticalScrollBar->setSingleStepSize (1.0);
  37128. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  37129. horizontalScrollBar->setSingleStepSize (1.0);
  37130. addAndMakeVisible (caret = new CaretComponent (*this));
  37131. Font f (12.0f);
  37132. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  37133. setFont (f);
  37134. resetToDefaultColours();
  37135. verticalScrollBar->addListener (this);
  37136. horizontalScrollBar->addListener (this);
  37137. document.addListener (this);
  37138. }
  37139. CodeEditorComponent::~CodeEditorComponent()
  37140. {
  37141. document.removeListener (this);
  37142. deleteAllChildren();
  37143. }
  37144. void CodeEditorComponent::loadContent (const String& newContent)
  37145. {
  37146. clearCachedIterators (0);
  37147. document.replaceAllContent (newContent);
  37148. document.clearUndoHistory();
  37149. document.setSavePoint();
  37150. caretPos.setPosition (0);
  37151. selectionStart.setPosition (0);
  37152. selectionEnd.setPosition (0);
  37153. scrollToLine (0);
  37154. }
  37155. bool CodeEditorComponent::isTextInputActive() const
  37156. {
  37157. return true;
  37158. }
  37159. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  37160. const CodeDocument::Position& affectedTextEnd)
  37161. {
  37162. clearCachedIterators (affectedTextStart.getLineNumber());
  37163. triggerAsyncUpdate();
  37164. caret->updatePosition();
  37165. columnToTryToMaintain = -1;
  37166. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  37167. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  37168. deselectAll();
  37169. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  37170. || caretPos.getPosition() < affectedTextStart.getPosition())
  37171. moveCaretTo (affectedTextStart, false);
  37172. updateScrollBars();
  37173. }
  37174. void CodeEditorComponent::resized()
  37175. {
  37176. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  37177. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  37178. lines.clear();
  37179. rebuildLineTokens();
  37180. caret->updatePosition();
  37181. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  37182. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  37183. updateScrollBars();
  37184. }
  37185. void CodeEditorComponent::paint (Graphics& g)
  37186. {
  37187. handleUpdateNowIfNeeded();
  37188. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  37189. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  37190. g.setFont (font);
  37191. const int baselineOffset = (int) font.getAscent();
  37192. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  37193. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  37194. const Rectangle<int> clip (g.getClipBounds());
  37195. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  37196. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  37197. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37198. {
  37199. lines.getUnchecked(j)->draw (*this, g, font,
  37200. (float) (gutter - xOffset * charWidth),
  37201. lineHeight * j, baselineOffset, lineHeight,
  37202. highlightColour);
  37203. }
  37204. }
  37205. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37206. {
  37207. if (scrollbarThickness != thickness)
  37208. {
  37209. scrollbarThickness = thickness;
  37210. resized();
  37211. }
  37212. }
  37213. void CodeEditorComponent::handleAsyncUpdate()
  37214. {
  37215. rebuildLineTokens();
  37216. }
  37217. void CodeEditorComponent::rebuildLineTokens()
  37218. {
  37219. cancelPendingUpdate();
  37220. const int numNeeded = linesOnScreen + 1;
  37221. int minLineToRepaint = numNeeded;
  37222. int maxLineToRepaint = 0;
  37223. if (numNeeded != lines.size())
  37224. {
  37225. lines.clear();
  37226. for (int i = numNeeded; --i >= 0;)
  37227. lines.add (new CodeEditorLine());
  37228. minLineToRepaint = 0;
  37229. maxLineToRepaint = numNeeded;
  37230. }
  37231. jassert (numNeeded == lines.size());
  37232. CodeDocument::Iterator source (&document);
  37233. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37234. for (int i = 0; i < numNeeded; ++i)
  37235. {
  37236. CodeEditorLine* const line = lines.getUnchecked(i);
  37237. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37238. selectionStart, selectionEnd))
  37239. {
  37240. minLineToRepaint = jmin (minLineToRepaint, i);
  37241. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37242. }
  37243. }
  37244. if (minLineToRepaint <= maxLineToRepaint)
  37245. {
  37246. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37247. verticalScrollBar->getX() - gutter,
  37248. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37249. }
  37250. }
  37251. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37252. {
  37253. caretPos = newPos;
  37254. columnToTryToMaintain = -1;
  37255. if (highlighting)
  37256. {
  37257. if (dragType == notDragging)
  37258. {
  37259. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37260. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37261. dragType = draggingSelectionStart;
  37262. else
  37263. dragType = draggingSelectionEnd;
  37264. }
  37265. if (dragType == draggingSelectionStart)
  37266. {
  37267. selectionStart = caretPos;
  37268. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37269. {
  37270. const CodeDocument::Position temp (selectionStart);
  37271. selectionStart = selectionEnd;
  37272. selectionEnd = temp;
  37273. dragType = draggingSelectionEnd;
  37274. }
  37275. }
  37276. else
  37277. {
  37278. selectionEnd = caretPos;
  37279. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37280. {
  37281. const CodeDocument::Position temp (selectionStart);
  37282. selectionStart = selectionEnd;
  37283. selectionEnd = temp;
  37284. dragType = draggingSelectionStart;
  37285. }
  37286. }
  37287. triggerAsyncUpdate();
  37288. }
  37289. else
  37290. {
  37291. deselectAll();
  37292. }
  37293. caret->updatePosition();
  37294. scrollToKeepCaretOnScreen();
  37295. updateScrollBars();
  37296. }
  37297. void CodeEditorComponent::deselectAll()
  37298. {
  37299. if (selectionStart != selectionEnd)
  37300. triggerAsyncUpdate();
  37301. selectionStart = caretPos;
  37302. selectionEnd = caretPos;
  37303. }
  37304. void CodeEditorComponent::updateScrollBars()
  37305. {
  37306. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37307. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  37308. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37309. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  37310. }
  37311. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37312. {
  37313. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37314. newFirstLineOnScreen);
  37315. if (newFirstLineOnScreen != firstLineOnScreen)
  37316. {
  37317. firstLineOnScreen = newFirstLineOnScreen;
  37318. caret->updatePosition();
  37319. updateCachedIterators (firstLineOnScreen);
  37320. triggerAsyncUpdate();
  37321. }
  37322. }
  37323. void CodeEditorComponent::scrollToColumnInternal (double column)
  37324. {
  37325. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37326. if (xOffset != newOffset)
  37327. {
  37328. xOffset = newOffset;
  37329. caret->updatePosition();
  37330. repaint();
  37331. }
  37332. }
  37333. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37334. {
  37335. scrollToLineInternal (newFirstLineOnScreen);
  37336. updateScrollBars();
  37337. }
  37338. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37339. {
  37340. scrollToColumnInternal (newFirstColumnOnScreen);
  37341. updateScrollBars();
  37342. }
  37343. void CodeEditorComponent::scrollBy (int deltaLines)
  37344. {
  37345. scrollToLine (firstLineOnScreen + deltaLines);
  37346. }
  37347. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37348. {
  37349. if (caretPos.getLineNumber() < firstLineOnScreen)
  37350. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37351. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37352. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37353. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37354. if (column >= xOffset + columnsOnScreen - 1)
  37355. scrollToColumn (column + 1 - columnsOnScreen);
  37356. else if (column < xOffset)
  37357. scrollToColumn (column);
  37358. }
  37359. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37360. {
  37361. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37362. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37363. roundToInt (charWidth),
  37364. lineHeight);
  37365. }
  37366. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37367. {
  37368. const int line = y / lineHeight + firstLineOnScreen;
  37369. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37370. const int index = columnToIndex (line, column);
  37371. return CodeDocument::Position (&document, line, index);
  37372. }
  37373. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37374. {
  37375. document.deleteSection (selectionStart, selectionEnd);
  37376. if (newText.isNotEmpty())
  37377. document.insertText (caretPos, newText);
  37378. scrollToKeepCaretOnScreen();
  37379. }
  37380. void CodeEditorComponent::insertTabAtCaret()
  37381. {
  37382. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37383. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37384. {
  37385. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37386. }
  37387. if (useSpacesForTabs)
  37388. {
  37389. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37390. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37391. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37392. }
  37393. else
  37394. {
  37395. insertTextAtCaret ("\t");
  37396. }
  37397. }
  37398. void CodeEditorComponent::cut()
  37399. {
  37400. insertTextAtCaret (String::empty);
  37401. }
  37402. void CodeEditorComponent::copy()
  37403. {
  37404. newTransaction();
  37405. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37406. if (selection.isNotEmpty())
  37407. SystemClipboard::copyTextToClipboard (selection);
  37408. }
  37409. void CodeEditorComponent::copyThenCut()
  37410. {
  37411. copy();
  37412. cut();
  37413. newTransaction();
  37414. }
  37415. void CodeEditorComponent::paste()
  37416. {
  37417. newTransaction();
  37418. const String clip (SystemClipboard::getTextFromClipboard());
  37419. if (clip.isNotEmpty())
  37420. insertTextAtCaret (clip);
  37421. newTransaction();
  37422. }
  37423. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37424. {
  37425. newTransaction();
  37426. if (moveInWholeWordSteps)
  37427. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37428. else
  37429. moveCaretTo (caretPos.movedBy (-1), selecting);
  37430. }
  37431. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37432. {
  37433. newTransaction();
  37434. if (moveInWholeWordSteps)
  37435. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37436. else
  37437. moveCaretTo (caretPos.movedBy (1), selecting);
  37438. }
  37439. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37440. {
  37441. CodeDocument::Position pos (caretPos);
  37442. const int newLineNum = pos.getLineNumber() + delta;
  37443. if (columnToTryToMaintain < 0)
  37444. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37445. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37446. const int colToMaintain = columnToTryToMaintain;
  37447. moveCaretTo (pos, selecting);
  37448. columnToTryToMaintain = colToMaintain;
  37449. }
  37450. void CodeEditorComponent::cursorDown (const bool selecting)
  37451. {
  37452. newTransaction();
  37453. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37454. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37455. else
  37456. moveLineDelta (1, selecting);
  37457. }
  37458. void CodeEditorComponent::cursorUp (const bool selecting)
  37459. {
  37460. newTransaction();
  37461. if (caretPos.getLineNumber() == 0)
  37462. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37463. else
  37464. moveLineDelta (-1, selecting);
  37465. }
  37466. void CodeEditorComponent::pageDown (const bool selecting)
  37467. {
  37468. newTransaction();
  37469. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37470. moveLineDelta (linesOnScreen, selecting);
  37471. }
  37472. void CodeEditorComponent::pageUp (const bool selecting)
  37473. {
  37474. newTransaction();
  37475. scrollBy (-linesOnScreen);
  37476. moveLineDelta (-linesOnScreen, selecting);
  37477. }
  37478. void CodeEditorComponent::scrollUp()
  37479. {
  37480. newTransaction();
  37481. scrollBy (1);
  37482. if (caretPos.getLineNumber() < firstLineOnScreen)
  37483. moveLineDelta (1, false);
  37484. }
  37485. void CodeEditorComponent::scrollDown()
  37486. {
  37487. newTransaction();
  37488. scrollBy (-1);
  37489. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37490. moveLineDelta (-1, false);
  37491. }
  37492. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37493. {
  37494. newTransaction();
  37495. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37496. }
  37497. static int findFirstNonWhitespaceChar (const String& line) throw()
  37498. {
  37499. const int len = line.length();
  37500. for (int i = 0; i < len; ++i)
  37501. if (! CharacterFunctions::isWhitespace (line [i]))
  37502. return i;
  37503. return 0;
  37504. }
  37505. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37506. {
  37507. newTransaction();
  37508. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  37509. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37510. index = 0;
  37511. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37512. }
  37513. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37514. {
  37515. newTransaction();
  37516. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37517. }
  37518. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37519. {
  37520. newTransaction();
  37521. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37522. }
  37523. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37524. {
  37525. if (moveInWholeWordSteps)
  37526. {
  37527. cut(); // in case something is already highlighted
  37528. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37529. }
  37530. else
  37531. {
  37532. if (selectionStart == selectionEnd)
  37533. selectionStart.moveBy (-1);
  37534. }
  37535. cut();
  37536. }
  37537. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37538. {
  37539. if (moveInWholeWordSteps)
  37540. {
  37541. cut(); // in case something is already highlighted
  37542. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37543. }
  37544. else
  37545. {
  37546. if (selectionStart == selectionEnd)
  37547. selectionEnd.moveBy (1);
  37548. else
  37549. newTransaction();
  37550. }
  37551. cut();
  37552. }
  37553. void CodeEditorComponent::selectAll()
  37554. {
  37555. newTransaction();
  37556. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37557. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37558. }
  37559. void CodeEditorComponent::undo()
  37560. {
  37561. document.undo();
  37562. scrollToKeepCaretOnScreen();
  37563. }
  37564. void CodeEditorComponent::redo()
  37565. {
  37566. document.redo();
  37567. scrollToKeepCaretOnScreen();
  37568. }
  37569. void CodeEditorComponent::newTransaction()
  37570. {
  37571. document.newTransaction();
  37572. startTimer (600);
  37573. }
  37574. void CodeEditorComponent::timerCallback()
  37575. {
  37576. newTransaction();
  37577. }
  37578. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37579. {
  37580. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37581. }
  37582. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37583. {
  37584. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37585. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37586. }
  37587. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37588. {
  37589. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37590. CodeDocument::Position (&document, range.getEnd()));
  37591. }
  37592. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37593. {
  37594. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37595. const bool shiftDown = key.getModifiers().isShiftDown();
  37596. if (key.isKeyCode (KeyPress::leftKey))
  37597. {
  37598. cursorLeft (moveInWholeWordSteps, shiftDown);
  37599. }
  37600. else if (key.isKeyCode (KeyPress::rightKey))
  37601. {
  37602. cursorRight (moveInWholeWordSteps, shiftDown);
  37603. }
  37604. else if (key.isKeyCode (KeyPress::upKey))
  37605. {
  37606. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37607. scrollDown();
  37608. #if JUCE_MAC
  37609. else if (key.getModifiers().isCommandDown())
  37610. goToStartOfDocument (shiftDown);
  37611. #endif
  37612. else
  37613. cursorUp (shiftDown);
  37614. }
  37615. else if (key.isKeyCode (KeyPress::downKey))
  37616. {
  37617. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37618. scrollUp();
  37619. #if JUCE_MAC
  37620. else if (key.getModifiers().isCommandDown())
  37621. goToEndOfDocument (shiftDown);
  37622. #endif
  37623. else
  37624. cursorDown (shiftDown);
  37625. }
  37626. else if (key.isKeyCode (KeyPress::pageDownKey))
  37627. {
  37628. pageDown (shiftDown);
  37629. }
  37630. else if (key.isKeyCode (KeyPress::pageUpKey))
  37631. {
  37632. pageUp (shiftDown);
  37633. }
  37634. else if (key.isKeyCode (KeyPress::homeKey))
  37635. {
  37636. if (moveInWholeWordSteps)
  37637. goToStartOfDocument (shiftDown);
  37638. else
  37639. goToStartOfLine (shiftDown);
  37640. }
  37641. else if (key.isKeyCode (KeyPress::endKey))
  37642. {
  37643. if (moveInWholeWordSteps)
  37644. goToEndOfDocument (shiftDown);
  37645. else
  37646. goToEndOfLine (shiftDown);
  37647. }
  37648. else if (key.isKeyCode (KeyPress::backspaceKey))
  37649. {
  37650. backspace (moveInWholeWordSteps);
  37651. }
  37652. else if (key.isKeyCode (KeyPress::deleteKey))
  37653. {
  37654. deleteForward (moveInWholeWordSteps);
  37655. }
  37656. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37657. {
  37658. copy();
  37659. }
  37660. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37661. {
  37662. copyThenCut();
  37663. }
  37664. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37665. {
  37666. paste();
  37667. }
  37668. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37669. {
  37670. undo();
  37671. }
  37672. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37673. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37674. {
  37675. redo();
  37676. }
  37677. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37678. {
  37679. selectAll();
  37680. }
  37681. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37682. {
  37683. insertTabAtCaret();
  37684. }
  37685. else if (key == KeyPress::returnKey)
  37686. {
  37687. newTransaction();
  37688. insertTextAtCaret (document.getNewLineCharacters());
  37689. }
  37690. else if (key.isKeyCode (KeyPress::escapeKey))
  37691. {
  37692. newTransaction();
  37693. }
  37694. else if (key.getTextCharacter() >= ' ')
  37695. {
  37696. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37697. }
  37698. else
  37699. {
  37700. return false;
  37701. }
  37702. return true;
  37703. }
  37704. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37705. {
  37706. newTransaction();
  37707. dragType = notDragging;
  37708. if (! e.mods.isPopupMenu())
  37709. {
  37710. beginDragAutoRepeat (100);
  37711. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37712. }
  37713. else
  37714. {
  37715. /*PopupMenu m;
  37716. addPopupMenuItems (m, &e);
  37717. const int result = m.show();
  37718. if (result != 0)
  37719. performPopupMenuAction (result);
  37720. */
  37721. }
  37722. }
  37723. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37724. {
  37725. if (! e.mods.isPopupMenu())
  37726. moveCaretTo (getPositionAt (e.x, e.y), true);
  37727. }
  37728. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37729. {
  37730. newTransaction();
  37731. beginDragAutoRepeat (0);
  37732. dragType = notDragging;
  37733. }
  37734. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37735. {
  37736. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37737. CodeDocument::Position tokenEnd (tokenStart);
  37738. if (e.getNumberOfClicks() > 2)
  37739. {
  37740. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37741. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37742. }
  37743. else
  37744. {
  37745. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37746. tokenEnd.moveBy (1);
  37747. tokenStart = tokenEnd;
  37748. while (tokenStart.getIndexInLine() > 0
  37749. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37750. tokenStart.moveBy (-1);
  37751. }
  37752. moveCaretTo (tokenEnd, false);
  37753. moveCaretTo (tokenStart, true);
  37754. }
  37755. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37756. {
  37757. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  37758. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  37759. {
  37760. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  37761. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  37762. }
  37763. else
  37764. {
  37765. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37766. }
  37767. }
  37768. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37769. {
  37770. if (scrollBarThatHasMoved == verticalScrollBar)
  37771. scrollToLineInternal ((int) newRangeStart);
  37772. else
  37773. scrollToColumnInternal (newRangeStart);
  37774. }
  37775. void CodeEditorComponent::focusGained (FocusChangeType)
  37776. {
  37777. caret->updatePosition();
  37778. }
  37779. void CodeEditorComponent::focusLost (FocusChangeType)
  37780. {
  37781. caret->updatePosition();
  37782. }
  37783. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37784. {
  37785. useSpacesForTabs = insertSpaces;
  37786. if (spacesPerTab != numSpaces)
  37787. {
  37788. spacesPerTab = numSpaces;
  37789. triggerAsyncUpdate();
  37790. }
  37791. }
  37792. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37793. {
  37794. const String line (document.getLine (lineNum));
  37795. jassert (index <= line.length());
  37796. int col = 0;
  37797. for (int i = 0; i < index; ++i)
  37798. {
  37799. if (line[i] != '\t')
  37800. ++col;
  37801. else
  37802. col += getTabSize() - (col % getTabSize());
  37803. }
  37804. return col;
  37805. }
  37806. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37807. {
  37808. const String line (document.getLine (lineNum));
  37809. const int lineLength = line.length();
  37810. int i, col = 0;
  37811. for (i = 0; i < lineLength; ++i)
  37812. {
  37813. if (line[i] != '\t')
  37814. ++col;
  37815. else
  37816. col += getTabSize() - (col % getTabSize());
  37817. if (col > column)
  37818. break;
  37819. }
  37820. return i;
  37821. }
  37822. void CodeEditorComponent::setFont (const Font& newFont)
  37823. {
  37824. font = newFont;
  37825. charWidth = font.getStringWidthFloat ("0");
  37826. lineHeight = roundToInt (font.getHeight());
  37827. resized();
  37828. }
  37829. void CodeEditorComponent::resetToDefaultColours()
  37830. {
  37831. coloursForTokenCategories.clear();
  37832. if (codeTokeniser != 0)
  37833. {
  37834. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37835. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37836. }
  37837. }
  37838. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37839. {
  37840. jassert (tokenType < 256);
  37841. while (coloursForTokenCategories.size() < tokenType)
  37842. coloursForTokenCategories.add (Colours::black);
  37843. coloursForTokenCategories.set (tokenType, colour);
  37844. repaint();
  37845. }
  37846. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37847. {
  37848. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37849. return findColour (CodeEditorComponent::defaultTextColourId);
  37850. return coloursForTokenCategories.getReference (tokenType);
  37851. }
  37852. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37853. {
  37854. int i;
  37855. for (i = cachedIterators.size(); --i >= 0;)
  37856. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37857. break;
  37858. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37859. }
  37860. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37861. {
  37862. const int maxNumCachedPositions = 5000;
  37863. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37864. if (cachedIterators.size() == 0)
  37865. cachedIterators.add (new CodeDocument::Iterator (&document));
  37866. if (codeTokeniser == 0)
  37867. return;
  37868. for (;;)
  37869. {
  37870. CodeDocument::Iterator* last = cachedIterators.getLast();
  37871. if (last->getLine() >= maxLineNum)
  37872. break;
  37873. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37874. cachedIterators.add (t);
  37875. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37876. for (;;)
  37877. {
  37878. codeTokeniser->readNextToken (*t);
  37879. if (t->getLine() >= targetLine)
  37880. break;
  37881. if (t->isEOF())
  37882. return;
  37883. }
  37884. }
  37885. }
  37886. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37887. {
  37888. if (codeTokeniser == 0)
  37889. return;
  37890. for (int i = cachedIterators.size(); --i >= 0;)
  37891. {
  37892. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37893. if (t->getPosition() <= position)
  37894. {
  37895. source = *t;
  37896. break;
  37897. }
  37898. }
  37899. while (source.getPosition() < position)
  37900. {
  37901. const CodeDocument::Iterator original (source);
  37902. codeTokeniser->readNextToken (source);
  37903. if (source.getPosition() > position || source.isEOF())
  37904. {
  37905. source = original;
  37906. break;
  37907. }
  37908. }
  37909. }
  37910. END_JUCE_NAMESPACE
  37911. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37912. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37913. BEGIN_JUCE_NAMESPACE
  37914. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37915. {
  37916. }
  37917. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37918. {
  37919. }
  37920. namespace CppTokeniser
  37921. {
  37922. static bool isIdentifierStart (const juce_wchar c) throw()
  37923. {
  37924. return CharacterFunctions::isLetter (c)
  37925. || c == '_' || c == '@';
  37926. }
  37927. static bool isIdentifierBody (const juce_wchar c) throw()
  37928. {
  37929. return CharacterFunctions::isLetterOrDigit (c)
  37930. || c == '_' || c == '@';
  37931. }
  37932. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37933. {
  37934. static const juce_wchar* const keywords2Char[] =
  37935. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37936. static const juce_wchar* const keywords3Char[] =
  37937. { 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 };
  37938. static const juce_wchar* const keywords4Char[] =
  37939. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37940. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37941. static const juce_wchar* const keywords5Char[] =
  37942. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37943. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37944. static const juce_wchar* const keywords6Char[] =
  37945. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37946. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37947. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37948. static const juce_wchar* const keywordsOther[] =
  37949. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37950. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37951. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37952. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37953. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37954. const juce_wchar* const* k;
  37955. switch (tokenLength)
  37956. {
  37957. case 2: k = keywords2Char; break;
  37958. case 3: k = keywords3Char; break;
  37959. case 4: k = keywords4Char; break;
  37960. case 5: k = keywords5Char; break;
  37961. case 6: k = keywords6Char; break;
  37962. default:
  37963. if (tokenLength < 2 || tokenLength > 16)
  37964. return false;
  37965. k = keywordsOther;
  37966. break;
  37967. }
  37968. int i = 0;
  37969. while (k[i] != 0)
  37970. {
  37971. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37972. return true;
  37973. ++i;
  37974. }
  37975. return false;
  37976. }
  37977. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37978. {
  37979. int tokenLength = 0;
  37980. juce_wchar possibleIdentifier [19];
  37981. while (isIdentifierBody (source.peekNextChar()))
  37982. {
  37983. const juce_wchar c = source.nextChar();
  37984. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37985. possibleIdentifier [tokenLength] = c;
  37986. ++tokenLength;
  37987. }
  37988. if (tokenLength > 1 && tokenLength <= 16)
  37989. {
  37990. possibleIdentifier [tokenLength] = 0;
  37991. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37992. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37993. }
  37994. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37995. }
  37996. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37997. {
  37998. const juce_wchar c = source.peekNextChar();
  37999. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  38000. source.skip();
  38001. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  38002. return false;
  38003. return true;
  38004. }
  38005. static bool isHexDigit (const juce_wchar c) throw()
  38006. {
  38007. return (c >= '0' && c <= '9')
  38008. || (c >= 'a' && c <= 'f')
  38009. || (c >= 'A' && c <= 'F');
  38010. }
  38011. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  38012. {
  38013. if (source.nextChar() != '0')
  38014. return false;
  38015. juce_wchar c = source.nextChar();
  38016. if (c != 'x' && c != 'X')
  38017. return false;
  38018. int numDigits = 0;
  38019. while (isHexDigit (source.peekNextChar()))
  38020. {
  38021. ++numDigits;
  38022. source.skip();
  38023. }
  38024. if (numDigits == 0)
  38025. return false;
  38026. return skipNumberSuffix (source);
  38027. }
  38028. static bool isOctalDigit (const juce_wchar c) throw()
  38029. {
  38030. return c >= '0' && c <= '7';
  38031. }
  38032. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  38033. {
  38034. if (source.nextChar() != '0')
  38035. return false;
  38036. if (! isOctalDigit (source.nextChar()))
  38037. return false;
  38038. while (isOctalDigit (source.peekNextChar()))
  38039. source.skip();
  38040. return skipNumberSuffix (source);
  38041. }
  38042. static bool isDecimalDigit (const juce_wchar c) throw()
  38043. {
  38044. return c >= '0' && c <= '9';
  38045. }
  38046. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  38047. {
  38048. int numChars = 0;
  38049. while (isDecimalDigit (source.peekNextChar()))
  38050. {
  38051. ++numChars;
  38052. source.skip();
  38053. }
  38054. if (numChars == 0)
  38055. return false;
  38056. return skipNumberSuffix (source);
  38057. }
  38058. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  38059. {
  38060. int numDigits = 0;
  38061. while (isDecimalDigit (source.peekNextChar()))
  38062. {
  38063. source.skip();
  38064. ++numDigits;
  38065. }
  38066. const bool hasPoint = (source.peekNextChar() == '.');
  38067. if (hasPoint)
  38068. {
  38069. source.skip();
  38070. while (isDecimalDigit (source.peekNextChar()))
  38071. {
  38072. source.skip();
  38073. ++numDigits;
  38074. }
  38075. }
  38076. if (numDigits == 0)
  38077. return false;
  38078. juce_wchar c = source.peekNextChar();
  38079. const bool hasExponent = (c == 'e' || c == 'E');
  38080. if (hasExponent)
  38081. {
  38082. source.skip();
  38083. c = source.peekNextChar();
  38084. if (c == '+' || c == '-')
  38085. source.skip();
  38086. int numExpDigits = 0;
  38087. while (isDecimalDigit (source.peekNextChar()))
  38088. {
  38089. source.skip();
  38090. ++numExpDigits;
  38091. }
  38092. if (numExpDigits == 0)
  38093. return false;
  38094. }
  38095. c = source.peekNextChar();
  38096. if (c == 'f' || c == 'F')
  38097. source.skip();
  38098. else if (! (hasExponent || hasPoint))
  38099. return false;
  38100. return true;
  38101. }
  38102. static int parseNumber (CodeDocument::Iterator& source)
  38103. {
  38104. const CodeDocument::Iterator original (source);
  38105. if (parseFloatLiteral (source))
  38106. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  38107. source = original;
  38108. if (parseHexLiteral (source))
  38109. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  38110. source = original;
  38111. if (parseOctalLiteral (source))
  38112. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  38113. source = original;
  38114. if (parseDecimalLiteral (source))
  38115. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  38116. source = original;
  38117. source.skip();
  38118. return CPlusPlusCodeTokeniser::tokenType_error;
  38119. }
  38120. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  38121. {
  38122. const juce_wchar quote = source.nextChar();
  38123. for (;;)
  38124. {
  38125. const juce_wchar c = source.nextChar();
  38126. if (c == quote || c == 0)
  38127. break;
  38128. if (c == '\\')
  38129. source.skip();
  38130. }
  38131. }
  38132. static void skipComment (CodeDocument::Iterator& source) throw()
  38133. {
  38134. bool lastWasStar = false;
  38135. for (;;)
  38136. {
  38137. const juce_wchar c = source.nextChar();
  38138. if (c == 0 || (c == '/' && lastWasStar))
  38139. break;
  38140. lastWasStar = (c == '*');
  38141. }
  38142. }
  38143. }
  38144. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  38145. {
  38146. int result = tokenType_error;
  38147. source.skipWhitespace();
  38148. juce_wchar firstChar = source.peekNextChar();
  38149. switch (firstChar)
  38150. {
  38151. case 0:
  38152. source.skip();
  38153. break;
  38154. case '0':
  38155. case '1':
  38156. case '2':
  38157. case '3':
  38158. case '4':
  38159. case '5':
  38160. case '6':
  38161. case '7':
  38162. case '8':
  38163. case '9':
  38164. result = CppTokeniser::parseNumber (source);
  38165. break;
  38166. case '.':
  38167. result = CppTokeniser::parseNumber (source);
  38168. if (result == tokenType_error)
  38169. result = tokenType_punctuation;
  38170. break;
  38171. case ',':
  38172. case ';':
  38173. case ':':
  38174. source.skip();
  38175. result = tokenType_punctuation;
  38176. break;
  38177. case '(':
  38178. case ')':
  38179. case '{':
  38180. case '}':
  38181. case '[':
  38182. case ']':
  38183. source.skip();
  38184. result = tokenType_bracket;
  38185. break;
  38186. case '"':
  38187. case '\'':
  38188. CppTokeniser::skipQuotedString (source);
  38189. result = tokenType_stringLiteral;
  38190. break;
  38191. case '+':
  38192. result = tokenType_operator;
  38193. source.skip();
  38194. if (source.peekNextChar() == '+')
  38195. source.skip();
  38196. else if (source.peekNextChar() == '=')
  38197. source.skip();
  38198. break;
  38199. case '-':
  38200. source.skip();
  38201. result = CppTokeniser::parseNumber (source);
  38202. if (result == tokenType_error)
  38203. {
  38204. result = tokenType_operator;
  38205. if (source.peekNextChar() == '-')
  38206. source.skip();
  38207. else if (source.peekNextChar() == '=')
  38208. source.skip();
  38209. }
  38210. break;
  38211. case '*':
  38212. case '%':
  38213. case '=':
  38214. case '!':
  38215. result = tokenType_operator;
  38216. source.skip();
  38217. if (source.peekNextChar() == '=')
  38218. source.skip();
  38219. break;
  38220. case '/':
  38221. result = tokenType_operator;
  38222. source.skip();
  38223. if (source.peekNextChar() == '=')
  38224. {
  38225. source.skip();
  38226. }
  38227. else if (source.peekNextChar() == '/')
  38228. {
  38229. result = tokenType_comment;
  38230. source.skipToEndOfLine();
  38231. }
  38232. else if (source.peekNextChar() == '*')
  38233. {
  38234. source.skip();
  38235. result = tokenType_comment;
  38236. CppTokeniser::skipComment (source);
  38237. }
  38238. break;
  38239. case '?':
  38240. case '~':
  38241. source.skip();
  38242. result = tokenType_operator;
  38243. break;
  38244. case '<':
  38245. source.skip();
  38246. result = tokenType_operator;
  38247. if (source.peekNextChar() == '=')
  38248. {
  38249. source.skip();
  38250. }
  38251. else if (source.peekNextChar() == '<')
  38252. {
  38253. source.skip();
  38254. if (source.peekNextChar() == '=')
  38255. source.skip();
  38256. }
  38257. break;
  38258. case '>':
  38259. source.skip();
  38260. result = tokenType_operator;
  38261. if (source.peekNextChar() == '=')
  38262. {
  38263. source.skip();
  38264. }
  38265. else if (source.peekNextChar() == '<')
  38266. {
  38267. source.skip();
  38268. if (source.peekNextChar() == '=')
  38269. source.skip();
  38270. }
  38271. break;
  38272. case '|':
  38273. source.skip();
  38274. result = tokenType_operator;
  38275. if (source.peekNextChar() == '=')
  38276. {
  38277. source.skip();
  38278. }
  38279. else if (source.peekNextChar() == '|')
  38280. {
  38281. source.skip();
  38282. if (source.peekNextChar() == '=')
  38283. source.skip();
  38284. }
  38285. break;
  38286. case '&':
  38287. source.skip();
  38288. result = tokenType_operator;
  38289. if (source.peekNextChar() == '=')
  38290. {
  38291. source.skip();
  38292. }
  38293. else if (source.peekNextChar() == '&')
  38294. {
  38295. source.skip();
  38296. if (source.peekNextChar() == '=')
  38297. source.skip();
  38298. }
  38299. break;
  38300. case '^':
  38301. source.skip();
  38302. result = tokenType_operator;
  38303. if (source.peekNextChar() == '=')
  38304. {
  38305. source.skip();
  38306. }
  38307. else if (source.peekNextChar() == '^')
  38308. {
  38309. source.skip();
  38310. if (source.peekNextChar() == '=')
  38311. source.skip();
  38312. }
  38313. break;
  38314. case '#':
  38315. result = tokenType_preprocessor;
  38316. source.skipToEndOfLine();
  38317. break;
  38318. default:
  38319. if (CppTokeniser::isIdentifierStart (firstChar))
  38320. result = CppTokeniser::parseIdentifier (source);
  38321. else
  38322. source.skip();
  38323. break;
  38324. }
  38325. return result;
  38326. }
  38327. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38328. {
  38329. const char* const types[] =
  38330. {
  38331. "Error",
  38332. "Comment",
  38333. "C++ keyword",
  38334. "Identifier",
  38335. "Integer literal",
  38336. "Float literal",
  38337. "String literal",
  38338. "Operator",
  38339. "Bracket",
  38340. "Punctuation",
  38341. "Preprocessor line",
  38342. 0
  38343. };
  38344. return StringArray (types);
  38345. }
  38346. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38347. {
  38348. const uint32 colours[] =
  38349. {
  38350. 0xffcc0000, // error
  38351. 0xff00aa00, // comment
  38352. 0xff0000cc, // keyword
  38353. 0xff000000, // identifier
  38354. 0xff880000, // int literal
  38355. 0xff885500, // float literal
  38356. 0xff990099, // string literal
  38357. 0xff225500, // operator
  38358. 0xff000055, // bracket
  38359. 0xff004400, // punctuation
  38360. 0xff660000 // preprocessor
  38361. };
  38362. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38363. return Colour (colours [tokenType]);
  38364. return Colours::black;
  38365. }
  38366. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38367. {
  38368. return CppTokeniser::isReservedKeyword (token, token.length());
  38369. }
  38370. END_JUCE_NAMESPACE
  38371. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38372. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38373. BEGIN_JUCE_NAMESPACE
  38374. ComboBox::ComboBox (const String& name)
  38375. : Component (name),
  38376. lastCurrentId (0),
  38377. isButtonDown (false),
  38378. separatorPending (false),
  38379. menuActive (false),
  38380. label (0)
  38381. {
  38382. noChoicesMessage = TRANS("(no choices)");
  38383. setRepaintsOnMouseActivity (true);
  38384. lookAndFeelChanged();
  38385. currentId.addListener (this);
  38386. }
  38387. ComboBox::~ComboBox()
  38388. {
  38389. currentId.removeListener (this);
  38390. if (menuActive)
  38391. PopupMenu::dismissAllActiveMenus();
  38392. label = 0;
  38393. deleteAllChildren();
  38394. }
  38395. void ComboBox::setEditableText (const bool isEditable)
  38396. {
  38397. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38398. {
  38399. label->setEditable (isEditable, isEditable, false);
  38400. setWantsKeyboardFocus (! isEditable);
  38401. resized();
  38402. }
  38403. }
  38404. bool ComboBox::isTextEditable() const throw()
  38405. {
  38406. return label->isEditable();
  38407. }
  38408. void ComboBox::setJustificationType (const Justification& justification)
  38409. {
  38410. label->setJustificationType (justification);
  38411. }
  38412. const Justification ComboBox::getJustificationType() const throw()
  38413. {
  38414. return label->getJustificationType();
  38415. }
  38416. void ComboBox::setTooltip (const String& newTooltip)
  38417. {
  38418. SettableTooltipClient::setTooltip (newTooltip);
  38419. label->setTooltip (newTooltip);
  38420. }
  38421. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38422. {
  38423. // you can't add empty strings to the list..
  38424. jassert (newItemText.isNotEmpty());
  38425. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38426. jassert (newItemId != 0);
  38427. // you shouldn't use duplicate item IDs!
  38428. jassert (getItemForId (newItemId) == 0);
  38429. if (newItemText.isNotEmpty() && newItemId != 0)
  38430. {
  38431. if (separatorPending)
  38432. {
  38433. separatorPending = false;
  38434. ItemInfo* const item = new ItemInfo();
  38435. item->itemId = 0;
  38436. item->isEnabled = false;
  38437. item->isHeading = false;
  38438. items.add (item);
  38439. }
  38440. ItemInfo* const item = new ItemInfo();
  38441. item->name = newItemText;
  38442. item->itemId = newItemId;
  38443. item->isEnabled = true;
  38444. item->isHeading = false;
  38445. items.add (item);
  38446. }
  38447. }
  38448. void ComboBox::addSeparator()
  38449. {
  38450. separatorPending = (items.size() > 0);
  38451. }
  38452. void ComboBox::addSectionHeading (const String& headingName)
  38453. {
  38454. // you can't add empty strings to the list..
  38455. jassert (headingName.isNotEmpty());
  38456. if (headingName.isNotEmpty())
  38457. {
  38458. if (separatorPending)
  38459. {
  38460. separatorPending = false;
  38461. ItemInfo* const item = new ItemInfo();
  38462. item->itemId = 0;
  38463. item->isEnabled = false;
  38464. item->isHeading = false;
  38465. items.add (item);
  38466. }
  38467. ItemInfo* const item = new ItemInfo();
  38468. item->name = headingName;
  38469. item->itemId = 0;
  38470. item->isEnabled = true;
  38471. item->isHeading = true;
  38472. items.add (item);
  38473. }
  38474. }
  38475. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38476. {
  38477. ItemInfo* const item = getItemForId (itemId);
  38478. if (item != 0)
  38479. item->isEnabled = shouldBeEnabled;
  38480. }
  38481. void ComboBox::changeItemText (const int itemId, const String& newText)
  38482. {
  38483. ItemInfo* const item = getItemForId (itemId);
  38484. jassert (item != 0);
  38485. if (item != 0)
  38486. item->name = newText;
  38487. }
  38488. void ComboBox::clear (const bool dontSendChangeMessage)
  38489. {
  38490. items.clear();
  38491. separatorPending = false;
  38492. if (! label->isEditable())
  38493. setSelectedItemIndex (-1, dontSendChangeMessage);
  38494. }
  38495. bool ComboBox::ItemInfo::isSeparator() const throw()
  38496. {
  38497. return name.isEmpty();
  38498. }
  38499. bool ComboBox::ItemInfo::isRealItem() const throw()
  38500. {
  38501. return ! (isHeading || name.isEmpty());
  38502. }
  38503. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38504. {
  38505. if (itemId != 0)
  38506. {
  38507. for (int i = items.size(); --i >= 0;)
  38508. if (items.getUnchecked(i)->itemId == itemId)
  38509. return items.getUnchecked(i);
  38510. }
  38511. return 0;
  38512. }
  38513. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38514. {
  38515. int n = 0;
  38516. for (int i = 0; i < items.size(); ++i)
  38517. {
  38518. ItemInfo* const item = items.getUnchecked(i);
  38519. if (item->isRealItem())
  38520. if (n++ == index)
  38521. return item;
  38522. }
  38523. return 0;
  38524. }
  38525. int ComboBox::getNumItems() const throw()
  38526. {
  38527. int n = 0;
  38528. for (int i = items.size(); --i >= 0;)
  38529. if (items.getUnchecked(i)->isRealItem())
  38530. ++n;
  38531. return n;
  38532. }
  38533. const String ComboBox::getItemText (const int index) const
  38534. {
  38535. const ItemInfo* const item = getItemForIndex (index);
  38536. if (item != 0)
  38537. return item->name;
  38538. return String::empty;
  38539. }
  38540. int ComboBox::getItemId (const int index) const throw()
  38541. {
  38542. const ItemInfo* const item = getItemForIndex (index);
  38543. return (item != 0) ? item->itemId : 0;
  38544. }
  38545. int ComboBox::indexOfItemId (const int itemId) const throw()
  38546. {
  38547. int n = 0;
  38548. for (int i = 0; i < items.size(); ++i)
  38549. {
  38550. const ItemInfo* const item = items.getUnchecked(i);
  38551. if (item->isRealItem())
  38552. {
  38553. if (item->itemId == itemId)
  38554. return n;
  38555. ++n;
  38556. }
  38557. }
  38558. return -1;
  38559. }
  38560. int ComboBox::getSelectedItemIndex() const
  38561. {
  38562. int index = indexOfItemId (currentId.getValue());
  38563. if (getText() != getItemText (index))
  38564. index = -1;
  38565. return index;
  38566. }
  38567. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38568. {
  38569. setSelectedId (getItemId (index), dontSendChangeMessage);
  38570. }
  38571. int ComboBox::getSelectedId() const throw()
  38572. {
  38573. const ItemInfo* const item = getItemForId (currentId.getValue());
  38574. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38575. }
  38576. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38577. {
  38578. const ItemInfo* const item = getItemForId (newItemId);
  38579. const String newItemText (item != 0 ? item->name : String::empty);
  38580. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38581. {
  38582. if (! dontSendChangeMessage)
  38583. triggerAsyncUpdate();
  38584. label->setText (newItemText, false);
  38585. lastCurrentId = newItemId;
  38586. currentId = newItemId;
  38587. repaint(); // for the benefit of the 'none selected' text
  38588. }
  38589. }
  38590. void ComboBox::valueChanged (Value&)
  38591. {
  38592. if (lastCurrentId != (int) currentId.getValue())
  38593. setSelectedId (currentId.getValue(), false);
  38594. }
  38595. const String ComboBox::getText() const
  38596. {
  38597. return label->getText();
  38598. }
  38599. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38600. {
  38601. for (int i = items.size(); --i >= 0;)
  38602. {
  38603. const ItemInfo* const item = items.getUnchecked(i);
  38604. if (item->isRealItem()
  38605. && item->name == newText)
  38606. {
  38607. setSelectedId (item->itemId, dontSendChangeMessage);
  38608. return;
  38609. }
  38610. }
  38611. lastCurrentId = 0;
  38612. currentId = 0;
  38613. if (label->getText() != newText)
  38614. {
  38615. label->setText (newText, false);
  38616. if (! dontSendChangeMessage)
  38617. triggerAsyncUpdate();
  38618. }
  38619. repaint();
  38620. }
  38621. void ComboBox::showEditor()
  38622. {
  38623. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38624. label->showEditor();
  38625. }
  38626. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38627. {
  38628. if (textWhenNothingSelected != newMessage)
  38629. {
  38630. textWhenNothingSelected = newMessage;
  38631. repaint();
  38632. }
  38633. }
  38634. const String ComboBox::getTextWhenNothingSelected() const
  38635. {
  38636. return textWhenNothingSelected;
  38637. }
  38638. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38639. {
  38640. noChoicesMessage = newMessage;
  38641. }
  38642. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38643. {
  38644. return noChoicesMessage;
  38645. }
  38646. void ComboBox::paint (Graphics& g)
  38647. {
  38648. getLookAndFeel().drawComboBox (g,
  38649. getWidth(),
  38650. getHeight(),
  38651. isButtonDown,
  38652. label->getRight(),
  38653. 0,
  38654. getWidth() - label->getRight(),
  38655. getHeight(),
  38656. *this);
  38657. if (textWhenNothingSelected.isNotEmpty()
  38658. && label->getText().isEmpty()
  38659. && ! label->isBeingEdited())
  38660. {
  38661. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38662. g.setFont (label->getFont());
  38663. g.drawFittedText (textWhenNothingSelected,
  38664. label->getX() + 2, label->getY() + 1,
  38665. label->getWidth() - 4, label->getHeight() - 2,
  38666. label->getJustificationType(),
  38667. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38668. }
  38669. }
  38670. void ComboBox::resized()
  38671. {
  38672. if (getHeight() > 0 && getWidth() > 0)
  38673. getLookAndFeel().positionComboBoxText (*this, *label);
  38674. }
  38675. void ComboBox::enablementChanged()
  38676. {
  38677. repaint();
  38678. }
  38679. void ComboBox::lookAndFeelChanged()
  38680. {
  38681. repaint();
  38682. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38683. if (label != 0)
  38684. {
  38685. newLabel->setEditable (label->isEditable());
  38686. newLabel->setJustificationType (label->getJustificationType());
  38687. newLabel->setTooltip (label->getTooltip());
  38688. newLabel->setText (label->getText(), false);
  38689. }
  38690. label = newLabel;
  38691. addAndMakeVisible (newLabel);
  38692. newLabel->addListener (this);
  38693. newLabel->addMouseListener (this, false);
  38694. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38695. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38696. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38697. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38698. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38699. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38700. resized();
  38701. }
  38702. void ComboBox::colourChanged()
  38703. {
  38704. lookAndFeelChanged();
  38705. }
  38706. bool ComboBox::keyPressed (const KeyPress& key)
  38707. {
  38708. bool used = false;
  38709. if (key.isKeyCode (KeyPress::upKey)
  38710. || key.isKeyCode (KeyPress::leftKey))
  38711. {
  38712. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38713. used = true;
  38714. }
  38715. else if (key.isKeyCode (KeyPress::downKey)
  38716. || key.isKeyCode (KeyPress::rightKey))
  38717. {
  38718. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38719. used = true;
  38720. }
  38721. else if (key.isKeyCode (KeyPress::returnKey))
  38722. {
  38723. showPopup();
  38724. used = true;
  38725. }
  38726. return used;
  38727. }
  38728. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38729. {
  38730. // only forward key events that aren't used by this component
  38731. return isKeyDown
  38732. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38733. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38734. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38735. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38736. }
  38737. void ComboBox::focusGained (FocusChangeType)
  38738. {
  38739. repaint();
  38740. }
  38741. void ComboBox::focusLost (FocusChangeType)
  38742. {
  38743. repaint();
  38744. }
  38745. void ComboBox::labelTextChanged (Label*)
  38746. {
  38747. triggerAsyncUpdate();
  38748. }
  38749. class ComboBox::Callback : public ModalComponentManager::Callback
  38750. {
  38751. public:
  38752. Callback (ComboBox* const box_)
  38753. : box (box_)
  38754. {
  38755. }
  38756. void modalStateFinished (int returnValue)
  38757. {
  38758. if (box != 0)
  38759. {
  38760. box->menuActive = false;
  38761. if (returnValue != 0)
  38762. box->setSelectedId (returnValue);
  38763. }
  38764. }
  38765. private:
  38766. Component::SafePointer<ComboBox> box;
  38767. Callback (const Callback&);
  38768. Callback& operator= (const Callback&);
  38769. };
  38770. void ComboBox::showPopup()
  38771. {
  38772. if (! menuActive)
  38773. {
  38774. const int selectedId = getSelectedId();
  38775. PopupMenu menu;
  38776. menu.setLookAndFeel (&getLookAndFeel());
  38777. for (int i = 0; i < items.size(); ++i)
  38778. {
  38779. const ItemInfo* const item = items.getUnchecked(i);
  38780. if (item->isSeparator())
  38781. menu.addSeparator();
  38782. else if (item->isHeading)
  38783. menu.addSectionHeader (item->name);
  38784. else
  38785. menu.addItem (item->itemId, item->name,
  38786. item->isEnabled, item->itemId == selectedId);
  38787. }
  38788. if (items.size() == 0)
  38789. menu.addItem (1, noChoicesMessage, false);
  38790. menuActive = true;
  38791. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38792. new Callback (this));
  38793. }
  38794. }
  38795. void ComboBox::mouseDown (const MouseEvent& e)
  38796. {
  38797. beginDragAutoRepeat (300);
  38798. isButtonDown = isEnabled();
  38799. if (isButtonDown
  38800. && (e.eventComponent == this || ! label->isEditable()))
  38801. {
  38802. showPopup();
  38803. }
  38804. }
  38805. void ComboBox::mouseDrag (const MouseEvent& e)
  38806. {
  38807. beginDragAutoRepeat (50);
  38808. if (isButtonDown && ! e.mouseWasClicked())
  38809. showPopup();
  38810. }
  38811. void ComboBox::mouseUp (const MouseEvent& e2)
  38812. {
  38813. if (isButtonDown)
  38814. {
  38815. isButtonDown = false;
  38816. repaint();
  38817. const MouseEvent e (e2.getEventRelativeTo (this));
  38818. if (reallyContains (e.x, e.y, true)
  38819. && (e2.eventComponent == this || ! label->isEditable()))
  38820. {
  38821. showPopup();
  38822. }
  38823. }
  38824. }
  38825. void ComboBox::addListener (Listener* const listener)
  38826. {
  38827. listeners.add (listener);
  38828. }
  38829. void ComboBox::removeListener (Listener* const listener)
  38830. {
  38831. listeners.remove (listener);
  38832. }
  38833. void ComboBox::handleAsyncUpdate()
  38834. {
  38835. Component::BailOutChecker checker (this);
  38836. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38837. }
  38838. END_JUCE_NAMESPACE
  38839. /*** End of inlined file: juce_ComboBox.cpp ***/
  38840. /*** Start of inlined file: juce_Label.cpp ***/
  38841. BEGIN_JUCE_NAMESPACE
  38842. Label::Label (const String& componentName,
  38843. const String& labelText)
  38844. : Component (componentName),
  38845. textValue (labelText),
  38846. lastTextValue (labelText),
  38847. font (15.0f),
  38848. justification (Justification::centredLeft),
  38849. ownerComponent (0),
  38850. horizontalBorderSize (5),
  38851. verticalBorderSize (1),
  38852. minimumHorizontalScale (0.7f),
  38853. editSingleClick (false),
  38854. editDoubleClick (false),
  38855. lossOfFocusDiscardsChanges (false)
  38856. {
  38857. setColour (TextEditor::textColourId, Colours::black);
  38858. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38859. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38860. textValue.addListener (this);
  38861. }
  38862. Label::~Label()
  38863. {
  38864. textValue.removeListener (this);
  38865. if (ownerComponent != 0)
  38866. ownerComponent->removeComponentListener (this);
  38867. editor = 0;
  38868. }
  38869. void Label::setText (const String& newText,
  38870. const bool broadcastChangeMessage)
  38871. {
  38872. hideEditor (true);
  38873. if (lastTextValue != newText)
  38874. {
  38875. lastTextValue = newText;
  38876. textValue = newText;
  38877. repaint();
  38878. textWasChanged();
  38879. if (ownerComponent != 0)
  38880. componentMovedOrResized (*ownerComponent, true, true);
  38881. if (broadcastChangeMessage)
  38882. callChangeListeners();
  38883. }
  38884. }
  38885. const String Label::getText (const bool returnActiveEditorContents) const
  38886. {
  38887. return (returnActiveEditorContents && isBeingEdited())
  38888. ? editor->getText()
  38889. : textValue.toString();
  38890. }
  38891. void Label::valueChanged (Value&)
  38892. {
  38893. if (lastTextValue != textValue.toString())
  38894. setText (textValue.toString(), true);
  38895. }
  38896. void Label::setFont (const Font& newFont)
  38897. {
  38898. if (font != newFont)
  38899. {
  38900. font = newFont;
  38901. repaint();
  38902. }
  38903. }
  38904. const Font& Label::getFont() const throw()
  38905. {
  38906. return font;
  38907. }
  38908. void Label::setEditable (const bool editOnSingleClick,
  38909. const bool editOnDoubleClick,
  38910. const bool lossOfFocusDiscardsChanges_)
  38911. {
  38912. editSingleClick = editOnSingleClick;
  38913. editDoubleClick = editOnDoubleClick;
  38914. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38915. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38916. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38917. }
  38918. void Label::setJustificationType (const Justification& newJustification)
  38919. {
  38920. if (justification != newJustification)
  38921. {
  38922. justification = newJustification;
  38923. repaint();
  38924. }
  38925. }
  38926. void Label::setBorderSize (int h, int v)
  38927. {
  38928. if (horizontalBorderSize != h || verticalBorderSize != v)
  38929. {
  38930. horizontalBorderSize = h;
  38931. verticalBorderSize = v;
  38932. repaint();
  38933. }
  38934. }
  38935. Component* Label::getAttachedComponent() const
  38936. {
  38937. return static_cast<Component*> (ownerComponent);
  38938. }
  38939. void Label::attachToComponent (Component* owner,
  38940. const bool onLeft)
  38941. {
  38942. if (ownerComponent != 0)
  38943. ownerComponent->removeComponentListener (this);
  38944. ownerComponent = owner;
  38945. leftOfOwnerComp = onLeft;
  38946. if (ownerComponent != 0)
  38947. {
  38948. setVisible (owner->isVisible());
  38949. ownerComponent->addComponentListener (this);
  38950. componentParentHierarchyChanged (*ownerComponent);
  38951. componentMovedOrResized (*ownerComponent, true, true);
  38952. }
  38953. }
  38954. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38955. {
  38956. if (leftOfOwnerComp)
  38957. {
  38958. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38959. component.getHeight());
  38960. setTopRightPosition (component.getX(), component.getY());
  38961. }
  38962. else
  38963. {
  38964. setSize (component.getWidth(),
  38965. 8 + roundToInt (getFont().getHeight()));
  38966. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38967. }
  38968. }
  38969. void Label::componentParentHierarchyChanged (Component& component)
  38970. {
  38971. if (component.getParentComponent() != 0)
  38972. component.getParentComponent()->addChildComponent (this);
  38973. }
  38974. void Label::componentVisibilityChanged (Component& component)
  38975. {
  38976. setVisible (component.isVisible());
  38977. }
  38978. void Label::textWasEdited()
  38979. {
  38980. }
  38981. void Label::textWasChanged()
  38982. {
  38983. }
  38984. void Label::showEditor()
  38985. {
  38986. if (editor == 0)
  38987. {
  38988. addAndMakeVisible (editor = createEditorComponent());
  38989. editor->setText (getText(), false);
  38990. editor->addListener (this);
  38991. editor->grabKeyboardFocus();
  38992. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38993. editor->addListener (this);
  38994. resized();
  38995. repaint();
  38996. editorShown (editor);
  38997. enterModalState (false);
  38998. editor->grabKeyboardFocus();
  38999. }
  39000. }
  39001. void Label::editorShown (TextEditor* /*editorComponent*/)
  39002. {
  39003. }
  39004. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  39005. {
  39006. }
  39007. bool Label::updateFromTextEditorContents()
  39008. {
  39009. jassert (editor != 0);
  39010. const String newText (editor->getText());
  39011. if (textValue.toString() != newText)
  39012. {
  39013. lastTextValue = newText;
  39014. textValue = newText;
  39015. repaint();
  39016. textWasChanged();
  39017. if (ownerComponent != 0)
  39018. componentMovedOrResized (*ownerComponent, true, true);
  39019. return true;
  39020. }
  39021. return false;
  39022. }
  39023. void Label::hideEditor (const bool discardCurrentEditorContents)
  39024. {
  39025. if (editor != 0)
  39026. {
  39027. Component::SafePointer<Component> deletionChecker (this);
  39028. editorAboutToBeHidden (editor);
  39029. const bool changed = (! discardCurrentEditorContents)
  39030. && updateFromTextEditorContents();
  39031. editor = 0;
  39032. repaint();
  39033. if (changed)
  39034. textWasEdited();
  39035. if (deletionChecker != 0)
  39036. exitModalState (0);
  39037. if (changed && deletionChecker != 0)
  39038. callChangeListeners();
  39039. }
  39040. }
  39041. void Label::inputAttemptWhenModal()
  39042. {
  39043. if (editor != 0)
  39044. {
  39045. if (lossOfFocusDiscardsChanges)
  39046. textEditorEscapeKeyPressed (*editor);
  39047. else
  39048. textEditorReturnKeyPressed (*editor);
  39049. }
  39050. }
  39051. bool Label::isBeingEdited() const throw()
  39052. {
  39053. return editor != 0;
  39054. }
  39055. TextEditor* Label::createEditorComponent()
  39056. {
  39057. TextEditor* const ed = new TextEditor (getName());
  39058. ed->setFont (font);
  39059. // copy these colours from our own settings..
  39060. const int cols[] = { TextEditor::backgroundColourId,
  39061. TextEditor::textColourId,
  39062. TextEditor::highlightColourId,
  39063. TextEditor::highlightedTextColourId,
  39064. TextEditor::caretColourId,
  39065. TextEditor::outlineColourId,
  39066. TextEditor::focusedOutlineColourId,
  39067. TextEditor::shadowColourId };
  39068. for (int i = 0; i < numElementsInArray (cols); ++i)
  39069. ed->setColour (cols[i], findColour (cols[i]));
  39070. return ed;
  39071. }
  39072. void Label::paint (Graphics& g)
  39073. {
  39074. getLookAndFeel().drawLabel (g, *this);
  39075. }
  39076. void Label::mouseUp (const MouseEvent& e)
  39077. {
  39078. if (editSingleClick
  39079. && e.mouseWasClicked()
  39080. && contains (e.x, e.y)
  39081. && ! e.mods.isPopupMenu())
  39082. {
  39083. showEditor();
  39084. }
  39085. }
  39086. void Label::mouseDoubleClick (const MouseEvent& e)
  39087. {
  39088. if (editDoubleClick && ! e.mods.isPopupMenu())
  39089. showEditor();
  39090. }
  39091. void Label::resized()
  39092. {
  39093. if (editor != 0)
  39094. editor->setBoundsInset (BorderSize (0));
  39095. }
  39096. void Label::focusGained (FocusChangeType cause)
  39097. {
  39098. if (editSingleClick && cause == focusChangedByTabKey)
  39099. showEditor();
  39100. }
  39101. void Label::enablementChanged()
  39102. {
  39103. repaint();
  39104. }
  39105. void Label::colourChanged()
  39106. {
  39107. repaint();
  39108. }
  39109. void Label::setMinimumHorizontalScale (const float newScale)
  39110. {
  39111. if (minimumHorizontalScale != newScale)
  39112. {
  39113. minimumHorizontalScale = newScale;
  39114. repaint();
  39115. }
  39116. }
  39117. // We'll use a custom focus traverser here to make sure focus goes from the
  39118. // text editor to another component rather than back to the label itself.
  39119. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  39120. {
  39121. public:
  39122. LabelKeyboardFocusTraverser() {}
  39123. Component* getNextComponent (Component* current)
  39124. {
  39125. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  39126. ? current->getParentComponent() : current);
  39127. }
  39128. Component* getPreviousComponent (Component* current)
  39129. {
  39130. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  39131. ? current->getParentComponent() : current);
  39132. }
  39133. };
  39134. KeyboardFocusTraverser* Label::createFocusTraverser()
  39135. {
  39136. return new LabelKeyboardFocusTraverser();
  39137. }
  39138. void Label::addListener (Listener* const listener)
  39139. {
  39140. listeners.add (listener);
  39141. }
  39142. void Label::removeListener (Listener* const listener)
  39143. {
  39144. listeners.remove (listener);
  39145. }
  39146. void Label::callChangeListeners()
  39147. {
  39148. Component::BailOutChecker checker (this);
  39149. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  39150. }
  39151. void Label::textEditorTextChanged (TextEditor& ed)
  39152. {
  39153. if (editor != 0)
  39154. {
  39155. jassert (&ed == editor);
  39156. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  39157. {
  39158. if (lossOfFocusDiscardsChanges)
  39159. textEditorEscapeKeyPressed (ed);
  39160. else
  39161. textEditorReturnKeyPressed (ed);
  39162. }
  39163. }
  39164. }
  39165. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  39166. {
  39167. if (editor != 0)
  39168. {
  39169. jassert (&ed == editor);
  39170. (void) ed;
  39171. const bool changed = updateFromTextEditorContents();
  39172. hideEditor (true);
  39173. if (changed)
  39174. {
  39175. Component::SafePointer<Component> deletionChecker (this);
  39176. textWasEdited();
  39177. if (deletionChecker != 0)
  39178. callChangeListeners();
  39179. }
  39180. }
  39181. }
  39182. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  39183. {
  39184. if (editor != 0)
  39185. {
  39186. jassert (&ed == editor);
  39187. (void) ed;
  39188. editor->setText (textValue.toString(), false);
  39189. hideEditor (true);
  39190. }
  39191. }
  39192. void Label::textEditorFocusLost (TextEditor& ed)
  39193. {
  39194. textEditorTextChanged (ed);
  39195. }
  39196. END_JUCE_NAMESPACE
  39197. /*** End of inlined file: juce_Label.cpp ***/
  39198. /*** Start of inlined file: juce_ListBox.cpp ***/
  39199. BEGIN_JUCE_NAMESPACE
  39200. class ListBoxRowComponent : public Component,
  39201. public TooltipClient
  39202. {
  39203. public:
  39204. ListBoxRowComponent (ListBox& owner_)
  39205. : owner (owner_),
  39206. row (-1),
  39207. selected (false),
  39208. isDragging (false)
  39209. {
  39210. }
  39211. ~ListBoxRowComponent()
  39212. {
  39213. deleteAllChildren();
  39214. }
  39215. void paint (Graphics& g)
  39216. {
  39217. if (owner.getModel() != 0)
  39218. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39219. }
  39220. void update (const int row_, const bool selected_)
  39221. {
  39222. if (row != row_ || selected != selected_)
  39223. {
  39224. repaint();
  39225. row = row_;
  39226. selected = selected_;
  39227. }
  39228. if (owner.getModel() != 0)
  39229. {
  39230. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  39231. if (customComp != 0)
  39232. {
  39233. addAndMakeVisible (customComp);
  39234. customComp->setBounds (getLocalBounds());
  39235. for (int i = getNumChildComponents(); --i >= 0;)
  39236. if (getChildComponent (i) != customComp)
  39237. delete getChildComponent (i);
  39238. }
  39239. else
  39240. {
  39241. deleteAllChildren();
  39242. }
  39243. }
  39244. }
  39245. void mouseDown (const MouseEvent& e)
  39246. {
  39247. isDragging = false;
  39248. selectRowOnMouseUp = false;
  39249. if (isEnabled())
  39250. {
  39251. if (! selected)
  39252. {
  39253. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39254. if (owner.getModel() != 0)
  39255. owner.getModel()->listBoxItemClicked (row, e);
  39256. }
  39257. else
  39258. {
  39259. selectRowOnMouseUp = true;
  39260. }
  39261. }
  39262. }
  39263. void mouseUp (const MouseEvent& e)
  39264. {
  39265. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39266. {
  39267. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39268. if (owner.getModel() != 0)
  39269. owner.getModel()->listBoxItemClicked (row, e);
  39270. }
  39271. }
  39272. void mouseDoubleClick (const MouseEvent& e)
  39273. {
  39274. if (owner.getModel() != 0 && isEnabled())
  39275. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39276. }
  39277. void mouseDrag (const MouseEvent& e)
  39278. {
  39279. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39280. {
  39281. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39282. if (selectedRows.size() > 0)
  39283. {
  39284. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39285. if (dragDescription.isNotEmpty())
  39286. {
  39287. isDragging = true;
  39288. owner.startDragAndDrop (e, dragDescription);
  39289. }
  39290. }
  39291. }
  39292. }
  39293. void resized()
  39294. {
  39295. if (getNumChildComponents() > 0)
  39296. getChildComponent(0)->setBounds (getLocalBounds());
  39297. }
  39298. const String getTooltip()
  39299. {
  39300. if (owner.getModel() != 0)
  39301. return owner.getModel()->getTooltipForRow (row);
  39302. return String::empty;
  39303. }
  39304. juce_UseDebuggingNewOperator
  39305. bool neededFlag;
  39306. private:
  39307. ListBox& owner;
  39308. int row;
  39309. bool selected, isDragging, selectRowOnMouseUp;
  39310. ListBoxRowComponent (const ListBoxRowComponent&);
  39311. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39312. };
  39313. class ListViewport : public Viewport
  39314. {
  39315. public:
  39316. int firstIndex, firstWholeIndex, lastWholeIndex;
  39317. bool hasUpdated;
  39318. ListViewport (ListBox& owner_)
  39319. : owner (owner_)
  39320. {
  39321. setWantsKeyboardFocus (false);
  39322. setViewedComponent (new Component());
  39323. getViewedComponent()->addMouseListener (this, false);
  39324. getViewedComponent()->setWantsKeyboardFocus (false);
  39325. }
  39326. ~ListViewport()
  39327. {
  39328. getViewedComponent()->removeMouseListener (this);
  39329. getViewedComponent()->deleteAllChildren();
  39330. }
  39331. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39332. {
  39333. return static_cast <ListBoxRowComponent*>
  39334. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  39335. }
  39336. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39337. {
  39338. const int index = getIndexOfChildComponent (rowComponent);
  39339. const int num = getViewedComponent()->getNumChildComponents();
  39340. for (int i = num; --i >= 0;)
  39341. if (((firstIndex + i) % jmax (1, num)) == index)
  39342. return firstIndex + i;
  39343. return -1;
  39344. }
  39345. Component* getComponentForRowIfOnscreen (const int row) const throw()
  39346. {
  39347. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  39348. ? getComponentForRow (row) : 0;
  39349. }
  39350. void visibleAreaChanged (int, int, int, int)
  39351. {
  39352. updateVisibleArea (true);
  39353. if (owner.getModel() != 0)
  39354. owner.getModel()->listWasScrolled();
  39355. }
  39356. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39357. {
  39358. hasUpdated = false;
  39359. const int newX = getViewedComponent()->getX();
  39360. int newY = getViewedComponent()->getY();
  39361. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39362. const int newH = owner.totalItems * owner.getRowHeight();
  39363. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39364. newY = getMaximumVisibleHeight() - newH;
  39365. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39366. if (makeSureItUpdatesContent && ! hasUpdated)
  39367. updateContents();
  39368. }
  39369. void updateContents()
  39370. {
  39371. hasUpdated = true;
  39372. const int rowHeight = owner.getRowHeight();
  39373. if (rowHeight > 0)
  39374. {
  39375. const int y = getViewPositionY();
  39376. const int w = getViewedComponent()->getWidth();
  39377. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39378. while (numNeeded > getViewedComponent()->getNumChildComponents())
  39379. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  39380. jassert (numNeeded >= 0);
  39381. while (numNeeded < getViewedComponent()->getNumChildComponents())
  39382. {
  39383. Component* const rowToRemove
  39384. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  39385. delete rowToRemove;
  39386. }
  39387. firstIndex = y / rowHeight;
  39388. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39389. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39390. for (int i = 0; i < numNeeded; ++i)
  39391. {
  39392. const int row = i + firstIndex;
  39393. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39394. if (rowComp != 0)
  39395. {
  39396. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39397. rowComp->update (row, owner.isRowSelected (row));
  39398. }
  39399. }
  39400. }
  39401. if (owner.headerComponent != 0)
  39402. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39403. owner.outlineThickness,
  39404. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39405. getViewedComponent()->getWidth()),
  39406. owner.headerComponent->getHeight());
  39407. }
  39408. void paint (Graphics& g)
  39409. {
  39410. if (isOpaque())
  39411. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39412. }
  39413. bool keyPressed (const KeyPress& key)
  39414. {
  39415. if (key.isKeyCode (KeyPress::upKey)
  39416. || key.isKeyCode (KeyPress::downKey)
  39417. || key.isKeyCode (KeyPress::pageUpKey)
  39418. || key.isKeyCode (KeyPress::pageDownKey)
  39419. || key.isKeyCode (KeyPress::homeKey)
  39420. || key.isKeyCode (KeyPress::endKey))
  39421. {
  39422. // we want to avoid these keypresses going to the viewport, and instead allow
  39423. // them to pass up to our listbox..
  39424. return false;
  39425. }
  39426. return Viewport::keyPressed (key);
  39427. }
  39428. juce_UseDebuggingNewOperator
  39429. private:
  39430. ListBox& owner;
  39431. ListViewport (const ListViewport&);
  39432. ListViewport& operator= (const ListViewport&);
  39433. };
  39434. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39435. : Component (name),
  39436. model (model_),
  39437. totalItems (0),
  39438. rowHeight (22),
  39439. minimumRowWidth (0),
  39440. outlineThickness (0),
  39441. lastRowSelected (-1),
  39442. mouseMoveSelects (false),
  39443. multipleSelection (false),
  39444. hasDoneInitialUpdate (false)
  39445. {
  39446. addAndMakeVisible (viewport = new ListViewport (*this));
  39447. setWantsKeyboardFocus (true);
  39448. colourChanged();
  39449. }
  39450. ListBox::~ListBox()
  39451. {
  39452. headerComponent = 0;
  39453. viewport = 0;
  39454. }
  39455. void ListBox::setModel (ListBoxModel* const newModel)
  39456. {
  39457. if (model != newModel)
  39458. {
  39459. model = newModel;
  39460. updateContent();
  39461. }
  39462. }
  39463. void ListBox::setMultipleSelectionEnabled (bool b)
  39464. {
  39465. multipleSelection = b;
  39466. }
  39467. void ListBox::setMouseMoveSelectsRows (bool b)
  39468. {
  39469. mouseMoveSelects = b;
  39470. if (b)
  39471. addMouseListener (this, true);
  39472. }
  39473. void ListBox::paint (Graphics& g)
  39474. {
  39475. if (! hasDoneInitialUpdate)
  39476. updateContent();
  39477. g.fillAll (findColour (backgroundColourId));
  39478. }
  39479. void ListBox::paintOverChildren (Graphics& g)
  39480. {
  39481. if (outlineThickness > 0)
  39482. {
  39483. g.setColour (findColour (outlineColourId));
  39484. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39485. }
  39486. }
  39487. void ListBox::resized()
  39488. {
  39489. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39490. outlineThickness,
  39491. outlineThickness,
  39492. outlineThickness));
  39493. viewport->setSingleStepSizes (20, getRowHeight());
  39494. viewport->updateVisibleArea (false);
  39495. }
  39496. void ListBox::visibilityChanged()
  39497. {
  39498. viewport->updateVisibleArea (true);
  39499. }
  39500. Viewport* ListBox::getViewport() const throw()
  39501. {
  39502. return viewport;
  39503. }
  39504. void ListBox::updateContent()
  39505. {
  39506. hasDoneInitialUpdate = true;
  39507. totalItems = (model != 0) ? model->getNumRows() : 0;
  39508. bool selectionChanged = false;
  39509. if (selected [selected.size() - 1] >= totalItems)
  39510. {
  39511. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39512. lastRowSelected = getSelectedRow (0);
  39513. selectionChanged = true;
  39514. }
  39515. viewport->updateVisibleArea (isVisible());
  39516. viewport->resized();
  39517. if (selectionChanged && model != 0)
  39518. model->selectedRowsChanged (lastRowSelected);
  39519. }
  39520. void ListBox::selectRow (const int row,
  39521. bool dontScroll,
  39522. bool deselectOthersFirst)
  39523. {
  39524. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39525. }
  39526. void ListBox::selectRowInternal (const int row,
  39527. bool dontScroll,
  39528. bool deselectOthersFirst,
  39529. bool isMouseClick)
  39530. {
  39531. if (! multipleSelection)
  39532. deselectOthersFirst = true;
  39533. if ((! isRowSelected (row))
  39534. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39535. {
  39536. if (((unsigned int) row) < (unsigned int) totalItems)
  39537. {
  39538. if (deselectOthersFirst)
  39539. selected.clear();
  39540. selected.addRange (Range<int> (row, row + 1));
  39541. if (getHeight() == 0 || getWidth() == 0)
  39542. dontScroll = true;
  39543. viewport->hasUpdated = false;
  39544. if (row < viewport->firstWholeIndex && ! dontScroll)
  39545. {
  39546. viewport->setViewPosition (viewport->getViewPositionX(),
  39547. row * getRowHeight());
  39548. }
  39549. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  39550. {
  39551. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  39552. if (row >= lastRowSelected + rowsOnScreen
  39553. && rowsOnScreen < totalItems - 1
  39554. && ! isMouseClick)
  39555. {
  39556. viewport->setViewPosition (viewport->getViewPositionX(),
  39557. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  39558. * getRowHeight());
  39559. }
  39560. else
  39561. {
  39562. viewport->setViewPosition (viewport->getViewPositionX(),
  39563. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39564. }
  39565. }
  39566. if (! viewport->hasUpdated)
  39567. viewport->updateContents();
  39568. lastRowSelected = row;
  39569. model->selectedRowsChanged (row);
  39570. }
  39571. else
  39572. {
  39573. if (deselectOthersFirst)
  39574. deselectAllRows();
  39575. }
  39576. }
  39577. }
  39578. void ListBox::deselectRow (const int row)
  39579. {
  39580. if (selected.contains (row))
  39581. {
  39582. selected.removeRange (Range <int> (row, row + 1));
  39583. if (row == lastRowSelected)
  39584. lastRowSelected = getSelectedRow (0);
  39585. viewport->updateContents();
  39586. model->selectedRowsChanged (lastRowSelected);
  39587. }
  39588. }
  39589. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39590. const bool sendNotificationEventToModel)
  39591. {
  39592. selected = setOfRowsToBeSelected;
  39593. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39594. if (! isRowSelected (lastRowSelected))
  39595. lastRowSelected = getSelectedRow (0);
  39596. viewport->updateContents();
  39597. if ((model != 0) && sendNotificationEventToModel)
  39598. model->selectedRowsChanged (lastRowSelected);
  39599. }
  39600. const SparseSet<int> ListBox::getSelectedRows() const
  39601. {
  39602. return selected;
  39603. }
  39604. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39605. {
  39606. if (multipleSelection && (firstRow != lastRow))
  39607. {
  39608. const int numRows = totalItems - 1;
  39609. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39610. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39611. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39612. jmax (firstRow, lastRow) + 1));
  39613. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39614. }
  39615. selectRowInternal (lastRow, false, false, true);
  39616. }
  39617. void ListBox::flipRowSelection (const int row)
  39618. {
  39619. if (isRowSelected (row))
  39620. deselectRow (row);
  39621. else
  39622. selectRowInternal (row, false, false, true);
  39623. }
  39624. void ListBox::deselectAllRows()
  39625. {
  39626. if (! selected.isEmpty())
  39627. {
  39628. selected.clear();
  39629. lastRowSelected = -1;
  39630. viewport->updateContents();
  39631. if (model != 0)
  39632. model->selectedRowsChanged (lastRowSelected);
  39633. }
  39634. }
  39635. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39636. const ModifierKeys& mods)
  39637. {
  39638. if (multipleSelection && mods.isCommandDown())
  39639. {
  39640. flipRowSelection (row);
  39641. }
  39642. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39643. {
  39644. selectRangeOfRows (lastRowSelected, row);
  39645. }
  39646. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39647. {
  39648. selectRowInternal (row, false, true, true);
  39649. }
  39650. }
  39651. int ListBox::getNumSelectedRows() const
  39652. {
  39653. return selected.size();
  39654. }
  39655. int ListBox::getSelectedRow (const int index) const
  39656. {
  39657. return (((unsigned int) index) < (unsigned int) selected.size())
  39658. ? selected [index] : -1;
  39659. }
  39660. bool ListBox::isRowSelected (const int row) const
  39661. {
  39662. return selected.contains (row);
  39663. }
  39664. int ListBox::getLastRowSelected() const
  39665. {
  39666. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39667. }
  39668. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39669. {
  39670. if (((unsigned int) x) < (unsigned int) getWidth())
  39671. {
  39672. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39673. if (((unsigned int) row) < (unsigned int) totalItems)
  39674. return row;
  39675. }
  39676. return -1;
  39677. }
  39678. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39679. {
  39680. if (((unsigned int) x) < (unsigned int) getWidth())
  39681. {
  39682. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39683. return jlimit (0, totalItems, row);
  39684. }
  39685. return -1;
  39686. }
  39687. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39688. {
  39689. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39690. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  39691. }
  39692. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39693. {
  39694. return viewport->getRowNumberOfComponent (rowComponent);
  39695. }
  39696. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39697. const bool relativeToComponentTopLeft) const throw()
  39698. {
  39699. int y = viewport->getY() + rowHeight * rowNumber;
  39700. if (relativeToComponentTopLeft)
  39701. y -= viewport->getViewPositionY();
  39702. return Rectangle<int> (viewport->getX(), y,
  39703. viewport->getViewedComponent()->getWidth(), rowHeight);
  39704. }
  39705. void ListBox::setVerticalPosition (const double proportion)
  39706. {
  39707. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39708. viewport->setViewPosition (viewport->getViewPositionX(),
  39709. jmax (0, roundToInt (proportion * offscreen)));
  39710. }
  39711. double ListBox::getVerticalPosition() const
  39712. {
  39713. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39714. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39715. : 0;
  39716. }
  39717. int ListBox::getVisibleRowWidth() const throw()
  39718. {
  39719. return viewport->getViewWidth();
  39720. }
  39721. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39722. {
  39723. if (row < viewport->firstWholeIndex)
  39724. {
  39725. viewport->setViewPosition (viewport->getViewPositionX(),
  39726. row * getRowHeight());
  39727. }
  39728. else if (row >= viewport->lastWholeIndex)
  39729. {
  39730. viewport->setViewPosition (viewport->getViewPositionX(),
  39731. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39732. }
  39733. }
  39734. bool ListBox::keyPressed (const KeyPress& key)
  39735. {
  39736. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39737. const bool multiple = multipleSelection
  39738. && (lastRowSelected >= 0)
  39739. && (key.getModifiers().isShiftDown()
  39740. || key.getModifiers().isCtrlDown()
  39741. || key.getModifiers().isCommandDown());
  39742. if (key.isKeyCode (KeyPress::upKey))
  39743. {
  39744. if (multiple)
  39745. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39746. else
  39747. selectRow (jmax (0, lastRowSelected - 1));
  39748. }
  39749. else if (key.isKeyCode (KeyPress::returnKey)
  39750. && isRowSelected (lastRowSelected))
  39751. {
  39752. if (model != 0)
  39753. model->returnKeyPressed (lastRowSelected);
  39754. }
  39755. else if (key.isKeyCode (KeyPress::pageUpKey))
  39756. {
  39757. if (multiple)
  39758. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39759. else
  39760. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39761. }
  39762. else if (key.isKeyCode (KeyPress::pageDownKey))
  39763. {
  39764. if (multiple)
  39765. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39766. else
  39767. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39768. }
  39769. else if (key.isKeyCode (KeyPress::homeKey))
  39770. {
  39771. if (multiple && key.getModifiers().isShiftDown())
  39772. selectRangeOfRows (lastRowSelected, 0);
  39773. else
  39774. selectRow (0);
  39775. }
  39776. else if (key.isKeyCode (KeyPress::endKey))
  39777. {
  39778. if (multiple && key.getModifiers().isShiftDown())
  39779. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39780. else
  39781. selectRow (totalItems - 1);
  39782. }
  39783. else if (key.isKeyCode (KeyPress::downKey))
  39784. {
  39785. if (multiple)
  39786. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39787. else
  39788. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39789. }
  39790. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39791. && isRowSelected (lastRowSelected))
  39792. {
  39793. if (model != 0)
  39794. model->deleteKeyPressed (lastRowSelected);
  39795. }
  39796. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39797. {
  39798. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39799. }
  39800. else
  39801. {
  39802. return false;
  39803. }
  39804. return true;
  39805. }
  39806. bool ListBox::keyStateChanged (const bool isKeyDown)
  39807. {
  39808. return isKeyDown
  39809. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39810. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39811. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39812. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39813. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39814. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39815. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39816. }
  39817. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39818. {
  39819. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39820. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39821. }
  39822. void ListBox::mouseMove (const MouseEvent& e)
  39823. {
  39824. if (mouseMoveSelects)
  39825. {
  39826. const MouseEvent e2 (e.getEventRelativeTo (this));
  39827. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39828. }
  39829. }
  39830. void ListBox::mouseExit (const MouseEvent& e)
  39831. {
  39832. mouseMove (e);
  39833. }
  39834. void ListBox::mouseUp (const MouseEvent& e)
  39835. {
  39836. if (e.mouseWasClicked() && model != 0)
  39837. model->backgroundClicked();
  39838. }
  39839. void ListBox::setRowHeight (const int newHeight)
  39840. {
  39841. rowHeight = jmax (1, newHeight);
  39842. viewport->setSingleStepSizes (20, rowHeight);
  39843. updateContent();
  39844. }
  39845. int ListBox::getNumRowsOnScreen() const throw()
  39846. {
  39847. return viewport->getMaximumVisibleHeight() / rowHeight;
  39848. }
  39849. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39850. {
  39851. minimumRowWidth = newMinimumWidth;
  39852. updateContent();
  39853. }
  39854. int ListBox::getVisibleContentWidth() const throw()
  39855. {
  39856. return viewport->getMaximumVisibleWidth();
  39857. }
  39858. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39859. {
  39860. return viewport->getVerticalScrollBar();
  39861. }
  39862. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39863. {
  39864. return viewport->getHorizontalScrollBar();
  39865. }
  39866. void ListBox::colourChanged()
  39867. {
  39868. setOpaque (findColour (backgroundColourId).isOpaque());
  39869. viewport->setOpaque (isOpaque());
  39870. repaint();
  39871. }
  39872. void ListBox::setOutlineThickness (const int outlineThickness_)
  39873. {
  39874. outlineThickness = outlineThickness_;
  39875. resized();
  39876. }
  39877. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39878. {
  39879. if (newHeaderComponent != headerComponent)
  39880. {
  39881. headerComponent = newHeaderComponent;
  39882. addAndMakeVisible (newHeaderComponent);
  39883. ListBox::resized();
  39884. }
  39885. }
  39886. void ListBox::repaintRow (const int rowNumber) throw()
  39887. {
  39888. repaint (getRowPosition (rowNumber, true));
  39889. }
  39890. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39891. {
  39892. Rectangle<int> imageArea;
  39893. const int firstRow = getRowContainingPosition (0, 0);
  39894. int i;
  39895. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39896. {
  39897. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39898. if (rowComp != 0 && isRowSelected (firstRow + i))
  39899. {
  39900. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39901. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39902. imageArea = imageArea.getUnion (rowRect);
  39903. }
  39904. }
  39905. imageArea = imageArea.getIntersection (getLocalBounds());
  39906. imageX = imageArea.getX();
  39907. imageY = imageArea.getY();
  39908. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39909. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39910. {
  39911. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39912. if (rowComp != 0 && isRowSelected (firstRow + i))
  39913. {
  39914. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39915. Graphics g (snapshot);
  39916. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39917. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  39918. rowComp->paintEntireComponent (g);
  39919. }
  39920. }
  39921. return snapshot;
  39922. }
  39923. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39924. {
  39925. DragAndDropContainer* const dragContainer
  39926. = DragAndDropContainer::findParentDragContainerFor (this);
  39927. if (dragContainer != 0)
  39928. {
  39929. int x, y;
  39930. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39931. dragImage.multiplyAllAlphas (0.6f);
  39932. MouseEvent e2 (e.getEventRelativeTo (this));
  39933. const Point<int> p (x - e2.x, y - e2.y);
  39934. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39935. }
  39936. else
  39937. {
  39938. // to be able to do a drag-and-drop operation, the listbox needs to
  39939. // be inside a component which is also a DragAndDropContainer.
  39940. jassertfalse;
  39941. }
  39942. }
  39943. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39944. {
  39945. (void) existingComponentToUpdate;
  39946. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39947. return 0;
  39948. }
  39949. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  39950. {
  39951. }
  39952. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  39953. {
  39954. }
  39955. void ListBoxModel::backgroundClicked()
  39956. {
  39957. }
  39958. void ListBoxModel::selectedRowsChanged (int)
  39959. {
  39960. }
  39961. void ListBoxModel::deleteKeyPressed (int)
  39962. {
  39963. }
  39964. void ListBoxModel::returnKeyPressed (int)
  39965. {
  39966. }
  39967. void ListBoxModel::listWasScrolled()
  39968. {
  39969. }
  39970. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  39971. {
  39972. return String::empty;
  39973. }
  39974. const String ListBoxModel::getTooltipForRow (int)
  39975. {
  39976. return String::empty;
  39977. }
  39978. END_JUCE_NAMESPACE
  39979. /*** End of inlined file: juce_ListBox.cpp ***/
  39980. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39981. BEGIN_JUCE_NAMESPACE
  39982. ProgressBar::ProgressBar (double& progress_)
  39983. : progress (progress_),
  39984. displayPercentage (true),
  39985. lastCallbackTime (0)
  39986. {
  39987. currentValue = jlimit (0.0, 1.0, progress);
  39988. }
  39989. ProgressBar::~ProgressBar()
  39990. {
  39991. }
  39992. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39993. {
  39994. displayPercentage = shouldDisplayPercentage;
  39995. repaint();
  39996. }
  39997. void ProgressBar::setTextToDisplay (const String& text)
  39998. {
  39999. displayPercentage = false;
  40000. displayedMessage = text;
  40001. }
  40002. void ProgressBar::lookAndFeelChanged()
  40003. {
  40004. setOpaque (findColour (backgroundColourId).isOpaque());
  40005. }
  40006. void ProgressBar::colourChanged()
  40007. {
  40008. lookAndFeelChanged();
  40009. }
  40010. void ProgressBar::paint (Graphics& g)
  40011. {
  40012. String text;
  40013. if (displayPercentage)
  40014. {
  40015. if (currentValue >= 0 && currentValue <= 1.0)
  40016. text << roundToInt (currentValue * 100.0) << '%';
  40017. }
  40018. else
  40019. {
  40020. text = displayedMessage;
  40021. }
  40022. getLookAndFeel().drawProgressBar (g, *this,
  40023. getWidth(), getHeight(),
  40024. currentValue, text);
  40025. }
  40026. void ProgressBar::visibilityChanged()
  40027. {
  40028. if (isVisible())
  40029. startTimer (30);
  40030. else
  40031. stopTimer();
  40032. }
  40033. void ProgressBar::timerCallback()
  40034. {
  40035. double newProgress = progress;
  40036. const uint32 now = Time::getMillisecondCounter();
  40037. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  40038. lastCallbackTime = now;
  40039. if (currentValue != newProgress
  40040. || newProgress < 0 || newProgress >= 1.0
  40041. || currentMessage != displayedMessage)
  40042. {
  40043. if (currentValue < newProgress
  40044. && newProgress >= 0 && newProgress < 1.0
  40045. && currentValue >= 0 && currentValue < 1.0)
  40046. {
  40047. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  40048. newProgress);
  40049. }
  40050. currentValue = newProgress;
  40051. currentMessage = displayedMessage;
  40052. repaint();
  40053. }
  40054. }
  40055. END_JUCE_NAMESPACE
  40056. /*** End of inlined file: juce_ProgressBar.cpp ***/
  40057. /*** Start of inlined file: juce_Slider.cpp ***/
  40058. BEGIN_JUCE_NAMESPACE
  40059. class SliderPopupDisplayComponent : public BubbleComponent
  40060. {
  40061. public:
  40062. SliderPopupDisplayComponent (Slider* const owner_)
  40063. : owner (owner_),
  40064. font (15.0f, Font::bold)
  40065. {
  40066. setAlwaysOnTop (true);
  40067. }
  40068. ~SliderPopupDisplayComponent()
  40069. {
  40070. }
  40071. void paintContent (Graphics& g, int w, int h)
  40072. {
  40073. g.setFont (font);
  40074. g.setColour (Colours::black);
  40075. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  40076. }
  40077. void getContentSize (int& w, int& h)
  40078. {
  40079. w = font.getStringWidth (text) + 18;
  40080. h = (int) (font.getHeight() * 1.6f);
  40081. }
  40082. void updatePosition (const String& newText)
  40083. {
  40084. if (text != newText)
  40085. {
  40086. text = newText;
  40087. repaint();
  40088. }
  40089. BubbleComponent::setPosition (owner);
  40090. }
  40091. juce_UseDebuggingNewOperator
  40092. private:
  40093. Slider* owner;
  40094. Font font;
  40095. String text;
  40096. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  40097. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  40098. };
  40099. Slider::Slider (const String& name)
  40100. : Component (name),
  40101. lastCurrentValue (0),
  40102. lastValueMin (0),
  40103. lastValueMax (0),
  40104. minimum (0),
  40105. maximum (10),
  40106. interval (0),
  40107. skewFactor (1.0),
  40108. velocityModeSensitivity (1.0),
  40109. velocityModeOffset (0.0),
  40110. velocityModeThreshold (1),
  40111. rotaryStart (float_Pi * 1.2f),
  40112. rotaryEnd (float_Pi * 2.8f),
  40113. numDecimalPlaces (7),
  40114. sliderRegionStart (0),
  40115. sliderRegionSize (1),
  40116. sliderBeingDragged (-1),
  40117. pixelsForFullDragExtent (250),
  40118. style (LinearHorizontal),
  40119. textBoxPos (TextBoxLeft),
  40120. textBoxWidth (80),
  40121. textBoxHeight (20),
  40122. incDecButtonMode (incDecButtonsNotDraggable),
  40123. editableText (true),
  40124. doubleClickToValue (false),
  40125. isVelocityBased (false),
  40126. userKeyOverridesVelocity (true),
  40127. rotaryStop (true),
  40128. incDecButtonsSideBySide (false),
  40129. sendChangeOnlyOnRelease (false),
  40130. popupDisplayEnabled (false),
  40131. menuEnabled (false),
  40132. menuShown (false),
  40133. scrollWheelEnabled (true),
  40134. snapsToMousePos (true),
  40135. valueBox (0),
  40136. incButton (0),
  40137. decButton (0),
  40138. popupDisplay (0),
  40139. parentForPopupDisplay (0)
  40140. {
  40141. setWantsKeyboardFocus (false);
  40142. setRepaintsOnMouseActivity (true);
  40143. lookAndFeelChanged();
  40144. updateText();
  40145. currentValue.addListener (this);
  40146. valueMin.addListener (this);
  40147. valueMax.addListener (this);
  40148. }
  40149. Slider::~Slider()
  40150. {
  40151. currentValue.removeListener (this);
  40152. valueMin.removeListener (this);
  40153. valueMax.removeListener (this);
  40154. popupDisplay = 0;
  40155. deleteAllChildren();
  40156. }
  40157. void Slider::handleAsyncUpdate()
  40158. {
  40159. cancelPendingUpdate();
  40160. Component::BailOutChecker checker (this);
  40161. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  40162. }
  40163. void Slider::sendDragStart()
  40164. {
  40165. startedDragging();
  40166. Component::BailOutChecker checker (this);
  40167. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  40168. }
  40169. void Slider::sendDragEnd()
  40170. {
  40171. stoppedDragging();
  40172. sliderBeingDragged = -1;
  40173. Component::BailOutChecker checker (this);
  40174. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  40175. }
  40176. void Slider::addListener (Listener* const listener)
  40177. {
  40178. listeners.add (listener);
  40179. }
  40180. void Slider::removeListener (Listener* const listener)
  40181. {
  40182. listeners.remove (listener);
  40183. }
  40184. void Slider::setSliderStyle (const SliderStyle newStyle)
  40185. {
  40186. if (style != newStyle)
  40187. {
  40188. style = newStyle;
  40189. repaint();
  40190. lookAndFeelChanged();
  40191. }
  40192. }
  40193. void Slider::setRotaryParameters (const float startAngleRadians,
  40194. const float endAngleRadians,
  40195. const bool stopAtEnd)
  40196. {
  40197. // make sure the values are sensible..
  40198. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  40199. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  40200. jassert (rotaryStart < rotaryEnd);
  40201. rotaryStart = startAngleRadians;
  40202. rotaryEnd = endAngleRadians;
  40203. rotaryStop = stopAtEnd;
  40204. }
  40205. void Slider::setVelocityBasedMode (const bool velBased)
  40206. {
  40207. isVelocityBased = velBased;
  40208. }
  40209. void Slider::setVelocityModeParameters (const double sensitivity,
  40210. const int threshold,
  40211. const double offset,
  40212. const bool userCanPressKeyToSwapMode)
  40213. {
  40214. jassert (threshold >= 0);
  40215. jassert (sensitivity > 0);
  40216. jassert (offset >= 0);
  40217. velocityModeSensitivity = sensitivity;
  40218. velocityModeOffset = offset;
  40219. velocityModeThreshold = threshold;
  40220. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  40221. }
  40222. void Slider::setSkewFactor (const double factor)
  40223. {
  40224. skewFactor = factor;
  40225. }
  40226. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  40227. {
  40228. if (maximum > minimum)
  40229. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  40230. / (maximum - minimum));
  40231. }
  40232. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  40233. {
  40234. jassert (distanceForFullScaleDrag > 0);
  40235. pixelsForFullDragExtent = distanceForFullScaleDrag;
  40236. }
  40237. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  40238. {
  40239. if (incDecButtonMode != mode)
  40240. {
  40241. incDecButtonMode = mode;
  40242. lookAndFeelChanged();
  40243. }
  40244. }
  40245. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40246. const bool isReadOnly,
  40247. const int textEntryBoxWidth,
  40248. const int textEntryBoxHeight)
  40249. {
  40250. if (textBoxPos != newPosition
  40251. || editableText != (! isReadOnly)
  40252. || textBoxWidth != textEntryBoxWidth
  40253. || textBoxHeight != textEntryBoxHeight)
  40254. {
  40255. textBoxPos = newPosition;
  40256. editableText = ! isReadOnly;
  40257. textBoxWidth = textEntryBoxWidth;
  40258. textBoxHeight = textEntryBoxHeight;
  40259. repaint();
  40260. lookAndFeelChanged();
  40261. }
  40262. }
  40263. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40264. {
  40265. editableText = shouldBeEditable;
  40266. if (valueBox != 0)
  40267. valueBox->setEditable (shouldBeEditable && isEnabled());
  40268. }
  40269. void Slider::showTextBox()
  40270. {
  40271. jassert (editableText); // this should probably be avoided in read-only sliders.
  40272. if (valueBox != 0)
  40273. valueBox->showEditor();
  40274. }
  40275. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40276. {
  40277. if (valueBox != 0)
  40278. {
  40279. valueBox->hideEditor (discardCurrentEditorContents);
  40280. if (discardCurrentEditorContents)
  40281. updateText();
  40282. }
  40283. }
  40284. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40285. {
  40286. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40287. }
  40288. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40289. {
  40290. snapsToMousePos = shouldSnapToMouse;
  40291. }
  40292. void Slider::setPopupDisplayEnabled (const bool enabled,
  40293. Component* const parentComponentToUse)
  40294. {
  40295. popupDisplayEnabled = enabled;
  40296. parentForPopupDisplay = parentComponentToUse;
  40297. }
  40298. void Slider::colourChanged()
  40299. {
  40300. lookAndFeelChanged();
  40301. }
  40302. void Slider::lookAndFeelChanged()
  40303. {
  40304. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40305. : getTextFromValue (currentValue.getValue()));
  40306. deleteAllChildren();
  40307. valueBox = 0;
  40308. LookAndFeel& lf = getLookAndFeel();
  40309. if (textBoxPos != NoTextBox)
  40310. {
  40311. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40312. valueBox->setWantsKeyboardFocus (false);
  40313. valueBox->setText (previousTextBoxContent, false);
  40314. valueBox->setEditable (editableText && isEnabled());
  40315. valueBox->addListener (this);
  40316. if (style == LinearBar)
  40317. valueBox->addMouseListener (this, false);
  40318. valueBox->setTooltip (getTooltip());
  40319. }
  40320. if (style == IncDecButtons)
  40321. {
  40322. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40323. incButton->addButtonListener (this);
  40324. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40325. decButton->addButtonListener (this);
  40326. if (incDecButtonMode != incDecButtonsNotDraggable)
  40327. {
  40328. incButton->addMouseListener (this, false);
  40329. decButton->addMouseListener (this, false);
  40330. }
  40331. else
  40332. {
  40333. incButton->setRepeatSpeed (300, 100, 20);
  40334. incButton->addMouseListener (decButton, false);
  40335. decButton->setRepeatSpeed (300, 100, 20);
  40336. decButton->addMouseListener (incButton, false);
  40337. }
  40338. incButton->setTooltip (getTooltip());
  40339. decButton->setTooltip (getTooltip());
  40340. }
  40341. setComponentEffect (lf.getSliderEffect());
  40342. resized();
  40343. repaint();
  40344. }
  40345. void Slider::setRange (const double newMin,
  40346. const double newMax,
  40347. const double newInt)
  40348. {
  40349. if (minimum != newMin
  40350. || maximum != newMax
  40351. || interval != newInt)
  40352. {
  40353. minimum = newMin;
  40354. maximum = newMax;
  40355. interval = newInt;
  40356. // figure out the number of DPs needed to display all values at this
  40357. // interval setting.
  40358. numDecimalPlaces = 7;
  40359. if (newInt != 0)
  40360. {
  40361. int v = abs ((int) (newInt * 10000000));
  40362. while ((v % 10) == 0)
  40363. {
  40364. --numDecimalPlaces;
  40365. v /= 10;
  40366. }
  40367. }
  40368. // keep the current values inside the new range..
  40369. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40370. {
  40371. setValue (getValue(), false, false);
  40372. }
  40373. else
  40374. {
  40375. setMinValue (getMinValue(), false, false);
  40376. setMaxValue (getMaxValue(), false, false);
  40377. }
  40378. updateText();
  40379. }
  40380. }
  40381. void Slider::triggerChangeMessage (const bool synchronous)
  40382. {
  40383. if (synchronous)
  40384. handleAsyncUpdate();
  40385. else
  40386. triggerAsyncUpdate();
  40387. valueChanged();
  40388. }
  40389. void Slider::valueChanged (Value& value)
  40390. {
  40391. if (value.refersToSameSourceAs (currentValue))
  40392. {
  40393. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40394. setValue (currentValue.getValue(), false, false);
  40395. }
  40396. else if (value.refersToSameSourceAs (valueMin))
  40397. setMinValue (valueMin.getValue(), false, false, true);
  40398. else if (value.refersToSameSourceAs (valueMax))
  40399. setMaxValue (valueMax.getValue(), false, false, true);
  40400. }
  40401. double Slider::getValue() const
  40402. {
  40403. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40404. // methods to get the two values.
  40405. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40406. return currentValue.getValue();
  40407. }
  40408. void Slider::setValue (double newValue,
  40409. const bool sendUpdateMessage,
  40410. const bool sendMessageSynchronously)
  40411. {
  40412. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40413. // methods to set the two values.
  40414. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40415. newValue = constrainedValue (newValue);
  40416. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40417. {
  40418. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40419. newValue = jlimit ((double) valueMin.getValue(),
  40420. (double) valueMax.getValue(),
  40421. newValue);
  40422. }
  40423. if (newValue != lastCurrentValue)
  40424. {
  40425. if (valueBox != 0)
  40426. valueBox->hideEditor (true);
  40427. lastCurrentValue = newValue;
  40428. currentValue = newValue;
  40429. updateText();
  40430. repaint();
  40431. if (popupDisplay != 0)
  40432. {
  40433. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40434. ->updatePosition (getTextFromValue (newValue));
  40435. popupDisplay->repaint();
  40436. }
  40437. if (sendUpdateMessage)
  40438. triggerChangeMessage (sendMessageSynchronously);
  40439. }
  40440. }
  40441. double Slider::getMinValue() const
  40442. {
  40443. // The minimum value only applies to sliders that are in two- or three-value mode.
  40444. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40445. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40446. return valueMin.getValue();
  40447. }
  40448. double Slider::getMaxValue() const
  40449. {
  40450. // The maximum value only applies to sliders that are in two- or three-value mode.
  40451. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40452. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40453. return valueMax.getValue();
  40454. }
  40455. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40456. {
  40457. // The minimum value only applies to sliders that are in two- or three-value mode.
  40458. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40459. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40460. newValue = constrainedValue (newValue);
  40461. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40462. {
  40463. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40464. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40465. newValue = jmin ((double) valueMax.getValue(), newValue);
  40466. }
  40467. else
  40468. {
  40469. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40470. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40471. newValue = jmin (lastCurrentValue, newValue);
  40472. }
  40473. if (lastValueMin != newValue)
  40474. {
  40475. lastValueMin = newValue;
  40476. valueMin = newValue;
  40477. repaint();
  40478. if (popupDisplay != 0)
  40479. {
  40480. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40481. ->updatePosition (getTextFromValue (newValue));
  40482. popupDisplay->repaint();
  40483. }
  40484. if (sendUpdateMessage)
  40485. triggerChangeMessage (sendMessageSynchronously);
  40486. }
  40487. }
  40488. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40489. {
  40490. // The maximum value only applies to sliders that are in two- or three-value mode.
  40491. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40492. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40493. newValue = constrainedValue (newValue);
  40494. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40495. {
  40496. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40497. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40498. newValue = jmax ((double) valueMin.getValue(), newValue);
  40499. }
  40500. else
  40501. {
  40502. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40503. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40504. newValue = jmax (lastCurrentValue, newValue);
  40505. }
  40506. if (lastValueMax != newValue)
  40507. {
  40508. lastValueMax = newValue;
  40509. valueMax = newValue;
  40510. repaint();
  40511. if (popupDisplay != 0)
  40512. {
  40513. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40514. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40515. popupDisplay->repaint();
  40516. }
  40517. if (sendUpdateMessage)
  40518. triggerChangeMessage (sendMessageSynchronously);
  40519. }
  40520. }
  40521. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40522. const double valueToSetOnDoubleClick)
  40523. {
  40524. doubleClickToValue = isDoubleClickEnabled;
  40525. doubleClickReturnValue = valueToSetOnDoubleClick;
  40526. }
  40527. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40528. {
  40529. isEnabled_ = doubleClickToValue;
  40530. return doubleClickReturnValue;
  40531. }
  40532. void Slider::updateText()
  40533. {
  40534. if (valueBox != 0)
  40535. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40536. }
  40537. void Slider::setTextValueSuffix (const String& suffix)
  40538. {
  40539. if (textSuffix != suffix)
  40540. {
  40541. textSuffix = suffix;
  40542. updateText();
  40543. }
  40544. }
  40545. const String Slider::getTextValueSuffix() const
  40546. {
  40547. return textSuffix;
  40548. }
  40549. const String Slider::getTextFromValue (double v)
  40550. {
  40551. if (getNumDecimalPlacesToDisplay() > 0)
  40552. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40553. else
  40554. return String (roundToInt (v)) + getTextValueSuffix();
  40555. }
  40556. double Slider::getValueFromText (const String& text)
  40557. {
  40558. String t (text.trimStart());
  40559. if (t.endsWith (textSuffix))
  40560. t = t.substring (0, t.length() - textSuffix.length());
  40561. while (t.startsWithChar ('+'))
  40562. t = t.substring (1).trimStart();
  40563. return t.initialSectionContainingOnly ("0123456789.,-")
  40564. .getDoubleValue();
  40565. }
  40566. double Slider::proportionOfLengthToValue (double proportion)
  40567. {
  40568. if (skewFactor != 1.0 && proportion > 0.0)
  40569. proportion = exp (log (proportion) / skewFactor);
  40570. return minimum + (maximum - minimum) * proportion;
  40571. }
  40572. double Slider::valueToProportionOfLength (double value)
  40573. {
  40574. const double n = (value - minimum) / (maximum - minimum);
  40575. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40576. }
  40577. double Slider::snapValue (double attemptedValue, const bool)
  40578. {
  40579. return attemptedValue;
  40580. }
  40581. void Slider::startedDragging()
  40582. {
  40583. }
  40584. void Slider::stoppedDragging()
  40585. {
  40586. }
  40587. void Slider::valueChanged()
  40588. {
  40589. }
  40590. void Slider::enablementChanged()
  40591. {
  40592. repaint();
  40593. }
  40594. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40595. {
  40596. menuEnabled = menuEnabled_;
  40597. }
  40598. void Slider::setScrollWheelEnabled (const bool enabled)
  40599. {
  40600. scrollWheelEnabled = enabled;
  40601. }
  40602. void Slider::labelTextChanged (Label* label)
  40603. {
  40604. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40605. if (newValue != (double) currentValue.getValue())
  40606. {
  40607. sendDragStart();
  40608. setValue (newValue, true, true);
  40609. sendDragEnd();
  40610. }
  40611. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40612. }
  40613. void Slider::buttonClicked (Button* button)
  40614. {
  40615. if (style == IncDecButtons)
  40616. {
  40617. sendDragStart();
  40618. if (button == incButton)
  40619. setValue (snapValue (getValue() + interval, false), true, true);
  40620. else if (button == decButton)
  40621. setValue (snapValue (getValue() - interval, false), true, true);
  40622. sendDragEnd();
  40623. }
  40624. }
  40625. double Slider::constrainedValue (double value) const
  40626. {
  40627. if (interval > 0)
  40628. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40629. if (value <= minimum || maximum <= minimum)
  40630. value = minimum;
  40631. else if (value >= maximum)
  40632. value = maximum;
  40633. return value;
  40634. }
  40635. float Slider::getLinearSliderPos (const double value)
  40636. {
  40637. double sliderPosProportional;
  40638. if (maximum > minimum)
  40639. {
  40640. if (value < minimum)
  40641. {
  40642. sliderPosProportional = 0.0;
  40643. }
  40644. else if (value > maximum)
  40645. {
  40646. sliderPosProportional = 1.0;
  40647. }
  40648. else
  40649. {
  40650. sliderPosProportional = valueToProportionOfLength (value);
  40651. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40652. }
  40653. }
  40654. else
  40655. {
  40656. sliderPosProportional = 0.5;
  40657. }
  40658. if (isVertical() || style == IncDecButtons)
  40659. sliderPosProportional = 1.0 - sliderPosProportional;
  40660. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40661. }
  40662. bool Slider::isHorizontal() const
  40663. {
  40664. return style == LinearHorizontal
  40665. || style == LinearBar
  40666. || style == TwoValueHorizontal
  40667. || style == ThreeValueHorizontal;
  40668. }
  40669. bool Slider::isVertical() const
  40670. {
  40671. return style == LinearVertical
  40672. || style == TwoValueVertical
  40673. || style == ThreeValueVertical;
  40674. }
  40675. bool Slider::incDecDragDirectionIsHorizontal() const
  40676. {
  40677. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40678. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40679. }
  40680. float Slider::getPositionOfValue (const double value)
  40681. {
  40682. if (isHorizontal() || isVertical())
  40683. {
  40684. return getLinearSliderPos (value);
  40685. }
  40686. else
  40687. {
  40688. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40689. return 0.0f;
  40690. }
  40691. }
  40692. void Slider::paint (Graphics& g)
  40693. {
  40694. if (style != IncDecButtons)
  40695. {
  40696. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40697. {
  40698. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40699. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40700. getLookAndFeel().drawRotarySlider (g,
  40701. sliderRect.getX(),
  40702. sliderRect.getY(),
  40703. sliderRect.getWidth(),
  40704. sliderRect.getHeight(),
  40705. sliderPos,
  40706. rotaryStart, rotaryEnd,
  40707. *this);
  40708. }
  40709. else
  40710. {
  40711. getLookAndFeel().drawLinearSlider (g,
  40712. sliderRect.getX(),
  40713. sliderRect.getY(),
  40714. sliderRect.getWidth(),
  40715. sliderRect.getHeight(),
  40716. getLinearSliderPos (lastCurrentValue),
  40717. getLinearSliderPos (lastValueMin),
  40718. getLinearSliderPos (lastValueMax),
  40719. style,
  40720. *this);
  40721. }
  40722. if (style == LinearBar && valueBox == 0)
  40723. {
  40724. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40725. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40726. }
  40727. }
  40728. }
  40729. void Slider::resized()
  40730. {
  40731. int minXSpace = 0;
  40732. int minYSpace = 0;
  40733. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40734. minXSpace = 30;
  40735. else
  40736. minYSpace = 15;
  40737. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40738. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40739. if (style == LinearBar)
  40740. {
  40741. if (valueBox != 0)
  40742. valueBox->setBounds (getLocalBounds());
  40743. }
  40744. else
  40745. {
  40746. if (textBoxPos == NoTextBox)
  40747. {
  40748. sliderRect = getLocalBounds();
  40749. }
  40750. else if (textBoxPos == TextBoxLeft)
  40751. {
  40752. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40753. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40754. }
  40755. else if (textBoxPos == TextBoxRight)
  40756. {
  40757. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40758. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40759. }
  40760. else if (textBoxPos == TextBoxAbove)
  40761. {
  40762. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40763. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40764. }
  40765. else if (textBoxPos == TextBoxBelow)
  40766. {
  40767. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40768. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40769. }
  40770. }
  40771. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40772. if (style == LinearBar)
  40773. {
  40774. const int barIndent = 1;
  40775. sliderRegionStart = barIndent;
  40776. sliderRegionSize = getWidth() - barIndent * 2;
  40777. sliderRect.setBounds (sliderRegionStart, barIndent,
  40778. sliderRegionSize, getHeight() - barIndent * 2);
  40779. }
  40780. else if (isHorizontal())
  40781. {
  40782. sliderRegionStart = sliderRect.getX() + indent;
  40783. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40784. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40785. sliderRegionSize, sliderRect.getHeight());
  40786. }
  40787. else if (isVertical())
  40788. {
  40789. sliderRegionStart = sliderRect.getY() + indent;
  40790. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40791. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40792. sliderRect.getWidth(), sliderRegionSize);
  40793. }
  40794. else
  40795. {
  40796. sliderRegionStart = 0;
  40797. sliderRegionSize = 100;
  40798. }
  40799. if (style == IncDecButtons)
  40800. {
  40801. Rectangle<int> buttonRect (sliderRect);
  40802. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40803. buttonRect.expand (-2, 0);
  40804. else
  40805. buttonRect.expand (0, -2);
  40806. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40807. if (incDecButtonsSideBySide)
  40808. {
  40809. decButton->setBounds (buttonRect.getX(),
  40810. buttonRect.getY(),
  40811. buttonRect.getWidth() / 2,
  40812. buttonRect.getHeight());
  40813. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40814. incButton->setBounds (buttonRect.getCentreX(),
  40815. buttonRect.getY(),
  40816. buttonRect.getWidth() / 2,
  40817. buttonRect.getHeight());
  40818. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40819. }
  40820. else
  40821. {
  40822. incButton->setBounds (buttonRect.getX(),
  40823. buttonRect.getY(),
  40824. buttonRect.getWidth(),
  40825. buttonRect.getHeight() / 2);
  40826. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40827. decButton->setBounds (buttonRect.getX(),
  40828. buttonRect.getCentreY(),
  40829. buttonRect.getWidth(),
  40830. buttonRect.getHeight() / 2);
  40831. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40832. }
  40833. }
  40834. }
  40835. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40836. {
  40837. repaint();
  40838. }
  40839. void Slider::mouseDown (const MouseEvent& e)
  40840. {
  40841. mouseWasHidden = false;
  40842. incDecDragged = false;
  40843. mouseXWhenLastDragged = e.x;
  40844. mouseYWhenLastDragged = e.y;
  40845. mouseDragStartX = e.getMouseDownX();
  40846. mouseDragStartY = e.getMouseDownY();
  40847. if (isEnabled())
  40848. {
  40849. if (e.mods.isPopupMenu() && menuEnabled)
  40850. {
  40851. menuShown = true;
  40852. PopupMenu m;
  40853. m.setLookAndFeel (&getLookAndFeel());
  40854. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40855. m.addSeparator();
  40856. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40857. {
  40858. PopupMenu rotaryMenu;
  40859. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40860. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40861. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40862. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40863. }
  40864. const int r = m.show();
  40865. if (r == 1)
  40866. {
  40867. setVelocityBasedMode (! isVelocityBased);
  40868. }
  40869. else if (r == 2)
  40870. {
  40871. setSliderStyle (Rotary);
  40872. }
  40873. else if (r == 3)
  40874. {
  40875. setSliderStyle (RotaryHorizontalDrag);
  40876. }
  40877. else if (r == 4)
  40878. {
  40879. setSliderStyle (RotaryVerticalDrag);
  40880. }
  40881. }
  40882. else if (maximum > minimum)
  40883. {
  40884. menuShown = false;
  40885. if (valueBox != 0)
  40886. valueBox->hideEditor (true);
  40887. sliderBeingDragged = 0;
  40888. if (style == TwoValueHorizontal
  40889. || style == TwoValueVertical
  40890. || style == ThreeValueHorizontal
  40891. || style == ThreeValueVertical)
  40892. {
  40893. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40894. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40895. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40896. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40897. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40898. {
  40899. if (maxPosDistance <= minPosDistance)
  40900. sliderBeingDragged = 2;
  40901. else
  40902. sliderBeingDragged = 1;
  40903. }
  40904. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40905. {
  40906. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40907. sliderBeingDragged = 1;
  40908. else if (normalPosDistance >= maxPosDistance)
  40909. sliderBeingDragged = 2;
  40910. }
  40911. }
  40912. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40913. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40914. * valueToProportionOfLength (currentValue.getValue());
  40915. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40916. : ((sliderBeingDragged == 1) ? valueMin
  40917. : currentValue)).getValue();
  40918. valueOnMouseDown = valueWhenLastDragged;
  40919. if (popupDisplayEnabled)
  40920. {
  40921. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40922. popupDisplay = popup;
  40923. if (parentForPopupDisplay != 0)
  40924. {
  40925. parentForPopupDisplay->addChildComponent (popup);
  40926. }
  40927. else
  40928. {
  40929. popup->addToDesktop (0);
  40930. }
  40931. popup->setVisible (true);
  40932. }
  40933. sendDragStart();
  40934. mouseDrag (e);
  40935. }
  40936. }
  40937. }
  40938. void Slider::mouseUp (const MouseEvent&)
  40939. {
  40940. if (isEnabled()
  40941. && (! menuShown)
  40942. && (maximum > minimum)
  40943. && (style != IncDecButtons || incDecDragged))
  40944. {
  40945. restoreMouseIfHidden();
  40946. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40947. triggerChangeMessage (false);
  40948. sendDragEnd();
  40949. popupDisplay = 0;
  40950. if (style == IncDecButtons)
  40951. {
  40952. incButton->setState (Button::buttonNormal);
  40953. decButton->setState (Button::buttonNormal);
  40954. }
  40955. }
  40956. }
  40957. void Slider::restoreMouseIfHidden()
  40958. {
  40959. if (mouseWasHidden)
  40960. {
  40961. mouseWasHidden = false;
  40962. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40963. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40964. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40965. : ((sliderBeingDragged == 1) ? getMinValue()
  40966. : (double) currentValue.getValue());
  40967. Point<int> mousePos;
  40968. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40969. {
  40970. mousePos = Desktop::getLastMouseDownPosition();
  40971. if (style == RotaryHorizontalDrag)
  40972. {
  40973. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40974. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40975. }
  40976. else
  40977. {
  40978. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40979. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40980. }
  40981. }
  40982. else
  40983. {
  40984. const int pixelPos = (int) getLinearSliderPos (pos);
  40985. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40986. isVertical() ? pixelPos : (getHeight() / 2)));
  40987. }
  40988. Desktop::setMousePosition (mousePos);
  40989. }
  40990. }
  40991. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40992. {
  40993. if (isEnabled()
  40994. && style != IncDecButtons
  40995. && style != Rotary
  40996. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40997. {
  40998. restoreMouseIfHidden();
  40999. }
  41000. }
  41001. static double smallestAngleBetween (double a1, double a2)
  41002. {
  41003. return jmin (std::abs (a1 - a2),
  41004. std::abs (a1 + double_Pi * 2.0 - a2),
  41005. std::abs (a2 + double_Pi * 2.0 - a1));
  41006. }
  41007. void Slider::mouseDrag (const MouseEvent& e)
  41008. {
  41009. if (isEnabled()
  41010. && (! menuShown)
  41011. && (maximum > minimum))
  41012. {
  41013. if (style == Rotary)
  41014. {
  41015. int dx = e.x - sliderRect.getCentreX();
  41016. int dy = e.y - sliderRect.getCentreY();
  41017. if (dx * dx + dy * dy > 25)
  41018. {
  41019. double angle = std::atan2 ((double) dx, (double) -dy);
  41020. while (angle < 0.0)
  41021. angle += double_Pi * 2.0;
  41022. if (rotaryStop && ! e.mouseWasClicked())
  41023. {
  41024. if (std::abs (angle - lastAngle) > double_Pi)
  41025. {
  41026. if (angle >= lastAngle)
  41027. angle -= double_Pi * 2.0;
  41028. else
  41029. angle += double_Pi * 2.0;
  41030. }
  41031. if (angle >= lastAngle)
  41032. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  41033. else
  41034. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  41035. }
  41036. else
  41037. {
  41038. while (angle < rotaryStart)
  41039. angle += double_Pi * 2.0;
  41040. if (angle > rotaryEnd)
  41041. {
  41042. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  41043. angle = rotaryStart;
  41044. else
  41045. angle = rotaryEnd;
  41046. }
  41047. }
  41048. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  41049. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  41050. lastAngle = angle;
  41051. }
  41052. }
  41053. else
  41054. {
  41055. if (style == LinearBar && e.mouseWasClicked()
  41056. && valueBox != 0 && valueBox->isEditable())
  41057. return;
  41058. if (style == IncDecButtons && ! incDecDragged)
  41059. {
  41060. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  41061. return;
  41062. incDecDragged = true;
  41063. mouseDragStartX = e.x;
  41064. mouseDragStartY = e.y;
  41065. }
  41066. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  41067. : false))
  41068. || ((maximum - minimum) / sliderRegionSize < interval))
  41069. {
  41070. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  41071. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  41072. if (style == RotaryHorizontalDrag
  41073. || style == RotaryVerticalDrag
  41074. || style == IncDecButtons
  41075. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  41076. && ! snapsToMousePos))
  41077. {
  41078. const int mouseDiff = (style == RotaryHorizontalDrag
  41079. || style == LinearHorizontal
  41080. || style == LinearBar
  41081. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  41082. ? e.x - mouseDragStartX
  41083. : mouseDragStartY - e.y;
  41084. double newPos = valueToProportionOfLength (valueOnMouseDown)
  41085. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  41086. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  41087. if (style == IncDecButtons)
  41088. {
  41089. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  41090. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  41091. }
  41092. }
  41093. else
  41094. {
  41095. if (isVertical())
  41096. scaledMousePos = 1.0 - scaledMousePos;
  41097. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  41098. }
  41099. }
  41100. else
  41101. {
  41102. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  41103. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  41104. ? e.x - mouseXWhenLastDragged
  41105. : e.y - mouseYWhenLastDragged;
  41106. const double maxSpeed = jmax (200, sliderRegionSize);
  41107. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  41108. if (speed != 0)
  41109. {
  41110. speed = 0.2 * velocityModeSensitivity
  41111. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  41112. + jmax (0.0, (double) (speed - velocityModeThreshold))
  41113. / maxSpeed))));
  41114. if (mouseDiff < 0)
  41115. speed = -speed;
  41116. if (isVertical() || style == RotaryVerticalDrag
  41117. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  41118. speed = -speed;
  41119. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  41120. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  41121. e.source.enableUnboundedMouseMovement (true, false);
  41122. mouseWasHidden = true;
  41123. }
  41124. }
  41125. }
  41126. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  41127. if (sliderBeingDragged == 0)
  41128. {
  41129. setValue (snapValue (valueWhenLastDragged, true),
  41130. ! sendChangeOnlyOnRelease, true);
  41131. }
  41132. else if (sliderBeingDragged == 1)
  41133. {
  41134. setMinValue (snapValue (valueWhenLastDragged, true),
  41135. ! sendChangeOnlyOnRelease, false, true);
  41136. if (e.mods.isShiftDown())
  41137. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  41138. else
  41139. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41140. }
  41141. else
  41142. {
  41143. jassert (sliderBeingDragged == 2);
  41144. setMaxValue (snapValue (valueWhenLastDragged, true),
  41145. ! sendChangeOnlyOnRelease, false, true);
  41146. if (e.mods.isShiftDown())
  41147. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  41148. else
  41149. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41150. }
  41151. mouseXWhenLastDragged = e.x;
  41152. mouseYWhenLastDragged = e.y;
  41153. }
  41154. }
  41155. void Slider::mouseDoubleClick (const MouseEvent&)
  41156. {
  41157. if (doubleClickToValue
  41158. && isEnabled()
  41159. && style != IncDecButtons
  41160. && minimum <= doubleClickReturnValue
  41161. && maximum >= doubleClickReturnValue)
  41162. {
  41163. sendDragStart();
  41164. setValue (doubleClickReturnValue, true, true);
  41165. sendDragEnd();
  41166. }
  41167. }
  41168. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  41169. {
  41170. if (scrollWheelEnabled && isEnabled()
  41171. && style != TwoValueHorizontal
  41172. && style != TwoValueVertical)
  41173. {
  41174. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  41175. {
  41176. if (valueBox != 0)
  41177. valueBox->hideEditor (false);
  41178. const double value = (double) currentValue.getValue();
  41179. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  41180. const double currentPos = valueToProportionOfLength (value);
  41181. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  41182. double delta = (newValue != value)
  41183. ? jmax (std::abs (newValue - value), interval) : 0;
  41184. if (value > newValue)
  41185. delta = -delta;
  41186. sendDragStart();
  41187. setValue (snapValue (value + delta, false), true, true);
  41188. sendDragEnd();
  41189. }
  41190. }
  41191. else
  41192. {
  41193. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  41194. }
  41195. }
  41196. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  41197. {
  41198. }
  41199. void SliderListener::sliderDragEnded (Slider*)
  41200. {
  41201. }
  41202. END_JUCE_NAMESPACE
  41203. /*** End of inlined file: juce_Slider.cpp ***/
  41204. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  41205. BEGIN_JUCE_NAMESPACE
  41206. class DragOverlayComp : public Component
  41207. {
  41208. public:
  41209. DragOverlayComp (const Image& image_)
  41210. : image (image_)
  41211. {
  41212. image.duplicateIfShared();
  41213. image.multiplyAllAlphas (0.8f);
  41214. setAlwaysOnTop (true);
  41215. }
  41216. ~DragOverlayComp()
  41217. {
  41218. }
  41219. void paint (Graphics& g)
  41220. {
  41221. g.drawImageAt (image, 0, 0);
  41222. }
  41223. private:
  41224. Image image;
  41225. DragOverlayComp (const DragOverlayComp&);
  41226. DragOverlayComp& operator= (const DragOverlayComp&);
  41227. };
  41228. TableHeaderComponent::TableHeaderComponent()
  41229. : columnsChanged (false),
  41230. columnsResized (false),
  41231. sortChanged (false),
  41232. menuActive (true),
  41233. stretchToFit (false),
  41234. columnIdBeingResized (0),
  41235. columnIdBeingDragged (0),
  41236. columnIdUnderMouse (0),
  41237. lastDeliberateWidth (0)
  41238. {
  41239. }
  41240. TableHeaderComponent::~TableHeaderComponent()
  41241. {
  41242. dragOverlayComp = 0;
  41243. }
  41244. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41245. {
  41246. menuActive = hasMenu;
  41247. }
  41248. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41249. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41250. {
  41251. if (onlyCountVisibleColumns)
  41252. {
  41253. int num = 0;
  41254. for (int i = columns.size(); --i >= 0;)
  41255. if (columns.getUnchecked(i)->isVisible())
  41256. ++num;
  41257. return num;
  41258. }
  41259. else
  41260. {
  41261. return columns.size();
  41262. }
  41263. }
  41264. const String TableHeaderComponent::getColumnName (const int columnId) const
  41265. {
  41266. const ColumnInfo* const ci = getInfoForId (columnId);
  41267. return ci != 0 ? ci->name : String::empty;
  41268. }
  41269. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41270. {
  41271. ColumnInfo* const ci = getInfoForId (columnId);
  41272. if (ci != 0 && ci->name != newName)
  41273. {
  41274. ci->name = newName;
  41275. sendColumnsChanged();
  41276. }
  41277. }
  41278. void TableHeaderComponent::addColumn (const String& columnName,
  41279. const int columnId,
  41280. const int width,
  41281. const int minimumWidth,
  41282. const int maximumWidth,
  41283. const int propertyFlags,
  41284. const int insertIndex)
  41285. {
  41286. // can't have a duplicate or null ID!
  41287. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41288. jassert (width > 0);
  41289. ColumnInfo* const ci = new ColumnInfo();
  41290. ci->name = columnName;
  41291. ci->id = columnId;
  41292. ci->width = width;
  41293. ci->lastDeliberateWidth = width;
  41294. ci->minimumWidth = minimumWidth;
  41295. ci->maximumWidth = maximumWidth;
  41296. if (ci->maximumWidth < 0)
  41297. ci->maximumWidth = std::numeric_limits<int>::max();
  41298. jassert (ci->maximumWidth >= ci->minimumWidth);
  41299. ci->propertyFlags = propertyFlags;
  41300. columns.insert (insertIndex, ci);
  41301. sendColumnsChanged();
  41302. }
  41303. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41304. {
  41305. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41306. if (index >= 0)
  41307. {
  41308. columns.remove (index);
  41309. sortChanged = true;
  41310. sendColumnsChanged();
  41311. }
  41312. }
  41313. void TableHeaderComponent::removeAllColumns()
  41314. {
  41315. if (columns.size() > 0)
  41316. {
  41317. columns.clear();
  41318. sendColumnsChanged();
  41319. }
  41320. }
  41321. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41322. {
  41323. const int currentIndex = getIndexOfColumnId (columnId, false);
  41324. newIndex = visibleIndexToTotalIndex (newIndex);
  41325. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41326. {
  41327. columns.move (currentIndex, newIndex);
  41328. sendColumnsChanged();
  41329. }
  41330. }
  41331. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41332. {
  41333. const ColumnInfo* const ci = getInfoForId (columnId);
  41334. return ci != 0 ? ci->width : 0;
  41335. }
  41336. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41337. {
  41338. ColumnInfo* const ci = getInfoForId (columnId);
  41339. if (ci != 0 && ci->width != newWidth)
  41340. {
  41341. const int numColumns = getNumColumns (true);
  41342. ci->lastDeliberateWidth = ci->width
  41343. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41344. if (stretchToFit)
  41345. {
  41346. const int index = getIndexOfColumnId (columnId, true) + 1;
  41347. if (((unsigned int) index) < (unsigned int) numColumns)
  41348. {
  41349. const int x = getColumnPosition (index).getX();
  41350. if (lastDeliberateWidth == 0)
  41351. lastDeliberateWidth = getTotalWidth();
  41352. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41353. }
  41354. }
  41355. repaint();
  41356. columnsResized = true;
  41357. triggerAsyncUpdate();
  41358. }
  41359. }
  41360. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41361. {
  41362. int n = 0;
  41363. for (int i = 0; i < columns.size(); ++i)
  41364. {
  41365. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41366. {
  41367. if (columns.getUnchecked(i)->id == columnId)
  41368. return n;
  41369. ++n;
  41370. }
  41371. }
  41372. return -1;
  41373. }
  41374. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41375. {
  41376. if (onlyCountVisibleColumns)
  41377. index = visibleIndexToTotalIndex (index);
  41378. const ColumnInfo* const ci = columns [index];
  41379. return (ci != 0) ? ci->id : 0;
  41380. }
  41381. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41382. {
  41383. int x = 0, width = 0, n = 0;
  41384. for (int i = 0; i < columns.size(); ++i)
  41385. {
  41386. x += width;
  41387. if (columns.getUnchecked(i)->isVisible())
  41388. {
  41389. width = columns.getUnchecked(i)->width;
  41390. if (n++ == index)
  41391. break;
  41392. }
  41393. else
  41394. {
  41395. width = 0;
  41396. }
  41397. }
  41398. return Rectangle<int> (x, 0, width, getHeight());
  41399. }
  41400. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41401. {
  41402. if (xToFind >= 0)
  41403. {
  41404. int x = 0;
  41405. for (int i = 0; i < columns.size(); ++i)
  41406. {
  41407. const ColumnInfo* const ci = columns.getUnchecked(i);
  41408. if (ci->isVisible())
  41409. {
  41410. x += ci->width;
  41411. if (xToFind < x)
  41412. return ci->id;
  41413. }
  41414. }
  41415. }
  41416. return 0;
  41417. }
  41418. int TableHeaderComponent::getTotalWidth() const
  41419. {
  41420. int w = 0;
  41421. for (int i = columns.size(); --i >= 0;)
  41422. if (columns.getUnchecked(i)->isVisible())
  41423. w += columns.getUnchecked(i)->width;
  41424. return w;
  41425. }
  41426. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41427. {
  41428. stretchToFit = shouldStretchToFit;
  41429. lastDeliberateWidth = getTotalWidth();
  41430. resized();
  41431. }
  41432. bool TableHeaderComponent::isStretchToFitActive() const
  41433. {
  41434. return stretchToFit;
  41435. }
  41436. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41437. {
  41438. if (stretchToFit && getWidth() > 0
  41439. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41440. {
  41441. lastDeliberateWidth = targetTotalWidth;
  41442. resizeColumnsToFit (0, targetTotalWidth);
  41443. }
  41444. }
  41445. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41446. {
  41447. targetTotalWidth = jmax (targetTotalWidth, 0);
  41448. StretchableObjectResizer sor;
  41449. int i;
  41450. for (i = firstColumnIndex; i < columns.size(); ++i)
  41451. {
  41452. ColumnInfo* const ci = columns.getUnchecked(i);
  41453. if (ci->isVisible())
  41454. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41455. }
  41456. sor.resizeToFit (targetTotalWidth);
  41457. int visIndex = 0;
  41458. for (i = firstColumnIndex; i < columns.size(); ++i)
  41459. {
  41460. ColumnInfo* const ci = columns.getUnchecked(i);
  41461. if (ci->isVisible())
  41462. {
  41463. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41464. (int) std::floor (sor.getItemSize (visIndex++)));
  41465. if (newWidth != ci->width)
  41466. {
  41467. ci->width = newWidth;
  41468. repaint();
  41469. columnsResized = true;
  41470. triggerAsyncUpdate();
  41471. }
  41472. }
  41473. }
  41474. }
  41475. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41476. {
  41477. ColumnInfo* const ci = getInfoForId (columnId);
  41478. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41479. {
  41480. if (shouldBeVisible)
  41481. ci->propertyFlags |= visible;
  41482. else
  41483. ci->propertyFlags &= ~visible;
  41484. sendColumnsChanged();
  41485. resized();
  41486. }
  41487. }
  41488. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41489. {
  41490. const ColumnInfo* const ci = getInfoForId (columnId);
  41491. return ci != 0 && ci->isVisible();
  41492. }
  41493. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41494. {
  41495. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41496. {
  41497. for (int i = columns.size(); --i >= 0;)
  41498. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41499. ColumnInfo* const ci = getInfoForId (columnId);
  41500. if (ci != 0)
  41501. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41502. reSortTable();
  41503. }
  41504. }
  41505. int TableHeaderComponent::getSortColumnId() const
  41506. {
  41507. for (int i = columns.size(); --i >= 0;)
  41508. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41509. return columns.getUnchecked(i)->id;
  41510. return 0;
  41511. }
  41512. bool TableHeaderComponent::isSortedForwards() const
  41513. {
  41514. for (int i = columns.size(); --i >= 0;)
  41515. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41516. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41517. return true;
  41518. }
  41519. void TableHeaderComponent::reSortTable()
  41520. {
  41521. sortChanged = true;
  41522. repaint();
  41523. triggerAsyncUpdate();
  41524. }
  41525. const String TableHeaderComponent::toString() const
  41526. {
  41527. String s;
  41528. XmlElement doc ("TABLELAYOUT");
  41529. doc.setAttribute ("sortedCol", getSortColumnId());
  41530. doc.setAttribute ("sortForwards", isSortedForwards());
  41531. for (int i = 0; i < columns.size(); ++i)
  41532. {
  41533. const ColumnInfo* const ci = columns.getUnchecked (i);
  41534. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41535. e->setAttribute ("id", ci->id);
  41536. e->setAttribute ("visible", ci->isVisible());
  41537. e->setAttribute ("width", ci->width);
  41538. }
  41539. return doc.createDocument (String::empty, true, false);
  41540. }
  41541. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41542. {
  41543. XmlDocument doc (storedVersion);
  41544. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41545. int index = 0;
  41546. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41547. {
  41548. forEachXmlChildElement (*storedXml, col)
  41549. {
  41550. const int tabId = col->getIntAttribute ("id");
  41551. ColumnInfo* const ci = getInfoForId (tabId);
  41552. if (ci != 0)
  41553. {
  41554. columns.move (columns.indexOf (ci), index);
  41555. ci->width = col->getIntAttribute ("width");
  41556. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41557. }
  41558. ++index;
  41559. }
  41560. columnsResized = true;
  41561. sendColumnsChanged();
  41562. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41563. storedXml->getBoolAttribute ("sortForwards", true));
  41564. }
  41565. }
  41566. void TableHeaderComponent::addListener (Listener* const newListener)
  41567. {
  41568. listeners.addIfNotAlreadyThere (newListener);
  41569. }
  41570. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41571. {
  41572. listeners.removeValue (listenerToRemove);
  41573. }
  41574. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41575. {
  41576. const ColumnInfo* const ci = getInfoForId (columnId);
  41577. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41578. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41579. }
  41580. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41581. {
  41582. for (int i = 0; i < columns.size(); ++i)
  41583. {
  41584. const ColumnInfo* const ci = columns.getUnchecked(i);
  41585. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41586. menu.addItem (ci->id, ci->name,
  41587. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41588. isColumnVisible (ci->id));
  41589. }
  41590. }
  41591. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41592. {
  41593. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41594. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41595. }
  41596. void TableHeaderComponent::paint (Graphics& g)
  41597. {
  41598. LookAndFeel& lf = getLookAndFeel();
  41599. lf.drawTableHeaderBackground (g, *this);
  41600. const Rectangle<int> clip (g.getClipBounds());
  41601. int x = 0;
  41602. for (int i = 0; i < columns.size(); ++i)
  41603. {
  41604. const ColumnInfo* const ci = columns.getUnchecked(i);
  41605. if (ci->isVisible())
  41606. {
  41607. if (x + ci->width > clip.getX()
  41608. && (ci->id != columnIdBeingDragged
  41609. || dragOverlayComp == 0
  41610. || ! dragOverlayComp->isVisible()))
  41611. {
  41612. g.saveState();
  41613. g.setOrigin (x, 0);
  41614. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41615. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41616. ci->id == columnIdUnderMouse,
  41617. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41618. ci->propertyFlags);
  41619. g.restoreState();
  41620. }
  41621. x += ci->width;
  41622. if (x >= clip.getRight())
  41623. break;
  41624. }
  41625. }
  41626. }
  41627. void TableHeaderComponent::resized()
  41628. {
  41629. }
  41630. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41631. {
  41632. updateColumnUnderMouse (e.x, e.y);
  41633. }
  41634. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41635. {
  41636. updateColumnUnderMouse (e.x, e.y);
  41637. }
  41638. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41639. {
  41640. updateColumnUnderMouse (e.x, e.y);
  41641. }
  41642. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41643. {
  41644. repaint();
  41645. columnIdBeingResized = 0;
  41646. columnIdBeingDragged = 0;
  41647. if (columnIdUnderMouse != 0)
  41648. {
  41649. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41650. if (e.mods.isPopupMenu())
  41651. columnClicked (columnIdUnderMouse, e.mods);
  41652. }
  41653. if (menuActive && e.mods.isPopupMenu())
  41654. showColumnChooserMenu (columnIdUnderMouse);
  41655. }
  41656. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41657. {
  41658. if (columnIdBeingResized == 0
  41659. && columnIdBeingDragged == 0
  41660. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41661. {
  41662. dragOverlayComp = 0;
  41663. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41664. if (columnIdBeingResized != 0)
  41665. {
  41666. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41667. initialColumnWidth = ci->width;
  41668. }
  41669. else
  41670. {
  41671. beginDrag (e);
  41672. }
  41673. }
  41674. if (columnIdBeingResized != 0)
  41675. {
  41676. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41677. if (ci != 0)
  41678. {
  41679. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41680. initialColumnWidth + e.getDistanceFromDragStartX());
  41681. if (stretchToFit)
  41682. {
  41683. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41684. int minWidthOnRight = 0;
  41685. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41686. if (columns.getUnchecked (i)->isVisible())
  41687. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41688. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41689. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41690. }
  41691. setColumnWidth (columnIdBeingResized, w);
  41692. }
  41693. }
  41694. else if (columnIdBeingDragged != 0)
  41695. {
  41696. if (e.y >= -50 && e.y < getHeight() + 50)
  41697. {
  41698. if (dragOverlayComp != 0)
  41699. {
  41700. dragOverlayComp->setVisible (true);
  41701. dragOverlayComp->setBounds (jlimit (0,
  41702. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41703. e.x - draggingColumnOffset),
  41704. 0,
  41705. dragOverlayComp->getWidth(),
  41706. getHeight());
  41707. for (int i = columns.size(); --i >= 0;)
  41708. {
  41709. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41710. int newIndex = currentIndex;
  41711. if (newIndex > 0)
  41712. {
  41713. // if the previous column isn't draggable, we can't move our column
  41714. // past it, because that'd change the undraggable column's position..
  41715. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41716. if ((previous->propertyFlags & draggable) != 0)
  41717. {
  41718. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41719. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41720. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41721. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41722. {
  41723. --newIndex;
  41724. }
  41725. }
  41726. }
  41727. if (newIndex < columns.size() - 1)
  41728. {
  41729. // if the next column isn't draggable, we can't move our column
  41730. // past it, because that'd change the undraggable column's position..
  41731. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41732. if ((nextCol->propertyFlags & draggable) != 0)
  41733. {
  41734. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41735. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41736. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41737. > abs (dragOverlayComp->getRight() - rightOfNext))
  41738. {
  41739. ++newIndex;
  41740. }
  41741. }
  41742. }
  41743. if (newIndex != currentIndex)
  41744. moveColumn (columnIdBeingDragged, newIndex);
  41745. else
  41746. break;
  41747. }
  41748. }
  41749. }
  41750. else
  41751. {
  41752. endDrag (draggingColumnOriginalIndex);
  41753. }
  41754. }
  41755. }
  41756. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41757. {
  41758. if (columnIdBeingDragged == 0)
  41759. {
  41760. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41761. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41762. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41763. {
  41764. columnIdBeingDragged = 0;
  41765. }
  41766. else
  41767. {
  41768. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41769. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41770. const int temp = columnIdBeingDragged;
  41771. columnIdBeingDragged = 0;
  41772. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41773. columnIdBeingDragged = temp;
  41774. dragOverlayComp->setBounds (columnRect);
  41775. for (int i = listeners.size(); --i >= 0;)
  41776. {
  41777. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41778. i = jmin (i, listeners.size() - 1);
  41779. }
  41780. }
  41781. }
  41782. }
  41783. void TableHeaderComponent::endDrag (const int finalIndex)
  41784. {
  41785. if (columnIdBeingDragged != 0)
  41786. {
  41787. moveColumn (columnIdBeingDragged, finalIndex);
  41788. columnIdBeingDragged = 0;
  41789. repaint();
  41790. for (int i = listeners.size(); --i >= 0;)
  41791. {
  41792. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41793. i = jmin (i, listeners.size() - 1);
  41794. }
  41795. }
  41796. }
  41797. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41798. {
  41799. mouseDrag (e);
  41800. for (int i = columns.size(); --i >= 0;)
  41801. if (columns.getUnchecked (i)->isVisible())
  41802. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41803. columnIdBeingResized = 0;
  41804. repaint();
  41805. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41806. updateColumnUnderMouse (e.x, e.y);
  41807. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41808. columnClicked (columnIdUnderMouse, e.mods);
  41809. dragOverlayComp = 0;
  41810. }
  41811. const MouseCursor TableHeaderComponent::getMouseCursor()
  41812. {
  41813. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41814. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41815. return Component::getMouseCursor();
  41816. }
  41817. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41818. {
  41819. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41820. }
  41821. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41822. {
  41823. for (int i = columns.size(); --i >= 0;)
  41824. if (columns.getUnchecked(i)->id == id)
  41825. return columns.getUnchecked(i);
  41826. return 0;
  41827. }
  41828. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41829. {
  41830. int n = 0;
  41831. for (int i = 0; i < columns.size(); ++i)
  41832. {
  41833. if (columns.getUnchecked(i)->isVisible())
  41834. {
  41835. if (n == visibleIndex)
  41836. return i;
  41837. ++n;
  41838. }
  41839. }
  41840. return -1;
  41841. }
  41842. void TableHeaderComponent::sendColumnsChanged()
  41843. {
  41844. if (stretchToFit && lastDeliberateWidth > 0)
  41845. resizeAllColumnsToFit (lastDeliberateWidth);
  41846. repaint();
  41847. columnsChanged = true;
  41848. triggerAsyncUpdate();
  41849. }
  41850. void TableHeaderComponent::handleAsyncUpdate()
  41851. {
  41852. const bool changed = columnsChanged || sortChanged;
  41853. const bool sized = columnsResized || changed;
  41854. const bool sorted = sortChanged;
  41855. columnsChanged = false;
  41856. columnsResized = false;
  41857. sortChanged = false;
  41858. if (sorted)
  41859. {
  41860. for (int i = listeners.size(); --i >= 0;)
  41861. {
  41862. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41863. i = jmin (i, listeners.size() - 1);
  41864. }
  41865. }
  41866. if (changed)
  41867. {
  41868. for (int i = listeners.size(); --i >= 0;)
  41869. {
  41870. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41871. i = jmin (i, listeners.size() - 1);
  41872. }
  41873. }
  41874. if (sized)
  41875. {
  41876. for (int i = listeners.size(); --i >= 0;)
  41877. {
  41878. listeners.getUnchecked(i)->tableColumnsResized (this);
  41879. i = jmin (i, listeners.size() - 1);
  41880. }
  41881. }
  41882. }
  41883. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41884. {
  41885. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41886. {
  41887. const int draggableDistance = 3;
  41888. int x = 0;
  41889. for (int i = 0; i < columns.size(); ++i)
  41890. {
  41891. const ColumnInfo* const ci = columns.getUnchecked(i);
  41892. if (ci->isVisible())
  41893. {
  41894. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41895. && (ci->propertyFlags & resizable) != 0)
  41896. return ci->id;
  41897. x += ci->width;
  41898. }
  41899. }
  41900. }
  41901. return 0;
  41902. }
  41903. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41904. {
  41905. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41906. ? getColumnIdAtX (x) : 0;
  41907. if (newCol != columnIdUnderMouse)
  41908. {
  41909. columnIdUnderMouse = newCol;
  41910. repaint();
  41911. }
  41912. }
  41913. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41914. {
  41915. PopupMenu m;
  41916. addMenuItems (m, columnIdClicked);
  41917. if (m.getNumItems() > 0)
  41918. {
  41919. m.setLookAndFeel (&getLookAndFeel());
  41920. const int result = m.show();
  41921. if (result != 0)
  41922. reactToMenuItem (result, columnIdClicked);
  41923. }
  41924. }
  41925. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41926. {
  41927. }
  41928. END_JUCE_NAMESPACE
  41929. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41930. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41931. BEGIN_JUCE_NAMESPACE
  41932. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41933. class TableListRowComp : public Component,
  41934. public TooltipClient
  41935. {
  41936. public:
  41937. TableListRowComp (TableListBox& owner_)
  41938. : owner (owner_),
  41939. row (-1),
  41940. isSelected (false)
  41941. {
  41942. }
  41943. ~TableListRowComp()
  41944. {
  41945. deleteAllChildren();
  41946. }
  41947. void paint (Graphics& g)
  41948. {
  41949. TableListBoxModel* const model = owner.getModel();
  41950. if (model != 0)
  41951. {
  41952. const TableHeaderComponent* const header = owner.getHeader();
  41953. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41954. const int numColumns = header->getNumColumns (true);
  41955. for (int i = 0; i < numColumns; ++i)
  41956. {
  41957. if (! columnsWithComponents [i])
  41958. {
  41959. const int columnId = header->getColumnIdOfIndex (i, true);
  41960. Rectangle<int> columnRect (header->getColumnPosition (i));
  41961. columnRect.setSize (columnRect.getWidth(), getHeight());
  41962. g.saveState();
  41963. g.reduceClipRegion (columnRect);
  41964. g.setOrigin (columnRect.getX(), 0);
  41965. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41966. g.restoreState();
  41967. }
  41968. }
  41969. }
  41970. }
  41971. void update (const int newRow, const bool isNowSelected)
  41972. {
  41973. if (newRow != row || isNowSelected != isSelected)
  41974. {
  41975. row = newRow;
  41976. isSelected = isNowSelected;
  41977. repaint();
  41978. deleteAllChildren();
  41979. }
  41980. if (row < owner.getNumRows())
  41981. {
  41982. jassert (row >= 0);
  41983. const Identifier tagPropertyName ("_tableLastUseNum");
  41984. const int newTag = Random::getSystemRandom().nextInt();
  41985. const TableHeaderComponent* const header = owner.getHeader();
  41986. const int numColumns = header->getNumColumns (true);
  41987. columnsWithComponents.clear();
  41988. if (owner.getModel() != 0)
  41989. {
  41990. for (int i = 0; i < numColumns; ++i)
  41991. {
  41992. const int columnId = header->getColumnIdOfIndex (i, true);
  41993. Component* const newComp
  41994. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41995. findChildComponentForColumn (columnId));
  41996. if (newComp != 0)
  41997. {
  41998. addAndMakeVisible (newComp);
  41999. newComp->getProperties().set (tagPropertyName, newTag);
  42000. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  42001. const Rectangle<int> columnRect (header->getColumnPosition (i));
  42002. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  42003. columnsWithComponents.setBit (i);
  42004. }
  42005. }
  42006. }
  42007. for (int i = getNumChildComponents(); --i >= 0;)
  42008. {
  42009. Component* const c = getChildComponent (i);
  42010. if ((int) c->getProperties() [tagPropertyName] != newTag)
  42011. delete c;
  42012. }
  42013. }
  42014. else
  42015. {
  42016. columnsWithComponents.clear();
  42017. deleteAllChildren();
  42018. }
  42019. }
  42020. void resized()
  42021. {
  42022. for (int i = getNumChildComponents(); --i >= 0;)
  42023. {
  42024. Component* const c = getChildComponent (i);
  42025. const int columnId = c->getProperties() [tableColumnPropertyTag];
  42026. if (columnId != 0)
  42027. {
  42028. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  42029. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  42030. }
  42031. }
  42032. }
  42033. void mouseDown (const MouseEvent& e)
  42034. {
  42035. isDragging = false;
  42036. selectRowOnMouseUp = false;
  42037. if (isEnabled())
  42038. {
  42039. if (! isSelected)
  42040. {
  42041. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  42042. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  42043. if (columnId != 0 && owner.getModel() != 0)
  42044. owner.getModel()->cellClicked (row, columnId, e);
  42045. }
  42046. else
  42047. {
  42048. selectRowOnMouseUp = true;
  42049. }
  42050. }
  42051. }
  42052. void mouseDrag (const MouseEvent& e)
  42053. {
  42054. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  42055. {
  42056. const SparseSet<int> selectedRows (owner.getSelectedRows());
  42057. if (selectedRows.size() > 0)
  42058. {
  42059. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  42060. if (dragDescription.isNotEmpty())
  42061. {
  42062. isDragging = true;
  42063. owner.startDragAndDrop (e, dragDescription);
  42064. }
  42065. }
  42066. }
  42067. }
  42068. void mouseUp (const MouseEvent& e)
  42069. {
  42070. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  42071. {
  42072. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  42073. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  42074. if (columnId != 0 && owner.getModel() != 0)
  42075. owner.getModel()->cellClicked (row, columnId, e);
  42076. }
  42077. }
  42078. void mouseDoubleClick (const MouseEvent& e)
  42079. {
  42080. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  42081. if (columnId != 0 && owner.getModel() != 0)
  42082. owner.getModel()->cellDoubleClicked (row, columnId, e);
  42083. }
  42084. const String getTooltip()
  42085. {
  42086. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  42087. if (columnId != 0 && owner.getModel() != 0)
  42088. return owner.getModel()->getCellTooltip (row, columnId);
  42089. return String::empty;
  42090. }
  42091. Component* findChildComponentForColumn (const int columnId) const
  42092. {
  42093. for (int i = getNumChildComponents(); --i >= 0;)
  42094. {
  42095. Component* const c = getChildComponent (i);
  42096. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  42097. return c;
  42098. }
  42099. return 0;
  42100. }
  42101. juce_UseDebuggingNewOperator
  42102. private:
  42103. TableListBox& owner;
  42104. int row;
  42105. bool isSelected, isDragging, selectRowOnMouseUp;
  42106. BigInteger columnsWithComponents;
  42107. TableListRowComp (const TableListRowComp&);
  42108. TableListRowComp& operator= (const TableListRowComp&);
  42109. };
  42110. class TableListBoxHeader : public TableHeaderComponent
  42111. {
  42112. public:
  42113. TableListBoxHeader (TableListBox& owner_)
  42114. : owner (owner_)
  42115. {
  42116. }
  42117. ~TableListBoxHeader()
  42118. {
  42119. }
  42120. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  42121. {
  42122. if (owner.isAutoSizeMenuOptionShown())
  42123. {
  42124. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  42125. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  42126. menu.addSeparator();
  42127. }
  42128. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  42129. }
  42130. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  42131. {
  42132. if (menuReturnId == 0xf836743)
  42133. {
  42134. owner.autoSizeColumn (columnIdClicked);
  42135. }
  42136. else if (menuReturnId == 0xf836744)
  42137. {
  42138. owner.autoSizeAllColumns();
  42139. }
  42140. else
  42141. {
  42142. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  42143. }
  42144. }
  42145. juce_UseDebuggingNewOperator
  42146. private:
  42147. TableListBox& owner;
  42148. TableListBoxHeader (const TableListBoxHeader&);
  42149. TableListBoxHeader& operator= (const TableListBoxHeader&);
  42150. };
  42151. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  42152. : ListBox (name, 0),
  42153. model (model_),
  42154. autoSizeOptionsShown (true)
  42155. {
  42156. ListBox::model = this;
  42157. header = new TableListBoxHeader (*this);
  42158. header->setSize (100, 28);
  42159. header->addListener (this);
  42160. setHeaderComponent (header);
  42161. }
  42162. TableListBox::~TableListBox()
  42163. {
  42164. header = 0;
  42165. }
  42166. void TableListBox::setModel (TableListBoxModel* const newModel)
  42167. {
  42168. if (model != newModel)
  42169. {
  42170. model = newModel;
  42171. updateContent();
  42172. }
  42173. }
  42174. int TableListBox::getHeaderHeight() const
  42175. {
  42176. return header->getHeight();
  42177. }
  42178. void TableListBox::setHeaderHeight (const int newHeight)
  42179. {
  42180. header->setSize (header->getWidth(), newHeight);
  42181. resized();
  42182. }
  42183. void TableListBox::autoSizeColumn (const int columnId)
  42184. {
  42185. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  42186. if (width > 0)
  42187. header->setColumnWidth (columnId, width);
  42188. }
  42189. void TableListBox::autoSizeAllColumns()
  42190. {
  42191. for (int i = 0; i < header->getNumColumns (true); ++i)
  42192. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  42193. }
  42194. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  42195. {
  42196. autoSizeOptionsShown = shouldBeShown;
  42197. }
  42198. bool TableListBox::isAutoSizeMenuOptionShown() const
  42199. {
  42200. return autoSizeOptionsShown;
  42201. }
  42202. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  42203. const int rowNumber,
  42204. const bool relativeToComponentTopLeft) const
  42205. {
  42206. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42207. if (relativeToComponentTopLeft)
  42208. headerCell.translate (header->getX(), 0);
  42209. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  42210. return Rectangle<int> (headerCell.getX(), row.getY(),
  42211. headerCell.getWidth(), row.getHeight());
  42212. }
  42213. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  42214. {
  42215. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  42216. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  42217. }
  42218. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  42219. {
  42220. ScrollBar* const scrollbar = getHorizontalScrollBar();
  42221. if (scrollbar != 0)
  42222. {
  42223. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42224. double x = scrollbar->getCurrentRangeStart();
  42225. const double w = scrollbar->getCurrentRangeSize();
  42226. if (pos.getX() < x)
  42227. x = pos.getX();
  42228. else if (pos.getRight() > x + w)
  42229. x += jmax (0.0, pos.getRight() - (x + w));
  42230. scrollbar->setCurrentRangeStart (x);
  42231. }
  42232. }
  42233. int TableListBox::getNumRows()
  42234. {
  42235. return model != 0 ? model->getNumRows() : 0;
  42236. }
  42237. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  42238. {
  42239. }
  42240. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  42241. {
  42242. if (existingComponentToUpdate == 0)
  42243. existingComponentToUpdate = new TableListRowComp (*this);
  42244. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  42245. return existingComponentToUpdate;
  42246. }
  42247. void TableListBox::selectedRowsChanged (int row)
  42248. {
  42249. if (model != 0)
  42250. model->selectedRowsChanged (row);
  42251. }
  42252. void TableListBox::deleteKeyPressed (int row)
  42253. {
  42254. if (model != 0)
  42255. model->deleteKeyPressed (row);
  42256. }
  42257. void TableListBox::returnKeyPressed (int row)
  42258. {
  42259. if (model != 0)
  42260. model->returnKeyPressed (row);
  42261. }
  42262. void TableListBox::backgroundClicked()
  42263. {
  42264. if (model != 0)
  42265. model->backgroundClicked();
  42266. }
  42267. void TableListBox::listWasScrolled()
  42268. {
  42269. if (model != 0)
  42270. model->listWasScrolled();
  42271. }
  42272. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42273. {
  42274. setMinimumContentWidth (header->getTotalWidth());
  42275. repaint();
  42276. updateColumnComponents();
  42277. }
  42278. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42279. {
  42280. setMinimumContentWidth (header->getTotalWidth());
  42281. repaint();
  42282. updateColumnComponents();
  42283. }
  42284. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42285. {
  42286. if (model != 0)
  42287. model->sortOrderChanged (header->getSortColumnId(),
  42288. header->isSortedForwards());
  42289. }
  42290. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42291. {
  42292. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42293. repaint();
  42294. }
  42295. void TableListBox::resized()
  42296. {
  42297. ListBox::resized();
  42298. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42299. setMinimumContentWidth (header->getTotalWidth());
  42300. }
  42301. void TableListBox::updateColumnComponents() const
  42302. {
  42303. const int firstRow = getRowContainingPosition (0, 0);
  42304. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42305. {
  42306. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42307. if (rowComp != 0)
  42308. rowComp->resized();
  42309. }
  42310. }
  42311. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42312. {
  42313. }
  42314. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42315. {
  42316. }
  42317. void TableListBoxModel::backgroundClicked()
  42318. {
  42319. }
  42320. void TableListBoxModel::sortOrderChanged (int, const bool)
  42321. {
  42322. }
  42323. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42324. {
  42325. return 0;
  42326. }
  42327. void TableListBoxModel::selectedRowsChanged (int)
  42328. {
  42329. }
  42330. void TableListBoxModel::deleteKeyPressed (int)
  42331. {
  42332. }
  42333. void TableListBoxModel::returnKeyPressed (int)
  42334. {
  42335. }
  42336. void TableListBoxModel::listWasScrolled()
  42337. {
  42338. }
  42339. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42340. {
  42341. return String::empty;
  42342. }
  42343. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42344. {
  42345. return String::empty;
  42346. }
  42347. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42348. {
  42349. (void) existingComponentToUpdate;
  42350. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42351. return 0;
  42352. }
  42353. END_JUCE_NAMESPACE
  42354. /*** End of inlined file: juce_TableListBox.cpp ***/
  42355. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42356. BEGIN_JUCE_NAMESPACE
  42357. // a word or space that can't be broken down any further
  42358. struct TextAtom
  42359. {
  42360. String atomText;
  42361. float width;
  42362. uint16 numChars;
  42363. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42364. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42365. const String getText (const juce_wchar passwordCharacter) const
  42366. {
  42367. if (passwordCharacter == 0)
  42368. return atomText;
  42369. else
  42370. return String::repeatedString (String::charToString (passwordCharacter),
  42371. atomText.length());
  42372. }
  42373. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42374. {
  42375. if (passwordCharacter == 0)
  42376. return atomText.substring (0, numChars);
  42377. else if (isNewLine())
  42378. return String::empty;
  42379. else
  42380. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42381. }
  42382. };
  42383. // a run of text with a single font and colour
  42384. class TextEditor::UniformTextSection
  42385. {
  42386. public:
  42387. UniformTextSection (const String& text,
  42388. const Font& font_,
  42389. const Colour& colour_,
  42390. const juce_wchar passwordCharacter)
  42391. : font (font_),
  42392. colour (colour_)
  42393. {
  42394. initialiseAtoms (text, passwordCharacter);
  42395. }
  42396. UniformTextSection (const UniformTextSection& other)
  42397. : font (other.font),
  42398. colour (other.colour)
  42399. {
  42400. atoms.ensureStorageAllocated (other.atoms.size());
  42401. for (int i = 0; i < other.atoms.size(); ++i)
  42402. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42403. }
  42404. ~UniformTextSection()
  42405. {
  42406. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42407. }
  42408. void clear()
  42409. {
  42410. for (int i = atoms.size(); --i >= 0;)
  42411. delete getAtom(i);
  42412. atoms.clear();
  42413. }
  42414. int getNumAtoms() const
  42415. {
  42416. return atoms.size();
  42417. }
  42418. TextAtom* getAtom (const int index) const throw()
  42419. {
  42420. return atoms.getUnchecked (index);
  42421. }
  42422. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42423. {
  42424. if (other.atoms.size() > 0)
  42425. {
  42426. TextAtom* const lastAtom = atoms.getLast();
  42427. int i = 0;
  42428. if (lastAtom != 0)
  42429. {
  42430. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42431. {
  42432. TextAtom* const first = other.getAtom(0);
  42433. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42434. {
  42435. lastAtom->atomText += first->atomText;
  42436. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42437. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42438. delete first;
  42439. ++i;
  42440. }
  42441. }
  42442. }
  42443. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42444. while (i < other.atoms.size())
  42445. {
  42446. atoms.add (other.getAtom(i));
  42447. ++i;
  42448. }
  42449. }
  42450. }
  42451. UniformTextSection* split (const int indexToBreakAt,
  42452. const juce_wchar passwordCharacter)
  42453. {
  42454. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42455. font, colour,
  42456. passwordCharacter);
  42457. int index = 0;
  42458. for (int i = 0; i < atoms.size(); ++i)
  42459. {
  42460. TextAtom* const atom = getAtom(i);
  42461. const int nextIndex = index + atom->numChars;
  42462. if (index == indexToBreakAt)
  42463. {
  42464. int j;
  42465. for (j = i; j < atoms.size(); ++j)
  42466. section2->atoms.add (getAtom (j));
  42467. for (j = atoms.size(); --j >= i;)
  42468. atoms.remove (j);
  42469. break;
  42470. }
  42471. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42472. {
  42473. TextAtom* const secondAtom = new TextAtom();
  42474. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42475. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42476. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42477. section2->atoms.add (secondAtom);
  42478. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42479. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42480. atom->numChars = (uint16) (indexToBreakAt - index);
  42481. int j;
  42482. for (j = i + 1; j < atoms.size(); ++j)
  42483. section2->atoms.add (getAtom (j));
  42484. for (j = atoms.size(); --j > i;)
  42485. atoms.remove (j);
  42486. break;
  42487. }
  42488. index = nextIndex;
  42489. }
  42490. return section2;
  42491. }
  42492. void appendAllText (String::Concatenator& concatenator) const
  42493. {
  42494. for (int i = 0; i < atoms.size(); ++i)
  42495. concatenator.append (getAtom(i)->atomText);
  42496. }
  42497. void appendSubstring (String::Concatenator& concatenator,
  42498. const Range<int>& range) const
  42499. {
  42500. int index = 0;
  42501. for (int i = 0; i < atoms.size(); ++i)
  42502. {
  42503. const TextAtom* const atom = getAtom (i);
  42504. const int nextIndex = index + atom->numChars;
  42505. if (range.getStart() < nextIndex)
  42506. {
  42507. if (range.getEnd() <= index)
  42508. break;
  42509. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42510. if (! r.isEmpty())
  42511. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42512. }
  42513. index = nextIndex;
  42514. }
  42515. }
  42516. int getTotalLength() const
  42517. {
  42518. int total = 0;
  42519. for (int i = atoms.size(); --i >= 0;)
  42520. total += getAtom(i)->numChars;
  42521. return total;
  42522. }
  42523. void setFont (const Font& newFont,
  42524. const juce_wchar passwordCharacter)
  42525. {
  42526. if (font != newFont)
  42527. {
  42528. font = newFont;
  42529. for (int i = atoms.size(); --i >= 0;)
  42530. {
  42531. TextAtom* const atom = atoms.getUnchecked(i);
  42532. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42533. }
  42534. }
  42535. }
  42536. juce_UseDebuggingNewOperator
  42537. Font font;
  42538. Colour colour;
  42539. private:
  42540. Array <TextAtom*> atoms;
  42541. void initialiseAtoms (const String& textToParse,
  42542. const juce_wchar passwordCharacter)
  42543. {
  42544. int i = 0;
  42545. const int len = textToParse.length();
  42546. const juce_wchar* const text = textToParse;
  42547. while (i < len)
  42548. {
  42549. int start = i;
  42550. // create a whitespace atom unless it starts with non-ws
  42551. if (CharacterFunctions::isWhitespace (text[i])
  42552. && text[i] != '\r'
  42553. && text[i] != '\n')
  42554. {
  42555. while (i < len
  42556. && CharacterFunctions::isWhitespace (text[i])
  42557. && text[i] != '\r'
  42558. && text[i] != '\n')
  42559. {
  42560. ++i;
  42561. }
  42562. }
  42563. else
  42564. {
  42565. if (text[i] == '\r')
  42566. {
  42567. ++i;
  42568. if ((i < len) && (text[i] == '\n'))
  42569. {
  42570. ++start;
  42571. ++i;
  42572. }
  42573. }
  42574. else if (text[i] == '\n')
  42575. {
  42576. ++i;
  42577. }
  42578. else
  42579. {
  42580. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42581. ++i;
  42582. }
  42583. }
  42584. TextAtom* const atom = new TextAtom();
  42585. atom->atomText = String (text + start, i - start);
  42586. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42587. atom->numChars = (uint16) (i - start);
  42588. atoms.add (atom);
  42589. }
  42590. }
  42591. UniformTextSection& operator= (const UniformTextSection& other);
  42592. };
  42593. class TextEditor::Iterator
  42594. {
  42595. public:
  42596. Iterator (const Array <UniformTextSection*>& sections_,
  42597. const float wordWrapWidth_,
  42598. const juce_wchar passwordCharacter_)
  42599. : indexInText (0),
  42600. lineY (0),
  42601. lineHeight (0),
  42602. maxDescent (0),
  42603. atomX (0),
  42604. atomRight (0),
  42605. atom (0),
  42606. currentSection (0),
  42607. sections (sections_),
  42608. sectionIndex (0),
  42609. atomIndex (0),
  42610. wordWrapWidth (wordWrapWidth_),
  42611. passwordCharacter (passwordCharacter_)
  42612. {
  42613. jassert (wordWrapWidth_ > 0);
  42614. if (sections.size() > 0)
  42615. {
  42616. currentSection = sections.getUnchecked (sectionIndex);
  42617. if (currentSection != 0)
  42618. beginNewLine();
  42619. }
  42620. }
  42621. Iterator (const Iterator& other)
  42622. : indexInText (other.indexInText),
  42623. lineY (other.lineY),
  42624. lineHeight (other.lineHeight),
  42625. maxDescent (other.maxDescent),
  42626. atomX (other.atomX),
  42627. atomRight (other.atomRight),
  42628. atom (other.atom),
  42629. currentSection (other.currentSection),
  42630. sections (other.sections),
  42631. sectionIndex (other.sectionIndex),
  42632. atomIndex (other.atomIndex),
  42633. wordWrapWidth (other.wordWrapWidth),
  42634. passwordCharacter (other.passwordCharacter),
  42635. tempAtom (other.tempAtom)
  42636. {
  42637. }
  42638. ~Iterator()
  42639. {
  42640. }
  42641. bool next()
  42642. {
  42643. if (atom == &tempAtom)
  42644. {
  42645. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42646. if (numRemaining > 0)
  42647. {
  42648. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42649. atomX = 0;
  42650. if (tempAtom.numChars > 0)
  42651. lineY += lineHeight;
  42652. indexInText += tempAtom.numChars;
  42653. GlyphArrangement g;
  42654. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42655. int split;
  42656. for (split = 0; split < g.getNumGlyphs(); ++split)
  42657. if (shouldWrap (g.getGlyph (split).getRight()))
  42658. break;
  42659. if (split > 0 && split <= numRemaining)
  42660. {
  42661. tempAtom.numChars = (uint16) split;
  42662. tempAtom.width = g.getGlyph (split - 1).getRight();
  42663. atomRight = atomX + tempAtom.width;
  42664. return true;
  42665. }
  42666. }
  42667. }
  42668. bool forceNewLine = false;
  42669. if (sectionIndex >= sections.size())
  42670. {
  42671. moveToEndOfLastAtom();
  42672. return false;
  42673. }
  42674. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42675. {
  42676. if (atomIndex >= currentSection->getNumAtoms())
  42677. {
  42678. if (++sectionIndex >= sections.size())
  42679. {
  42680. moveToEndOfLastAtom();
  42681. return false;
  42682. }
  42683. atomIndex = 0;
  42684. currentSection = sections.getUnchecked (sectionIndex);
  42685. }
  42686. else
  42687. {
  42688. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42689. if (! lastAtom->isWhitespace())
  42690. {
  42691. // handle the case where the last atom in a section is actually part of the same
  42692. // word as the first atom of the next section...
  42693. float right = atomRight + lastAtom->width;
  42694. float lineHeight2 = lineHeight;
  42695. float maxDescent2 = maxDescent;
  42696. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42697. {
  42698. const UniformTextSection* const s = sections.getUnchecked (section);
  42699. if (s->getNumAtoms() == 0)
  42700. break;
  42701. const TextAtom* const nextAtom = s->getAtom (0);
  42702. if (nextAtom->isWhitespace())
  42703. break;
  42704. right += nextAtom->width;
  42705. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42706. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42707. if (shouldWrap (right))
  42708. {
  42709. lineHeight = lineHeight2;
  42710. maxDescent = maxDescent2;
  42711. forceNewLine = true;
  42712. break;
  42713. }
  42714. if (s->getNumAtoms() > 1)
  42715. break;
  42716. }
  42717. }
  42718. }
  42719. }
  42720. if (atom != 0)
  42721. {
  42722. atomX = atomRight;
  42723. indexInText += atom->numChars;
  42724. if (atom->isNewLine())
  42725. beginNewLine();
  42726. }
  42727. atom = currentSection->getAtom (atomIndex);
  42728. atomRight = atomX + atom->width;
  42729. ++atomIndex;
  42730. if (shouldWrap (atomRight) || forceNewLine)
  42731. {
  42732. if (atom->isWhitespace())
  42733. {
  42734. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42735. atomRight = jmin (atomRight, wordWrapWidth);
  42736. }
  42737. else
  42738. {
  42739. atomRight = atom->width;
  42740. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42741. {
  42742. tempAtom = *atom;
  42743. tempAtom.width = 0;
  42744. tempAtom.numChars = 0;
  42745. atom = &tempAtom;
  42746. if (atomX > 0)
  42747. beginNewLine();
  42748. return next();
  42749. }
  42750. beginNewLine();
  42751. return true;
  42752. }
  42753. }
  42754. return true;
  42755. }
  42756. void beginNewLine()
  42757. {
  42758. atomX = 0;
  42759. lineY += lineHeight;
  42760. int tempSectionIndex = sectionIndex;
  42761. int tempAtomIndex = atomIndex;
  42762. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42763. lineHeight = section->font.getHeight();
  42764. maxDescent = section->font.getDescent();
  42765. float x = (atom != 0) ? atom->width : 0;
  42766. while (! shouldWrap (x))
  42767. {
  42768. if (tempSectionIndex >= sections.size())
  42769. break;
  42770. bool checkSize = false;
  42771. if (tempAtomIndex >= section->getNumAtoms())
  42772. {
  42773. if (++tempSectionIndex >= sections.size())
  42774. break;
  42775. tempAtomIndex = 0;
  42776. section = sections.getUnchecked (tempSectionIndex);
  42777. checkSize = true;
  42778. }
  42779. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42780. if (nextAtom == 0)
  42781. break;
  42782. x += nextAtom->width;
  42783. if (shouldWrap (x) || nextAtom->isNewLine())
  42784. break;
  42785. if (checkSize)
  42786. {
  42787. lineHeight = jmax (lineHeight, section->font.getHeight());
  42788. maxDescent = jmax (maxDescent, section->font.getDescent());
  42789. }
  42790. ++tempAtomIndex;
  42791. }
  42792. }
  42793. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42794. {
  42795. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42796. {
  42797. if (lastSection != currentSection)
  42798. {
  42799. lastSection = currentSection;
  42800. g.setColour (currentSection->colour);
  42801. g.setFont (currentSection->font);
  42802. }
  42803. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42804. GlyphArrangement ga;
  42805. ga.addLineOfText (currentSection->font,
  42806. atom->getTrimmedText (passwordCharacter),
  42807. atomX,
  42808. (float) roundToInt (lineY + lineHeight - maxDescent));
  42809. ga.draw (g);
  42810. }
  42811. }
  42812. void drawSelection (Graphics& g,
  42813. const Range<int>& selection) const
  42814. {
  42815. const int startX = roundToInt (indexToX (selection.getStart()));
  42816. const int endX = roundToInt (indexToX (selection.getEnd()));
  42817. const int y = roundToInt (lineY);
  42818. const int nextY = roundToInt (lineY + lineHeight);
  42819. g.fillRect (startX, y, endX - startX, nextY - y);
  42820. }
  42821. void drawSelectedText (Graphics& g,
  42822. const Range<int>& selection,
  42823. const Colour& selectedTextColour) const
  42824. {
  42825. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42826. {
  42827. GlyphArrangement ga;
  42828. ga.addLineOfText (currentSection->font,
  42829. atom->getTrimmedText (passwordCharacter),
  42830. atomX,
  42831. (float) roundToInt (lineY + lineHeight - maxDescent));
  42832. if (selection.getEnd() < indexInText + atom->numChars)
  42833. {
  42834. GlyphArrangement ga2 (ga);
  42835. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42836. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42837. g.setColour (currentSection->colour);
  42838. ga2.draw (g);
  42839. }
  42840. if (selection.getStart() > indexInText)
  42841. {
  42842. GlyphArrangement ga2 (ga);
  42843. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42844. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42845. g.setColour (currentSection->colour);
  42846. ga2.draw (g);
  42847. }
  42848. g.setColour (selectedTextColour);
  42849. ga.draw (g);
  42850. }
  42851. }
  42852. float indexToX (const int indexToFind) const
  42853. {
  42854. if (indexToFind <= indexInText)
  42855. return atomX;
  42856. if (indexToFind >= indexInText + atom->numChars)
  42857. return atomRight;
  42858. GlyphArrangement g;
  42859. g.addLineOfText (currentSection->font,
  42860. atom->getText (passwordCharacter),
  42861. atomX, 0.0f);
  42862. if (indexToFind - indexInText >= g.getNumGlyphs())
  42863. return atomRight;
  42864. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42865. }
  42866. int xToIndex (const float xToFind) const
  42867. {
  42868. if (xToFind <= atomX || atom->isNewLine())
  42869. return indexInText;
  42870. if (xToFind >= atomRight)
  42871. return indexInText + atom->numChars;
  42872. GlyphArrangement g;
  42873. g.addLineOfText (currentSection->font,
  42874. atom->getText (passwordCharacter),
  42875. atomX, 0.0f);
  42876. int j;
  42877. for (j = 0; j < g.getNumGlyphs(); ++j)
  42878. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42879. break;
  42880. return indexInText + j;
  42881. }
  42882. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42883. {
  42884. while (next())
  42885. {
  42886. if (indexInText + atom->numChars > index)
  42887. {
  42888. cx = indexToX (index);
  42889. cy = lineY;
  42890. lineHeight_ = lineHeight;
  42891. return true;
  42892. }
  42893. }
  42894. cx = atomX;
  42895. cy = lineY;
  42896. lineHeight_ = lineHeight;
  42897. return false;
  42898. }
  42899. juce_UseDebuggingNewOperator
  42900. int indexInText;
  42901. float lineY, lineHeight, maxDescent;
  42902. float atomX, atomRight;
  42903. const TextAtom* atom;
  42904. const UniformTextSection* currentSection;
  42905. private:
  42906. const Array <UniformTextSection*>& sections;
  42907. int sectionIndex, atomIndex;
  42908. const float wordWrapWidth;
  42909. const juce_wchar passwordCharacter;
  42910. TextAtom tempAtom;
  42911. Iterator& operator= (const Iterator&);
  42912. void moveToEndOfLastAtom()
  42913. {
  42914. if (atom != 0)
  42915. {
  42916. atomX = atomRight;
  42917. if (atom->isNewLine())
  42918. {
  42919. atomX = 0.0f;
  42920. lineY += lineHeight;
  42921. }
  42922. }
  42923. }
  42924. bool shouldWrap (const float x) const
  42925. {
  42926. return (x - 0.0001f) >= wordWrapWidth;
  42927. }
  42928. };
  42929. class TextEditor::InsertAction : public UndoableAction
  42930. {
  42931. TextEditor& owner;
  42932. const String text;
  42933. const int insertIndex, oldCaretPos, newCaretPos;
  42934. const Font font;
  42935. const Colour colour;
  42936. InsertAction (const InsertAction&);
  42937. InsertAction& operator= (const InsertAction&);
  42938. public:
  42939. InsertAction (TextEditor& owner_,
  42940. const String& text_,
  42941. const int insertIndex_,
  42942. const Font& font_,
  42943. const Colour& colour_,
  42944. const int oldCaretPos_,
  42945. const int newCaretPos_)
  42946. : owner (owner_),
  42947. text (text_),
  42948. insertIndex (insertIndex_),
  42949. oldCaretPos (oldCaretPos_),
  42950. newCaretPos (newCaretPos_),
  42951. font (font_),
  42952. colour (colour_)
  42953. {
  42954. }
  42955. ~InsertAction()
  42956. {
  42957. }
  42958. bool perform()
  42959. {
  42960. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42961. return true;
  42962. }
  42963. bool undo()
  42964. {
  42965. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42966. return true;
  42967. }
  42968. int getSizeInUnits()
  42969. {
  42970. return text.length() + 16;
  42971. }
  42972. };
  42973. class TextEditor::RemoveAction : public UndoableAction
  42974. {
  42975. TextEditor& owner;
  42976. const Range<int> range;
  42977. const int oldCaretPos, newCaretPos;
  42978. Array <UniformTextSection*> removedSections;
  42979. RemoveAction (const RemoveAction&);
  42980. RemoveAction& operator= (const RemoveAction&);
  42981. public:
  42982. RemoveAction (TextEditor& owner_,
  42983. const Range<int> range_,
  42984. const int oldCaretPos_,
  42985. const int newCaretPos_,
  42986. const Array <UniformTextSection*>& removedSections_)
  42987. : owner (owner_),
  42988. range (range_),
  42989. oldCaretPos (oldCaretPos_),
  42990. newCaretPos (newCaretPos_),
  42991. removedSections (removedSections_)
  42992. {
  42993. }
  42994. ~RemoveAction()
  42995. {
  42996. for (int i = removedSections.size(); --i >= 0;)
  42997. {
  42998. UniformTextSection* const section = removedSections.getUnchecked (i);
  42999. section->clear();
  43000. delete section;
  43001. }
  43002. }
  43003. bool perform()
  43004. {
  43005. owner.remove (range, 0, newCaretPos);
  43006. return true;
  43007. }
  43008. bool undo()
  43009. {
  43010. owner.reinsert (range.getStart(), removedSections);
  43011. owner.moveCursorTo (oldCaretPos, false);
  43012. return true;
  43013. }
  43014. int getSizeInUnits()
  43015. {
  43016. int n = 0;
  43017. for (int i = removedSections.size(); --i >= 0;)
  43018. n += removedSections.getUnchecked (i)->getTotalLength();
  43019. return n + 16;
  43020. }
  43021. };
  43022. class TextEditor::TextHolderComponent : public Component,
  43023. public Timer,
  43024. public Value::Listener
  43025. {
  43026. public:
  43027. TextHolderComponent (TextEditor& owner_)
  43028. : owner (owner_)
  43029. {
  43030. setWantsKeyboardFocus (false);
  43031. setInterceptsMouseClicks (false, true);
  43032. owner.getTextValue().addListener (this);
  43033. }
  43034. ~TextHolderComponent()
  43035. {
  43036. owner.getTextValue().removeListener (this);
  43037. }
  43038. void paint (Graphics& g)
  43039. {
  43040. owner.drawContent (g);
  43041. }
  43042. void timerCallback()
  43043. {
  43044. owner.timerCallbackInt();
  43045. }
  43046. const MouseCursor getMouseCursor()
  43047. {
  43048. return owner.getMouseCursor();
  43049. }
  43050. void valueChanged (Value&)
  43051. {
  43052. owner.textWasChangedByValue();
  43053. }
  43054. private:
  43055. TextEditor& owner;
  43056. TextHolderComponent (const TextHolderComponent&);
  43057. TextHolderComponent& operator= (const TextHolderComponent&);
  43058. };
  43059. class TextEditorViewport : public Viewport
  43060. {
  43061. public:
  43062. TextEditorViewport (TextEditor* const owner_)
  43063. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  43064. {
  43065. }
  43066. ~TextEditorViewport()
  43067. {
  43068. }
  43069. void visibleAreaChanged (int, int, int, int)
  43070. {
  43071. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  43072. // appear and disappear, causing the wrap width to change.
  43073. {
  43074. const float wordWrapWidth = owner->getWordWrapWidth();
  43075. if (wordWrapWidth != lastWordWrapWidth)
  43076. {
  43077. lastWordWrapWidth = wordWrapWidth;
  43078. rentrant = true;
  43079. owner->updateTextHolderSize();
  43080. rentrant = false;
  43081. }
  43082. }
  43083. }
  43084. private:
  43085. TextEditor* const owner;
  43086. float lastWordWrapWidth;
  43087. bool rentrant;
  43088. TextEditorViewport (const TextEditorViewport&);
  43089. TextEditorViewport& operator= (const TextEditorViewport&);
  43090. };
  43091. namespace TextEditorDefs
  43092. {
  43093. const int flashSpeedIntervalMs = 380;
  43094. const int textChangeMessageId = 0x10003001;
  43095. const int returnKeyMessageId = 0x10003002;
  43096. const int escapeKeyMessageId = 0x10003003;
  43097. const int focusLossMessageId = 0x10003004;
  43098. const int maxActionsPerTransaction = 100;
  43099. static int getCharacterCategory (const juce_wchar character)
  43100. {
  43101. return CharacterFunctions::isLetterOrDigit (character)
  43102. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43103. }
  43104. }
  43105. TextEditor::TextEditor (const String& name,
  43106. const juce_wchar passwordCharacter_)
  43107. : Component (name),
  43108. borderSize (1, 1, 1, 3),
  43109. readOnly (false),
  43110. multiline (false),
  43111. wordWrap (false),
  43112. returnKeyStartsNewLine (false),
  43113. caretVisible (true),
  43114. popupMenuEnabled (true),
  43115. selectAllTextWhenFocused (false),
  43116. scrollbarVisible (true),
  43117. wasFocused (false),
  43118. caretFlashState (true),
  43119. keepCursorOnScreen (true),
  43120. tabKeyUsed (false),
  43121. menuActive (false),
  43122. valueTextNeedsUpdating (false),
  43123. cursorX (0),
  43124. cursorY (0),
  43125. cursorHeight (0),
  43126. maxTextLength (0),
  43127. leftIndent (4),
  43128. topIndent (4),
  43129. lastTransactionTime (0),
  43130. currentFont (14.0f),
  43131. totalNumChars (0),
  43132. caretPosition (0),
  43133. passwordCharacter (passwordCharacter_),
  43134. dragType (notDragging)
  43135. {
  43136. setOpaque (true);
  43137. addAndMakeVisible (viewport = new TextEditorViewport (this));
  43138. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  43139. viewport->setWantsKeyboardFocus (false);
  43140. viewport->setScrollBarsShown (false, false);
  43141. setMouseCursor (MouseCursor::IBeamCursor);
  43142. setWantsKeyboardFocus (true);
  43143. }
  43144. TextEditor::~TextEditor()
  43145. {
  43146. textValue.referTo (Value());
  43147. clearInternal (0);
  43148. viewport = 0;
  43149. textHolder = 0;
  43150. }
  43151. void TextEditor::newTransaction()
  43152. {
  43153. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43154. undoManager.beginNewTransaction();
  43155. }
  43156. void TextEditor::doUndoRedo (const bool isRedo)
  43157. {
  43158. if (! isReadOnly())
  43159. {
  43160. if (isRedo ? undoManager.redo()
  43161. : undoManager.undo())
  43162. {
  43163. scrollToMakeSureCursorIsVisible();
  43164. repaint();
  43165. textChanged();
  43166. }
  43167. }
  43168. }
  43169. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  43170. const bool shouldWordWrap)
  43171. {
  43172. if (multiline != shouldBeMultiLine
  43173. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  43174. {
  43175. multiline = shouldBeMultiLine;
  43176. wordWrap = shouldWordWrap && shouldBeMultiLine;
  43177. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  43178. scrollbarVisible && multiline);
  43179. viewport->setViewPosition (0, 0);
  43180. resized();
  43181. scrollToMakeSureCursorIsVisible();
  43182. }
  43183. }
  43184. bool TextEditor::isMultiLine() const
  43185. {
  43186. return multiline;
  43187. }
  43188. void TextEditor::setScrollbarsShown (bool shown)
  43189. {
  43190. if (scrollbarVisible != shown)
  43191. {
  43192. scrollbarVisible = shown;
  43193. shown = shown && isMultiLine();
  43194. viewport->setScrollBarsShown (shown, shown);
  43195. }
  43196. }
  43197. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  43198. {
  43199. if (readOnly != shouldBeReadOnly)
  43200. {
  43201. readOnly = shouldBeReadOnly;
  43202. enablementChanged();
  43203. }
  43204. }
  43205. bool TextEditor::isReadOnly() const
  43206. {
  43207. return readOnly || ! isEnabled();
  43208. }
  43209. bool TextEditor::isTextInputActive() const
  43210. {
  43211. return ! isReadOnly();
  43212. }
  43213. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  43214. {
  43215. returnKeyStartsNewLine = shouldStartNewLine;
  43216. }
  43217. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  43218. {
  43219. tabKeyUsed = shouldTabKeyBeUsed;
  43220. }
  43221. void TextEditor::setPopupMenuEnabled (const bool b)
  43222. {
  43223. popupMenuEnabled = b;
  43224. }
  43225. void TextEditor::setSelectAllWhenFocused (const bool b)
  43226. {
  43227. selectAllTextWhenFocused = b;
  43228. }
  43229. const Font TextEditor::getFont() const
  43230. {
  43231. return currentFont;
  43232. }
  43233. void TextEditor::setFont (const Font& newFont)
  43234. {
  43235. currentFont = newFont;
  43236. scrollToMakeSureCursorIsVisible();
  43237. }
  43238. void TextEditor::applyFontToAllText (const Font& newFont)
  43239. {
  43240. currentFont = newFont;
  43241. const Colour overallColour (findColour (textColourId));
  43242. for (int i = sections.size(); --i >= 0;)
  43243. {
  43244. UniformTextSection* const uts = sections.getUnchecked (i);
  43245. uts->setFont (newFont, passwordCharacter);
  43246. uts->colour = overallColour;
  43247. }
  43248. coalesceSimilarSections();
  43249. updateTextHolderSize();
  43250. scrollToMakeSureCursorIsVisible();
  43251. repaint();
  43252. }
  43253. void TextEditor::colourChanged()
  43254. {
  43255. setOpaque (findColour (backgroundColourId).isOpaque());
  43256. repaint();
  43257. }
  43258. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  43259. {
  43260. caretVisible = shouldCaretBeVisible;
  43261. if (shouldCaretBeVisible)
  43262. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43263. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  43264. : MouseCursor::NormalCursor);
  43265. }
  43266. void TextEditor::setInputRestrictions (const int maxLen,
  43267. const String& chars)
  43268. {
  43269. maxTextLength = jmax (0, maxLen);
  43270. allowedCharacters = chars;
  43271. }
  43272. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  43273. {
  43274. textToShowWhenEmpty = text;
  43275. colourForTextWhenEmpty = colourToUse;
  43276. }
  43277. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43278. {
  43279. if (passwordCharacter != newPasswordCharacter)
  43280. {
  43281. passwordCharacter = newPasswordCharacter;
  43282. resized();
  43283. repaint();
  43284. }
  43285. }
  43286. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43287. {
  43288. viewport->setScrollBarThickness (newThicknessPixels);
  43289. }
  43290. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43291. {
  43292. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43293. }
  43294. void TextEditor::clear()
  43295. {
  43296. clearInternal (0);
  43297. updateTextHolderSize();
  43298. undoManager.clearUndoHistory();
  43299. }
  43300. void TextEditor::setText (const String& newText,
  43301. const bool sendTextChangeMessage)
  43302. {
  43303. const int newLength = newText.length();
  43304. if (newLength != getTotalNumChars() || getText() != newText)
  43305. {
  43306. const int oldCursorPos = caretPosition;
  43307. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43308. clearInternal (0);
  43309. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43310. // if you're adding text with line-feeds to a single-line text editor, it
  43311. // ain't gonna look right!
  43312. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43313. if (cursorWasAtEnd && ! isMultiLine())
  43314. moveCursorTo (getTotalNumChars(), false);
  43315. else
  43316. moveCursorTo (oldCursorPos, false);
  43317. if (sendTextChangeMessage)
  43318. textChanged();
  43319. updateTextHolderSize();
  43320. scrollToMakeSureCursorIsVisible();
  43321. undoManager.clearUndoHistory();
  43322. repaint();
  43323. }
  43324. }
  43325. Value& TextEditor::getTextValue()
  43326. {
  43327. if (valueTextNeedsUpdating)
  43328. {
  43329. valueTextNeedsUpdating = false;
  43330. textValue = getText();
  43331. }
  43332. return textValue;
  43333. }
  43334. void TextEditor::textWasChangedByValue()
  43335. {
  43336. if (textValue.getValueSource().getReferenceCount() > 1)
  43337. setText (textValue.getValue());
  43338. }
  43339. void TextEditor::textChanged()
  43340. {
  43341. updateTextHolderSize();
  43342. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43343. if (textValue.getValueSource().getReferenceCount() > 1)
  43344. {
  43345. valueTextNeedsUpdating = false;
  43346. textValue = getText();
  43347. }
  43348. }
  43349. void TextEditor::returnPressed()
  43350. {
  43351. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43352. }
  43353. void TextEditor::escapePressed()
  43354. {
  43355. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43356. }
  43357. void TextEditor::addListener (Listener* const newListener)
  43358. {
  43359. listeners.add (newListener);
  43360. }
  43361. void TextEditor::removeListener (Listener* const listenerToRemove)
  43362. {
  43363. listeners.remove (listenerToRemove);
  43364. }
  43365. void TextEditor::timerCallbackInt()
  43366. {
  43367. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43368. if (caretFlashState != newState)
  43369. {
  43370. caretFlashState = newState;
  43371. if (caretFlashState)
  43372. wasFocused = true;
  43373. if (caretVisible
  43374. && hasKeyboardFocus (false)
  43375. && ! isReadOnly())
  43376. {
  43377. repaintCaret();
  43378. }
  43379. }
  43380. const unsigned int now = Time::getApproximateMillisecondCounter();
  43381. if (now > lastTransactionTime + 200)
  43382. newTransaction();
  43383. }
  43384. void TextEditor::repaintCaret()
  43385. {
  43386. if (! findColour (caretColourId).isTransparent())
  43387. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43388. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43389. 4,
  43390. roundToInt (cursorHeight) + 2);
  43391. }
  43392. void TextEditor::repaintText (const Range<int>& range)
  43393. {
  43394. if (! range.isEmpty())
  43395. {
  43396. float x = 0, y = 0, lh = currentFont.getHeight();
  43397. const float wordWrapWidth = getWordWrapWidth();
  43398. if (wordWrapWidth > 0)
  43399. {
  43400. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43401. i.getCharPosition (range.getStart(), x, y, lh);
  43402. const int y1 = (int) y;
  43403. int y2;
  43404. if (range.getEnd() >= getTotalNumChars())
  43405. {
  43406. y2 = textHolder->getHeight();
  43407. }
  43408. else
  43409. {
  43410. i.getCharPosition (range.getEnd(), x, y, lh);
  43411. y2 = (int) (y + lh * 2.0f);
  43412. }
  43413. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43414. }
  43415. }
  43416. }
  43417. void TextEditor::moveCaret (int newCaretPos)
  43418. {
  43419. if (newCaretPos < 0)
  43420. newCaretPos = 0;
  43421. else if (newCaretPos > getTotalNumChars())
  43422. newCaretPos = getTotalNumChars();
  43423. if (newCaretPos != getCaretPosition())
  43424. {
  43425. repaintCaret();
  43426. caretFlashState = true;
  43427. caretPosition = newCaretPos;
  43428. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43429. scrollToMakeSureCursorIsVisible();
  43430. repaintCaret();
  43431. }
  43432. }
  43433. void TextEditor::setCaretPosition (const int newIndex)
  43434. {
  43435. moveCursorTo (newIndex, false);
  43436. }
  43437. int TextEditor::getCaretPosition() const
  43438. {
  43439. return caretPosition;
  43440. }
  43441. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43442. const int desiredCaretY)
  43443. {
  43444. updateCaretPosition();
  43445. int vx = roundToInt (cursorX) - desiredCaretX;
  43446. int vy = roundToInt (cursorY) - desiredCaretY;
  43447. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43448. {
  43449. vx += desiredCaretX - proportionOfWidth (0.2f);
  43450. }
  43451. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43452. {
  43453. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43454. }
  43455. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43456. if (! isMultiLine())
  43457. {
  43458. vy = viewport->getViewPositionY();
  43459. }
  43460. else
  43461. {
  43462. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43463. const int curH = roundToInt (cursorHeight);
  43464. if (desiredCaretY < 0)
  43465. {
  43466. vy = jmax (0, desiredCaretY + vy);
  43467. }
  43468. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43469. {
  43470. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43471. }
  43472. }
  43473. viewport->setViewPosition (vx, vy);
  43474. }
  43475. const Rectangle<int> TextEditor::getCaretRectangle()
  43476. {
  43477. updateCaretPosition();
  43478. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43479. roundToInt (cursorY) - viewport->getY(),
  43480. 1, roundToInt (cursorHeight));
  43481. }
  43482. float TextEditor::getWordWrapWidth() const
  43483. {
  43484. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43485. : 1.0e10f;
  43486. }
  43487. void TextEditor::updateTextHolderSize()
  43488. {
  43489. const float wordWrapWidth = getWordWrapWidth();
  43490. if (wordWrapWidth > 0)
  43491. {
  43492. float maxWidth = 0.0f;
  43493. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43494. while (i.next())
  43495. maxWidth = jmax (maxWidth, i.atomRight);
  43496. const int w = leftIndent + roundToInt (maxWidth);
  43497. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43498. currentFont.getHeight()));
  43499. textHolder->setSize (w + 1, h + 1);
  43500. }
  43501. }
  43502. int TextEditor::getTextWidth() const
  43503. {
  43504. return textHolder->getWidth();
  43505. }
  43506. int TextEditor::getTextHeight() const
  43507. {
  43508. return textHolder->getHeight();
  43509. }
  43510. void TextEditor::setIndents (const int newLeftIndent,
  43511. const int newTopIndent)
  43512. {
  43513. leftIndent = newLeftIndent;
  43514. topIndent = newTopIndent;
  43515. }
  43516. void TextEditor::setBorder (const BorderSize& border)
  43517. {
  43518. borderSize = border;
  43519. resized();
  43520. }
  43521. const BorderSize TextEditor::getBorder() const
  43522. {
  43523. return borderSize;
  43524. }
  43525. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43526. {
  43527. keepCursorOnScreen = shouldScrollToShowCursor;
  43528. }
  43529. void TextEditor::updateCaretPosition()
  43530. {
  43531. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43532. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43533. }
  43534. void TextEditor::scrollToMakeSureCursorIsVisible()
  43535. {
  43536. updateCaretPosition();
  43537. if (keepCursorOnScreen)
  43538. {
  43539. int x = viewport->getViewPositionX();
  43540. int y = viewport->getViewPositionY();
  43541. const int relativeCursorX = roundToInt (cursorX) - x;
  43542. const int relativeCursorY = roundToInt (cursorY) - y;
  43543. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43544. {
  43545. x += relativeCursorX - proportionOfWidth (0.2f);
  43546. }
  43547. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43548. {
  43549. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43550. }
  43551. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43552. if (! isMultiLine())
  43553. {
  43554. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43555. }
  43556. else
  43557. {
  43558. const int curH = roundToInt (cursorHeight);
  43559. if (relativeCursorY < 0)
  43560. {
  43561. y = jmax (0, relativeCursorY + y);
  43562. }
  43563. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43564. {
  43565. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43566. }
  43567. }
  43568. viewport->setViewPosition (x, y);
  43569. }
  43570. }
  43571. void TextEditor::moveCursorTo (const int newPosition,
  43572. const bool isSelecting)
  43573. {
  43574. if (isSelecting)
  43575. {
  43576. moveCaret (newPosition);
  43577. const Range<int> oldSelection (selection);
  43578. if (dragType == notDragging)
  43579. {
  43580. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43581. dragType = draggingSelectionStart;
  43582. else
  43583. dragType = draggingSelectionEnd;
  43584. }
  43585. if (dragType == draggingSelectionStart)
  43586. {
  43587. if (getCaretPosition() >= selection.getEnd())
  43588. dragType = draggingSelectionEnd;
  43589. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43590. }
  43591. else
  43592. {
  43593. if (getCaretPosition() < selection.getStart())
  43594. dragType = draggingSelectionStart;
  43595. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43596. }
  43597. repaintText (selection.getUnionWith (oldSelection));
  43598. }
  43599. else
  43600. {
  43601. dragType = notDragging;
  43602. repaintText (selection);
  43603. moveCaret (newPosition);
  43604. selection = Range<int>::emptyRange (getCaretPosition());
  43605. }
  43606. }
  43607. int TextEditor::getTextIndexAt (const int x,
  43608. const int y)
  43609. {
  43610. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43611. (float) (y + viewport->getViewPositionY() - topIndent));
  43612. }
  43613. void TextEditor::insertTextAtCaret (const String& newText_)
  43614. {
  43615. String newText (newText_);
  43616. if (allowedCharacters.isNotEmpty())
  43617. newText = newText.retainCharacters (allowedCharacters);
  43618. if ((! returnKeyStartsNewLine) && newText == "\n")
  43619. {
  43620. returnPressed();
  43621. return;
  43622. }
  43623. if (! isMultiLine())
  43624. newText = newText.replaceCharacters ("\r\n", " ");
  43625. else
  43626. newText = newText.replace ("\r\n", "\n");
  43627. const int newCaretPos = selection.getStart() + newText.length();
  43628. const int insertIndex = selection.getStart();
  43629. remove (selection, getUndoManager(),
  43630. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43631. if (maxTextLength > 0)
  43632. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43633. if (newText.isNotEmpty())
  43634. insert (newText,
  43635. insertIndex,
  43636. currentFont,
  43637. findColour (textColourId),
  43638. getUndoManager(),
  43639. newCaretPos);
  43640. textChanged();
  43641. }
  43642. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43643. {
  43644. moveCursorTo (newSelection.getStart(), false);
  43645. moveCursorTo (newSelection.getEnd(), true);
  43646. }
  43647. void TextEditor::copy()
  43648. {
  43649. if (passwordCharacter == 0)
  43650. {
  43651. const String selectedText (getHighlightedText());
  43652. if (selectedText.isNotEmpty())
  43653. SystemClipboard::copyTextToClipboard (selectedText);
  43654. }
  43655. }
  43656. void TextEditor::paste()
  43657. {
  43658. if (! isReadOnly())
  43659. {
  43660. const String clip (SystemClipboard::getTextFromClipboard());
  43661. if (clip.isNotEmpty())
  43662. insertTextAtCaret (clip);
  43663. }
  43664. }
  43665. void TextEditor::cut()
  43666. {
  43667. if (! isReadOnly())
  43668. {
  43669. moveCaret (selection.getEnd());
  43670. insertTextAtCaret (String::empty);
  43671. }
  43672. }
  43673. void TextEditor::drawContent (Graphics& g)
  43674. {
  43675. const float wordWrapWidth = getWordWrapWidth();
  43676. if (wordWrapWidth > 0)
  43677. {
  43678. g.setOrigin (leftIndent, topIndent);
  43679. const Rectangle<int> clip (g.getClipBounds());
  43680. Colour selectedTextColour;
  43681. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43682. while (i.lineY + 200.0 < clip.getY() && i.next())
  43683. {}
  43684. if (! selection.isEmpty())
  43685. {
  43686. g.setColour (findColour (highlightColourId)
  43687. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43688. selectedTextColour = findColour (highlightedTextColourId);
  43689. Iterator i2 (i);
  43690. while (i2.next() && i2.lineY < clip.getBottom())
  43691. {
  43692. if (i2.lineY + i2.lineHeight >= clip.getY()
  43693. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43694. {
  43695. i2.drawSelection (g, selection);
  43696. }
  43697. }
  43698. }
  43699. const UniformTextSection* lastSection = 0;
  43700. while (i.next() && i.lineY < clip.getBottom())
  43701. {
  43702. if (i.lineY + i.lineHeight >= clip.getY())
  43703. {
  43704. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43705. {
  43706. i.drawSelectedText (g, selection, selectedTextColour);
  43707. lastSection = 0;
  43708. }
  43709. else
  43710. {
  43711. i.draw (g, lastSection);
  43712. }
  43713. }
  43714. }
  43715. }
  43716. }
  43717. void TextEditor::paint (Graphics& g)
  43718. {
  43719. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43720. }
  43721. void TextEditor::paintOverChildren (Graphics& g)
  43722. {
  43723. if (caretFlashState
  43724. && hasKeyboardFocus (false)
  43725. && caretVisible
  43726. && ! isReadOnly())
  43727. {
  43728. g.setColour (findColour (caretColourId));
  43729. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43730. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43731. 2.0f, cursorHeight);
  43732. }
  43733. if (textToShowWhenEmpty.isNotEmpty()
  43734. && (! hasKeyboardFocus (false))
  43735. && getTotalNumChars() == 0)
  43736. {
  43737. g.setColour (colourForTextWhenEmpty);
  43738. g.setFont (getFont());
  43739. if (isMultiLine())
  43740. {
  43741. g.drawText (textToShowWhenEmpty,
  43742. 0, 0, getWidth(), getHeight(),
  43743. Justification::centred, true);
  43744. }
  43745. else
  43746. {
  43747. g.drawText (textToShowWhenEmpty,
  43748. leftIndent, topIndent,
  43749. viewport->getWidth() - leftIndent,
  43750. viewport->getHeight() - topIndent,
  43751. Justification::centredLeft, true);
  43752. }
  43753. }
  43754. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43755. }
  43756. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43757. {
  43758. public:
  43759. TextEditorMenuPerformer (TextEditor* const editor_)
  43760. : editor (editor_)
  43761. {
  43762. }
  43763. void modalStateFinished (int returnValue)
  43764. {
  43765. if (editor != 0 && returnValue != 0)
  43766. editor->performPopupMenuAction (returnValue);
  43767. }
  43768. private:
  43769. Component::SafePointer<TextEditor> editor;
  43770. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43771. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43772. };
  43773. void TextEditor::mouseDown (const MouseEvent& e)
  43774. {
  43775. beginDragAutoRepeat (100);
  43776. newTransaction();
  43777. if (wasFocused || ! selectAllTextWhenFocused)
  43778. {
  43779. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43780. {
  43781. moveCursorTo (getTextIndexAt (e.x, e.y),
  43782. e.mods.isShiftDown());
  43783. }
  43784. else
  43785. {
  43786. PopupMenu m;
  43787. m.setLookAndFeel (&getLookAndFeel());
  43788. addPopupMenuItems (m, &e);
  43789. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43790. }
  43791. }
  43792. }
  43793. void TextEditor::mouseDrag (const MouseEvent& e)
  43794. {
  43795. if (wasFocused || ! selectAllTextWhenFocused)
  43796. {
  43797. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43798. {
  43799. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43800. }
  43801. }
  43802. }
  43803. void TextEditor::mouseUp (const MouseEvent& e)
  43804. {
  43805. newTransaction();
  43806. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43807. if (wasFocused || ! selectAllTextWhenFocused)
  43808. {
  43809. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43810. {
  43811. moveCaret (getTextIndexAt (e.x, e.y));
  43812. }
  43813. }
  43814. wasFocused = true;
  43815. }
  43816. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43817. {
  43818. int tokenEnd = getTextIndexAt (e.x, e.y);
  43819. int tokenStart = tokenEnd;
  43820. if (e.getNumberOfClicks() > 3)
  43821. {
  43822. tokenStart = 0;
  43823. tokenEnd = getTotalNumChars();
  43824. }
  43825. else
  43826. {
  43827. const String t (getText());
  43828. const int totalLength = getTotalNumChars();
  43829. while (tokenEnd < totalLength)
  43830. {
  43831. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43832. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43833. ++tokenEnd;
  43834. else
  43835. break;
  43836. }
  43837. tokenStart = tokenEnd;
  43838. while (tokenStart > 0)
  43839. {
  43840. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43841. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43842. --tokenStart;
  43843. else
  43844. break;
  43845. }
  43846. if (e.getNumberOfClicks() > 2)
  43847. {
  43848. while (tokenEnd < totalLength)
  43849. {
  43850. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43851. ++tokenEnd;
  43852. else
  43853. break;
  43854. }
  43855. while (tokenStart > 0)
  43856. {
  43857. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43858. --tokenStart;
  43859. else
  43860. break;
  43861. }
  43862. }
  43863. }
  43864. moveCursorTo (tokenEnd, false);
  43865. moveCursorTo (tokenStart, true);
  43866. }
  43867. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43868. {
  43869. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43870. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43871. }
  43872. bool TextEditor::keyPressed (const KeyPress& key)
  43873. {
  43874. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43875. return false;
  43876. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43877. if (key.isKeyCode (KeyPress::leftKey)
  43878. || key.isKeyCode (KeyPress::upKey))
  43879. {
  43880. newTransaction();
  43881. int newPos;
  43882. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43883. newPos = indexAtPosition (cursorX, cursorY - 1);
  43884. else if (moveInWholeWordSteps)
  43885. newPos = findWordBreakBefore (getCaretPosition());
  43886. else
  43887. newPos = getCaretPosition() - 1;
  43888. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43889. }
  43890. else if (key.isKeyCode (KeyPress::rightKey)
  43891. || key.isKeyCode (KeyPress::downKey))
  43892. {
  43893. newTransaction();
  43894. int newPos;
  43895. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43896. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43897. else if (moveInWholeWordSteps)
  43898. newPos = findWordBreakAfter (getCaretPosition());
  43899. else
  43900. newPos = getCaretPosition() + 1;
  43901. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43902. }
  43903. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43904. {
  43905. newTransaction();
  43906. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43907. key.getModifiers().isShiftDown());
  43908. }
  43909. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43910. {
  43911. newTransaction();
  43912. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43913. key.getModifiers().isShiftDown());
  43914. }
  43915. else if (key.isKeyCode (KeyPress::homeKey))
  43916. {
  43917. newTransaction();
  43918. if (isMultiLine() && ! moveInWholeWordSteps)
  43919. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43920. key.getModifiers().isShiftDown());
  43921. else
  43922. moveCursorTo (0, key.getModifiers().isShiftDown());
  43923. }
  43924. else if (key.isKeyCode (KeyPress::endKey))
  43925. {
  43926. newTransaction();
  43927. if (isMultiLine() && ! moveInWholeWordSteps)
  43928. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43929. key.getModifiers().isShiftDown());
  43930. else
  43931. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43932. }
  43933. else if (key.isKeyCode (KeyPress::backspaceKey))
  43934. {
  43935. if (moveInWholeWordSteps)
  43936. {
  43937. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43938. }
  43939. else
  43940. {
  43941. if (selection.isEmpty() && selection.getStart() > 0)
  43942. selection.setStart (selection.getEnd() - 1);
  43943. }
  43944. cut();
  43945. }
  43946. else if (key.isKeyCode (KeyPress::deleteKey))
  43947. {
  43948. if (key.getModifiers().isShiftDown())
  43949. copy();
  43950. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43951. selection.setEnd (selection.getStart() + 1);
  43952. cut();
  43953. }
  43954. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43955. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43956. {
  43957. newTransaction();
  43958. copy();
  43959. }
  43960. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43961. {
  43962. newTransaction();
  43963. copy();
  43964. cut();
  43965. }
  43966. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43967. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43968. {
  43969. newTransaction();
  43970. paste();
  43971. }
  43972. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43973. {
  43974. newTransaction();
  43975. doUndoRedo (false);
  43976. }
  43977. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43978. {
  43979. newTransaction();
  43980. doUndoRedo (true);
  43981. }
  43982. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43983. {
  43984. newTransaction();
  43985. moveCursorTo (getTotalNumChars(), false);
  43986. moveCursorTo (0, true);
  43987. }
  43988. else if (key == KeyPress::returnKey)
  43989. {
  43990. newTransaction();
  43991. insertTextAtCaret ("\n");
  43992. }
  43993. else if (key.isKeyCode (KeyPress::escapeKey))
  43994. {
  43995. newTransaction();
  43996. moveCursorTo (getCaretPosition(), false);
  43997. escapePressed();
  43998. }
  43999. else if (key.getTextCharacter() >= ' '
  44000. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  44001. {
  44002. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  44003. lastTransactionTime = Time::getApproximateMillisecondCounter();
  44004. }
  44005. else
  44006. {
  44007. return false;
  44008. }
  44009. return true;
  44010. }
  44011. bool TextEditor::keyStateChanged (const bool isKeyDown)
  44012. {
  44013. if (! isKeyDown)
  44014. return false;
  44015. #if JUCE_WINDOWS
  44016. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  44017. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  44018. #endif
  44019. // (overridden to avoid forwarding key events to the parent)
  44020. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  44021. }
  44022. const int baseMenuItemID = 0x7fff0000;
  44023. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  44024. {
  44025. const bool writable = ! isReadOnly();
  44026. if (passwordCharacter == 0)
  44027. {
  44028. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  44029. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  44030. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  44031. }
  44032. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  44033. m.addSeparator();
  44034. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  44035. m.addSeparator();
  44036. if (getUndoManager() != 0)
  44037. {
  44038. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  44039. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  44040. }
  44041. }
  44042. void TextEditor::performPopupMenuAction (const int menuItemID)
  44043. {
  44044. switch (menuItemID)
  44045. {
  44046. case baseMenuItemID + 1:
  44047. copy();
  44048. cut();
  44049. break;
  44050. case baseMenuItemID + 2:
  44051. copy();
  44052. break;
  44053. case baseMenuItemID + 3:
  44054. paste();
  44055. break;
  44056. case baseMenuItemID + 4:
  44057. cut();
  44058. break;
  44059. case baseMenuItemID + 5:
  44060. moveCursorTo (getTotalNumChars(), false);
  44061. moveCursorTo (0, true);
  44062. break;
  44063. case baseMenuItemID + 6:
  44064. doUndoRedo (false);
  44065. break;
  44066. case baseMenuItemID + 7:
  44067. doUndoRedo (true);
  44068. break;
  44069. default:
  44070. break;
  44071. }
  44072. }
  44073. void TextEditor::focusGained (FocusChangeType)
  44074. {
  44075. newTransaction();
  44076. caretFlashState = true;
  44077. if (selectAllTextWhenFocused)
  44078. {
  44079. moveCursorTo (0, false);
  44080. moveCursorTo (getTotalNumChars(), true);
  44081. }
  44082. repaint();
  44083. if (caretVisible)
  44084. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  44085. ComponentPeer* const peer = getPeer();
  44086. if (peer != 0 && ! isReadOnly())
  44087. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  44088. }
  44089. void TextEditor::focusLost (FocusChangeType)
  44090. {
  44091. newTransaction();
  44092. wasFocused = false;
  44093. textHolder->stopTimer();
  44094. caretFlashState = false;
  44095. postCommandMessage (TextEditorDefs::focusLossMessageId);
  44096. repaint();
  44097. }
  44098. void TextEditor::resized()
  44099. {
  44100. viewport->setBoundsInset (borderSize);
  44101. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  44102. updateTextHolderSize();
  44103. if (! isMultiLine())
  44104. {
  44105. scrollToMakeSureCursorIsVisible();
  44106. }
  44107. else
  44108. {
  44109. updateCaretPosition();
  44110. }
  44111. }
  44112. void TextEditor::handleCommandMessage (const int commandId)
  44113. {
  44114. Component::BailOutChecker checker (this);
  44115. switch (commandId)
  44116. {
  44117. case TextEditorDefs::textChangeMessageId:
  44118. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  44119. break;
  44120. case TextEditorDefs::returnKeyMessageId:
  44121. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  44122. break;
  44123. case TextEditorDefs::escapeKeyMessageId:
  44124. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  44125. break;
  44126. case TextEditorDefs::focusLossMessageId:
  44127. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  44128. break;
  44129. default:
  44130. jassertfalse;
  44131. break;
  44132. }
  44133. }
  44134. void TextEditor::enablementChanged()
  44135. {
  44136. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  44137. : MouseCursor::IBeamCursor);
  44138. repaint();
  44139. }
  44140. UndoManager* TextEditor::getUndoManager() throw()
  44141. {
  44142. return isReadOnly() ? 0 : &undoManager;
  44143. }
  44144. void TextEditor::clearInternal (UndoManager* const um)
  44145. {
  44146. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  44147. }
  44148. void TextEditor::insert (const String& text,
  44149. const int insertIndex,
  44150. const Font& font,
  44151. const Colour& colour,
  44152. UndoManager* const um,
  44153. const int caretPositionToMoveTo)
  44154. {
  44155. if (text.isNotEmpty())
  44156. {
  44157. if (um != 0)
  44158. {
  44159. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44160. newTransaction();
  44161. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  44162. caretPosition, caretPositionToMoveTo));
  44163. }
  44164. else
  44165. {
  44166. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  44167. // a line gets moved due to word wrap
  44168. int index = 0;
  44169. int nextIndex = 0;
  44170. for (int i = 0; i < sections.size(); ++i)
  44171. {
  44172. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44173. if (insertIndex == index)
  44174. {
  44175. sections.insert (i, new UniformTextSection (text,
  44176. font, colour,
  44177. passwordCharacter));
  44178. break;
  44179. }
  44180. else if (insertIndex > index && insertIndex < nextIndex)
  44181. {
  44182. splitSection (i, insertIndex - index);
  44183. sections.insert (i + 1, new UniformTextSection (text,
  44184. font, colour,
  44185. passwordCharacter));
  44186. break;
  44187. }
  44188. index = nextIndex;
  44189. }
  44190. if (nextIndex == insertIndex)
  44191. sections.add (new UniformTextSection (text,
  44192. font, colour,
  44193. passwordCharacter));
  44194. coalesceSimilarSections();
  44195. totalNumChars = -1;
  44196. valueTextNeedsUpdating = true;
  44197. moveCursorTo (caretPositionToMoveTo, false);
  44198. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  44199. }
  44200. }
  44201. }
  44202. void TextEditor::reinsert (const int insertIndex,
  44203. const Array <UniformTextSection*>& sectionsToInsert)
  44204. {
  44205. int index = 0;
  44206. int nextIndex = 0;
  44207. for (int i = 0; i < sections.size(); ++i)
  44208. {
  44209. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44210. if (insertIndex == index)
  44211. {
  44212. for (int j = sectionsToInsert.size(); --j >= 0;)
  44213. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44214. break;
  44215. }
  44216. else if (insertIndex > index && insertIndex < nextIndex)
  44217. {
  44218. splitSection (i, insertIndex - index);
  44219. for (int j = sectionsToInsert.size(); --j >= 0;)
  44220. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44221. break;
  44222. }
  44223. index = nextIndex;
  44224. }
  44225. if (nextIndex == insertIndex)
  44226. {
  44227. for (int j = 0; j < sectionsToInsert.size(); ++j)
  44228. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44229. }
  44230. coalesceSimilarSections();
  44231. totalNumChars = -1;
  44232. valueTextNeedsUpdating = true;
  44233. }
  44234. void TextEditor::remove (const Range<int>& range,
  44235. UndoManager* const um,
  44236. const int caretPositionToMoveTo)
  44237. {
  44238. if (! range.isEmpty())
  44239. {
  44240. int index = 0;
  44241. for (int i = 0; i < sections.size(); ++i)
  44242. {
  44243. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  44244. if (range.getStart() > index && range.getStart() < nextIndex)
  44245. {
  44246. splitSection (i, range.getStart() - index);
  44247. --i;
  44248. }
  44249. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  44250. {
  44251. splitSection (i, range.getEnd() - index);
  44252. --i;
  44253. }
  44254. else
  44255. {
  44256. index = nextIndex;
  44257. if (index > range.getEnd())
  44258. break;
  44259. }
  44260. }
  44261. index = 0;
  44262. if (um != 0)
  44263. {
  44264. Array <UniformTextSection*> removedSections;
  44265. for (int i = 0; i < sections.size(); ++i)
  44266. {
  44267. if (range.getEnd() <= range.getStart())
  44268. break;
  44269. UniformTextSection* const section = sections.getUnchecked (i);
  44270. const int nextIndex = index + section->getTotalLength();
  44271. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  44272. removedSections.add (new UniformTextSection (*section));
  44273. index = nextIndex;
  44274. }
  44275. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44276. newTransaction();
  44277. um->perform (new RemoveAction (*this, range, caretPosition,
  44278. caretPositionToMoveTo, removedSections));
  44279. }
  44280. else
  44281. {
  44282. Range<int> remainingRange (range);
  44283. for (int i = 0; i < sections.size(); ++i)
  44284. {
  44285. UniformTextSection* const section = sections.getUnchecked (i);
  44286. const int nextIndex = index + section->getTotalLength();
  44287. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44288. {
  44289. sections.remove(i);
  44290. section->clear();
  44291. delete section;
  44292. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44293. if (remainingRange.isEmpty())
  44294. break;
  44295. --i;
  44296. }
  44297. else
  44298. {
  44299. index = nextIndex;
  44300. }
  44301. }
  44302. coalesceSimilarSections();
  44303. totalNumChars = -1;
  44304. valueTextNeedsUpdating = true;
  44305. moveCursorTo (caretPositionToMoveTo, false);
  44306. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44307. }
  44308. }
  44309. }
  44310. const String TextEditor::getText() const
  44311. {
  44312. String t;
  44313. t.preallocateStorage (getTotalNumChars());
  44314. String::Concatenator concatenator (t);
  44315. for (int i = 0; i < sections.size(); ++i)
  44316. sections.getUnchecked (i)->appendAllText (concatenator);
  44317. return t;
  44318. }
  44319. const String TextEditor::getTextInRange (const Range<int>& range) const
  44320. {
  44321. String t;
  44322. if (! range.isEmpty())
  44323. {
  44324. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44325. String::Concatenator concatenator (t);
  44326. int index = 0;
  44327. for (int i = 0; i < sections.size(); ++i)
  44328. {
  44329. const UniformTextSection* const s = sections.getUnchecked (i);
  44330. const int nextIndex = index + s->getTotalLength();
  44331. if (range.getStart() < nextIndex)
  44332. {
  44333. if (range.getEnd() <= index)
  44334. break;
  44335. s->appendSubstring (concatenator, range - index);
  44336. }
  44337. index = nextIndex;
  44338. }
  44339. }
  44340. return t;
  44341. }
  44342. const String TextEditor::getHighlightedText() const
  44343. {
  44344. return getTextInRange (selection);
  44345. }
  44346. int TextEditor::getTotalNumChars() const
  44347. {
  44348. if (totalNumChars < 0)
  44349. {
  44350. totalNumChars = 0;
  44351. for (int i = sections.size(); --i >= 0;)
  44352. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44353. }
  44354. return totalNumChars;
  44355. }
  44356. bool TextEditor::isEmpty() const
  44357. {
  44358. return getTotalNumChars() == 0;
  44359. }
  44360. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44361. {
  44362. const float wordWrapWidth = getWordWrapWidth();
  44363. if (wordWrapWidth > 0 && sections.size() > 0)
  44364. {
  44365. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44366. i.getCharPosition (index, cx, cy, lineHeight);
  44367. }
  44368. else
  44369. {
  44370. cx = cy = 0;
  44371. lineHeight = currentFont.getHeight();
  44372. }
  44373. }
  44374. int TextEditor::indexAtPosition (const float x, const float y)
  44375. {
  44376. const float wordWrapWidth = getWordWrapWidth();
  44377. if (wordWrapWidth > 0)
  44378. {
  44379. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44380. while (i.next())
  44381. {
  44382. if (i.lineY + i.lineHeight > y)
  44383. {
  44384. if (i.lineY > y)
  44385. return jmax (0, i.indexInText - 1);
  44386. if (i.atomX >= x)
  44387. return i.indexInText;
  44388. if (x < i.atomRight)
  44389. return i.xToIndex (x);
  44390. }
  44391. }
  44392. }
  44393. return getTotalNumChars();
  44394. }
  44395. int TextEditor::findWordBreakAfter (const int position) const
  44396. {
  44397. const String t (getTextInRange (Range<int> (position, position + 512)));
  44398. const int totalLength = t.length();
  44399. int i = 0;
  44400. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44401. ++i;
  44402. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44403. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44404. ++i;
  44405. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44406. ++i;
  44407. return position + i;
  44408. }
  44409. int TextEditor::findWordBreakBefore (const int position) const
  44410. {
  44411. if (position <= 0)
  44412. return 0;
  44413. const int startOfBuffer = jmax (0, position - 512);
  44414. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44415. int i = position - startOfBuffer;
  44416. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44417. --i;
  44418. if (i > 0)
  44419. {
  44420. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44421. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44422. --i;
  44423. }
  44424. jassert (startOfBuffer + i >= 0);
  44425. return startOfBuffer + i;
  44426. }
  44427. void TextEditor::splitSection (const int sectionIndex,
  44428. const int charToSplitAt)
  44429. {
  44430. jassert (sections[sectionIndex] != 0);
  44431. sections.insert (sectionIndex + 1,
  44432. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44433. }
  44434. void TextEditor::coalesceSimilarSections()
  44435. {
  44436. for (int i = 0; i < sections.size() - 1; ++i)
  44437. {
  44438. UniformTextSection* const s1 = sections.getUnchecked (i);
  44439. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44440. if (s1->font == s2->font
  44441. && s1->colour == s2->colour)
  44442. {
  44443. s1->append (*s2, passwordCharacter);
  44444. sections.remove (i + 1);
  44445. delete s2;
  44446. --i;
  44447. }
  44448. }
  44449. }
  44450. END_JUCE_NAMESPACE
  44451. /*** End of inlined file: juce_TextEditor.cpp ***/
  44452. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44453. BEGIN_JUCE_NAMESPACE
  44454. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44455. class ToolbarSpacerComp : public ToolbarItemComponent
  44456. {
  44457. public:
  44458. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44459. : ToolbarItemComponent (itemId_, String::empty, false),
  44460. fixedSize (fixedSize_),
  44461. drawBar (drawBar_)
  44462. {
  44463. }
  44464. ~ToolbarSpacerComp()
  44465. {
  44466. }
  44467. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44468. int& preferredSize, int& minSize, int& maxSize)
  44469. {
  44470. if (fixedSize <= 0)
  44471. {
  44472. preferredSize = toolbarThickness * 2;
  44473. minSize = 4;
  44474. maxSize = 32768;
  44475. }
  44476. else
  44477. {
  44478. maxSize = roundToInt (toolbarThickness * fixedSize);
  44479. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44480. preferredSize = maxSize;
  44481. if (getEditingMode() == editableOnPalette)
  44482. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44483. }
  44484. return true;
  44485. }
  44486. void paintButtonArea (Graphics&, int, int, bool, bool)
  44487. {
  44488. }
  44489. void contentAreaChanged (const Rectangle<int>&)
  44490. {
  44491. }
  44492. int getResizeOrder() const throw()
  44493. {
  44494. return fixedSize <= 0 ? 0 : 1;
  44495. }
  44496. void paint (Graphics& g)
  44497. {
  44498. const int w = getWidth();
  44499. const int h = getHeight();
  44500. if (drawBar)
  44501. {
  44502. g.setColour (findColour (Toolbar::separatorColourId, true));
  44503. const float thickness = 0.2f;
  44504. if (isToolbarVertical())
  44505. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44506. else
  44507. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44508. }
  44509. if (getEditingMode() != normalMode && ! drawBar)
  44510. {
  44511. g.setColour (findColour (Toolbar::separatorColourId, true));
  44512. const int indentX = jmin (2, (w - 3) / 2);
  44513. const int indentY = jmin (2, (h - 3) / 2);
  44514. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44515. if (fixedSize <= 0)
  44516. {
  44517. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44518. if (isToolbarVertical())
  44519. {
  44520. x1 = w * 0.5f;
  44521. y1 = h * 0.4f;
  44522. x2 = x1;
  44523. y2 = indentX * 2.0f;
  44524. x3 = x1;
  44525. y3 = h * 0.6f;
  44526. x4 = x1;
  44527. y4 = h - y2;
  44528. hw = w * 0.15f;
  44529. hl = w * 0.2f;
  44530. }
  44531. else
  44532. {
  44533. x1 = w * 0.4f;
  44534. y1 = h * 0.5f;
  44535. x2 = indentX * 2.0f;
  44536. y2 = y1;
  44537. x3 = w * 0.6f;
  44538. y3 = y1;
  44539. x4 = w - x2;
  44540. y4 = y1;
  44541. hw = h * 0.15f;
  44542. hl = h * 0.2f;
  44543. }
  44544. Path p;
  44545. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44546. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44547. g.fillPath (p);
  44548. }
  44549. }
  44550. }
  44551. juce_UseDebuggingNewOperator
  44552. private:
  44553. const float fixedSize;
  44554. const bool drawBar;
  44555. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44556. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44557. };
  44558. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44559. {
  44560. public:
  44561. MissingItemsComponent (Toolbar& owner_, const int height_)
  44562. : PopupMenuCustomComponent (true),
  44563. owner (owner_),
  44564. height (height_)
  44565. {
  44566. for (int i = owner_.items.size(); --i >= 0;)
  44567. {
  44568. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44569. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44570. {
  44571. oldIndexes.insert (0, i);
  44572. addAndMakeVisible (tc, 0);
  44573. }
  44574. }
  44575. layout (400);
  44576. }
  44577. ~MissingItemsComponent()
  44578. {
  44579. // deleting the toolbar while its menu it open??
  44580. jassert (owner.isValidComponent());
  44581. for (int i = 0; i < getNumChildComponents(); ++i)
  44582. {
  44583. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44584. if (tc != 0)
  44585. {
  44586. tc->setVisible (false);
  44587. const int index = oldIndexes.remove (i);
  44588. owner.addChildComponent (tc, index);
  44589. --i;
  44590. }
  44591. }
  44592. owner.resized();
  44593. }
  44594. void layout (const int preferredWidth)
  44595. {
  44596. const int indent = 8;
  44597. int x = indent;
  44598. int y = indent;
  44599. int maxX = 0;
  44600. for (int i = 0; i < getNumChildComponents(); ++i)
  44601. {
  44602. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44603. if (tc != 0)
  44604. {
  44605. int preferredSize = 1, minSize = 1, maxSize = 1;
  44606. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44607. {
  44608. if (x + preferredSize > preferredWidth && x > indent)
  44609. {
  44610. x = indent;
  44611. y += height;
  44612. }
  44613. tc->setBounds (x, y, preferredSize, height);
  44614. x += preferredSize;
  44615. maxX = jmax (maxX, x);
  44616. }
  44617. }
  44618. }
  44619. setSize (maxX + 8, y + height + 8);
  44620. }
  44621. void getIdealSize (int& idealWidth, int& idealHeight)
  44622. {
  44623. idealWidth = getWidth();
  44624. idealHeight = getHeight();
  44625. }
  44626. juce_UseDebuggingNewOperator
  44627. private:
  44628. Toolbar& owner;
  44629. const int height;
  44630. Array <int> oldIndexes;
  44631. MissingItemsComponent (const MissingItemsComponent&);
  44632. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44633. };
  44634. Toolbar::Toolbar()
  44635. : vertical (false),
  44636. isEditingActive (false),
  44637. toolbarStyle (Toolbar::iconsOnly)
  44638. {
  44639. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44640. missingItemsButton->setAlwaysOnTop (true);
  44641. missingItemsButton->addButtonListener (this);
  44642. }
  44643. Toolbar::~Toolbar()
  44644. {
  44645. animator.cancelAllAnimations (true);
  44646. deleteAllChildren();
  44647. }
  44648. void Toolbar::setVertical (const bool shouldBeVertical)
  44649. {
  44650. if (vertical != shouldBeVertical)
  44651. {
  44652. vertical = shouldBeVertical;
  44653. resized();
  44654. }
  44655. }
  44656. void Toolbar::clear()
  44657. {
  44658. for (int i = items.size(); --i >= 0;)
  44659. {
  44660. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44661. items.remove (i);
  44662. delete tc;
  44663. }
  44664. resized();
  44665. }
  44666. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44667. {
  44668. if (itemId == ToolbarItemFactory::separatorBarId)
  44669. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44670. else if (itemId == ToolbarItemFactory::spacerId)
  44671. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44672. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44673. return new ToolbarSpacerComp (itemId, 0, false);
  44674. return factory.createItem (itemId);
  44675. }
  44676. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44677. const int itemId,
  44678. const int insertIndex)
  44679. {
  44680. // An ID can't be zero - this might indicate a mistake somewhere?
  44681. jassert (itemId != 0);
  44682. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44683. if (tc != 0)
  44684. {
  44685. #if JUCE_DEBUG
  44686. Array <int> allowedIds;
  44687. factory.getAllToolbarItemIds (allowedIds);
  44688. // If your factory can create an item for a given ID, it must also return
  44689. // that ID from its getAllToolbarItemIds() method!
  44690. jassert (allowedIds.contains (itemId));
  44691. #endif
  44692. items.insert (insertIndex, tc);
  44693. addAndMakeVisible (tc, insertIndex);
  44694. }
  44695. }
  44696. void Toolbar::addItem (ToolbarItemFactory& factory,
  44697. const int itemId,
  44698. const int insertIndex)
  44699. {
  44700. addItemInternal (factory, itemId, insertIndex);
  44701. resized();
  44702. }
  44703. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44704. {
  44705. Array <int> ids;
  44706. factoryToUse.getDefaultItemSet (ids);
  44707. clear();
  44708. for (int i = 0; i < ids.size(); ++i)
  44709. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44710. resized();
  44711. }
  44712. void Toolbar::removeToolbarItem (const int itemIndex)
  44713. {
  44714. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44715. if (tc != 0)
  44716. {
  44717. items.removeValue (tc);
  44718. delete tc;
  44719. resized();
  44720. }
  44721. }
  44722. int Toolbar::getNumItems() const throw()
  44723. {
  44724. return items.size();
  44725. }
  44726. int Toolbar::getItemId (const int itemIndex) const throw()
  44727. {
  44728. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44729. return tc != 0 ? tc->getItemId() : 0;
  44730. }
  44731. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44732. {
  44733. return items [itemIndex];
  44734. }
  44735. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44736. {
  44737. for (;;)
  44738. {
  44739. index += delta;
  44740. ToolbarItemComponent* const tc = getItemComponent (index);
  44741. if (tc == 0)
  44742. break;
  44743. if (tc->isActive)
  44744. return tc;
  44745. }
  44746. return 0;
  44747. }
  44748. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44749. {
  44750. if (toolbarStyle != newStyle)
  44751. {
  44752. toolbarStyle = newStyle;
  44753. updateAllItemPositions (false);
  44754. }
  44755. }
  44756. const String Toolbar::toString() const
  44757. {
  44758. String s ("TB:");
  44759. for (int i = 0; i < getNumItems(); ++i)
  44760. s << getItemId(i) << ' ';
  44761. return s.trimEnd();
  44762. }
  44763. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44764. const String& savedVersion)
  44765. {
  44766. if (! savedVersion.startsWith ("TB:"))
  44767. return false;
  44768. StringArray tokens;
  44769. tokens.addTokens (savedVersion.substring (3), false);
  44770. clear();
  44771. for (int i = 0; i < tokens.size(); ++i)
  44772. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44773. resized();
  44774. return true;
  44775. }
  44776. void Toolbar::paint (Graphics& g)
  44777. {
  44778. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44779. }
  44780. int Toolbar::getThickness() const throw()
  44781. {
  44782. return vertical ? getWidth() : getHeight();
  44783. }
  44784. int Toolbar::getLength() const throw()
  44785. {
  44786. return vertical ? getHeight() : getWidth();
  44787. }
  44788. void Toolbar::setEditingActive (const bool active)
  44789. {
  44790. if (isEditingActive != active)
  44791. {
  44792. isEditingActive = active;
  44793. updateAllItemPositions (false);
  44794. }
  44795. }
  44796. void Toolbar::resized()
  44797. {
  44798. updateAllItemPositions (false);
  44799. }
  44800. void Toolbar::updateAllItemPositions (const bool animate)
  44801. {
  44802. if (getWidth() > 0 && getHeight() > 0)
  44803. {
  44804. StretchableObjectResizer resizer;
  44805. int i;
  44806. for (i = 0; i < items.size(); ++i)
  44807. {
  44808. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44809. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44810. : ToolbarItemComponent::normalMode);
  44811. tc->setStyle (toolbarStyle);
  44812. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44813. int preferredSize = 1, minSize = 1, maxSize = 1;
  44814. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44815. preferredSize, minSize, maxSize))
  44816. {
  44817. tc->isActive = true;
  44818. resizer.addItem (preferredSize, minSize, maxSize,
  44819. spacer != 0 ? spacer->getResizeOrder() : 2);
  44820. }
  44821. else
  44822. {
  44823. tc->isActive = false;
  44824. tc->setVisible (false);
  44825. }
  44826. }
  44827. resizer.resizeToFit (getLength());
  44828. int totalLength = 0;
  44829. for (i = 0; i < resizer.getNumItems(); ++i)
  44830. totalLength += (int) resizer.getItemSize (i);
  44831. const bool itemsOffTheEnd = totalLength > getLength();
  44832. const int extrasButtonSize = getThickness() / 2;
  44833. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44834. missingItemsButton->setVisible (itemsOffTheEnd);
  44835. missingItemsButton->setEnabled (! isEditingActive);
  44836. if (vertical)
  44837. missingItemsButton->setCentrePosition (getWidth() / 2,
  44838. getHeight() - 4 - extrasButtonSize / 2);
  44839. else
  44840. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44841. getHeight() / 2);
  44842. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44843. : missingItemsButton->getX()) - 4
  44844. : getLength();
  44845. int pos = 0, activeIndex = 0;
  44846. for (i = 0; i < items.size(); ++i)
  44847. {
  44848. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44849. if (tc->isActive)
  44850. {
  44851. const int size = (int) resizer.getItemSize (activeIndex++);
  44852. Rectangle<int> newBounds;
  44853. if (vertical)
  44854. newBounds.setBounds (0, pos, getWidth(), size);
  44855. else
  44856. newBounds.setBounds (pos, 0, size, getHeight());
  44857. if (animate)
  44858. {
  44859. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  44860. }
  44861. else
  44862. {
  44863. animator.cancelAnimation (tc, false);
  44864. tc->setBounds (newBounds);
  44865. }
  44866. pos += size;
  44867. tc->setVisible (pos <= maxLength
  44868. && ((! tc->isBeingDragged)
  44869. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44870. }
  44871. }
  44872. }
  44873. }
  44874. void Toolbar::buttonClicked (Button*)
  44875. {
  44876. jassert (missingItemsButton->isShowing());
  44877. if (missingItemsButton->isShowing())
  44878. {
  44879. PopupMenu m;
  44880. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44881. m.showAt (missingItemsButton);
  44882. }
  44883. }
  44884. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44885. Component* /*sourceComponent*/)
  44886. {
  44887. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44888. }
  44889. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44890. {
  44891. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44892. if (tc != 0)
  44893. {
  44894. if (getNumItems() == 0)
  44895. {
  44896. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44897. {
  44898. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44899. if (palette != 0)
  44900. palette->replaceComponent (tc);
  44901. }
  44902. else
  44903. {
  44904. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44905. }
  44906. items.add (tc);
  44907. addChildComponent (tc);
  44908. updateAllItemPositions (false);
  44909. }
  44910. else
  44911. {
  44912. for (int i = getNumItems(); --i >= 0;)
  44913. {
  44914. int currentIndex = getIndexOfChildComponent (tc);
  44915. if (currentIndex < 0)
  44916. {
  44917. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44918. {
  44919. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44920. if (palette != 0)
  44921. palette->replaceComponent (tc);
  44922. }
  44923. else
  44924. {
  44925. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44926. }
  44927. items.add (tc);
  44928. addChildComponent (tc);
  44929. currentIndex = getIndexOfChildComponent (tc);
  44930. updateAllItemPositions (true);
  44931. }
  44932. int newIndex = currentIndex;
  44933. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44934. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44935. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  44936. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44937. if (prev != 0)
  44938. {
  44939. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  44940. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44941. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44942. {
  44943. newIndex = getIndexOfChildComponent (prev);
  44944. }
  44945. }
  44946. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44947. if (next != 0)
  44948. {
  44949. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  44950. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44951. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44952. {
  44953. newIndex = getIndexOfChildComponent (next) + 1;
  44954. }
  44955. }
  44956. if (newIndex != currentIndex)
  44957. {
  44958. items.removeValue (tc);
  44959. removeChildComponent (tc);
  44960. addChildComponent (tc, newIndex);
  44961. items.insert (newIndex, tc);
  44962. updateAllItemPositions (true);
  44963. }
  44964. else
  44965. {
  44966. break;
  44967. }
  44968. }
  44969. }
  44970. }
  44971. }
  44972. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44973. {
  44974. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44975. if (tc != 0)
  44976. {
  44977. if (isParentOf (tc))
  44978. {
  44979. items.removeValue (tc);
  44980. removeChildComponent (tc);
  44981. updateAllItemPositions (true);
  44982. }
  44983. }
  44984. }
  44985. void Toolbar::itemDropped (const String&, Component*, int, int)
  44986. {
  44987. }
  44988. void Toolbar::mouseDown (const MouseEvent& e)
  44989. {
  44990. if (e.mods.isPopupMenu())
  44991. {
  44992. }
  44993. }
  44994. class ToolbarCustomisationDialog : public DialogWindow
  44995. {
  44996. public:
  44997. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44998. Toolbar* const toolbar_,
  44999. const int optionFlags)
  45000. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  45001. toolbar (toolbar_)
  45002. {
  45003. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  45004. setResizable (true, true);
  45005. setResizeLimits (400, 300, 1500, 1000);
  45006. positionNearBar();
  45007. }
  45008. ~ToolbarCustomisationDialog()
  45009. {
  45010. setContentComponent (0, true);
  45011. }
  45012. void closeButtonPressed()
  45013. {
  45014. setVisible (false);
  45015. }
  45016. bool canModalEventBeSentToComponent (const Component* comp)
  45017. {
  45018. return toolbar->isParentOf (comp);
  45019. }
  45020. void positionNearBar()
  45021. {
  45022. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  45023. const int tbx = toolbar->getScreenX();
  45024. const int tby = toolbar->getScreenY();
  45025. const int gap = 8;
  45026. int x, y;
  45027. if (toolbar->isVertical())
  45028. {
  45029. y = tby;
  45030. if (tbx > screenSize.getCentreX())
  45031. x = tbx - getWidth() - gap;
  45032. else
  45033. x = tbx + toolbar->getWidth() + gap;
  45034. }
  45035. else
  45036. {
  45037. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  45038. if (tby > screenSize.getCentreY())
  45039. y = tby - getHeight() - gap;
  45040. else
  45041. y = tby + toolbar->getHeight() + gap;
  45042. }
  45043. setTopLeftPosition (x, y);
  45044. }
  45045. private:
  45046. Toolbar* const toolbar;
  45047. class CustomiserPanel : public Component,
  45048. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  45049. private ButtonListener
  45050. {
  45051. public:
  45052. CustomiserPanel (ToolbarItemFactory& factory_,
  45053. Toolbar* const toolbar_,
  45054. const int optionFlags)
  45055. : factory (factory_),
  45056. toolbar (toolbar_),
  45057. styleBox (0),
  45058. defaultButton (0)
  45059. {
  45060. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  45061. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  45062. | Toolbar::allowIconsWithTextChoice
  45063. | Toolbar::allowTextOnlyChoice)) != 0)
  45064. {
  45065. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  45066. styleBox->setEditableText (false);
  45067. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  45068. styleBox->addItem (TRANS("Show icons only"), 1);
  45069. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  45070. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  45071. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  45072. styleBox->addItem (TRANS("Show descriptions only"), 3);
  45073. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  45074. styleBox->setSelectedId (1);
  45075. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  45076. styleBox->setSelectedId (2);
  45077. else if (toolbar_->getStyle() == Toolbar::textOnly)
  45078. styleBox->setSelectedId (3);
  45079. styleBox->addListener (this);
  45080. }
  45081. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  45082. {
  45083. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  45084. defaultButton->addButtonListener (this);
  45085. }
  45086. addAndMakeVisible (instructions = new Label (String::empty,
  45087. 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.")));
  45088. instructions->setFont (Font (13.0f));
  45089. setSize (500, 300);
  45090. }
  45091. ~CustomiserPanel()
  45092. {
  45093. deleteAllChildren();
  45094. }
  45095. void comboBoxChanged (ComboBox*)
  45096. {
  45097. if (styleBox->getSelectedId() == 1)
  45098. toolbar->setStyle (Toolbar::iconsOnly);
  45099. else if (styleBox->getSelectedId() == 2)
  45100. toolbar->setStyle (Toolbar::iconsWithText);
  45101. else if (styleBox->getSelectedId() == 3)
  45102. toolbar->setStyle (Toolbar::textOnly);
  45103. palette->resized(); // to make it update the styles
  45104. }
  45105. void buttonClicked (Button*)
  45106. {
  45107. toolbar->addDefaultItems (factory);
  45108. }
  45109. void paint (Graphics& g)
  45110. {
  45111. Colour background;
  45112. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  45113. if (dw != 0)
  45114. background = dw->getBackgroundColour();
  45115. g.setColour (background.contrasting().withAlpha (0.3f));
  45116. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  45117. }
  45118. void resized()
  45119. {
  45120. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  45121. if (styleBox != 0)
  45122. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  45123. if (defaultButton != 0)
  45124. {
  45125. defaultButton->changeWidthToFitText (22);
  45126. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  45127. }
  45128. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  45129. }
  45130. private:
  45131. ToolbarItemFactory& factory;
  45132. Toolbar* const toolbar;
  45133. Label* instructions;
  45134. ToolbarItemPalette* palette;
  45135. ComboBox* styleBox;
  45136. TextButton* defaultButton;
  45137. };
  45138. };
  45139. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  45140. {
  45141. setEditingActive (true);
  45142. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  45143. dw.runModalLoop();
  45144. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  45145. setEditingActive (false);
  45146. }
  45147. END_JUCE_NAMESPACE
  45148. /*** End of inlined file: juce_Toolbar.cpp ***/
  45149. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  45150. BEGIN_JUCE_NAMESPACE
  45151. ToolbarItemFactory::ToolbarItemFactory()
  45152. {
  45153. }
  45154. ToolbarItemFactory::~ToolbarItemFactory()
  45155. {
  45156. }
  45157. class ItemDragAndDropOverlayComponent : public Component
  45158. {
  45159. public:
  45160. ItemDragAndDropOverlayComponent()
  45161. : isDragging (false)
  45162. {
  45163. setAlwaysOnTop (true);
  45164. setRepaintsOnMouseActivity (true);
  45165. setMouseCursor (MouseCursor::DraggingHandCursor);
  45166. }
  45167. ~ItemDragAndDropOverlayComponent()
  45168. {
  45169. }
  45170. void paint (Graphics& g)
  45171. {
  45172. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45173. if (isMouseOverOrDragging()
  45174. && tc != 0
  45175. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45176. {
  45177. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  45178. g.drawRect (0, 0, getWidth(), getHeight(),
  45179. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  45180. }
  45181. }
  45182. void mouseDown (const MouseEvent& e)
  45183. {
  45184. isDragging = false;
  45185. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45186. if (tc != 0)
  45187. {
  45188. tc->dragOffsetX = e.x;
  45189. tc->dragOffsetY = e.y;
  45190. }
  45191. }
  45192. void mouseDrag (const MouseEvent& e)
  45193. {
  45194. if (! (isDragging || e.mouseWasClicked()))
  45195. {
  45196. isDragging = true;
  45197. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  45198. if (dnd != 0)
  45199. {
  45200. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  45201. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45202. if (tc != 0)
  45203. {
  45204. tc->isBeingDragged = true;
  45205. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45206. tc->setVisible (false);
  45207. }
  45208. }
  45209. }
  45210. }
  45211. void mouseUp (const MouseEvent&)
  45212. {
  45213. isDragging = false;
  45214. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45215. if (tc != 0)
  45216. {
  45217. tc->isBeingDragged = false;
  45218. Toolbar* const tb = tc->getToolbar();
  45219. if (tb != 0)
  45220. tb->updateAllItemPositions (true);
  45221. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45222. delete tc;
  45223. }
  45224. }
  45225. void parentSizeChanged()
  45226. {
  45227. setBounds (0, 0, getParentWidth(), getParentHeight());
  45228. }
  45229. juce_UseDebuggingNewOperator
  45230. private:
  45231. bool isDragging;
  45232. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  45233. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  45234. };
  45235. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  45236. const String& labelText,
  45237. const bool isBeingUsedAsAButton_)
  45238. : Button (labelText),
  45239. itemId (itemId_),
  45240. mode (normalMode),
  45241. toolbarStyle (Toolbar::iconsOnly),
  45242. dragOffsetX (0),
  45243. dragOffsetY (0),
  45244. isActive (true),
  45245. isBeingDragged (false),
  45246. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  45247. {
  45248. // Your item ID can't be 0!
  45249. jassert (itemId_ != 0);
  45250. }
  45251. ToolbarItemComponent::~ToolbarItemComponent()
  45252. {
  45253. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45254. overlayComp = 0;
  45255. }
  45256. Toolbar* ToolbarItemComponent::getToolbar() const
  45257. {
  45258. return dynamic_cast <Toolbar*> (getParentComponent());
  45259. }
  45260. bool ToolbarItemComponent::isToolbarVertical() const
  45261. {
  45262. const Toolbar* const t = getToolbar();
  45263. return t != 0 && t->isVertical();
  45264. }
  45265. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  45266. {
  45267. if (toolbarStyle != newStyle)
  45268. {
  45269. toolbarStyle = newStyle;
  45270. repaint();
  45271. resized();
  45272. }
  45273. }
  45274. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  45275. {
  45276. if (isBeingUsedAsAButton)
  45277. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45278. over, down, *this);
  45279. if (toolbarStyle != Toolbar::iconsOnly)
  45280. {
  45281. const int indent = contentArea.getX();
  45282. int y = indent;
  45283. int h = getHeight() - indent * 2;
  45284. if (toolbarStyle == Toolbar::iconsWithText)
  45285. {
  45286. y = contentArea.getBottom() + indent / 2;
  45287. h -= contentArea.getHeight();
  45288. }
  45289. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45290. getButtonText(), *this);
  45291. }
  45292. if (! contentArea.isEmpty())
  45293. {
  45294. g.saveState();
  45295. g.setOrigin (contentArea.getX(), contentArea.getY());
  45296. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  45297. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45298. g.restoreState();
  45299. }
  45300. }
  45301. void ToolbarItemComponent::resized()
  45302. {
  45303. if (toolbarStyle != Toolbar::textOnly)
  45304. {
  45305. const int indent = jmin (proportionOfWidth (0.08f),
  45306. proportionOfHeight (0.08f));
  45307. contentArea = Rectangle<int> (indent, indent,
  45308. getWidth() - indent * 2,
  45309. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45310. : (getHeight() - indent * 2));
  45311. }
  45312. else
  45313. {
  45314. contentArea = Rectangle<int>();
  45315. }
  45316. contentAreaChanged (contentArea);
  45317. }
  45318. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45319. {
  45320. if (mode != newMode)
  45321. {
  45322. mode = newMode;
  45323. repaint();
  45324. if (mode == normalMode)
  45325. {
  45326. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45327. overlayComp = 0;
  45328. }
  45329. else if (overlayComp == 0)
  45330. {
  45331. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45332. overlayComp->parentSizeChanged();
  45333. }
  45334. resized();
  45335. }
  45336. }
  45337. END_JUCE_NAMESPACE
  45338. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45339. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45340. BEGIN_JUCE_NAMESPACE
  45341. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45342. Toolbar* const toolbar_)
  45343. : factory (factory_),
  45344. toolbar (toolbar_)
  45345. {
  45346. Component* const itemHolder = new Component();
  45347. Array <int> allIds;
  45348. factory_.getAllToolbarItemIds (allIds);
  45349. for (int i = 0; i < allIds.size(); ++i)
  45350. {
  45351. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45352. jassert (tc != 0);
  45353. if (tc != 0)
  45354. {
  45355. itemHolder->addAndMakeVisible (tc);
  45356. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45357. }
  45358. }
  45359. viewport = new Viewport();
  45360. viewport->setViewedComponent (itemHolder);
  45361. addAndMakeVisible (viewport);
  45362. }
  45363. ToolbarItemPalette::~ToolbarItemPalette()
  45364. {
  45365. viewport->getViewedComponent()->deleteAllChildren();
  45366. deleteAllChildren();
  45367. }
  45368. void ToolbarItemPalette::resized()
  45369. {
  45370. viewport->setBoundsInset (BorderSize (1));
  45371. Component* const itemHolder = viewport->getViewedComponent();
  45372. const int indent = 8;
  45373. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  45374. const int height = toolbar->getThickness();
  45375. int x = indent;
  45376. int y = indent;
  45377. int maxX = 0;
  45378. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45379. {
  45380. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45381. if (tc != 0)
  45382. {
  45383. tc->setStyle (toolbar->getStyle());
  45384. int preferredSize = 1, minSize = 1, maxSize = 1;
  45385. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45386. {
  45387. if (x + preferredSize > preferredWidth && x > indent)
  45388. {
  45389. x = indent;
  45390. y += height;
  45391. }
  45392. tc->setBounds (x, y, preferredSize, height);
  45393. x += preferredSize + 8;
  45394. maxX = jmax (maxX, x);
  45395. }
  45396. }
  45397. }
  45398. itemHolder->setSize (maxX, y + height + 8);
  45399. }
  45400. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45401. {
  45402. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45403. jassert (tc != 0);
  45404. if (tc != 0)
  45405. {
  45406. tc->setBounds (comp->getBounds());
  45407. tc->setStyle (toolbar->getStyle());
  45408. tc->setEditingMode (comp->getEditingMode());
  45409. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45410. }
  45411. }
  45412. END_JUCE_NAMESPACE
  45413. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45414. /*** Start of inlined file: juce_TreeView.cpp ***/
  45415. BEGIN_JUCE_NAMESPACE
  45416. class TreeViewContentComponent : public Component,
  45417. public TooltipClient
  45418. {
  45419. public:
  45420. TreeViewContentComponent (TreeView& owner_)
  45421. : owner (owner_),
  45422. buttonUnderMouse (0),
  45423. isDragging (false)
  45424. {
  45425. }
  45426. ~TreeViewContentComponent()
  45427. {
  45428. deleteAllChildren();
  45429. }
  45430. void mouseDown (const MouseEvent& e)
  45431. {
  45432. updateButtonUnderMouse (e);
  45433. isDragging = false;
  45434. needSelectionOnMouseUp = false;
  45435. Rectangle<int> pos;
  45436. TreeViewItem* const item = findItemAt (e.y, pos);
  45437. if (item == 0)
  45438. return;
  45439. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45440. // as selection clicks)
  45441. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45442. {
  45443. if (e.x >= pos.getX() - owner.getIndentSize())
  45444. item->setOpen (! item->isOpen());
  45445. // (clicks to the left of an open/close button are ignored)
  45446. }
  45447. else
  45448. {
  45449. // mouse-down inside the body of the item..
  45450. if (! owner.isMultiSelectEnabled())
  45451. item->setSelected (true, true);
  45452. else if (item->isSelected())
  45453. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45454. else
  45455. selectBasedOnModifiers (item, e.mods);
  45456. if (e.x >= pos.getX())
  45457. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45458. }
  45459. }
  45460. void mouseUp (const MouseEvent& e)
  45461. {
  45462. updateButtonUnderMouse (e);
  45463. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45464. {
  45465. Rectangle<int> pos;
  45466. TreeViewItem* const item = findItemAt (e.y, pos);
  45467. if (item != 0)
  45468. selectBasedOnModifiers (item, e.mods);
  45469. }
  45470. }
  45471. void mouseDoubleClick (const MouseEvent& e)
  45472. {
  45473. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45474. {
  45475. Rectangle<int> pos;
  45476. TreeViewItem* const item = findItemAt (e.y, pos);
  45477. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45478. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45479. }
  45480. }
  45481. void mouseDrag (const MouseEvent& e)
  45482. {
  45483. if (isEnabled()
  45484. && ! (isDragging || e.mouseWasClicked()
  45485. || e.getDistanceFromDragStart() < 5
  45486. || e.mods.isPopupMenu()))
  45487. {
  45488. isDragging = true;
  45489. Rectangle<int> pos;
  45490. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45491. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45492. {
  45493. const String dragDescription (item->getDragSourceDescription());
  45494. if (dragDescription.isNotEmpty())
  45495. {
  45496. DragAndDropContainer* const dragContainer
  45497. = DragAndDropContainer::findParentDragContainerFor (this);
  45498. if (dragContainer != 0)
  45499. {
  45500. pos.setSize (pos.getWidth(), item->itemHeight);
  45501. Image dragImage (Component::createComponentSnapshot (pos, true));
  45502. dragImage.multiplyAllAlphas (0.6f);
  45503. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45504. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45505. }
  45506. else
  45507. {
  45508. // to be able to do a drag-and-drop operation, the treeview needs to
  45509. // be inside a component which is also a DragAndDropContainer.
  45510. jassertfalse;
  45511. }
  45512. }
  45513. }
  45514. }
  45515. }
  45516. void mouseMove (const MouseEvent& e)
  45517. {
  45518. updateButtonUnderMouse (e);
  45519. }
  45520. void mouseExit (const MouseEvent& e)
  45521. {
  45522. updateButtonUnderMouse (e);
  45523. }
  45524. void paint (Graphics& g)
  45525. {
  45526. if (owner.rootItem != 0)
  45527. {
  45528. owner.handleAsyncUpdate();
  45529. if (! owner.rootItemVisible)
  45530. g.setOrigin (0, -owner.rootItem->itemHeight);
  45531. owner.rootItem->paintRecursively (g, getWidth());
  45532. }
  45533. }
  45534. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45535. {
  45536. if (owner.rootItem != 0)
  45537. {
  45538. owner.handleAsyncUpdate();
  45539. if (! owner.rootItemVisible)
  45540. y += owner.rootItem->itemHeight;
  45541. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45542. if (ti != 0)
  45543. itemPosition = ti->getItemPosition (false);
  45544. return ti;
  45545. }
  45546. return 0;
  45547. }
  45548. void updateComponents()
  45549. {
  45550. const int visibleTop = -getY();
  45551. const int visibleBottom = visibleTop + getParentHeight();
  45552. BigInteger itemsToKeep;
  45553. {
  45554. TreeViewItem* item = owner.rootItem;
  45555. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45556. while (item != 0 && y < visibleBottom)
  45557. {
  45558. y += item->itemHeight;
  45559. if (y >= visibleTop)
  45560. {
  45561. const int index = rowComponentIds.indexOf (item->uid);
  45562. if (index < 0)
  45563. {
  45564. Component* const comp = item->createItemComponent();
  45565. if (comp != 0)
  45566. {
  45567. addAndMakeVisible (comp);
  45568. itemsToKeep.setBit (rowComponentItems.size());
  45569. rowComponentItems.add (item);
  45570. rowComponentIds.add (item->uid);
  45571. rowComponents.add (comp);
  45572. }
  45573. }
  45574. else
  45575. {
  45576. itemsToKeep.setBit (index);
  45577. }
  45578. }
  45579. item = item->getNextVisibleItem (true);
  45580. }
  45581. }
  45582. for (int i = rowComponentItems.size(); --i >= 0;)
  45583. {
  45584. Component* const comp = rowComponents.getUnchecked(i);
  45585. bool keep = false;
  45586. if (isParentOf (comp))
  45587. {
  45588. if (itemsToKeep[i])
  45589. {
  45590. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  45591. Rectangle<int> pos (item->getItemPosition (false));
  45592. pos.setSize (pos.getWidth(), item->itemHeight);
  45593. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45594. {
  45595. keep = true;
  45596. comp->setBounds (pos);
  45597. }
  45598. }
  45599. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  45600. {
  45601. keep = true;
  45602. comp->setSize (0, 0);
  45603. }
  45604. }
  45605. if (! keep)
  45606. {
  45607. delete comp;
  45608. rowComponents.remove (i);
  45609. rowComponentIds.remove (i);
  45610. rowComponentItems.remove (i);
  45611. }
  45612. }
  45613. }
  45614. void updateButtonUnderMouse (const MouseEvent& e)
  45615. {
  45616. TreeViewItem* newItem = 0;
  45617. if (owner.openCloseButtonsVisible)
  45618. {
  45619. Rectangle<int> pos;
  45620. TreeViewItem* item = findItemAt (e.y, pos);
  45621. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45622. {
  45623. newItem = item;
  45624. if (! newItem->mightContainSubItems())
  45625. newItem = 0;
  45626. }
  45627. }
  45628. if (buttonUnderMouse != newItem)
  45629. {
  45630. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45631. {
  45632. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45633. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45634. }
  45635. buttonUnderMouse = newItem;
  45636. if (buttonUnderMouse != 0)
  45637. {
  45638. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45639. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45640. }
  45641. }
  45642. }
  45643. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45644. {
  45645. return item == buttonUnderMouse;
  45646. }
  45647. void resized()
  45648. {
  45649. owner.itemsChanged();
  45650. }
  45651. const String getTooltip()
  45652. {
  45653. Rectangle<int> pos;
  45654. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45655. if (item != 0)
  45656. return item->getTooltip();
  45657. return owner.getTooltip();
  45658. }
  45659. juce_UseDebuggingNewOperator
  45660. private:
  45661. TreeView& owner;
  45662. Array <TreeViewItem*> rowComponentItems;
  45663. Array <int> rowComponentIds;
  45664. Array <Component*> rowComponents;
  45665. TreeViewItem* buttonUnderMouse;
  45666. bool isDragging, needSelectionOnMouseUp;
  45667. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45668. {
  45669. TreeViewItem* firstSelected = 0;
  45670. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45671. {
  45672. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45673. jassert (lastSelected != 0);
  45674. int rowStart = firstSelected->getRowNumberInTree();
  45675. int rowEnd = lastSelected->getRowNumberInTree();
  45676. if (rowStart > rowEnd)
  45677. swapVariables (rowStart, rowEnd);
  45678. int ourRow = item->getRowNumberInTree();
  45679. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45680. if (ourRow > otherEnd)
  45681. swapVariables (ourRow, otherEnd);
  45682. for (int i = ourRow; i <= otherEnd; ++i)
  45683. owner.getItemOnRow (i)->setSelected (true, false);
  45684. }
  45685. else
  45686. {
  45687. const bool cmd = modifiers.isCommandDown();
  45688. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45689. }
  45690. }
  45691. bool containsItem (TreeViewItem* const item) const
  45692. {
  45693. for (int i = rowComponentItems.size(); --i >= 0;)
  45694. if (rowComponentItems.getUnchecked(i) == item)
  45695. return true;
  45696. return false;
  45697. }
  45698. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45699. {
  45700. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45701. {
  45702. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45703. if (source->isDragging())
  45704. {
  45705. Component* const underMouse = source->getComponentUnderMouse();
  45706. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45707. return true;
  45708. }
  45709. }
  45710. return false;
  45711. }
  45712. TreeViewContentComponent (const TreeViewContentComponent&);
  45713. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45714. };
  45715. class TreeView::TreeViewport : public Viewport
  45716. {
  45717. public:
  45718. TreeViewport() throw() : lastX (-1) {}
  45719. ~TreeViewport() throw() {}
  45720. void updateComponents (const bool triggerResize = false)
  45721. {
  45722. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45723. if (tvc != 0)
  45724. {
  45725. if (triggerResize)
  45726. tvc->resized();
  45727. else
  45728. tvc->updateComponents();
  45729. }
  45730. repaint();
  45731. }
  45732. void visibleAreaChanged (int x, int, int, int)
  45733. {
  45734. const bool hasScrolledSideways = (x != lastX);
  45735. lastX = x;
  45736. updateComponents (hasScrolledSideways);
  45737. }
  45738. juce_UseDebuggingNewOperator
  45739. private:
  45740. int lastX;
  45741. TreeViewport (const TreeViewport&);
  45742. TreeViewport& operator= (const TreeViewport&);
  45743. };
  45744. TreeView::TreeView (const String& componentName)
  45745. : Component (componentName),
  45746. rootItem (0),
  45747. indentSize (24),
  45748. defaultOpenness (false),
  45749. needsRecalculating (true),
  45750. rootItemVisible (true),
  45751. multiSelectEnabled (false),
  45752. openCloseButtonsVisible (true)
  45753. {
  45754. addAndMakeVisible (viewport = new TreeViewport());
  45755. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45756. viewport->setWantsKeyboardFocus (false);
  45757. setWantsKeyboardFocus (true);
  45758. }
  45759. TreeView::~TreeView()
  45760. {
  45761. if (rootItem != 0)
  45762. rootItem->setOwnerView (0);
  45763. }
  45764. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45765. {
  45766. if (rootItem != newRootItem)
  45767. {
  45768. if (newRootItem != 0)
  45769. {
  45770. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45771. if (newRootItem->ownerView != 0)
  45772. newRootItem->ownerView->setRootItem (0);
  45773. }
  45774. if (rootItem != 0)
  45775. rootItem->setOwnerView (0);
  45776. rootItem = newRootItem;
  45777. if (newRootItem != 0)
  45778. newRootItem->setOwnerView (this);
  45779. needsRecalculating = true;
  45780. handleAsyncUpdate();
  45781. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45782. {
  45783. rootItem->setOpen (false); // force a re-open
  45784. rootItem->setOpen (true);
  45785. }
  45786. }
  45787. }
  45788. void TreeView::deleteRootItem()
  45789. {
  45790. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45791. setRootItem (0);
  45792. }
  45793. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45794. {
  45795. rootItemVisible = shouldBeVisible;
  45796. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45797. {
  45798. rootItem->setOpen (false); // force a re-open
  45799. rootItem->setOpen (true);
  45800. }
  45801. itemsChanged();
  45802. }
  45803. void TreeView::colourChanged()
  45804. {
  45805. setOpaque (findColour (backgroundColourId).isOpaque());
  45806. repaint();
  45807. }
  45808. void TreeView::setIndentSize (const int newIndentSize)
  45809. {
  45810. if (indentSize != newIndentSize)
  45811. {
  45812. indentSize = newIndentSize;
  45813. resized();
  45814. }
  45815. }
  45816. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45817. {
  45818. if (defaultOpenness != isOpenByDefault)
  45819. {
  45820. defaultOpenness = isOpenByDefault;
  45821. itemsChanged();
  45822. }
  45823. }
  45824. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45825. {
  45826. multiSelectEnabled = canMultiSelect;
  45827. }
  45828. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45829. {
  45830. if (openCloseButtonsVisible != shouldBeVisible)
  45831. {
  45832. openCloseButtonsVisible = shouldBeVisible;
  45833. itemsChanged();
  45834. }
  45835. }
  45836. Viewport* TreeView::getViewport() const throw()
  45837. {
  45838. return viewport;
  45839. }
  45840. void TreeView::clearSelectedItems()
  45841. {
  45842. if (rootItem != 0)
  45843. rootItem->deselectAllRecursively();
  45844. }
  45845. int TreeView::getNumSelectedItems() const throw()
  45846. {
  45847. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45848. }
  45849. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45850. {
  45851. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45852. }
  45853. int TreeView::getNumRowsInTree() const
  45854. {
  45855. if (rootItem != 0)
  45856. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45857. return 0;
  45858. }
  45859. TreeViewItem* TreeView::getItemOnRow (int index) const
  45860. {
  45861. if (! rootItemVisible)
  45862. ++index;
  45863. if (rootItem != 0 && index >= 0)
  45864. return rootItem->getItemOnRow (index);
  45865. return 0;
  45866. }
  45867. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45868. {
  45869. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45870. Rectangle<int> pos;
  45871. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45872. }
  45873. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45874. {
  45875. if (rootItem == 0)
  45876. return 0;
  45877. return rootItem->findItemFromIdentifierString (identifierString);
  45878. }
  45879. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45880. {
  45881. XmlElement* e = 0;
  45882. if (rootItem != 0)
  45883. {
  45884. e = rootItem->getOpennessState();
  45885. if (e != 0 && alsoIncludeScrollPosition)
  45886. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45887. }
  45888. return e;
  45889. }
  45890. void TreeView::restoreOpennessState (const XmlElement& newState)
  45891. {
  45892. if (rootItem != 0)
  45893. {
  45894. rootItem->restoreOpennessState (newState);
  45895. if (newState.hasAttribute ("scrollPos"))
  45896. viewport->setViewPosition (viewport->getViewPositionX(),
  45897. newState.getIntAttribute ("scrollPos"));
  45898. }
  45899. }
  45900. void TreeView::paint (Graphics& g)
  45901. {
  45902. g.fillAll (findColour (backgroundColourId));
  45903. }
  45904. void TreeView::resized()
  45905. {
  45906. viewport->setBounds (getLocalBounds());
  45907. itemsChanged();
  45908. handleAsyncUpdate();
  45909. }
  45910. void TreeView::enablementChanged()
  45911. {
  45912. repaint();
  45913. }
  45914. void TreeView::moveSelectedRow (int delta)
  45915. {
  45916. if (delta == 0)
  45917. return;
  45918. int rowSelected = 0;
  45919. TreeViewItem* const firstSelected = getSelectedItem (0);
  45920. if (firstSelected != 0)
  45921. rowSelected = firstSelected->getRowNumberInTree();
  45922. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45923. for (;;)
  45924. {
  45925. TreeViewItem* item = getItemOnRow (rowSelected);
  45926. if (item != 0)
  45927. {
  45928. if (! item->canBeSelected())
  45929. {
  45930. // if the row we want to highlight doesn't allow it, try skipping
  45931. // to the next item..
  45932. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45933. rowSelected + (delta < 0 ? -1 : 1));
  45934. if (rowSelected != nextRowToTry)
  45935. {
  45936. rowSelected = nextRowToTry;
  45937. continue;
  45938. }
  45939. else
  45940. {
  45941. break;
  45942. }
  45943. }
  45944. item->setSelected (true, true);
  45945. scrollToKeepItemVisible (item);
  45946. }
  45947. break;
  45948. }
  45949. }
  45950. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45951. {
  45952. if (item != 0 && item->ownerView == this)
  45953. {
  45954. handleAsyncUpdate();
  45955. item = item->getDeepestOpenParentItem();
  45956. int y = item->y;
  45957. int viewTop = viewport->getViewPositionY();
  45958. if (y < viewTop)
  45959. {
  45960. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45961. }
  45962. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45963. {
  45964. viewport->setViewPosition (viewport->getViewPositionX(),
  45965. (y + item->itemHeight) - viewport->getViewHeight());
  45966. }
  45967. }
  45968. }
  45969. bool TreeView::keyPressed (const KeyPress& key)
  45970. {
  45971. if (key.isKeyCode (KeyPress::upKey))
  45972. {
  45973. moveSelectedRow (-1);
  45974. }
  45975. else if (key.isKeyCode (KeyPress::downKey))
  45976. {
  45977. moveSelectedRow (1);
  45978. }
  45979. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45980. {
  45981. if (rootItem != 0)
  45982. {
  45983. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45984. if (key.isKeyCode (KeyPress::pageUpKey))
  45985. rowsOnScreen = -rowsOnScreen;
  45986. moveSelectedRow (rowsOnScreen);
  45987. }
  45988. }
  45989. else if (key.isKeyCode (KeyPress::homeKey))
  45990. {
  45991. moveSelectedRow (-0x3fffffff);
  45992. }
  45993. else if (key.isKeyCode (KeyPress::endKey))
  45994. {
  45995. moveSelectedRow (0x3fffffff);
  45996. }
  45997. else if (key.isKeyCode (KeyPress::returnKey))
  45998. {
  45999. TreeViewItem* const firstSelected = getSelectedItem (0);
  46000. if (firstSelected != 0)
  46001. firstSelected->setOpen (! firstSelected->isOpen());
  46002. }
  46003. else if (key.isKeyCode (KeyPress::leftKey))
  46004. {
  46005. TreeViewItem* const firstSelected = getSelectedItem (0);
  46006. if (firstSelected != 0)
  46007. {
  46008. if (firstSelected->isOpen())
  46009. {
  46010. firstSelected->setOpen (false);
  46011. }
  46012. else
  46013. {
  46014. TreeViewItem* parent = firstSelected->parentItem;
  46015. if ((! rootItemVisible) && parent == rootItem)
  46016. parent = 0;
  46017. if (parent != 0)
  46018. {
  46019. parent->setSelected (true, true);
  46020. scrollToKeepItemVisible (parent);
  46021. }
  46022. }
  46023. }
  46024. }
  46025. else if (key.isKeyCode (KeyPress::rightKey))
  46026. {
  46027. TreeViewItem* const firstSelected = getSelectedItem (0);
  46028. if (firstSelected != 0)
  46029. {
  46030. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  46031. moveSelectedRow (1);
  46032. else
  46033. firstSelected->setOpen (true);
  46034. }
  46035. }
  46036. else
  46037. {
  46038. return false;
  46039. }
  46040. return true;
  46041. }
  46042. void TreeView::itemsChanged() throw()
  46043. {
  46044. needsRecalculating = true;
  46045. repaint();
  46046. triggerAsyncUpdate();
  46047. }
  46048. void TreeView::handleAsyncUpdate()
  46049. {
  46050. if (needsRecalculating)
  46051. {
  46052. needsRecalculating = false;
  46053. const ScopedLock sl (nodeAlterationLock);
  46054. if (rootItem != 0)
  46055. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  46056. viewport->updateComponents();
  46057. if (rootItem != 0)
  46058. {
  46059. viewport->getViewedComponent()
  46060. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  46061. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  46062. }
  46063. else
  46064. {
  46065. viewport->getViewedComponent()->setSize (0, 0);
  46066. }
  46067. }
  46068. }
  46069. class TreeView::InsertPointHighlight : public Component
  46070. {
  46071. public:
  46072. InsertPointHighlight()
  46073. : lastItem (0)
  46074. {
  46075. setSize (100, 12);
  46076. setAlwaysOnTop (true);
  46077. setInterceptsMouseClicks (false, false);
  46078. }
  46079. ~InsertPointHighlight() {}
  46080. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  46081. {
  46082. lastItem = item;
  46083. lastIndex = insertIndex;
  46084. const int offset = getHeight() / 2;
  46085. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  46086. }
  46087. void paint (Graphics& g)
  46088. {
  46089. Path p;
  46090. const float h = (float) getHeight();
  46091. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  46092. p.startNewSubPath (h - 2.0f, h / 2.0f);
  46093. p.lineTo ((float) getWidth(), h / 2.0f);
  46094. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  46095. g.strokePath (p, PathStrokeType (2.0f));
  46096. }
  46097. TreeViewItem* lastItem;
  46098. int lastIndex;
  46099. private:
  46100. InsertPointHighlight (const InsertPointHighlight&);
  46101. InsertPointHighlight& operator= (const InsertPointHighlight&);
  46102. };
  46103. class TreeView::TargetGroupHighlight : public Component
  46104. {
  46105. public:
  46106. TargetGroupHighlight()
  46107. {
  46108. setAlwaysOnTop (true);
  46109. setInterceptsMouseClicks (false, false);
  46110. }
  46111. ~TargetGroupHighlight() {}
  46112. void setTargetPosition (TreeViewItem* const item) throw()
  46113. {
  46114. Rectangle<int> r (item->getItemPosition (true));
  46115. r.setHeight (item->getItemHeight());
  46116. setBounds (r);
  46117. }
  46118. void paint (Graphics& g)
  46119. {
  46120. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  46121. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  46122. }
  46123. private:
  46124. TargetGroupHighlight (const TargetGroupHighlight&);
  46125. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  46126. };
  46127. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  46128. {
  46129. beginDragAutoRepeat (100);
  46130. if (dragInsertPointHighlight == 0)
  46131. {
  46132. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  46133. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  46134. }
  46135. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  46136. dragTargetGroupHighlight->setTargetPosition (item);
  46137. }
  46138. void TreeView::hideDragHighlight() throw()
  46139. {
  46140. dragInsertPointHighlight = 0;
  46141. dragTargetGroupHighlight = 0;
  46142. }
  46143. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  46144. const StringArray& files, const String& sourceDescription,
  46145. Component* sourceComponent) const throw()
  46146. {
  46147. insertIndex = 0;
  46148. TreeViewItem* item = getItemAt (y);
  46149. if (item == 0)
  46150. return 0;
  46151. Rectangle<int> itemPos (item->getItemPosition (true));
  46152. insertIndex = item->getIndexInParent();
  46153. const int oldY = y;
  46154. y = itemPos.getY();
  46155. if (item->getNumSubItems() == 0 || ! item->isOpen())
  46156. {
  46157. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46158. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46159. {
  46160. // Check if we're trying to drag into an empty group item..
  46161. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  46162. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  46163. {
  46164. insertIndex = 0;
  46165. x = itemPos.getX() + getIndentSize();
  46166. y = itemPos.getBottom();
  46167. return item;
  46168. }
  46169. }
  46170. }
  46171. if (oldY > itemPos.getCentreY())
  46172. {
  46173. y += item->getItemHeight();
  46174. while (item->isLastOfSiblings() && item->parentItem != 0
  46175. && item->parentItem->parentItem != 0)
  46176. {
  46177. if (x > itemPos.getX())
  46178. break;
  46179. item = item->parentItem;
  46180. itemPos = item->getItemPosition (true);
  46181. insertIndex = item->getIndexInParent();
  46182. }
  46183. ++insertIndex;
  46184. }
  46185. x = itemPos.getX();
  46186. return item->parentItem;
  46187. }
  46188. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46189. {
  46190. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  46191. int insertIndex;
  46192. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46193. if (item != 0)
  46194. {
  46195. if (scrolled || dragInsertPointHighlight == 0
  46196. || dragInsertPointHighlight->lastItem != item
  46197. || dragInsertPointHighlight->lastIndex != insertIndex)
  46198. {
  46199. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46200. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46201. showDragHighlight (item, insertIndex, x, y);
  46202. else
  46203. hideDragHighlight();
  46204. }
  46205. }
  46206. else
  46207. {
  46208. hideDragHighlight();
  46209. }
  46210. }
  46211. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46212. {
  46213. hideDragHighlight();
  46214. int insertIndex;
  46215. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46216. if (item != 0)
  46217. {
  46218. if (files.size() > 0)
  46219. {
  46220. if (item->isInterestedInFileDrag (files))
  46221. item->filesDropped (files, insertIndex);
  46222. }
  46223. else
  46224. {
  46225. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46226. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  46227. }
  46228. }
  46229. }
  46230. bool TreeView::isInterestedInFileDrag (const StringArray&)
  46231. {
  46232. return true;
  46233. }
  46234. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  46235. {
  46236. fileDragMove (files, x, y);
  46237. }
  46238. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  46239. {
  46240. handleDrag (files, String::empty, 0, x, y);
  46241. }
  46242. void TreeView::fileDragExit (const StringArray&)
  46243. {
  46244. hideDragHighlight();
  46245. }
  46246. void TreeView::filesDropped (const StringArray& files, int x, int y)
  46247. {
  46248. handleDrop (files, String::empty, 0, x, y);
  46249. }
  46250. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46251. {
  46252. return true;
  46253. }
  46254. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46255. {
  46256. itemDragMove (sourceDescription, sourceComponent, x, y);
  46257. }
  46258. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46259. {
  46260. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  46261. }
  46262. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46263. {
  46264. hideDragHighlight();
  46265. }
  46266. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46267. {
  46268. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  46269. }
  46270. enum TreeViewOpenness
  46271. {
  46272. opennessDefault = 0,
  46273. opennessClosed = 1,
  46274. opennessOpen = 2
  46275. };
  46276. TreeViewItem::TreeViewItem()
  46277. : ownerView (0),
  46278. parentItem (0),
  46279. y (0),
  46280. itemHeight (0),
  46281. totalHeight (0),
  46282. selected (false),
  46283. redrawNeeded (true),
  46284. drawLinesInside (true),
  46285. drawsInLeftMargin (false),
  46286. openness (opennessDefault)
  46287. {
  46288. static int nextUID = 0;
  46289. uid = nextUID++;
  46290. }
  46291. TreeViewItem::~TreeViewItem()
  46292. {
  46293. }
  46294. const String TreeViewItem::getUniqueName() const
  46295. {
  46296. return String::empty;
  46297. }
  46298. void TreeViewItem::itemOpennessChanged (bool)
  46299. {
  46300. }
  46301. int TreeViewItem::getNumSubItems() const throw()
  46302. {
  46303. return subItems.size();
  46304. }
  46305. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46306. {
  46307. return subItems [index];
  46308. }
  46309. void TreeViewItem::clearSubItems()
  46310. {
  46311. if (subItems.size() > 0)
  46312. {
  46313. if (ownerView != 0)
  46314. {
  46315. const ScopedLock sl (ownerView->nodeAlterationLock);
  46316. subItems.clear();
  46317. treeHasChanged();
  46318. }
  46319. else
  46320. {
  46321. subItems.clear();
  46322. }
  46323. }
  46324. }
  46325. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46326. {
  46327. if (newItem != 0)
  46328. {
  46329. newItem->parentItem = this;
  46330. newItem->setOwnerView (ownerView);
  46331. newItem->y = 0;
  46332. newItem->itemHeight = newItem->getItemHeight();
  46333. newItem->totalHeight = 0;
  46334. newItem->itemWidth = newItem->getItemWidth();
  46335. newItem->totalWidth = 0;
  46336. if (ownerView != 0)
  46337. {
  46338. const ScopedLock sl (ownerView->nodeAlterationLock);
  46339. subItems.insert (insertPosition, newItem);
  46340. treeHasChanged();
  46341. if (newItem->isOpen())
  46342. newItem->itemOpennessChanged (true);
  46343. }
  46344. else
  46345. {
  46346. subItems.insert (insertPosition, newItem);
  46347. if (newItem->isOpen())
  46348. newItem->itemOpennessChanged (true);
  46349. }
  46350. }
  46351. }
  46352. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46353. {
  46354. if (ownerView != 0)
  46355. {
  46356. const ScopedLock sl (ownerView->nodeAlterationLock);
  46357. if (((unsigned int) index) < (unsigned int) subItems.size())
  46358. {
  46359. subItems.remove (index, deleteItem);
  46360. treeHasChanged();
  46361. }
  46362. }
  46363. else
  46364. {
  46365. subItems.remove (index, deleteItem);
  46366. }
  46367. }
  46368. bool TreeViewItem::isOpen() const throw()
  46369. {
  46370. if (openness == opennessDefault)
  46371. return ownerView != 0 && ownerView->defaultOpenness;
  46372. else
  46373. return openness == opennessOpen;
  46374. }
  46375. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46376. {
  46377. if (isOpen() != shouldBeOpen)
  46378. {
  46379. openness = shouldBeOpen ? opennessOpen
  46380. : opennessClosed;
  46381. treeHasChanged();
  46382. itemOpennessChanged (isOpen());
  46383. }
  46384. }
  46385. bool TreeViewItem::isSelected() const throw()
  46386. {
  46387. return selected;
  46388. }
  46389. void TreeViewItem::deselectAllRecursively()
  46390. {
  46391. setSelected (false, false);
  46392. for (int i = 0; i < subItems.size(); ++i)
  46393. subItems.getUnchecked(i)->deselectAllRecursively();
  46394. }
  46395. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46396. const bool deselectOtherItemsFirst)
  46397. {
  46398. if (shouldBeSelected && ! canBeSelected())
  46399. return;
  46400. if (deselectOtherItemsFirst)
  46401. getTopLevelItem()->deselectAllRecursively();
  46402. if (shouldBeSelected != selected)
  46403. {
  46404. selected = shouldBeSelected;
  46405. if (ownerView != 0)
  46406. ownerView->repaint();
  46407. itemSelectionChanged (shouldBeSelected);
  46408. }
  46409. }
  46410. void TreeViewItem::paintItem (Graphics&, int, int)
  46411. {
  46412. }
  46413. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46414. {
  46415. ownerView->getLookAndFeel()
  46416. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46417. }
  46418. void TreeViewItem::itemClicked (const MouseEvent&)
  46419. {
  46420. }
  46421. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46422. {
  46423. if (mightContainSubItems())
  46424. setOpen (! isOpen());
  46425. }
  46426. void TreeViewItem::itemSelectionChanged (bool)
  46427. {
  46428. }
  46429. const String TreeViewItem::getTooltip()
  46430. {
  46431. return String::empty;
  46432. }
  46433. const String TreeViewItem::getDragSourceDescription()
  46434. {
  46435. return String::empty;
  46436. }
  46437. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46438. {
  46439. return false;
  46440. }
  46441. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46442. {
  46443. }
  46444. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46445. {
  46446. return false;
  46447. }
  46448. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46449. {
  46450. }
  46451. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46452. {
  46453. const int indentX = getIndentX();
  46454. int width = itemWidth;
  46455. if (ownerView != 0 && width < 0)
  46456. width = ownerView->viewport->getViewWidth() - indentX;
  46457. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46458. if (relativeToTreeViewTopLeft)
  46459. r -= ownerView->viewport->getViewPosition();
  46460. return r;
  46461. }
  46462. void TreeViewItem::treeHasChanged() const throw()
  46463. {
  46464. if (ownerView != 0)
  46465. ownerView->itemsChanged();
  46466. }
  46467. void TreeViewItem::repaintItem() const
  46468. {
  46469. if (ownerView != 0 && areAllParentsOpen())
  46470. {
  46471. Rectangle<int> r (getItemPosition (true));
  46472. r.setLeft (0);
  46473. ownerView->viewport->repaint (r);
  46474. }
  46475. }
  46476. bool TreeViewItem::areAllParentsOpen() const throw()
  46477. {
  46478. return parentItem == 0
  46479. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46480. }
  46481. void TreeViewItem::updatePositions (int newY)
  46482. {
  46483. y = newY;
  46484. itemHeight = getItemHeight();
  46485. totalHeight = itemHeight;
  46486. itemWidth = getItemWidth();
  46487. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46488. if (isOpen())
  46489. {
  46490. newY += totalHeight;
  46491. for (int i = 0; i < subItems.size(); ++i)
  46492. {
  46493. TreeViewItem* const ti = subItems.getUnchecked(i);
  46494. ti->updatePositions (newY);
  46495. newY += ti->totalHeight;
  46496. totalHeight += ti->totalHeight;
  46497. totalWidth = jmax (totalWidth, ti->totalWidth);
  46498. }
  46499. }
  46500. }
  46501. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46502. {
  46503. TreeViewItem* result = this;
  46504. TreeViewItem* item = this;
  46505. while (item->parentItem != 0)
  46506. {
  46507. item = item->parentItem;
  46508. if (! item->isOpen())
  46509. result = item;
  46510. }
  46511. return result;
  46512. }
  46513. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46514. {
  46515. ownerView = newOwner;
  46516. for (int i = subItems.size(); --i >= 0;)
  46517. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46518. }
  46519. int TreeViewItem::getIndentX() const throw()
  46520. {
  46521. const int indentWidth = ownerView->getIndentSize();
  46522. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46523. if (! ownerView->openCloseButtonsVisible)
  46524. x -= indentWidth;
  46525. TreeViewItem* p = parentItem;
  46526. while (p != 0)
  46527. {
  46528. x += indentWidth;
  46529. p = p->parentItem;
  46530. }
  46531. return x;
  46532. }
  46533. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46534. {
  46535. drawsInLeftMargin = canDrawInLeftMargin;
  46536. }
  46537. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46538. {
  46539. jassert (ownerView != 0);
  46540. if (ownerView == 0)
  46541. return;
  46542. const int indent = getIndentX();
  46543. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46544. {
  46545. g.saveState();
  46546. g.setOrigin (indent, 0);
  46547. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46548. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46549. paintItem (g, itemW, itemHeight);
  46550. g.restoreState();
  46551. }
  46552. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46553. const float halfH = itemHeight * 0.5f;
  46554. int depth = 0;
  46555. TreeViewItem* p = parentItem;
  46556. while (p != 0)
  46557. {
  46558. ++depth;
  46559. p = p->parentItem;
  46560. }
  46561. if (! ownerView->rootItemVisible)
  46562. --depth;
  46563. const int indentWidth = ownerView->getIndentSize();
  46564. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46565. {
  46566. float x = (depth + 0.5f) * indentWidth;
  46567. if (depth >= 0)
  46568. {
  46569. if (parentItem != 0 && parentItem->drawLinesInside)
  46570. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46571. if ((parentItem != 0 && parentItem->drawLinesInside)
  46572. || (parentItem == 0 && drawLinesInside))
  46573. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46574. }
  46575. p = parentItem;
  46576. int d = depth;
  46577. while (p != 0 && --d >= 0)
  46578. {
  46579. x -= (float) indentWidth;
  46580. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46581. && ! p->isLastOfSiblings())
  46582. {
  46583. g.drawLine (x, 0, x, (float) itemHeight);
  46584. }
  46585. p = p->parentItem;
  46586. }
  46587. if (mightContainSubItems())
  46588. {
  46589. g.saveState();
  46590. g.setOrigin (depth * indentWidth, 0);
  46591. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46592. paintOpenCloseButton (g, indentWidth, itemHeight,
  46593. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46594. ->isMouseOverButton (this));
  46595. g.restoreState();
  46596. }
  46597. }
  46598. if (isOpen())
  46599. {
  46600. const Rectangle<int> clip (g.getClipBounds());
  46601. for (int i = 0; i < subItems.size(); ++i)
  46602. {
  46603. TreeViewItem* const ti = subItems.getUnchecked(i);
  46604. const int relY = ti->y - y;
  46605. if (relY >= clip.getBottom())
  46606. break;
  46607. if (relY + ti->totalHeight >= clip.getY())
  46608. {
  46609. g.saveState();
  46610. g.setOrigin (0, relY);
  46611. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46612. ti->paintRecursively (g, width);
  46613. g.restoreState();
  46614. }
  46615. }
  46616. }
  46617. }
  46618. bool TreeViewItem::isLastOfSiblings() const throw()
  46619. {
  46620. return parentItem == 0
  46621. || parentItem->subItems.getLast() == this;
  46622. }
  46623. int TreeViewItem::getIndexInParent() const throw()
  46624. {
  46625. if (parentItem == 0)
  46626. return 0;
  46627. return parentItem->subItems.indexOf (this);
  46628. }
  46629. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46630. {
  46631. return (parentItem == 0) ? this
  46632. : parentItem->getTopLevelItem();
  46633. }
  46634. int TreeViewItem::getNumRows() const throw()
  46635. {
  46636. int num = 1;
  46637. if (isOpen())
  46638. {
  46639. for (int i = subItems.size(); --i >= 0;)
  46640. num += subItems.getUnchecked(i)->getNumRows();
  46641. }
  46642. return num;
  46643. }
  46644. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46645. {
  46646. if (index == 0)
  46647. return this;
  46648. if (index > 0 && isOpen())
  46649. {
  46650. --index;
  46651. for (int i = 0; i < subItems.size(); ++i)
  46652. {
  46653. TreeViewItem* const item = subItems.getUnchecked(i);
  46654. if (index == 0)
  46655. return item;
  46656. const int numRows = item->getNumRows();
  46657. if (numRows > index)
  46658. return item->getItemOnRow (index);
  46659. index -= numRows;
  46660. }
  46661. }
  46662. return 0;
  46663. }
  46664. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46665. {
  46666. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46667. {
  46668. const int h = itemHeight;
  46669. if (targetY < h)
  46670. return this;
  46671. if (isOpen())
  46672. {
  46673. targetY -= h;
  46674. for (int i = 0; i < subItems.size(); ++i)
  46675. {
  46676. TreeViewItem* const ti = subItems.getUnchecked(i);
  46677. if (targetY < ti->totalHeight)
  46678. return ti->findItemRecursively (targetY);
  46679. targetY -= ti->totalHeight;
  46680. }
  46681. }
  46682. }
  46683. return 0;
  46684. }
  46685. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46686. {
  46687. int total = 0;
  46688. if (isSelected())
  46689. ++total;
  46690. for (int i = subItems.size(); --i >= 0;)
  46691. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46692. return total;
  46693. }
  46694. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46695. {
  46696. if (isSelected())
  46697. {
  46698. if (index == 0)
  46699. return this;
  46700. --index;
  46701. }
  46702. if (index >= 0)
  46703. {
  46704. for (int i = 0; i < subItems.size(); ++i)
  46705. {
  46706. TreeViewItem* const item = subItems.getUnchecked(i);
  46707. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46708. if (found != 0)
  46709. return found;
  46710. index -= item->countSelectedItemsRecursively();
  46711. }
  46712. }
  46713. return 0;
  46714. }
  46715. int TreeViewItem::getRowNumberInTree() const throw()
  46716. {
  46717. if (parentItem != 0 && ownerView != 0)
  46718. {
  46719. int n = 1 + parentItem->getRowNumberInTree();
  46720. int ourIndex = parentItem->subItems.indexOf (this);
  46721. jassert (ourIndex >= 0);
  46722. while (--ourIndex >= 0)
  46723. n += parentItem->subItems [ourIndex]->getNumRows();
  46724. if (parentItem->parentItem == 0
  46725. && ! ownerView->rootItemVisible)
  46726. --n;
  46727. return n;
  46728. }
  46729. else
  46730. {
  46731. return 0;
  46732. }
  46733. }
  46734. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46735. {
  46736. drawLinesInside = drawLines;
  46737. }
  46738. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46739. {
  46740. if (recurse && isOpen() && subItems.size() > 0)
  46741. return subItems [0];
  46742. if (parentItem != 0)
  46743. {
  46744. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46745. if (nextIndex >= parentItem->subItems.size())
  46746. return parentItem->getNextVisibleItem (false);
  46747. return parentItem->subItems [nextIndex];
  46748. }
  46749. return 0;
  46750. }
  46751. const String TreeViewItem::getItemIdentifierString() const
  46752. {
  46753. String s;
  46754. if (parentItem != 0)
  46755. s = parentItem->getItemIdentifierString();
  46756. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46757. }
  46758. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46759. {
  46760. const String thisId (getUniqueName());
  46761. if (thisId == identifierString)
  46762. return this;
  46763. if (identifierString.startsWith (thisId + "/"))
  46764. {
  46765. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46766. bool wasOpen = isOpen();
  46767. setOpen (true);
  46768. for (int i = subItems.size(); --i >= 0;)
  46769. {
  46770. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46771. if (item != 0)
  46772. return item;
  46773. }
  46774. setOpen (wasOpen);
  46775. }
  46776. return 0;
  46777. }
  46778. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46779. {
  46780. if (e.hasTagName ("CLOSED"))
  46781. {
  46782. setOpen (false);
  46783. }
  46784. else if (e.hasTagName ("OPEN"))
  46785. {
  46786. setOpen (true);
  46787. forEachXmlChildElement (e, n)
  46788. {
  46789. const String id (n->getStringAttribute ("id"));
  46790. for (int i = 0; i < subItems.size(); ++i)
  46791. {
  46792. TreeViewItem* const ti = subItems.getUnchecked(i);
  46793. if (ti->getUniqueName() == id)
  46794. {
  46795. ti->restoreOpennessState (*n);
  46796. break;
  46797. }
  46798. }
  46799. }
  46800. }
  46801. }
  46802. XmlElement* TreeViewItem::getOpennessState() const throw()
  46803. {
  46804. const String name (getUniqueName());
  46805. if (name.isNotEmpty())
  46806. {
  46807. XmlElement* e;
  46808. if (isOpen())
  46809. {
  46810. e = new XmlElement ("OPEN");
  46811. for (int i = 0; i < subItems.size(); ++i)
  46812. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46813. }
  46814. else
  46815. {
  46816. e = new XmlElement ("CLOSED");
  46817. }
  46818. e->setAttribute ("id", name);
  46819. return e;
  46820. }
  46821. else
  46822. {
  46823. // trying to save the openness for an element that has no name - this won't
  46824. // work because it needs the names to identify what to open.
  46825. jassertfalse;
  46826. }
  46827. return 0;
  46828. }
  46829. END_JUCE_NAMESPACE
  46830. /*** End of inlined file: juce_TreeView.cpp ***/
  46831. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46832. BEGIN_JUCE_NAMESPACE
  46833. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46834. : fileList (listToShow)
  46835. {
  46836. }
  46837. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46838. {
  46839. }
  46840. FileBrowserListener::~FileBrowserListener()
  46841. {
  46842. }
  46843. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46844. {
  46845. listeners.add (listener);
  46846. }
  46847. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46848. {
  46849. listeners.remove (listener);
  46850. }
  46851. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46852. {
  46853. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46854. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46855. }
  46856. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46857. {
  46858. if (fileList.getDirectory().exists())
  46859. {
  46860. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46861. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46862. }
  46863. }
  46864. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46865. {
  46866. if (fileList.getDirectory().exists())
  46867. {
  46868. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46869. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46870. }
  46871. }
  46872. END_JUCE_NAMESPACE
  46873. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46874. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46875. BEGIN_JUCE_NAMESPACE
  46876. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46877. TimeSliceThread& thread_)
  46878. : fileFilter (fileFilter_),
  46879. thread (thread_),
  46880. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46881. fileFindHandle (0),
  46882. shouldStop (true)
  46883. {
  46884. }
  46885. DirectoryContentsList::~DirectoryContentsList()
  46886. {
  46887. clear();
  46888. }
  46889. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46890. {
  46891. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46892. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46893. }
  46894. bool DirectoryContentsList::ignoresHiddenFiles() const
  46895. {
  46896. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46897. }
  46898. const File& DirectoryContentsList::getDirectory() const
  46899. {
  46900. return root;
  46901. }
  46902. void DirectoryContentsList::setDirectory (const File& directory,
  46903. const bool includeDirectories,
  46904. const bool includeFiles)
  46905. {
  46906. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46907. if (directory != root)
  46908. {
  46909. clear();
  46910. root = directory;
  46911. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46912. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46913. }
  46914. int newFlags = fileTypeFlags;
  46915. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46916. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46917. setTypeFlags (newFlags);
  46918. }
  46919. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46920. {
  46921. if (fileTypeFlags != newFlags)
  46922. {
  46923. fileTypeFlags = newFlags;
  46924. refresh();
  46925. }
  46926. }
  46927. void DirectoryContentsList::clear()
  46928. {
  46929. shouldStop = true;
  46930. thread.removeTimeSliceClient (this);
  46931. fileFindHandle = 0;
  46932. if (files.size() > 0)
  46933. {
  46934. files.clear();
  46935. changed();
  46936. }
  46937. }
  46938. void DirectoryContentsList::refresh()
  46939. {
  46940. clear();
  46941. if (root.isDirectory())
  46942. {
  46943. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46944. shouldStop = false;
  46945. thread.addTimeSliceClient (this);
  46946. }
  46947. }
  46948. int DirectoryContentsList::getNumFiles() const
  46949. {
  46950. return files.size();
  46951. }
  46952. bool DirectoryContentsList::getFileInfo (const int index,
  46953. FileInfo& result) const
  46954. {
  46955. const ScopedLock sl (fileListLock);
  46956. const FileInfo* const info = files [index];
  46957. if (info != 0)
  46958. {
  46959. result = *info;
  46960. return true;
  46961. }
  46962. return false;
  46963. }
  46964. const File DirectoryContentsList::getFile (const int index) const
  46965. {
  46966. const ScopedLock sl (fileListLock);
  46967. const FileInfo* const info = files [index];
  46968. if (info != 0)
  46969. return root.getChildFile (info->filename);
  46970. return File::nonexistent;
  46971. }
  46972. bool DirectoryContentsList::isStillLoading() const
  46973. {
  46974. return fileFindHandle != 0;
  46975. }
  46976. void DirectoryContentsList::changed()
  46977. {
  46978. sendChangeMessage (this);
  46979. }
  46980. bool DirectoryContentsList::useTimeSlice()
  46981. {
  46982. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46983. bool hasChanged = false;
  46984. for (int i = 100; --i >= 0;)
  46985. {
  46986. if (! checkNextFile (hasChanged))
  46987. {
  46988. if (hasChanged)
  46989. changed();
  46990. return false;
  46991. }
  46992. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46993. break;
  46994. }
  46995. if (hasChanged)
  46996. changed();
  46997. return true;
  46998. }
  46999. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  47000. {
  47001. if (fileFindHandle != 0)
  47002. {
  47003. bool fileFoundIsDir, isHidden, isReadOnly;
  47004. int64 fileSize;
  47005. Time modTime, creationTime;
  47006. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  47007. &modTime, &creationTime, &isReadOnly))
  47008. {
  47009. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  47010. fileSize, modTime, creationTime, isReadOnly))
  47011. {
  47012. hasChanged = true;
  47013. }
  47014. return true;
  47015. }
  47016. else
  47017. {
  47018. fileFindHandle = 0;
  47019. }
  47020. }
  47021. return false;
  47022. }
  47023. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  47024. const DirectoryContentsList::FileInfo* const second)
  47025. {
  47026. #if JUCE_WINDOWS
  47027. if (first->isDirectory != second->isDirectory)
  47028. return first->isDirectory ? -1 : 1;
  47029. #endif
  47030. return first->filename.compareIgnoreCase (second->filename);
  47031. }
  47032. bool DirectoryContentsList::addFile (const File& file,
  47033. const bool isDir,
  47034. const int64 fileSize,
  47035. const Time& modTime,
  47036. const Time& creationTime,
  47037. const bool isReadOnly)
  47038. {
  47039. if (fileFilter == 0
  47040. || ((! isDir) && fileFilter->isFileSuitable (file))
  47041. || (isDir && fileFilter->isDirectorySuitable (file)))
  47042. {
  47043. ScopedPointer <FileInfo> info (new FileInfo());
  47044. info->filename = file.getFileName();
  47045. info->fileSize = fileSize;
  47046. info->modificationTime = modTime;
  47047. info->creationTime = creationTime;
  47048. info->isDirectory = isDir;
  47049. info->isReadOnly = isReadOnly;
  47050. const ScopedLock sl (fileListLock);
  47051. for (int i = files.size(); --i >= 0;)
  47052. if (files.getUnchecked(i)->filename == info->filename)
  47053. return false;
  47054. files.addSorted (*this, info.release());
  47055. return true;
  47056. }
  47057. return false;
  47058. }
  47059. END_JUCE_NAMESPACE
  47060. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  47061. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  47062. BEGIN_JUCE_NAMESPACE
  47063. FileBrowserComponent::FileBrowserComponent (int flags_,
  47064. const File& initialFileOrDirectory,
  47065. const FileFilter* fileFilter_,
  47066. FilePreviewComponent* previewComp_)
  47067. : FileFilter (String::empty),
  47068. fileFilter (fileFilter_),
  47069. flags (flags_),
  47070. previewComp (previewComp_),
  47071. thread ("Juce FileBrowser")
  47072. {
  47073. // You need to specify one or other of the open/save flags..
  47074. jassert ((flags & (saveMode | openMode)) != 0);
  47075. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  47076. // You need to specify at least one of these flags..
  47077. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  47078. String filename;
  47079. if (initialFileOrDirectory == File::nonexistent)
  47080. {
  47081. currentRoot = File::getCurrentWorkingDirectory();
  47082. }
  47083. else if (initialFileOrDirectory.isDirectory())
  47084. {
  47085. currentRoot = initialFileOrDirectory;
  47086. }
  47087. else
  47088. {
  47089. chosenFiles.add (initialFileOrDirectory);
  47090. currentRoot = initialFileOrDirectory.getParentDirectory();
  47091. filename = initialFileOrDirectory.getFileName();
  47092. }
  47093. fileList = new DirectoryContentsList (this, thread);
  47094. if ((flags & useTreeView) != 0)
  47095. {
  47096. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  47097. if ((flags & canSelectMultipleItems) != 0)
  47098. tree->setMultiSelectEnabled (true);
  47099. addAndMakeVisible (tree);
  47100. fileListComponent = tree;
  47101. }
  47102. else
  47103. {
  47104. FileListComponent* const list = new FileListComponent (*fileList);
  47105. list->setOutlineThickness (1);
  47106. if ((flags & canSelectMultipleItems) != 0)
  47107. list->setMultipleSelectionEnabled (true);
  47108. addAndMakeVisible (list);
  47109. fileListComponent = list;
  47110. }
  47111. fileListComponent->addListener (this);
  47112. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  47113. currentPathBox->setEditableText (true);
  47114. StringArray rootNames, rootPaths;
  47115. const BigInteger separators (getRoots (rootNames, rootPaths));
  47116. for (int i = 0; i < rootNames.size(); ++i)
  47117. {
  47118. if (separators [i])
  47119. currentPathBox->addSeparator();
  47120. currentPathBox->addItem (rootNames[i], i + 1);
  47121. }
  47122. currentPathBox->addSeparator();
  47123. currentPathBox->addListener (this);
  47124. addAndMakeVisible (filenameBox = new TextEditor());
  47125. filenameBox->setMultiLine (false);
  47126. filenameBox->setSelectAllWhenFocused (true);
  47127. filenameBox->setText (filename, false);
  47128. filenameBox->addListener (this);
  47129. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  47130. Label* label = new Label ("f", TRANS("file:"));
  47131. addAndMakeVisible (label);
  47132. label->attachToComponent (filenameBox, true);
  47133. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  47134. goUpButton->addButtonListener (this);
  47135. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  47136. if (previewComp != 0)
  47137. addAndMakeVisible (previewComp);
  47138. setRoot (currentRoot);
  47139. thread.startThread (4);
  47140. }
  47141. FileBrowserComponent::~FileBrowserComponent()
  47142. {
  47143. if (previewComp != 0)
  47144. removeChildComponent (previewComp);
  47145. deleteAllChildren();
  47146. fileList = 0;
  47147. thread.stopThread (10000);
  47148. }
  47149. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  47150. {
  47151. listeners.add (newListener);
  47152. }
  47153. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  47154. {
  47155. listeners.remove (listener);
  47156. }
  47157. bool FileBrowserComponent::isSaveMode() const throw()
  47158. {
  47159. return (flags & saveMode) != 0;
  47160. }
  47161. int FileBrowserComponent::getNumSelectedFiles() const throw()
  47162. {
  47163. if (chosenFiles.size() == 0 && currentFileIsValid())
  47164. return 1;
  47165. return chosenFiles.size();
  47166. }
  47167. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  47168. {
  47169. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  47170. return currentRoot;
  47171. if (! filenameBox->isReadOnly())
  47172. return currentRoot.getChildFile (filenameBox->getText());
  47173. return chosenFiles[index];
  47174. }
  47175. bool FileBrowserComponent::currentFileIsValid() const
  47176. {
  47177. if (isSaveMode())
  47178. return ! getSelectedFile (0).isDirectory();
  47179. else
  47180. return getSelectedFile (0).exists();
  47181. }
  47182. const File FileBrowserComponent::getHighlightedFile() const throw()
  47183. {
  47184. return fileListComponent->getSelectedFile (0);
  47185. }
  47186. void FileBrowserComponent::deselectAllFiles()
  47187. {
  47188. fileListComponent->deselectAllFiles();
  47189. }
  47190. bool FileBrowserComponent::isFileSuitable (const File& file) const
  47191. {
  47192. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  47193. : false;
  47194. }
  47195. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  47196. {
  47197. return true;
  47198. }
  47199. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  47200. {
  47201. if (f.isDirectory())
  47202. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  47203. return (flags & canSelectFiles) != 0 && f.exists()
  47204. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  47205. }
  47206. const File FileBrowserComponent::getRoot() const
  47207. {
  47208. return currentRoot;
  47209. }
  47210. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  47211. {
  47212. if (currentRoot != newRootDirectory)
  47213. {
  47214. fileListComponent->scrollToTop();
  47215. String path (newRootDirectory.getFullPathName());
  47216. if (path.isEmpty())
  47217. path = File::separatorString;
  47218. StringArray rootNames, rootPaths;
  47219. getRoots (rootNames, rootPaths);
  47220. if (! rootPaths.contains (path, true))
  47221. {
  47222. bool alreadyListed = false;
  47223. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  47224. {
  47225. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  47226. {
  47227. alreadyListed = true;
  47228. break;
  47229. }
  47230. }
  47231. if (! alreadyListed)
  47232. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  47233. }
  47234. }
  47235. currentRoot = newRootDirectory;
  47236. fileList->setDirectory (currentRoot, true, true);
  47237. String currentRootName (currentRoot.getFullPathName());
  47238. if (currentRootName.isEmpty())
  47239. currentRootName = File::separatorString;
  47240. currentPathBox->setText (currentRootName, true);
  47241. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  47242. && currentRoot.getParentDirectory() != currentRoot);
  47243. }
  47244. void FileBrowserComponent::goUp()
  47245. {
  47246. setRoot (getRoot().getParentDirectory());
  47247. }
  47248. void FileBrowserComponent::refresh()
  47249. {
  47250. fileList->refresh();
  47251. }
  47252. const String FileBrowserComponent::getActionVerb() const
  47253. {
  47254. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  47255. }
  47256. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  47257. {
  47258. return previewComp;
  47259. }
  47260. void FileBrowserComponent::resized()
  47261. {
  47262. getLookAndFeel()
  47263. .layoutFileBrowserComponent (*this, fileListComponent,
  47264. previewComp, currentPathBox,
  47265. filenameBox, goUpButton);
  47266. }
  47267. void FileBrowserComponent::sendListenerChangeMessage()
  47268. {
  47269. Component::BailOutChecker checker (this);
  47270. if (previewComp != 0)
  47271. previewComp->selectedFileChanged (getSelectedFile (0));
  47272. // You shouldn't delete the browser when the file gets changed!
  47273. jassert (! checker.shouldBailOut());
  47274. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  47275. }
  47276. void FileBrowserComponent::selectionChanged()
  47277. {
  47278. StringArray newFilenames;
  47279. bool resetChosenFiles = true;
  47280. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47281. {
  47282. const File f (fileListComponent->getSelectedFile (i));
  47283. if (isFileOrDirSuitable (f))
  47284. {
  47285. if (resetChosenFiles)
  47286. {
  47287. chosenFiles.clear();
  47288. resetChosenFiles = false;
  47289. }
  47290. chosenFiles.add (f);
  47291. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47292. }
  47293. }
  47294. if (newFilenames.size() > 0)
  47295. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  47296. sendListenerChangeMessage();
  47297. }
  47298. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47299. {
  47300. Component::BailOutChecker checker (this);
  47301. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47302. }
  47303. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47304. {
  47305. if (f.isDirectory())
  47306. {
  47307. setRoot (f);
  47308. if ((flags & canSelectDirectories) != 0)
  47309. filenameBox->setText (String::empty);
  47310. }
  47311. else
  47312. {
  47313. Component::BailOutChecker checker (this);
  47314. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47315. }
  47316. }
  47317. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47318. {
  47319. (void) key;
  47320. #if JUCE_LINUX || JUCE_WINDOWS
  47321. if (key.getModifiers().isCommandDown()
  47322. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47323. {
  47324. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47325. fileList->refresh();
  47326. return true;
  47327. }
  47328. #endif
  47329. return false;
  47330. }
  47331. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47332. {
  47333. sendListenerChangeMessage();
  47334. }
  47335. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47336. {
  47337. if (filenameBox->getText().containsChar (File::separator))
  47338. {
  47339. const File f (currentRoot.getChildFile (filenameBox->getText()));
  47340. if (f.isDirectory())
  47341. {
  47342. setRoot (f);
  47343. chosenFiles.clear();
  47344. filenameBox->setText (String::empty);
  47345. }
  47346. else
  47347. {
  47348. setRoot (f.getParentDirectory());
  47349. chosenFiles.clear();
  47350. chosenFiles.add (f);
  47351. filenameBox->setText (f.getFileName());
  47352. }
  47353. }
  47354. else
  47355. {
  47356. fileDoubleClicked (getSelectedFile (0));
  47357. }
  47358. }
  47359. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47360. {
  47361. }
  47362. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47363. {
  47364. if (! isSaveMode())
  47365. selectionChanged();
  47366. }
  47367. void FileBrowserComponent::buttonClicked (Button*)
  47368. {
  47369. goUp();
  47370. }
  47371. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47372. {
  47373. const String newText (currentPathBox->getText().trim().unquoted());
  47374. if (newText.isNotEmpty())
  47375. {
  47376. const int index = currentPathBox->getSelectedId() - 1;
  47377. StringArray rootNames, rootPaths;
  47378. getRoots (rootNames, rootPaths);
  47379. if (rootPaths [index].isNotEmpty())
  47380. {
  47381. setRoot (File (rootPaths [index]));
  47382. }
  47383. else
  47384. {
  47385. File f (newText);
  47386. for (;;)
  47387. {
  47388. if (f.isDirectory())
  47389. {
  47390. setRoot (f);
  47391. break;
  47392. }
  47393. if (f.getParentDirectory() == f)
  47394. break;
  47395. f = f.getParentDirectory();
  47396. }
  47397. }
  47398. }
  47399. }
  47400. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47401. {
  47402. BigInteger separators;
  47403. #if JUCE_WINDOWS
  47404. Array<File> roots;
  47405. File::findFileSystemRoots (roots);
  47406. rootPaths.clear();
  47407. for (int i = 0; i < roots.size(); ++i)
  47408. {
  47409. const File& drive = roots.getReference(i);
  47410. String name (drive.getFullPathName());
  47411. rootPaths.add (name);
  47412. if (drive.isOnHardDisk())
  47413. {
  47414. String volume (drive.getVolumeLabel());
  47415. if (volume.isEmpty())
  47416. volume = TRANS("Hard Drive");
  47417. name << " [" << drive.getVolumeLabel() << ']';
  47418. }
  47419. else if (drive.isOnCDRomDrive())
  47420. {
  47421. name << TRANS(" [CD/DVD drive]");
  47422. }
  47423. rootNames.add (name);
  47424. }
  47425. separators.setBit (rootPaths.size());
  47426. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47427. rootNames.add ("Documents");
  47428. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47429. rootNames.add ("Desktop");
  47430. #endif
  47431. #if JUCE_MAC
  47432. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47433. rootNames.add ("Home folder");
  47434. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47435. rootNames.add ("Documents");
  47436. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47437. rootNames.add ("Desktop");
  47438. separators.setBit (rootPaths.size());
  47439. Array <File> volumes;
  47440. File vol ("/Volumes");
  47441. vol.findChildFiles (volumes, File::findDirectories, false);
  47442. for (int i = 0; i < volumes.size(); ++i)
  47443. {
  47444. const File& volume = volumes.getReference(i);
  47445. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47446. {
  47447. rootPaths.add (volume.getFullPathName());
  47448. rootNames.add (volume.getFileName());
  47449. }
  47450. }
  47451. #endif
  47452. #if JUCE_LINUX
  47453. rootPaths.add ("/");
  47454. rootNames.add ("/");
  47455. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47456. rootNames.add ("Home folder");
  47457. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47458. rootNames.add ("Desktop");
  47459. #endif
  47460. return separators;
  47461. }
  47462. END_JUCE_NAMESPACE
  47463. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47464. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47465. BEGIN_JUCE_NAMESPACE
  47466. FileChooser::FileChooser (const String& chooserBoxTitle,
  47467. const File& currentFileOrDirectory,
  47468. const String& fileFilters,
  47469. const bool useNativeDialogBox_)
  47470. : title (chooserBoxTitle),
  47471. filters (fileFilters),
  47472. startingFile (currentFileOrDirectory),
  47473. useNativeDialogBox (useNativeDialogBox_)
  47474. {
  47475. #if JUCE_LINUX
  47476. useNativeDialogBox = false;
  47477. #endif
  47478. if (! fileFilters.containsNonWhitespaceChars())
  47479. filters = "*";
  47480. }
  47481. FileChooser::~FileChooser()
  47482. {
  47483. }
  47484. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47485. {
  47486. return showDialog (false, true, false, false, false, previewComponent);
  47487. }
  47488. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47489. {
  47490. return showDialog (false, true, false, false, true, previewComponent);
  47491. }
  47492. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47493. {
  47494. return showDialog (true, true, false, false, true, previewComponent);
  47495. }
  47496. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47497. {
  47498. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47499. }
  47500. bool FileChooser::browseForDirectory()
  47501. {
  47502. return showDialog (true, false, false, false, false, 0);
  47503. }
  47504. const File FileChooser::getResult() const
  47505. {
  47506. // if you've used a multiple-file select, you should use the getResults() method
  47507. // to retrieve all the files that were chosen.
  47508. jassert (results.size() <= 1);
  47509. return results.getFirst();
  47510. }
  47511. const Array<File>& FileChooser::getResults() const
  47512. {
  47513. return results;
  47514. }
  47515. bool FileChooser::showDialog (const bool selectsDirectories,
  47516. const bool selectsFiles,
  47517. const bool isSave,
  47518. const bool warnAboutOverwritingExistingFiles,
  47519. const bool selectMultipleFiles,
  47520. FilePreviewComponent* const previewComponent)
  47521. {
  47522. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47523. results.clear();
  47524. // the preview component needs to be the right size before you pass it in here..
  47525. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47526. && previewComponent->getHeight() > 10));
  47527. #if JUCE_WINDOWS
  47528. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47529. #elif JUCE_MAC
  47530. if (useNativeDialogBox && (previewComponent == 0))
  47531. #else
  47532. if (false)
  47533. #endif
  47534. {
  47535. showPlatformDialog (results, title, startingFile, filters,
  47536. selectsDirectories, selectsFiles, isSave,
  47537. warnAboutOverwritingExistingFiles,
  47538. selectMultipleFiles,
  47539. previewComponent);
  47540. }
  47541. else
  47542. {
  47543. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47544. selectsDirectories ? "*" : String::empty,
  47545. String::empty);
  47546. int flags = isSave ? FileBrowserComponent::saveMode
  47547. : FileBrowserComponent::openMode;
  47548. if (selectsFiles)
  47549. flags |= FileBrowserComponent::canSelectFiles;
  47550. if (selectsDirectories)
  47551. {
  47552. flags |= FileBrowserComponent::canSelectDirectories;
  47553. if (! isSave)
  47554. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47555. }
  47556. if (selectMultipleFiles)
  47557. flags |= FileBrowserComponent::canSelectMultipleItems;
  47558. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47559. FileChooserDialogBox box (title, String::empty,
  47560. browserComponent,
  47561. warnAboutOverwritingExistingFiles,
  47562. browserComponent.findColour (AlertWindow::backgroundColourId));
  47563. if (box.show())
  47564. {
  47565. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47566. results.add (browserComponent.getSelectedFile (i));
  47567. }
  47568. }
  47569. if (previouslyFocused != 0)
  47570. previouslyFocused->grabKeyboardFocus();
  47571. return results.size() > 0;
  47572. }
  47573. FilePreviewComponent::FilePreviewComponent()
  47574. {
  47575. }
  47576. FilePreviewComponent::~FilePreviewComponent()
  47577. {
  47578. }
  47579. END_JUCE_NAMESPACE
  47580. /*** End of inlined file: juce_FileChooser.cpp ***/
  47581. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47582. BEGIN_JUCE_NAMESPACE
  47583. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47584. const String& instructions,
  47585. FileBrowserComponent& chooserComponent,
  47586. const bool warnAboutOverwritingExistingFiles_,
  47587. const Colour& backgroundColour)
  47588. : ResizableWindow (name, backgroundColour, true),
  47589. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47590. {
  47591. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47592. setResizable (true, true);
  47593. setResizeLimits (300, 300, 1200, 1000);
  47594. content->okButton.addButtonListener (this);
  47595. content->cancelButton.addButtonListener (this);
  47596. content->chooserComponent.addListener (this);
  47597. }
  47598. FileChooserDialogBox::~FileChooserDialogBox()
  47599. {
  47600. content->chooserComponent.removeListener (this);
  47601. }
  47602. bool FileChooserDialogBox::show (int w, int h)
  47603. {
  47604. return showAt (-1, -1, w, h);
  47605. }
  47606. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47607. {
  47608. if (w <= 0)
  47609. {
  47610. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47611. if (previewComp != 0)
  47612. w = 400 + previewComp->getWidth();
  47613. else
  47614. w = 600;
  47615. }
  47616. if (h <= 0)
  47617. h = 500;
  47618. if (x < 0 || y < 0)
  47619. centreWithSize (w, h);
  47620. else
  47621. setBounds (x, y, w, h);
  47622. const bool ok = (runModalLoop() != 0);
  47623. setVisible (false);
  47624. return ok;
  47625. }
  47626. void FileChooserDialogBox::buttonClicked (Button* button)
  47627. {
  47628. if (button == &(content->okButton))
  47629. {
  47630. if (warnAboutOverwritingExistingFiles
  47631. && content->chooserComponent.isSaveMode()
  47632. && content->chooserComponent.getSelectedFile(0).exists())
  47633. {
  47634. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47635. TRANS("File already exists"),
  47636. TRANS("There's already a file called:")
  47637. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47638. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47639. TRANS("overwrite"),
  47640. TRANS("cancel")))
  47641. {
  47642. return;
  47643. }
  47644. }
  47645. exitModalState (1);
  47646. }
  47647. else if (button == &(content->cancelButton))
  47648. {
  47649. closeButtonPressed();
  47650. }
  47651. }
  47652. void FileChooserDialogBox::closeButtonPressed()
  47653. {
  47654. setVisible (false);
  47655. }
  47656. void FileChooserDialogBox::selectionChanged()
  47657. {
  47658. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47659. }
  47660. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47661. {
  47662. }
  47663. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47664. {
  47665. selectionChanged();
  47666. content->okButton.triggerClick();
  47667. }
  47668. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47669. : Component (name), instructions (instructions_),
  47670. chooserComponent (chooserComponent_),
  47671. okButton (chooserComponent_.getActionVerb()),
  47672. cancelButton (TRANS ("Cancel"))
  47673. {
  47674. addAndMakeVisible (&chooserComponent);
  47675. addAndMakeVisible (&okButton);
  47676. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47677. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47678. addAndMakeVisible (&cancelButton);
  47679. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47680. setInterceptsMouseClicks (false, true);
  47681. }
  47682. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47683. {
  47684. }
  47685. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47686. {
  47687. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47688. text.draw (g);
  47689. }
  47690. void FileChooserDialogBox::ContentComponent::resized()
  47691. {
  47692. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47693. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47694. const int y = roundToInt (bb.getBottom()) + 10;
  47695. const int buttonHeight = 26;
  47696. const int buttonY = getHeight() - buttonHeight - 8;
  47697. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47698. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47699. proportionOfWidth (0.2f), buttonHeight);
  47700. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47701. proportionOfWidth (0.2f), buttonHeight);
  47702. }
  47703. END_JUCE_NAMESPACE
  47704. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47705. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47706. BEGIN_JUCE_NAMESPACE
  47707. FileFilter::FileFilter (const String& filterDescription)
  47708. : description (filterDescription)
  47709. {
  47710. }
  47711. FileFilter::~FileFilter()
  47712. {
  47713. }
  47714. const String& FileFilter::getDescription() const throw()
  47715. {
  47716. return description;
  47717. }
  47718. END_JUCE_NAMESPACE
  47719. /*** End of inlined file: juce_FileFilter.cpp ***/
  47720. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47721. BEGIN_JUCE_NAMESPACE
  47722. const Image juce_createIconForFile (const File& file);
  47723. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47724. : ListBox (String::empty, 0),
  47725. DirectoryContentsDisplayComponent (listToShow)
  47726. {
  47727. setModel (this);
  47728. fileList.addChangeListener (this);
  47729. }
  47730. FileListComponent::~FileListComponent()
  47731. {
  47732. fileList.removeChangeListener (this);
  47733. }
  47734. int FileListComponent::getNumSelectedFiles() const
  47735. {
  47736. return getNumSelectedRows();
  47737. }
  47738. const File FileListComponent::getSelectedFile (int index) const
  47739. {
  47740. return fileList.getFile (getSelectedRow (index));
  47741. }
  47742. void FileListComponent::deselectAllFiles()
  47743. {
  47744. deselectAllRows();
  47745. }
  47746. void FileListComponent::scrollToTop()
  47747. {
  47748. getVerticalScrollBar()->setCurrentRangeStart (0);
  47749. }
  47750. void FileListComponent::changeListenerCallback (void*)
  47751. {
  47752. updateContent();
  47753. if (lastDirectory != fileList.getDirectory())
  47754. {
  47755. lastDirectory = fileList.getDirectory();
  47756. deselectAllRows();
  47757. }
  47758. }
  47759. class FileListItemComponent : public Component,
  47760. public TimeSliceClient,
  47761. public AsyncUpdater
  47762. {
  47763. public:
  47764. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47765. : owner (owner_), thread (thread_),
  47766. highlighted (false), index (0), icon (0)
  47767. {
  47768. }
  47769. ~FileListItemComponent()
  47770. {
  47771. thread.removeTimeSliceClient (this);
  47772. clearIcon();
  47773. }
  47774. void paint (Graphics& g)
  47775. {
  47776. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47777. file.getFileName(),
  47778. &icon,
  47779. fileSize, modTime,
  47780. isDirectory, highlighted,
  47781. index);
  47782. }
  47783. void mouseDown (const MouseEvent& e)
  47784. {
  47785. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47786. owner.sendMouseClickMessage (file, e);
  47787. }
  47788. void mouseDoubleClick (const MouseEvent&)
  47789. {
  47790. owner.sendDoubleClickMessage (file);
  47791. }
  47792. void update (const File& root,
  47793. const DirectoryContentsList::FileInfo* const fileInfo,
  47794. const int index_,
  47795. const bool highlighted_)
  47796. {
  47797. thread.removeTimeSliceClient (this);
  47798. if (highlighted_ != highlighted
  47799. || index_ != index)
  47800. {
  47801. index = index_;
  47802. highlighted = highlighted_;
  47803. repaint();
  47804. }
  47805. File newFile;
  47806. String newFileSize;
  47807. String newModTime;
  47808. if (fileInfo != 0)
  47809. {
  47810. newFile = root.getChildFile (fileInfo->filename);
  47811. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47812. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47813. }
  47814. if (newFile != file
  47815. || fileSize != newFileSize
  47816. || modTime != newModTime)
  47817. {
  47818. file = newFile;
  47819. fileSize = newFileSize;
  47820. modTime = newModTime;
  47821. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47822. repaint();
  47823. clearIcon();
  47824. }
  47825. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47826. {
  47827. updateIcon (true);
  47828. if (! icon.isValid())
  47829. thread.addTimeSliceClient (this);
  47830. }
  47831. }
  47832. bool useTimeSlice()
  47833. {
  47834. updateIcon (false);
  47835. return false;
  47836. }
  47837. void handleAsyncUpdate()
  47838. {
  47839. repaint();
  47840. }
  47841. juce_UseDebuggingNewOperator
  47842. private:
  47843. FileListComponent& owner;
  47844. TimeSliceThread& thread;
  47845. bool highlighted;
  47846. int index;
  47847. File file;
  47848. String fileSize;
  47849. String modTime;
  47850. Image icon;
  47851. bool isDirectory;
  47852. void clearIcon()
  47853. {
  47854. icon = Image::null;
  47855. }
  47856. void updateIcon (const bool onlyUpdateIfCached)
  47857. {
  47858. if (icon.isNull())
  47859. {
  47860. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47861. Image im (ImageCache::getFromHashCode (hashCode));
  47862. if (im.isNull() && ! onlyUpdateIfCached)
  47863. {
  47864. im = juce_createIconForFile (file);
  47865. if (im.isValid())
  47866. ImageCache::addImageToCache (im, hashCode);
  47867. }
  47868. if (im.isValid())
  47869. {
  47870. icon = im;
  47871. triggerAsyncUpdate();
  47872. }
  47873. }
  47874. }
  47875. };
  47876. int FileListComponent::getNumRows()
  47877. {
  47878. return fileList.getNumFiles();
  47879. }
  47880. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47881. {
  47882. }
  47883. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47884. {
  47885. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47886. if (comp == 0)
  47887. {
  47888. delete existingComponentToUpdate;
  47889. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47890. }
  47891. DirectoryContentsList::FileInfo fileInfo;
  47892. if (fileList.getFileInfo (row, fileInfo))
  47893. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47894. else
  47895. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47896. return comp;
  47897. }
  47898. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47899. {
  47900. sendSelectionChangeMessage();
  47901. }
  47902. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47903. {
  47904. }
  47905. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47906. {
  47907. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47908. }
  47909. END_JUCE_NAMESPACE
  47910. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47911. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47912. BEGIN_JUCE_NAMESPACE
  47913. FilenameComponent::FilenameComponent (const String& name,
  47914. const File& currentFile,
  47915. const bool canEditFilename,
  47916. const bool isDirectory,
  47917. const bool isForSaving,
  47918. const String& fileBrowserWildcard,
  47919. const String& enforcedSuffix_,
  47920. const String& textWhenNothingSelected)
  47921. : Component (name),
  47922. maxRecentFiles (30),
  47923. isDir (isDirectory),
  47924. isSaving (isForSaving),
  47925. isFileDragOver (false),
  47926. wildcard (fileBrowserWildcard),
  47927. enforcedSuffix (enforcedSuffix_)
  47928. {
  47929. addAndMakeVisible (&filenameBox);
  47930. filenameBox.setEditableText (canEditFilename);
  47931. filenameBox.addListener (this);
  47932. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47933. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47934. setBrowseButtonText ("...");
  47935. setCurrentFile (currentFile, true);
  47936. }
  47937. FilenameComponent::~FilenameComponent()
  47938. {
  47939. }
  47940. void FilenameComponent::paintOverChildren (Graphics& g)
  47941. {
  47942. if (isFileDragOver)
  47943. {
  47944. g.setColour (Colours::red.withAlpha (0.2f));
  47945. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47946. }
  47947. }
  47948. void FilenameComponent::resized()
  47949. {
  47950. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47951. }
  47952. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47953. {
  47954. browseButtonText = newBrowseButtonText;
  47955. lookAndFeelChanged();
  47956. }
  47957. void FilenameComponent::lookAndFeelChanged()
  47958. {
  47959. browseButton = 0;
  47960. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47961. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47962. resized();
  47963. browseButton->addButtonListener (this);
  47964. }
  47965. void FilenameComponent::setTooltip (const String& newTooltip)
  47966. {
  47967. SettableTooltipClient::setTooltip (newTooltip);
  47968. filenameBox.setTooltip (newTooltip);
  47969. }
  47970. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47971. {
  47972. defaultBrowseFile = newDefaultDirectory;
  47973. }
  47974. void FilenameComponent::buttonClicked (Button*)
  47975. {
  47976. FileChooser fc (TRANS("Choose a new file"),
  47977. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47978. : getCurrentFile(),
  47979. wildcard);
  47980. if (isDir ? fc.browseForDirectory()
  47981. : (isSaving ? fc.browseForFileToSave (false)
  47982. : fc.browseForFileToOpen()))
  47983. {
  47984. setCurrentFile (fc.getResult(), true);
  47985. }
  47986. }
  47987. void FilenameComponent::comboBoxChanged (ComboBox*)
  47988. {
  47989. setCurrentFile (getCurrentFile(), true);
  47990. }
  47991. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47992. {
  47993. return true;
  47994. }
  47995. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47996. {
  47997. isFileDragOver = false;
  47998. repaint();
  47999. const File f (filenames[0]);
  48000. if (f.exists() && (f.isDirectory() == isDir))
  48001. setCurrentFile (f, true);
  48002. }
  48003. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  48004. {
  48005. isFileDragOver = true;
  48006. repaint();
  48007. }
  48008. void FilenameComponent::fileDragExit (const StringArray&)
  48009. {
  48010. isFileDragOver = false;
  48011. repaint();
  48012. }
  48013. const File FilenameComponent::getCurrentFile() const
  48014. {
  48015. File f (filenameBox.getText());
  48016. if (enforcedSuffix.isNotEmpty())
  48017. f = f.withFileExtension (enforcedSuffix);
  48018. return f;
  48019. }
  48020. void FilenameComponent::setCurrentFile (File newFile,
  48021. const bool addToRecentlyUsedList,
  48022. const bool sendChangeNotification)
  48023. {
  48024. if (enforcedSuffix.isNotEmpty())
  48025. newFile = newFile.withFileExtension (enforcedSuffix);
  48026. if (newFile.getFullPathName() != lastFilename)
  48027. {
  48028. lastFilename = newFile.getFullPathName();
  48029. if (addToRecentlyUsedList)
  48030. addRecentlyUsedFile (newFile);
  48031. filenameBox.setText (lastFilename, true);
  48032. if (sendChangeNotification)
  48033. triggerAsyncUpdate();
  48034. }
  48035. }
  48036. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  48037. {
  48038. filenameBox.setEditableText (shouldBeEditable);
  48039. }
  48040. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  48041. {
  48042. StringArray names;
  48043. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  48044. names.add (filenameBox.getItemText (i));
  48045. return names;
  48046. }
  48047. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  48048. {
  48049. if (filenames != getRecentlyUsedFilenames())
  48050. {
  48051. filenameBox.clear();
  48052. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  48053. filenameBox.addItem (filenames[i], i + 1);
  48054. }
  48055. }
  48056. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  48057. {
  48058. maxRecentFiles = jmax (1, newMaximum);
  48059. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  48060. }
  48061. void FilenameComponent::addRecentlyUsedFile (const File& file)
  48062. {
  48063. StringArray files (getRecentlyUsedFilenames());
  48064. if (file.getFullPathName().isNotEmpty())
  48065. {
  48066. files.removeString (file.getFullPathName(), true);
  48067. files.insert (0, file.getFullPathName());
  48068. setRecentlyUsedFilenames (files);
  48069. }
  48070. }
  48071. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  48072. {
  48073. listeners.add (listener);
  48074. }
  48075. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  48076. {
  48077. listeners.remove (listener);
  48078. }
  48079. void FilenameComponent::handleAsyncUpdate()
  48080. {
  48081. Component::BailOutChecker checker (this);
  48082. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  48083. }
  48084. END_JUCE_NAMESPACE
  48085. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  48086. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48087. BEGIN_JUCE_NAMESPACE
  48088. FileSearchPathListComponent::FileSearchPathListComponent()
  48089. {
  48090. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  48091. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  48092. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  48093. listBox->setOutlineThickness (1);
  48094. addAndMakeVisible (addButton = new TextButton ("+"));
  48095. addButton->addButtonListener (this);
  48096. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  48097. addAndMakeVisible (removeButton = new TextButton ("-"));
  48098. removeButton->addButtonListener (this);
  48099. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  48100. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  48101. changeButton->addButtonListener (this);
  48102. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  48103. upButton->addButtonListener (this);
  48104. {
  48105. Path arrowPath;
  48106. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  48107. DrawablePath arrowImage;
  48108. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  48109. arrowImage.setPath (arrowPath);
  48110. upButton->setImages (&arrowImage);
  48111. }
  48112. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  48113. downButton->addButtonListener (this);
  48114. {
  48115. Path arrowPath;
  48116. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  48117. DrawablePath arrowImage;
  48118. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  48119. arrowImage.setPath (arrowPath);
  48120. downButton->setImages (&arrowImage);
  48121. }
  48122. updateButtons();
  48123. }
  48124. FileSearchPathListComponent::~FileSearchPathListComponent()
  48125. {
  48126. deleteAllChildren();
  48127. }
  48128. void FileSearchPathListComponent::updateButtons()
  48129. {
  48130. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  48131. removeButton->setEnabled (anythingSelected);
  48132. changeButton->setEnabled (anythingSelected);
  48133. upButton->setEnabled (anythingSelected);
  48134. downButton->setEnabled (anythingSelected);
  48135. }
  48136. void FileSearchPathListComponent::changed()
  48137. {
  48138. listBox->updateContent();
  48139. listBox->repaint();
  48140. updateButtons();
  48141. }
  48142. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  48143. {
  48144. if (newPath.toString() != path.toString())
  48145. {
  48146. path = newPath;
  48147. changed();
  48148. }
  48149. }
  48150. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  48151. {
  48152. defaultBrowseTarget = newDefaultDirectory;
  48153. }
  48154. int FileSearchPathListComponent::getNumRows()
  48155. {
  48156. return path.getNumPaths();
  48157. }
  48158. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  48159. {
  48160. if (rowIsSelected)
  48161. g.fillAll (findColour (TextEditor::highlightColourId));
  48162. g.setColour (findColour (ListBox::textColourId));
  48163. Font f (height * 0.7f);
  48164. f.setHorizontalScale (0.9f);
  48165. g.setFont (f);
  48166. g.drawText (path [rowNumber].getFullPathName(),
  48167. 4, 0, width - 6, height,
  48168. Justification::centredLeft, true);
  48169. }
  48170. void FileSearchPathListComponent::deleteKeyPressed (int row)
  48171. {
  48172. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  48173. {
  48174. path.remove (row);
  48175. changed();
  48176. }
  48177. }
  48178. void FileSearchPathListComponent::returnKeyPressed (int row)
  48179. {
  48180. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  48181. if (chooser.browseForDirectory())
  48182. {
  48183. path.remove (row);
  48184. path.add (chooser.getResult(), row);
  48185. changed();
  48186. }
  48187. }
  48188. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  48189. {
  48190. returnKeyPressed (row);
  48191. }
  48192. void FileSearchPathListComponent::selectedRowsChanged (int)
  48193. {
  48194. updateButtons();
  48195. }
  48196. void FileSearchPathListComponent::paint (Graphics& g)
  48197. {
  48198. g.fillAll (findColour (backgroundColourId));
  48199. }
  48200. void FileSearchPathListComponent::resized()
  48201. {
  48202. const int buttonH = 22;
  48203. const int buttonY = getHeight() - buttonH - 4;
  48204. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  48205. addButton->setBounds (2, buttonY, buttonH, buttonH);
  48206. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  48207. changeButton->changeWidthToFitText (buttonH);
  48208. downButton->setSize (buttonH * 2, buttonH);
  48209. upButton->setSize (buttonH * 2, buttonH);
  48210. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  48211. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  48212. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  48213. }
  48214. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  48215. {
  48216. return true;
  48217. }
  48218. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  48219. {
  48220. for (int i = filenames.size(); --i >= 0;)
  48221. {
  48222. const File f (filenames[i]);
  48223. if (f.isDirectory())
  48224. {
  48225. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  48226. path.add (f, row);
  48227. changed();
  48228. }
  48229. }
  48230. }
  48231. void FileSearchPathListComponent::buttonClicked (Button* button)
  48232. {
  48233. const int currentRow = listBox->getSelectedRow();
  48234. if (button == removeButton)
  48235. {
  48236. deleteKeyPressed (currentRow);
  48237. }
  48238. else if (button == addButton)
  48239. {
  48240. File start (defaultBrowseTarget);
  48241. if (start == File::nonexistent)
  48242. start = path [0];
  48243. if (start == File::nonexistent)
  48244. start = File::getCurrentWorkingDirectory();
  48245. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  48246. if (chooser.browseForDirectory())
  48247. {
  48248. path.add (chooser.getResult(), currentRow);
  48249. }
  48250. }
  48251. else if (button == changeButton)
  48252. {
  48253. returnKeyPressed (currentRow);
  48254. }
  48255. else if (button == upButton)
  48256. {
  48257. if (currentRow > 0 && currentRow < path.getNumPaths())
  48258. {
  48259. const File f (path[currentRow]);
  48260. path.remove (currentRow);
  48261. path.add (f, currentRow - 1);
  48262. listBox->selectRow (currentRow - 1);
  48263. }
  48264. }
  48265. else if (button == downButton)
  48266. {
  48267. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  48268. {
  48269. const File f (path[currentRow]);
  48270. path.remove (currentRow);
  48271. path.add (f, currentRow + 1);
  48272. listBox->selectRow (currentRow + 1);
  48273. }
  48274. }
  48275. changed();
  48276. }
  48277. END_JUCE_NAMESPACE
  48278. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48279. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48280. BEGIN_JUCE_NAMESPACE
  48281. const Image juce_createIconForFile (const File& file);
  48282. class FileListTreeItem : public TreeViewItem,
  48283. public TimeSliceClient,
  48284. public AsyncUpdater,
  48285. public ChangeListener
  48286. {
  48287. public:
  48288. FileListTreeItem (FileTreeComponent& owner_,
  48289. DirectoryContentsList* const parentContentsList_,
  48290. const int indexInContentsList_,
  48291. const File& file_,
  48292. TimeSliceThread& thread_)
  48293. : file (file_),
  48294. owner (owner_),
  48295. parentContentsList (parentContentsList_),
  48296. indexInContentsList (indexInContentsList_),
  48297. subContentsList (0),
  48298. canDeleteSubContentsList (false),
  48299. thread (thread_),
  48300. icon (0)
  48301. {
  48302. DirectoryContentsList::FileInfo fileInfo;
  48303. if (parentContentsList_ != 0
  48304. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48305. {
  48306. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48307. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48308. isDirectory = fileInfo.isDirectory;
  48309. }
  48310. else
  48311. {
  48312. isDirectory = true;
  48313. }
  48314. }
  48315. ~FileListTreeItem()
  48316. {
  48317. thread.removeTimeSliceClient (this);
  48318. clearSubItems();
  48319. if (canDeleteSubContentsList)
  48320. delete subContentsList;
  48321. }
  48322. bool mightContainSubItems() { return isDirectory; }
  48323. const String getUniqueName() const { return file.getFullPathName(); }
  48324. int getItemHeight() const { return 22; }
  48325. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48326. void itemOpennessChanged (bool isNowOpen)
  48327. {
  48328. if (isNowOpen)
  48329. {
  48330. clearSubItems();
  48331. isDirectory = file.isDirectory();
  48332. if (isDirectory)
  48333. {
  48334. if (subContentsList == 0)
  48335. {
  48336. jassert (parentContentsList != 0);
  48337. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48338. l->setDirectory (file, true, true);
  48339. setSubContentsList (l);
  48340. canDeleteSubContentsList = true;
  48341. }
  48342. changeListenerCallback (0);
  48343. }
  48344. }
  48345. }
  48346. void setSubContentsList (DirectoryContentsList* newList)
  48347. {
  48348. jassert (subContentsList == 0);
  48349. subContentsList = newList;
  48350. newList->addChangeListener (this);
  48351. }
  48352. void changeListenerCallback (void*)
  48353. {
  48354. clearSubItems();
  48355. if (isOpen() && subContentsList != 0)
  48356. {
  48357. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48358. {
  48359. FileListTreeItem* const item
  48360. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48361. addSubItem (item);
  48362. }
  48363. }
  48364. }
  48365. void paintItem (Graphics& g, int width, int height)
  48366. {
  48367. if (file != File::nonexistent)
  48368. {
  48369. updateIcon (true);
  48370. if (icon.isNull())
  48371. thread.addTimeSliceClient (this);
  48372. }
  48373. owner.getLookAndFeel()
  48374. .drawFileBrowserRow (g, width, height,
  48375. file.getFileName(),
  48376. &icon, fileSize, modTime,
  48377. isDirectory, isSelected(),
  48378. indexInContentsList);
  48379. }
  48380. void itemClicked (const MouseEvent& e)
  48381. {
  48382. owner.sendMouseClickMessage (file, e);
  48383. }
  48384. void itemDoubleClicked (const MouseEvent& e)
  48385. {
  48386. TreeViewItem::itemDoubleClicked (e);
  48387. owner.sendDoubleClickMessage (file);
  48388. }
  48389. void itemSelectionChanged (bool)
  48390. {
  48391. owner.sendSelectionChangeMessage();
  48392. }
  48393. bool useTimeSlice()
  48394. {
  48395. updateIcon (false);
  48396. thread.removeTimeSliceClient (this);
  48397. return false;
  48398. }
  48399. void handleAsyncUpdate()
  48400. {
  48401. owner.repaint();
  48402. }
  48403. const File file;
  48404. juce_UseDebuggingNewOperator
  48405. private:
  48406. FileTreeComponent& owner;
  48407. DirectoryContentsList* parentContentsList;
  48408. int indexInContentsList;
  48409. DirectoryContentsList* subContentsList;
  48410. bool isDirectory, canDeleteSubContentsList;
  48411. TimeSliceThread& thread;
  48412. Image icon;
  48413. String fileSize;
  48414. String modTime;
  48415. void updateIcon (const bool onlyUpdateIfCached)
  48416. {
  48417. if (icon.isNull())
  48418. {
  48419. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48420. Image im (ImageCache::getFromHashCode (hashCode));
  48421. if (im.isNull() && ! onlyUpdateIfCached)
  48422. {
  48423. im = juce_createIconForFile (file);
  48424. if (im.isValid())
  48425. ImageCache::addImageToCache (im, hashCode);
  48426. }
  48427. if (im.isValid())
  48428. {
  48429. icon = im;
  48430. triggerAsyncUpdate();
  48431. }
  48432. }
  48433. }
  48434. };
  48435. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48436. : DirectoryContentsDisplayComponent (listToShow)
  48437. {
  48438. FileListTreeItem* const root
  48439. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48440. listToShow.getTimeSliceThread());
  48441. root->setSubContentsList (&listToShow);
  48442. setRootItemVisible (false);
  48443. setRootItem (root);
  48444. }
  48445. FileTreeComponent::~FileTreeComponent()
  48446. {
  48447. deleteRootItem();
  48448. }
  48449. const File FileTreeComponent::getSelectedFile (const int index) const
  48450. {
  48451. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48452. return item != 0 ? item->file
  48453. : File::nonexistent;
  48454. }
  48455. void FileTreeComponent::deselectAllFiles()
  48456. {
  48457. clearSelectedItems();
  48458. }
  48459. void FileTreeComponent::scrollToTop()
  48460. {
  48461. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48462. }
  48463. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48464. {
  48465. dragAndDropDescription = description;
  48466. }
  48467. END_JUCE_NAMESPACE
  48468. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48469. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48470. BEGIN_JUCE_NAMESPACE
  48471. ImagePreviewComponent::ImagePreviewComponent()
  48472. {
  48473. }
  48474. ImagePreviewComponent::~ImagePreviewComponent()
  48475. {
  48476. }
  48477. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48478. {
  48479. const int availableW = proportionOfWidth (0.97f);
  48480. const int availableH = getHeight() - 13 * 4;
  48481. const double scale = jmin (1.0,
  48482. availableW / (double) w,
  48483. availableH / (double) h);
  48484. w = roundToInt (scale * w);
  48485. h = roundToInt (scale * h);
  48486. }
  48487. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48488. {
  48489. if (fileToLoad != file)
  48490. {
  48491. fileToLoad = file;
  48492. startTimer (100);
  48493. }
  48494. }
  48495. void ImagePreviewComponent::timerCallback()
  48496. {
  48497. stopTimer();
  48498. currentThumbnail = Image::null;
  48499. currentDetails = String::empty;
  48500. repaint();
  48501. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48502. if (in != 0)
  48503. {
  48504. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48505. if (format != 0)
  48506. {
  48507. currentThumbnail = format->decodeImage (*in);
  48508. if (currentThumbnail.isValid())
  48509. {
  48510. int w = currentThumbnail.getWidth();
  48511. int h = currentThumbnail.getHeight();
  48512. currentDetails
  48513. << fileToLoad.getFileName() << "\n"
  48514. << format->getFormatName() << "\n"
  48515. << w << " x " << h << " pixels\n"
  48516. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48517. getThumbSize (w, h);
  48518. currentThumbnail = currentThumbnail.rescaled (w, h);
  48519. }
  48520. }
  48521. }
  48522. }
  48523. void ImagePreviewComponent::paint (Graphics& g)
  48524. {
  48525. if (currentThumbnail.isValid())
  48526. {
  48527. g.setFont (13.0f);
  48528. int w = currentThumbnail.getWidth();
  48529. int h = currentThumbnail.getHeight();
  48530. getThumbSize (w, h);
  48531. const int numLines = 4;
  48532. const int totalH = 13 * numLines + h + 4;
  48533. const int y = (getHeight() - totalH) / 2;
  48534. g.drawImageWithin (currentThumbnail,
  48535. (getWidth() - w) / 2, y, w, h,
  48536. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48537. false);
  48538. g.drawFittedText (currentDetails,
  48539. 0, y + h + 4, getWidth(), 100,
  48540. Justification::centredTop, numLines);
  48541. }
  48542. }
  48543. END_JUCE_NAMESPACE
  48544. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48545. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48546. BEGIN_JUCE_NAMESPACE
  48547. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48548. const String& directoryWildcardPatterns,
  48549. const String& description_)
  48550. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48551. : (description_ + " (" + fileWildcardPatterns + ")"))
  48552. {
  48553. parse (fileWildcardPatterns, fileWildcards);
  48554. parse (directoryWildcardPatterns, directoryWildcards);
  48555. }
  48556. WildcardFileFilter::~WildcardFileFilter()
  48557. {
  48558. }
  48559. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48560. {
  48561. return match (file, fileWildcards);
  48562. }
  48563. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48564. {
  48565. return match (file, directoryWildcards);
  48566. }
  48567. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48568. {
  48569. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48570. result.trim();
  48571. result.removeEmptyStrings();
  48572. // special case for *.*, because people use it to mean "any file", but it
  48573. // would actually ignore files with no extension.
  48574. for (int i = result.size(); --i >= 0;)
  48575. if (result[i] == "*.*")
  48576. result.set (i, "*");
  48577. }
  48578. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48579. {
  48580. const String filename (file.getFileName());
  48581. for (int i = wildcards.size(); --i >= 0;)
  48582. if (filename.matchesWildcard (wildcards[i], true))
  48583. return true;
  48584. return false;
  48585. }
  48586. END_JUCE_NAMESPACE
  48587. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48588. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48589. BEGIN_JUCE_NAMESPACE
  48590. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48591. {
  48592. }
  48593. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48594. {
  48595. }
  48596. namespace KeyboardFocusHelpers
  48597. {
  48598. // This will sort a set of components, so that they are ordered in terms of
  48599. // left-to-right and then top-to-bottom.
  48600. class ScreenPositionComparator
  48601. {
  48602. public:
  48603. ScreenPositionComparator() {}
  48604. static int compareElements (const Component* const first, const Component* const second)
  48605. {
  48606. int explicitOrder1 = first->getExplicitFocusOrder();
  48607. if (explicitOrder1 <= 0)
  48608. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48609. int explicitOrder2 = second->getExplicitFocusOrder();
  48610. if (explicitOrder2 <= 0)
  48611. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48612. if (explicitOrder1 != explicitOrder2)
  48613. return explicitOrder1 - explicitOrder2;
  48614. const int diff = first->getY() - second->getY();
  48615. return (diff == 0) ? first->getX() - second->getX()
  48616. : diff;
  48617. }
  48618. };
  48619. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48620. {
  48621. if (parent->getNumChildComponents() > 0)
  48622. {
  48623. Array <Component*> localComps;
  48624. ScreenPositionComparator comparator;
  48625. int i;
  48626. for (i = parent->getNumChildComponents(); --i >= 0;)
  48627. {
  48628. Component* const c = parent->getChildComponent (i);
  48629. if (c->isVisible() && c->isEnabled())
  48630. localComps.addSorted (comparator, c);
  48631. }
  48632. for (i = 0; i < localComps.size(); ++i)
  48633. {
  48634. Component* const c = localComps.getUnchecked (i);
  48635. if (c->getWantsKeyboardFocus())
  48636. comps.add (c);
  48637. if (! c->isFocusContainer())
  48638. findAllFocusableComponents (c, comps);
  48639. }
  48640. }
  48641. }
  48642. }
  48643. static Component* getIncrementedComponent (Component* const current, const int delta)
  48644. {
  48645. Component* focusContainer = current->getParentComponent();
  48646. if (focusContainer != 0)
  48647. {
  48648. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48649. focusContainer = focusContainer->getParentComponent();
  48650. if (focusContainer != 0)
  48651. {
  48652. Array <Component*> comps;
  48653. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48654. if (comps.size() > 0)
  48655. {
  48656. const int index = comps.indexOf (current);
  48657. return comps [(index + comps.size() + delta) % comps.size()];
  48658. }
  48659. }
  48660. }
  48661. return 0;
  48662. }
  48663. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48664. {
  48665. return getIncrementedComponent (current, 1);
  48666. }
  48667. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48668. {
  48669. return getIncrementedComponent (current, -1);
  48670. }
  48671. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48672. {
  48673. Array <Component*> comps;
  48674. if (parentComponent != 0)
  48675. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48676. return comps.getFirst();
  48677. }
  48678. END_JUCE_NAMESPACE
  48679. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48680. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48681. BEGIN_JUCE_NAMESPACE
  48682. bool KeyListener::keyStateChanged (const bool, Component*)
  48683. {
  48684. return false;
  48685. }
  48686. END_JUCE_NAMESPACE
  48687. /*** End of inlined file: juce_KeyListener.cpp ***/
  48688. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48689. BEGIN_JUCE_NAMESPACE
  48690. // N.B. these two includes are put here deliberately to avoid problems with
  48691. // old GCCs failing on long include paths
  48692. const int maxKeys = 3;
  48693. class KeyMappingChangeButton : public Button
  48694. {
  48695. public:
  48696. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  48697. const CommandID commandID_,
  48698. const String& keyName,
  48699. const int keyNum_)
  48700. : Button (keyName),
  48701. owner (owner_),
  48702. commandID (commandID_),
  48703. keyNum (keyNum_)
  48704. {
  48705. setWantsKeyboardFocus (false);
  48706. setTriggeredOnMouseDown (keyNum >= 0);
  48707. if (keyNum_ < 0)
  48708. setTooltip (TRANS("adds a new key-mapping"));
  48709. else
  48710. setTooltip (TRANS("click to change this key-mapping"));
  48711. }
  48712. ~KeyMappingChangeButton()
  48713. {
  48714. }
  48715. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48716. {
  48717. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48718. keyNum >= 0 ? getName() : String::empty);
  48719. }
  48720. void clicked()
  48721. {
  48722. if (keyNum >= 0)
  48723. {
  48724. // existing key clicked..
  48725. PopupMenu m;
  48726. m.addItem (1, TRANS("change this key-mapping"));
  48727. m.addSeparator();
  48728. m.addItem (2, TRANS("remove this key-mapping"));
  48729. const int res = m.show();
  48730. if (res == 1)
  48731. {
  48732. owner->assignNewKey (commandID, keyNum);
  48733. }
  48734. else if (res == 2)
  48735. {
  48736. owner->getMappings()->removeKeyPress (commandID, keyNum);
  48737. }
  48738. }
  48739. else
  48740. {
  48741. // + button pressed..
  48742. owner->assignNewKey (commandID, -1);
  48743. }
  48744. }
  48745. void fitToContent (const int h) throw()
  48746. {
  48747. if (keyNum < 0)
  48748. {
  48749. setSize (h, h);
  48750. }
  48751. else
  48752. {
  48753. Font f (h * 0.6f);
  48754. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48755. }
  48756. }
  48757. juce_UseDebuggingNewOperator
  48758. private:
  48759. KeyMappingEditorComponent* const owner;
  48760. const CommandID commandID;
  48761. const int keyNum;
  48762. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48763. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48764. };
  48765. class KeyMappingItemComponent : public Component
  48766. {
  48767. public:
  48768. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  48769. const CommandID commandID_)
  48770. : owner (owner_),
  48771. commandID (commandID_)
  48772. {
  48773. setInterceptsMouseClicks (false, true);
  48774. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  48775. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  48776. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  48777. {
  48778. KeyMappingChangeButton* const kb
  48779. = new KeyMappingChangeButton (owner_, commandID,
  48780. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48781. kb->setEnabled (! isReadOnly);
  48782. addAndMakeVisible (kb);
  48783. }
  48784. KeyMappingChangeButton* const kb
  48785. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  48786. addChildComponent (kb);
  48787. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  48788. }
  48789. ~KeyMappingItemComponent()
  48790. {
  48791. deleteAllChildren();
  48792. }
  48793. void paint (Graphics& g)
  48794. {
  48795. g.setFont (getHeight() * 0.7f);
  48796. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48797. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48798. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48799. Justification::centredLeft, true);
  48800. }
  48801. void resized()
  48802. {
  48803. int x = getWidth() - 4;
  48804. for (int i = getNumChildComponents(); --i >= 0;)
  48805. {
  48806. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48807. kb->fitToContent (getHeight() - 2);
  48808. kb->setTopRightPosition (x, 1);
  48809. x -= kb->getWidth() + 5;
  48810. }
  48811. }
  48812. juce_UseDebuggingNewOperator
  48813. private:
  48814. KeyMappingEditorComponent* const owner;
  48815. const CommandID commandID;
  48816. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48817. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48818. };
  48819. class KeyMappingTreeViewItem : public TreeViewItem
  48820. {
  48821. public:
  48822. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  48823. const CommandID commandID_)
  48824. : owner (owner_),
  48825. commandID (commandID_)
  48826. {
  48827. }
  48828. ~KeyMappingTreeViewItem()
  48829. {
  48830. }
  48831. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48832. bool mightContainSubItems() { return false; }
  48833. int getItemHeight() const { return 20; }
  48834. Component* createItemComponent()
  48835. {
  48836. return new KeyMappingItemComponent (owner, commandID);
  48837. }
  48838. juce_UseDebuggingNewOperator
  48839. private:
  48840. KeyMappingEditorComponent* const owner;
  48841. const CommandID commandID;
  48842. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48843. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48844. };
  48845. class KeyCategoryTreeViewItem : public TreeViewItem
  48846. {
  48847. public:
  48848. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  48849. const String& name)
  48850. : owner (owner_),
  48851. categoryName (name)
  48852. {
  48853. }
  48854. ~KeyCategoryTreeViewItem()
  48855. {
  48856. }
  48857. const String getUniqueName() const { return categoryName + "_cat"; }
  48858. bool mightContainSubItems() { return true; }
  48859. int getItemHeight() const { return 28; }
  48860. void paintItem (Graphics& g, int width, int height)
  48861. {
  48862. g.setFont (height * 0.6f, Font::bold);
  48863. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  48864. g.drawText (categoryName,
  48865. 2, 0, width - 2, height,
  48866. Justification::centredLeft, true);
  48867. }
  48868. void itemOpennessChanged (bool isNowOpen)
  48869. {
  48870. if (isNowOpen)
  48871. {
  48872. if (getNumSubItems() == 0)
  48873. {
  48874. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48875. for (int i = 0; i < commands.size(); ++i)
  48876. {
  48877. if (owner->shouldCommandBeIncluded (commands[i]))
  48878. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48879. }
  48880. }
  48881. }
  48882. else
  48883. {
  48884. clearSubItems();
  48885. }
  48886. }
  48887. juce_UseDebuggingNewOperator
  48888. private:
  48889. KeyMappingEditorComponent* owner;
  48890. String categoryName;
  48891. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48892. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48893. };
  48894. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48895. const bool showResetToDefaultButton)
  48896. : mappings (mappingManager)
  48897. {
  48898. jassert (mappingManager != 0); // can't be null!
  48899. mappingManager->addChangeListener (this);
  48900. setLinesDrawnForSubItems (false);
  48901. resetButton = 0;
  48902. if (showResetToDefaultButton)
  48903. {
  48904. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  48905. resetButton->addButtonListener (this);
  48906. }
  48907. addAndMakeVisible (tree = new TreeView());
  48908. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48909. tree->setRootItemVisible (false);
  48910. tree->setDefaultOpenness (true);
  48911. tree->setRootItem (this);
  48912. }
  48913. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48914. {
  48915. mappings->removeChangeListener (this);
  48916. deleteAllChildren();
  48917. }
  48918. bool KeyMappingEditorComponent::mightContainSubItems()
  48919. {
  48920. return true;
  48921. }
  48922. const String KeyMappingEditorComponent::getUniqueName() const
  48923. {
  48924. return "keys";
  48925. }
  48926. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48927. const Colour& textColour)
  48928. {
  48929. setColour (backgroundColourId, mainBackground);
  48930. setColour (textColourId, textColour);
  48931. tree->setColour (TreeView::backgroundColourId, mainBackground);
  48932. }
  48933. void KeyMappingEditorComponent::parentHierarchyChanged()
  48934. {
  48935. changeListenerCallback (0);
  48936. }
  48937. void KeyMappingEditorComponent::resized()
  48938. {
  48939. int h = getHeight();
  48940. if (resetButton != 0)
  48941. {
  48942. const int buttonHeight = 20;
  48943. h -= buttonHeight + 8;
  48944. int x = getWidth() - 8;
  48945. resetButton->changeWidthToFitText (buttonHeight);
  48946. resetButton->setTopRightPosition (x, h + 6);
  48947. }
  48948. tree->setBounds (0, 0, getWidth(), h);
  48949. }
  48950. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48951. {
  48952. if (button == resetButton)
  48953. {
  48954. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48955. TRANS("Reset to defaults"),
  48956. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48957. TRANS("Reset")))
  48958. {
  48959. mappings->resetToDefaultMappings();
  48960. }
  48961. }
  48962. }
  48963. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48964. {
  48965. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  48966. clearSubItems();
  48967. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48968. for (int i = 0; i < categories.size(); ++i)
  48969. {
  48970. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48971. int count = 0;
  48972. for (int j = 0; j < commands.size(); ++j)
  48973. if (shouldCommandBeIncluded (commands[j]))
  48974. ++count;
  48975. if (count > 0)
  48976. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  48977. }
  48978. if (oldOpenness != 0)
  48979. tree->restoreOpennessState (*oldOpenness);
  48980. }
  48981. class KeyEntryWindow : public AlertWindow
  48982. {
  48983. public:
  48984. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  48985. : AlertWindow (TRANS("New key-mapping"),
  48986. TRANS("Please press a key combination now..."),
  48987. AlertWindow::NoIcon),
  48988. owner (owner_)
  48989. {
  48990. addButton (TRANS("ok"), 1);
  48991. addButton (TRANS("cancel"), 0);
  48992. // (avoid return + escape keys getting processed by the buttons..)
  48993. for (int i = getNumChildComponents(); --i >= 0;)
  48994. getChildComponent (i)->setWantsKeyboardFocus (false);
  48995. setWantsKeyboardFocus (true);
  48996. grabKeyboardFocus();
  48997. }
  48998. ~KeyEntryWindow()
  48999. {
  49000. }
  49001. bool keyPressed (const KeyPress& key)
  49002. {
  49003. lastPress = key;
  49004. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  49005. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  49006. if (previousCommand != 0)
  49007. {
  49008. message << "\n\n"
  49009. << TRANS("(Currently assigned to \"")
  49010. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  49011. << "\")";
  49012. }
  49013. setMessage (message);
  49014. return true;
  49015. }
  49016. bool keyStateChanged (bool)
  49017. {
  49018. return true;
  49019. }
  49020. KeyPress lastPress;
  49021. juce_UseDebuggingNewOperator
  49022. private:
  49023. KeyMappingEditorComponent* owner;
  49024. KeyEntryWindow (const KeyEntryWindow&);
  49025. KeyEntryWindow& operator= (const KeyEntryWindow&);
  49026. };
  49027. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  49028. {
  49029. KeyEntryWindow entryWindow (this);
  49030. if (entryWindow.runModalLoop() != 0)
  49031. {
  49032. entryWindow.setVisible (false);
  49033. if (entryWindow.lastPress.isValid())
  49034. {
  49035. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  49036. if (previousCommand != 0)
  49037. {
  49038. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  49039. TRANS("Change key-mapping"),
  49040. TRANS("This key is already assigned to the command \"")
  49041. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  49042. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  49043. TRANS("re-assign"),
  49044. TRANS("cancel")))
  49045. {
  49046. return;
  49047. }
  49048. }
  49049. mappings->removeKeyPress (entryWindow.lastPress);
  49050. if (index >= 0)
  49051. mappings->removeKeyPress (commandID, index);
  49052. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  49053. }
  49054. }
  49055. }
  49056. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  49057. {
  49058. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  49059. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  49060. }
  49061. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  49062. {
  49063. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  49064. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  49065. }
  49066. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  49067. {
  49068. return key.getTextDescription();
  49069. }
  49070. END_JUCE_NAMESPACE
  49071. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  49072. /*** Start of inlined file: juce_KeyPress.cpp ***/
  49073. BEGIN_JUCE_NAMESPACE
  49074. KeyPress::KeyPress() throw()
  49075. : keyCode (0),
  49076. mods (0),
  49077. textCharacter (0)
  49078. {
  49079. }
  49080. KeyPress::KeyPress (const int keyCode_,
  49081. const ModifierKeys& mods_,
  49082. const juce_wchar textCharacter_) throw()
  49083. : keyCode (keyCode_),
  49084. mods (mods_),
  49085. textCharacter (textCharacter_)
  49086. {
  49087. }
  49088. KeyPress::KeyPress (const int keyCode_) throw()
  49089. : keyCode (keyCode_),
  49090. textCharacter (0)
  49091. {
  49092. }
  49093. KeyPress::KeyPress (const KeyPress& other) throw()
  49094. : keyCode (other.keyCode),
  49095. mods (other.mods),
  49096. textCharacter (other.textCharacter)
  49097. {
  49098. }
  49099. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  49100. {
  49101. keyCode = other.keyCode;
  49102. mods = other.mods;
  49103. textCharacter = other.textCharacter;
  49104. return *this;
  49105. }
  49106. bool KeyPress::operator== (const KeyPress& other) const throw()
  49107. {
  49108. return mods.getRawFlags() == other.mods.getRawFlags()
  49109. && (textCharacter == other.textCharacter
  49110. || textCharacter == 0
  49111. || other.textCharacter == 0)
  49112. && (keyCode == other.keyCode
  49113. || (keyCode < 256
  49114. && other.keyCode < 256
  49115. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  49116. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  49117. }
  49118. bool KeyPress::operator!= (const KeyPress& other) const throw()
  49119. {
  49120. return ! operator== (other);
  49121. }
  49122. bool KeyPress::isCurrentlyDown() const
  49123. {
  49124. return isKeyCurrentlyDown (keyCode)
  49125. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  49126. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  49127. }
  49128. namespace KeyPressHelpers
  49129. {
  49130. struct KeyNameAndCode
  49131. {
  49132. const char* name;
  49133. int code;
  49134. };
  49135. static const KeyNameAndCode translations[] =
  49136. {
  49137. { "spacebar", KeyPress::spaceKey },
  49138. { "return", KeyPress::returnKey },
  49139. { "escape", KeyPress::escapeKey },
  49140. { "backspace", KeyPress::backspaceKey },
  49141. { "cursor left", KeyPress::leftKey },
  49142. { "cursor right", KeyPress::rightKey },
  49143. { "cursor up", KeyPress::upKey },
  49144. { "cursor down", KeyPress::downKey },
  49145. { "page up", KeyPress::pageUpKey },
  49146. { "page down", KeyPress::pageDownKey },
  49147. { "home", KeyPress::homeKey },
  49148. { "end", KeyPress::endKey },
  49149. { "delete", KeyPress::deleteKey },
  49150. { "insert", KeyPress::insertKey },
  49151. { "tab", KeyPress::tabKey },
  49152. { "play", KeyPress::playKey },
  49153. { "stop", KeyPress::stopKey },
  49154. { "fast forward", KeyPress::fastForwardKey },
  49155. { "rewind", KeyPress::rewindKey }
  49156. };
  49157. static const String numberPadPrefix() { return "numpad "; }
  49158. }
  49159. const KeyPress KeyPress::createFromDescription (const String& desc)
  49160. {
  49161. int modifiers = 0;
  49162. if (desc.containsWholeWordIgnoreCase ("ctrl")
  49163. || desc.containsWholeWordIgnoreCase ("control")
  49164. || desc.containsWholeWordIgnoreCase ("ctl"))
  49165. modifiers |= ModifierKeys::ctrlModifier;
  49166. if (desc.containsWholeWordIgnoreCase ("shift")
  49167. || desc.containsWholeWordIgnoreCase ("shft"))
  49168. modifiers |= ModifierKeys::shiftModifier;
  49169. if (desc.containsWholeWordIgnoreCase ("alt")
  49170. || desc.containsWholeWordIgnoreCase ("option"))
  49171. modifiers |= ModifierKeys::altModifier;
  49172. if (desc.containsWholeWordIgnoreCase ("command")
  49173. || desc.containsWholeWordIgnoreCase ("cmd"))
  49174. modifiers |= ModifierKeys::commandModifier;
  49175. int key = 0;
  49176. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49177. {
  49178. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  49179. {
  49180. key = KeyPressHelpers::translations[i].code;
  49181. break;
  49182. }
  49183. }
  49184. if (key == 0)
  49185. {
  49186. // see if it's a numpad key..
  49187. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  49188. {
  49189. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  49190. if (lastChar >= '0' && lastChar <= '9')
  49191. key = numberPad0 + lastChar - '0';
  49192. else if (lastChar == '+')
  49193. key = numberPadAdd;
  49194. else if (lastChar == '-')
  49195. key = numberPadSubtract;
  49196. else if (lastChar == '*')
  49197. key = numberPadMultiply;
  49198. else if (lastChar == '/')
  49199. key = numberPadDivide;
  49200. else if (lastChar == '.')
  49201. key = numberPadDecimalPoint;
  49202. else if (lastChar == '=')
  49203. key = numberPadEquals;
  49204. else if (desc.endsWith ("separator"))
  49205. key = numberPadSeparator;
  49206. else if (desc.endsWith ("delete"))
  49207. key = numberPadDelete;
  49208. }
  49209. if (key == 0)
  49210. {
  49211. // see if it's a function key..
  49212. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  49213. for (int i = 1; i <= 12; ++i)
  49214. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  49215. key = F1Key + i - 1;
  49216. if (key == 0)
  49217. {
  49218. // give up and use the hex code..
  49219. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  49220. .toLowerCase()
  49221. .retainCharacters ("0123456789abcdef")
  49222. .getHexValue32();
  49223. if (hexCode > 0)
  49224. key = hexCode;
  49225. else
  49226. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  49227. }
  49228. }
  49229. }
  49230. return KeyPress (key, ModifierKeys (modifiers), 0);
  49231. }
  49232. const String KeyPress::getTextDescription() const
  49233. {
  49234. String desc;
  49235. if (keyCode > 0)
  49236. {
  49237. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  49238. // want to store it as being a slash, not shift+whatever.
  49239. if (textCharacter == '/')
  49240. return "/";
  49241. if (mods.isCtrlDown())
  49242. desc << "ctrl + ";
  49243. if (mods.isShiftDown())
  49244. desc << "shift + ";
  49245. #if JUCE_MAC
  49246. // only do this on the mac, because on Windows ctrl and command are the same,
  49247. // and this would get confusing
  49248. if (mods.isCommandDown())
  49249. desc << "command + ";
  49250. if (mods.isAltDown())
  49251. desc << "option + ";
  49252. #else
  49253. if (mods.isAltDown())
  49254. desc << "alt + ";
  49255. #endif
  49256. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49257. if (keyCode == KeyPressHelpers::translations[i].code)
  49258. return desc + KeyPressHelpers::translations[i].name;
  49259. if (keyCode >= F1Key && keyCode <= F16Key)
  49260. desc << 'F' << (1 + keyCode - F1Key);
  49261. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  49262. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  49263. else if (keyCode >= 33 && keyCode < 176)
  49264. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  49265. else if (keyCode == numberPadAdd)
  49266. desc << KeyPressHelpers::numberPadPrefix() << '+';
  49267. else if (keyCode == numberPadSubtract)
  49268. desc << KeyPressHelpers::numberPadPrefix() << '-';
  49269. else if (keyCode == numberPadMultiply)
  49270. desc << KeyPressHelpers::numberPadPrefix() << '*';
  49271. else if (keyCode == numberPadDivide)
  49272. desc << KeyPressHelpers::numberPadPrefix() << '/';
  49273. else if (keyCode == numberPadSeparator)
  49274. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  49275. else if (keyCode == numberPadDecimalPoint)
  49276. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49277. else if (keyCode == numberPadDelete)
  49278. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49279. else
  49280. desc << '#' << String::toHexString (keyCode);
  49281. }
  49282. return desc;
  49283. }
  49284. END_JUCE_NAMESPACE
  49285. /*** End of inlined file: juce_KeyPress.cpp ***/
  49286. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49287. BEGIN_JUCE_NAMESPACE
  49288. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49289. : commandManager (commandManager_)
  49290. {
  49291. // A manager is needed to get the descriptions of commands, and will be called when
  49292. // a command is invoked. So you can't leave this null..
  49293. jassert (commandManager_ != 0);
  49294. Desktop::getInstance().addFocusChangeListener (this);
  49295. }
  49296. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49297. : commandManager (other.commandManager)
  49298. {
  49299. Desktop::getInstance().addFocusChangeListener (this);
  49300. }
  49301. KeyPressMappingSet::~KeyPressMappingSet()
  49302. {
  49303. Desktop::getInstance().removeFocusChangeListener (this);
  49304. }
  49305. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49306. {
  49307. for (int i = 0; i < mappings.size(); ++i)
  49308. if (mappings.getUnchecked(i)->commandID == commandID)
  49309. return mappings.getUnchecked (i)->keypresses;
  49310. return Array <KeyPress> ();
  49311. }
  49312. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49313. const KeyPress& newKeyPress,
  49314. int insertIndex)
  49315. {
  49316. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49317. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49318. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49319. && ! newKeyPress.getModifiers().isShiftDown()));
  49320. if (findCommandForKeyPress (newKeyPress) != commandID)
  49321. {
  49322. removeKeyPress (newKeyPress);
  49323. if (newKeyPress.isValid())
  49324. {
  49325. for (int i = mappings.size(); --i >= 0;)
  49326. {
  49327. if (mappings.getUnchecked(i)->commandID == commandID)
  49328. {
  49329. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49330. sendChangeMessage (this);
  49331. return;
  49332. }
  49333. }
  49334. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49335. if (ci != 0)
  49336. {
  49337. CommandMapping* const cm = new CommandMapping();
  49338. cm->commandID = commandID;
  49339. cm->keypresses.add (newKeyPress);
  49340. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49341. mappings.add (cm);
  49342. sendChangeMessage (this);
  49343. }
  49344. }
  49345. }
  49346. }
  49347. void KeyPressMappingSet::resetToDefaultMappings()
  49348. {
  49349. mappings.clear();
  49350. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49351. {
  49352. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49353. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49354. {
  49355. addKeyPress (ci->commandID,
  49356. ci->defaultKeypresses.getReference (j));
  49357. }
  49358. }
  49359. sendChangeMessage (this);
  49360. }
  49361. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49362. {
  49363. clearAllKeyPresses (commandID);
  49364. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49365. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49366. {
  49367. addKeyPress (ci->commandID,
  49368. ci->defaultKeypresses.getReference (j));
  49369. }
  49370. }
  49371. void KeyPressMappingSet::clearAllKeyPresses()
  49372. {
  49373. if (mappings.size() > 0)
  49374. {
  49375. sendChangeMessage (this);
  49376. mappings.clear();
  49377. }
  49378. }
  49379. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49380. {
  49381. for (int i = mappings.size(); --i >= 0;)
  49382. {
  49383. if (mappings.getUnchecked(i)->commandID == commandID)
  49384. {
  49385. mappings.remove (i);
  49386. sendChangeMessage (this);
  49387. }
  49388. }
  49389. }
  49390. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49391. {
  49392. if (keypress.isValid())
  49393. {
  49394. for (int i = mappings.size(); --i >= 0;)
  49395. {
  49396. CommandMapping* const cm = mappings.getUnchecked(i);
  49397. for (int j = cm->keypresses.size(); --j >= 0;)
  49398. {
  49399. if (keypress == cm->keypresses [j])
  49400. {
  49401. cm->keypresses.remove (j);
  49402. sendChangeMessage (this);
  49403. }
  49404. }
  49405. }
  49406. }
  49407. }
  49408. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49409. {
  49410. for (int i = mappings.size(); --i >= 0;)
  49411. {
  49412. if (mappings.getUnchecked(i)->commandID == commandID)
  49413. {
  49414. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49415. sendChangeMessage (this);
  49416. break;
  49417. }
  49418. }
  49419. }
  49420. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49421. {
  49422. for (int i = 0; i < mappings.size(); ++i)
  49423. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49424. return mappings.getUnchecked(i)->commandID;
  49425. return 0;
  49426. }
  49427. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49428. {
  49429. for (int i = mappings.size(); --i >= 0;)
  49430. if (mappings.getUnchecked(i)->commandID == commandID)
  49431. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49432. return false;
  49433. }
  49434. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49435. const KeyPress& key,
  49436. const bool isKeyDown,
  49437. const int millisecsSinceKeyPressed,
  49438. Component* const originatingComponent) const
  49439. {
  49440. ApplicationCommandTarget::InvocationInfo info (commandID);
  49441. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49442. info.isKeyDown = isKeyDown;
  49443. info.keyPress = key;
  49444. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49445. info.originatingComponent = originatingComponent;
  49446. commandManager->invoke (info, false);
  49447. }
  49448. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49449. {
  49450. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49451. {
  49452. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49453. {
  49454. // if the XML was created as a set of differences from the default mappings,
  49455. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49456. resetToDefaultMappings();
  49457. }
  49458. else
  49459. {
  49460. // if the XML was created calling createXml (false), then we need to clear all
  49461. // the keys and treat the xml as describing the entire set of mappings.
  49462. clearAllKeyPresses();
  49463. }
  49464. forEachXmlChildElement (xmlVersion, map)
  49465. {
  49466. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49467. if (commandId != 0)
  49468. {
  49469. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49470. if (map->hasTagName ("MAPPING"))
  49471. {
  49472. addKeyPress (commandId, key);
  49473. }
  49474. else if (map->hasTagName ("UNMAPPING"))
  49475. {
  49476. if (containsMapping (commandId, key))
  49477. removeKeyPress (key);
  49478. }
  49479. }
  49480. }
  49481. return true;
  49482. }
  49483. return false;
  49484. }
  49485. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49486. {
  49487. ScopedPointer <KeyPressMappingSet> defaultSet;
  49488. if (saveDifferencesFromDefaultSet)
  49489. {
  49490. defaultSet = new KeyPressMappingSet (commandManager);
  49491. defaultSet->resetToDefaultMappings();
  49492. }
  49493. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49494. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49495. int i;
  49496. for (i = 0; i < mappings.size(); ++i)
  49497. {
  49498. const CommandMapping* const cm = mappings.getUnchecked(i);
  49499. for (int j = 0; j < cm->keypresses.size(); ++j)
  49500. {
  49501. if (defaultSet == 0
  49502. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49503. {
  49504. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49505. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49506. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49507. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49508. }
  49509. }
  49510. }
  49511. if (defaultSet != 0)
  49512. {
  49513. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49514. {
  49515. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49516. for (int j = 0; j < cm->keypresses.size(); ++j)
  49517. {
  49518. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49519. {
  49520. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49521. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49522. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49523. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49524. }
  49525. }
  49526. }
  49527. }
  49528. return doc;
  49529. }
  49530. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49531. Component* originatingComponent)
  49532. {
  49533. bool used = false;
  49534. const CommandID commandID = findCommandForKeyPress (key);
  49535. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49536. if (ci != 0
  49537. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49538. {
  49539. ApplicationCommandInfo info (0);
  49540. if (commandManager->getTargetForCommand (commandID, info) != 0
  49541. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49542. {
  49543. invokeCommand (commandID, key, true, 0, originatingComponent);
  49544. used = true;
  49545. }
  49546. else
  49547. {
  49548. if (originatingComponent != 0)
  49549. originatingComponent->getLookAndFeel().playAlertSound();
  49550. }
  49551. }
  49552. return used;
  49553. }
  49554. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49555. {
  49556. bool used = false;
  49557. const uint32 now = Time::getMillisecondCounter();
  49558. for (int i = mappings.size(); --i >= 0;)
  49559. {
  49560. CommandMapping* const cm = mappings.getUnchecked(i);
  49561. if (cm->wantsKeyUpDownCallbacks)
  49562. {
  49563. for (int j = cm->keypresses.size(); --j >= 0;)
  49564. {
  49565. const KeyPress key (cm->keypresses.getReference (j));
  49566. const bool isDown = key.isCurrentlyDown();
  49567. int keyPressEntryIndex = 0;
  49568. bool wasDown = false;
  49569. for (int k = keysDown.size(); --k >= 0;)
  49570. {
  49571. if (key == keysDown.getUnchecked(k)->key)
  49572. {
  49573. keyPressEntryIndex = k;
  49574. wasDown = true;
  49575. used = true;
  49576. break;
  49577. }
  49578. }
  49579. if (isDown != wasDown)
  49580. {
  49581. int millisecs = 0;
  49582. if (isDown)
  49583. {
  49584. KeyPressTime* const k = new KeyPressTime();
  49585. k->key = key;
  49586. k->timeWhenPressed = now;
  49587. keysDown.add (k);
  49588. }
  49589. else
  49590. {
  49591. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49592. if (now > pressTime)
  49593. millisecs = now - pressTime;
  49594. keysDown.remove (keyPressEntryIndex);
  49595. }
  49596. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49597. used = true;
  49598. }
  49599. }
  49600. }
  49601. }
  49602. return used;
  49603. }
  49604. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49605. {
  49606. if (focusedComponent != 0)
  49607. focusedComponent->keyStateChanged (false);
  49608. }
  49609. END_JUCE_NAMESPACE
  49610. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49611. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49612. BEGIN_JUCE_NAMESPACE
  49613. ModifierKeys::ModifierKeys (const int flags_) throw()
  49614. : flags (flags_)
  49615. {
  49616. }
  49617. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49618. : flags (other.flags)
  49619. {
  49620. }
  49621. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49622. {
  49623. flags = other.flags;
  49624. return *this;
  49625. }
  49626. ModifierKeys ModifierKeys::currentModifiers;
  49627. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49628. {
  49629. return currentModifiers;
  49630. }
  49631. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49632. {
  49633. int num = 0;
  49634. if (isLeftButtonDown()) ++num;
  49635. if (isRightButtonDown()) ++num;
  49636. if (isMiddleButtonDown()) ++num;
  49637. return num;
  49638. }
  49639. END_JUCE_NAMESPACE
  49640. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49641. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49642. BEGIN_JUCE_NAMESPACE
  49643. class ComponentAnimator::AnimationTask
  49644. {
  49645. public:
  49646. AnimationTask (Component* const comp)
  49647. : component (comp)
  49648. {
  49649. }
  49650. Component::SafePointer<Component> component;
  49651. Rectangle<int> destination;
  49652. int msElapsed, msTotal;
  49653. double startSpeed, midSpeed, endSpeed, lastProgress;
  49654. double left, top, right, bottom;
  49655. bool useTimeslice (const int elapsed)
  49656. {
  49657. if (component == 0)
  49658. return false;
  49659. msElapsed += elapsed;
  49660. double newProgress = msElapsed / (double) msTotal;
  49661. if (newProgress >= 0 && newProgress < 1.0)
  49662. {
  49663. newProgress = timeToDistance (newProgress);
  49664. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49665. jassert (newProgress >= lastProgress);
  49666. lastProgress = newProgress;
  49667. left += (destination.getX() - left) * delta;
  49668. top += (destination.getY() - top) * delta;
  49669. right += (destination.getRight() - right) * delta;
  49670. bottom += (destination.getBottom() - bottom) * delta;
  49671. if (delta < 1.0)
  49672. {
  49673. const Rectangle<int> newBounds (roundToInt (left),
  49674. roundToInt (top),
  49675. roundToInt (right - left),
  49676. roundToInt (bottom - top));
  49677. if (newBounds != destination)
  49678. {
  49679. component->setBounds (newBounds);
  49680. return true;
  49681. }
  49682. }
  49683. }
  49684. component->setBounds (destination);
  49685. return false;
  49686. }
  49687. void moveToFinalDestination()
  49688. {
  49689. if (component != 0)
  49690. component->setBounds (destination);
  49691. }
  49692. private:
  49693. inline double timeToDistance (const double time) const
  49694. {
  49695. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49696. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49697. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49698. }
  49699. };
  49700. ComponentAnimator::ComponentAnimator()
  49701. : lastTime (0)
  49702. {
  49703. }
  49704. ComponentAnimator::~ComponentAnimator()
  49705. {
  49706. cancelAllAnimations (false);
  49707. jassert (tasks.size() == 0);
  49708. }
  49709. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49710. {
  49711. for (int i = tasks.size(); --i >= 0;)
  49712. if (component == tasks.getUnchecked(i)->component.getComponent())
  49713. return tasks.getUnchecked(i);
  49714. return 0;
  49715. }
  49716. void ComponentAnimator::animateComponent (Component* const component,
  49717. const Rectangle<int>& finalPosition,
  49718. const int millisecondsToSpendMoving,
  49719. const double startSpeed,
  49720. const double endSpeed)
  49721. {
  49722. if (component != 0)
  49723. {
  49724. AnimationTask* at = findTaskFor (component);
  49725. if (at == 0)
  49726. {
  49727. at = new AnimationTask (component);
  49728. tasks.add (at);
  49729. sendChangeMessage (this);
  49730. }
  49731. at->msElapsed = 0;
  49732. at->lastProgress = 0;
  49733. at->msTotal = jmax (1, millisecondsToSpendMoving);
  49734. at->destination = finalPosition;
  49735. // the speeds must be 0 or greater!
  49736. jassert (startSpeed >= 0 && endSpeed >= 0)
  49737. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  49738. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  49739. at->midSpeed = invTotalDistance;
  49740. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  49741. at->left = component->getX();
  49742. at->top = component->getY();
  49743. at->right = component->getRight();
  49744. at->bottom = component->getBottom();
  49745. if (! isTimerRunning())
  49746. {
  49747. lastTime = Time::getMillisecondCounter();
  49748. startTimer (1000 / 50);
  49749. }
  49750. }
  49751. }
  49752. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49753. {
  49754. for (int i = tasks.size(); --i >= 0;)
  49755. {
  49756. AnimationTask* const at = tasks.getUnchecked(i);
  49757. if (moveComponentsToTheirFinalPositions)
  49758. at->moveToFinalDestination();
  49759. delete at;
  49760. tasks.remove (i);
  49761. sendChangeMessage (this);
  49762. }
  49763. }
  49764. void ComponentAnimator::cancelAnimation (Component* const component,
  49765. const bool moveComponentToItsFinalPosition)
  49766. {
  49767. AnimationTask* const at = findTaskFor (component);
  49768. if (at != 0)
  49769. {
  49770. if (moveComponentToItsFinalPosition)
  49771. at->moveToFinalDestination();
  49772. tasks.removeValue (at);
  49773. delete at;
  49774. sendChangeMessage (this);
  49775. }
  49776. }
  49777. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49778. {
  49779. AnimationTask* const at = findTaskFor (component);
  49780. if (at != 0)
  49781. return at->destination;
  49782. else if (component != 0)
  49783. return component->getBounds();
  49784. return Rectangle<int>();
  49785. }
  49786. bool ComponentAnimator::isAnimating (Component* component) const
  49787. {
  49788. return findTaskFor (component) != 0;
  49789. }
  49790. void ComponentAnimator::timerCallback()
  49791. {
  49792. const uint32 timeNow = Time::getMillisecondCounter();
  49793. if (lastTime == 0 || lastTime == timeNow)
  49794. lastTime = timeNow;
  49795. const int elapsed = timeNow - lastTime;
  49796. for (int i = tasks.size(); --i >= 0;)
  49797. {
  49798. AnimationTask* const at = tasks.getUnchecked(i);
  49799. if (! at->useTimeslice (elapsed))
  49800. {
  49801. tasks.remove (i);
  49802. delete at;
  49803. sendChangeMessage (this);
  49804. }
  49805. }
  49806. lastTime = timeNow;
  49807. if (tasks.size() == 0)
  49808. stopTimer();
  49809. }
  49810. END_JUCE_NAMESPACE
  49811. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49812. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49813. BEGIN_JUCE_NAMESPACE
  49814. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49815. : minW (0),
  49816. maxW (0x3fffffff),
  49817. minH (0),
  49818. maxH (0x3fffffff),
  49819. minOffTop (0),
  49820. minOffLeft (0),
  49821. minOffBottom (0),
  49822. minOffRight (0),
  49823. aspectRatio (0.0)
  49824. {
  49825. }
  49826. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49827. {
  49828. }
  49829. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49830. {
  49831. minW = minimumWidth;
  49832. }
  49833. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49834. {
  49835. maxW = maximumWidth;
  49836. }
  49837. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49838. {
  49839. minH = minimumHeight;
  49840. }
  49841. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49842. {
  49843. maxH = maximumHeight;
  49844. }
  49845. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49846. {
  49847. jassert (maxW >= minimumWidth);
  49848. jassert (maxH >= minimumHeight);
  49849. jassert (minimumWidth > 0 && minimumHeight > 0);
  49850. minW = minimumWidth;
  49851. minH = minimumHeight;
  49852. if (minW > maxW)
  49853. maxW = minW;
  49854. if (minH > maxH)
  49855. maxH = minH;
  49856. }
  49857. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49858. {
  49859. jassert (maximumWidth >= minW);
  49860. jassert (maximumHeight >= minH);
  49861. jassert (maximumWidth > 0 && maximumHeight > 0);
  49862. maxW = jmax (minW, maximumWidth);
  49863. maxH = jmax (minH, maximumHeight);
  49864. }
  49865. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49866. const int minimumHeight,
  49867. const int maximumWidth,
  49868. const int maximumHeight) throw()
  49869. {
  49870. jassert (maximumWidth >= minimumWidth);
  49871. jassert (maximumHeight >= minimumHeight);
  49872. jassert (maximumWidth > 0 && maximumHeight > 0);
  49873. jassert (minimumWidth > 0 && minimumHeight > 0);
  49874. minW = jmax (0, minimumWidth);
  49875. minH = jmax (0, minimumHeight);
  49876. maxW = jmax (minW, maximumWidth);
  49877. maxH = jmax (minH, maximumHeight);
  49878. }
  49879. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49880. const int minimumWhenOffTheLeft,
  49881. const int minimumWhenOffTheBottom,
  49882. const int minimumWhenOffTheRight) throw()
  49883. {
  49884. minOffTop = minimumWhenOffTheTop;
  49885. minOffLeft = minimumWhenOffTheLeft;
  49886. minOffBottom = minimumWhenOffTheBottom;
  49887. minOffRight = minimumWhenOffTheRight;
  49888. }
  49889. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49890. {
  49891. aspectRatio = jmax (0.0, widthOverHeight);
  49892. }
  49893. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49894. {
  49895. return aspectRatio;
  49896. }
  49897. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49898. const Rectangle<int>& targetBounds,
  49899. const bool isStretchingTop,
  49900. const bool isStretchingLeft,
  49901. const bool isStretchingBottom,
  49902. const bool isStretchingRight)
  49903. {
  49904. jassert (component != 0);
  49905. Rectangle<int> limits, bounds (targetBounds);
  49906. BorderSize border;
  49907. Component* const parent = component->getParentComponent();
  49908. if (parent == 0)
  49909. {
  49910. ComponentPeer* peer = component->getPeer();
  49911. if (peer != 0)
  49912. border = peer->getFrameSize();
  49913. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49914. }
  49915. else
  49916. {
  49917. limits.setSize (parent->getWidth(), parent->getHeight());
  49918. }
  49919. border.addTo (bounds);
  49920. checkBounds (bounds,
  49921. border.addedTo (component->getBounds()), limits,
  49922. isStretchingTop, isStretchingLeft,
  49923. isStretchingBottom, isStretchingRight);
  49924. border.subtractFrom (bounds);
  49925. applyBoundsToComponent (component, bounds);
  49926. }
  49927. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49928. {
  49929. setBoundsForComponent (component, component->getBounds(),
  49930. false, false, false, false);
  49931. }
  49932. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49933. const Rectangle<int>& bounds)
  49934. {
  49935. component->setBounds (bounds);
  49936. }
  49937. void ComponentBoundsConstrainer::resizeStart()
  49938. {
  49939. }
  49940. void ComponentBoundsConstrainer::resizeEnd()
  49941. {
  49942. }
  49943. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49944. const Rectangle<int>& old,
  49945. const Rectangle<int>& limits,
  49946. const bool isStretchingTop,
  49947. const bool isStretchingLeft,
  49948. const bool isStretchingBottom,
  49949. const bool isStretchingRight)
  49950. {
  49951. int x = bounds.getX();
  49952. int y = bounds.getY();
  49953. int w = bounds.getWidth();
  49954. int h = bounds.getHeight();
  49955. // constrain the size if it's being stretched..
  49956. if (isStretchingLeft)
  49957. {
  49958. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  49959. w = old.getRight() - x;
  49960. }
  49961. if (isStretchingRight)
  49962. {
  49963. w = jlimit (minW, maxW, w);
  49964. }
  49965. if (isStretchingTop)
  49966. {
  49967. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  49968. h = old.getBottom() - y;
  49969. }
  49970. if (isStretchingBottom)
  49971. {
  49972. h = jlimit (minH, maxH, h);
  49973. }
  49974. // constrain the aspect ratio if one has been specified..
  49975. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49976. {
  49977. bool adjustWidth;
  49978. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49979. {
  49980. adjustWidth = true;
  49981. }
  49982. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49983. {
  49984. adjustWidth = false;
  49985. }
  49986. else
  49987. {
  49988. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49989. const double newRatio = std::abs (w / (double) h);
  49990. adjustWidth = (oldRatio > newRatio);
  49991. }
  49992. if (adjustWidth)
  49993. {
  49994. w = roundToInt (h * aspectRatio);
  49995. if (w > maxW || w < minW)
  49996. {
  49997. w = jlimit (minW, maxW, w);
  49998. h = roundToInt (w / aspectRatio);
  49999. }
  50000. }
  50001. else
  50002. {
  50003. h = roundToInt (w / aspectRatio);
  50004. if (h > maxH || h < minH)
  50005. {
  50006. h = jlimit (minH, maxH, h);
  50007. w = roundToInt (h * aspectRatio);
  50008. }
  50009. }
  50010. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  50011. {
  50012. x = old.getX() + (old.getWidth() - w) / 2;
  50013. }
  50014. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  50015. {
  50016. y = old.getY() + (old.getHeight() - h) / 2;
  50017. }
  50018. else
  50019. {
  50020. if (isStretchingLeft)
  50021. x = old.getRight() - w;
  50022. if (isStretchingTop)
  50023. y = old.getBottom() - h;
  50024. }
  50025. }
  50026. // ...and constrain the position if limits have been set for that.
  50027. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  50028. {
  50029. if (minOffTop > 0)
  50030. {
  50031. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  50032. if (y < limit)
  50033. {
  50034. if (isStretchingTop)
  50035. h -= (limit - y);
  50036. y = limit;
  50037. }
  50038. }
  50039. if (minOffLeft > 0)
  50040. {
  50041. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  50042. if (x < limit)
  50043. {
  50044. if (isStretchingLeft)
  50045. w -= (limit - x);
  50046. x = limit;
  50047. }
  50048. }
  50049. if (minOffBottom > 0)
  50050. {
  50051. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  50052. if (y > limit)
  50053. {
  50054. if (isStretchingBottom)
  50055. h += (limit - y);
  50056. else
  50057. y = limit;
  50058. }
  50059. }
  50060. if (minOffRight > 0)
  50061. {
  50062. const int limit = limits.getRight() - jmin (minOffRight, w);
  50063. if (x > limit)
  50064. {
  50065. if (isStretchingRight)
  50066. w += (limit - x);
  50067. else
  50068. x = limit;
  50069. }
  50070. }
  50071. }
  50072. jassert (w >= 0 && h >= 0);
  50073. bounds = Rectangle<int> (x, y, w, h);
  50074. }
  50075. END_JUCE_NAMESPACE
  50076. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  50077. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50078. BEGIN_JUCE_NAMESPACE
  50079. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  50080. : component (component_),
  50081. lastPeer (0),
  50082. reentrant (false)
  50083. {
  50084. jassert (component != 0); // can't use this with a null pointer..
  50085. component->addComponentListener (this);
  50086. registerWithParentComps();
  50087. }
  50088. ComponentMovementWatcher::~ComponentMovementWatcher()
  50089. {
  50090. component->removeComponentListener (this);
  50091. unregister();
  50092. }
  50093. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  50094. {
  50095. // agh! don't delete the target component without deleting this object first!
  50096. jassert (component != 0);
  50097. if (! reentrant)
  50098. {
  50099. reentrant = true;
  50100. ComponentPeer* const peer = component->getPeer();
  50101. if (peer != lastPeer)
  50102. {
  50103. componentPeerChanged();
  50104. if (component == 0)
  50105. return;
  50106. lastPeer = peer;
  50107. }
  50108. unregister();
  50109. registerWithParentComps();
  50110. reentrant = false;
  50111. componentMovedOrResized (*component, true, true);
  50112. }
  50113. }
  50114. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  50115. {
  50116. // agh! don't delete the target component without deleting this object first!
  50117. jassert (component != 0);
  50118. if (wasMoved)
  50119. {
  50120. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  50121. wasMoved = lastBounds.getPosition() != pos;
  50122. lastBounds.setPosition (pos);
  50123. }
  50124. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  50125. lastBounds.setSize (component->getWidth(), component->getHeight());
  50126. if (wasMoved || wasResized)
  50127. componentMovedOrResized (wasMoved, wasResized);
  50128. }
  50129. void ComponentMovementWatcher::registerWithParentComps()
  50130. {
  50131. Component* p = component->getParentComponent();
  50132. while (p != 0)
  50133. {
  50134. p->addComponentListener (this);
  50135. registeredParentComps.add (p);
  50136. p = p->getParentComponent();
  50137. }
  50138. }
  50139. void ComponentMovementWatcher::unregister()
  50140. {
  50141. for (int i = registeredParentComps.size(); --i >= 0;)
  50142. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  50143. registeredParentComps.clear();
  50144. }
  50145. END_JUCE_NAMESPACE
  50146. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50147. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  50148. BEGIN_JUCE_NAMESPACE
  50149. GroupComponent::GroupComponent (const String& componentName,
  50150. const String& labelText)
  50151. : Component (componentName),
  50152. text (labelText),
  50153. justification (Justification::left)
  50154. {
  50155. setInterceptsMouseClicks (false, true);
  50156. }
  50157. GroupComponent::~GroupComponent()
  50158. {
  50159. }
  50160. void GroupComponent::setText (const String& newText)
  50161. {
  50162. if (text != newText)
  50163. {
  50164. text = newText;
  50165. repaint();
  50166. }
  50167. }
  50168. const String GroupComponent::getText() const
  50169. {
  50170. return text;
  50171. }
  50172. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  50173. {
  50174. if (justification != newJustification)
  50175. {
  50176. justification = newJustification;
  50177. repaint();
  50178. }
  50179. }
  50180. void GroupComponent::paint (Graphics& g)
  50181. {
  50182. getLookAndFeel()
  50183. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  50184. text, justification,
  50185. *this);
  50186. }
  50187. void GroupComponent::enablementChanged()
  50188. {
  50189. repaint();
  50190. }
  50191. void GroupComponent::colourChanged()
  50192. {
  50193. repaint();
  50194. }
  50195. END_JUCE_NAMESPACE
  50196. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50197. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50198. BEGIN_JUCE_NAMESPACE
  50199. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50200. : DocumentWindow (String::empty, backgroundColour,
  50201. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50202. {
  50203. }
  50204. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50205. {
  50206. }
  50207. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50208. {
  50209. MultiDocumentPanel* const owner = getOwner();
  50210. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50211. if (owner != 0)
  50212. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50213. }
  50214. void MultiDocumentPanelWindow::closeButtonPressed()
  50215. {
  50216. MultiDocumentPanel* const owner = getOwner();
  50217. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50218. if (owner != 0)
  50219. owner->closeDocument (getContentComponent(), true);
  50220. }
  50221. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50222. {
  50223. DocumentWindow::activeWindowStatusChanged();
  50224. updateOrder();
  50225. }
  50226. void MultiDocumentPanelWindow::broughtToFront()
  50227. {
  50228. DocumentWindow::broughtToFront();
  50229. updateOrder();
  50230. }
  50231. void MultiDocumentPanelWindow::updateOrder()
  50232. {
  50233. MultiDocumentPanel* const owner = getOwner();
  50234. if (owner != 0)
  50235. owner->updateOrder();
  50236. }
  50237. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50238. {
  50239. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50240. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50241. }
  50242. class MDITabbedComponentInternal : public TabbedComponent
  50243. {
  50244. public:
  50245. MDITabbedComponentInternal()
  50246. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50247. {
  50248. }
  50249. ~MDITabbedComponentInternal()
  50250. {
  50251. }
  50252. void currentTabChanged (int, const String&)
  50253. {
  50254. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50255. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50256. if (owner != 0)
  50257. owner->updateOrder();
  50258. }
  50259. };
  50260. MultiDocumentPanel::MultiDocumentPanel()
  50261. : mode (MaximisedWindowsWithTabs),
  50262. backgroundColour (Colours::lightblue),
  50263. maximumNumDocuments (0),
  50264. numDocsBeforeTabsUsed (0)
  50265. {
  50266. setOpaque (true);
  50267. }
  50268. MultiDocumentPanel::~MultiDocumentPanel()
  50269. {
  50270. closeAllDocuments (false);
  50271. }
  50272. static bool shouldDeleteComp (Component* const c)
  50273. {
  50274. return c->getProperties() ["mdiDocumentDelete_"];
  50275. }
  50276. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50277. {
  50278. while (components.size() > 0)
  50279. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50280. return false;
  50281. return true;
  50282. }
  50283. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50284. {
  50285. return new MultiDocumentPanelWindow (backgroundColour);
  50286. }
  50287. void MultiDocumentPanel::addWindow (Component* component)
  50288. {
  50289. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50290. dw->setResizable (true, false);
  50291. dw->setContentComponent (component, false, true);
  50292. dw->setName (component->getName());
  50293. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50294. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50295. int x = 4;
  50296. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50297. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50298. x += 16;
  50299. dw->setTopLeftPosition (x, x);
  50300. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50301. if (pos.toString().isNotEmpty())
  50302. dw->restoreWindowStateFromString (pos.toString());
  50303. addAndMakeVisible (dw);
  50304. dw->toFront (true);
  50305. }
  50306. bool MultiDocumentPanel::addDocument (Component* const component,
  50307. const Colour& docColour,
  50308. const bool deleteWhenRemoved)
  50309. {
  50310. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50311. // with a frame-within-a-frame! Just pass in the bare content component.
  50312. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50313. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50314. return false;
  50315. components.add (component);
  50316. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50317. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50318. component->addComponentListener (this);
  50319. if (mode == FloatingWindows)
  50320. {
  50321. if (isFullscreenWhenOneDocument())
  50322. {
  50323. if (components.size() == 1)
  50324. {
  50325. addAndMakeVisible (component);
  50326. }
  50327. else
  50328. {
  50329. if (components.size() == 2)
  50330. addWindow (components.getFirst());
  50331. addWindow (component);
  50332. }
  50333. }
  50334. else
  50335. {
  50336. addWindow (component);
  50337. }
  50338. }
  50339. else
  50340. {
  50341. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50342. {
  50343. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50344. Array <Component*> temp (components);
  50345. for (int i = 0; i < temp.size(); ++i)
  50346. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50347. resized();
  50348. }
  50349. else
  50350. {
  50351. if (tabComponent != 0)
  50352. tabComponent->addTab (component->getName(), docColour, component, false);
  50353. else
  50354. addAndMakeVisible (component);
  50355. }
  50356. setActiveDocument (component);
  50357. }
  50358. resized();
  50359. activeDocumentChanged();
  50360. return true;
  50361. }
  50362. bool MultiDocumentPanel::closeDocument (Component* component,
  50363. const bool checkItsOkToCloseFirst)
  50364. {
  50365. if (components.contains (component))
  50366. {
  50367. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50368. return false;
  50369. component->removeComponentListener (this);
  50370. const bool shouldDelete = shouldDeleteComp (component);
  50371. component->getProperties().remove ("mdiDocumentDelete_");
  50372. component->getProperties().remove ("mdiDocumentBkg_");
  50373. if (mode == FloatingWindows)
  50374. {
  50375. for (int i = getNumChildComponents(); --i >= 0;)
  50376. {
  50377. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50378. if (dw != 0 && dw->getContentComponent() == component)
  50379. {
  50380. dw->setContentComponent (0, false);
  50381. delete dw;
  50382. break;
  50383. }
  50384. }
  50385. if (shouldDelete)
  50386. delete component;
  50387. components.removeValue (component);
  50388. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50389. {
  50390. for (int i = getNumChildComponents(); --i >= 0;)
  50391. {
  50392. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50393. if (dw != 0)
  50394. {
  50395. dw->setContentComponent (0, false);
  50396. delete dw;
  50397. }
  50398. }
  50399. addAndMakeVisible (components.getFirst());
  50400. }
  50401. }
  50402. else
  50403. {
  50404. jassert (components.indexOf (component) >= 0);
  50405. if (tabComponent != 0)
  50406. {
  50407. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50408. if (tabComponent->getTabContentComponent (i) == component)
  50409. tabComponent->removeTab (i);
  50410. }
  50411. else
  50412. {
  50413. removeChildComponent (component);
  50414. }
  50415. if (shouldDelete)
  50416. delete component;
  50417. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50418. tabComponent = 0;
  50419. components.removeValue (component);
  50420. if (components.size() > 0 && tabComponent == 0)
  50421. addAndMakeVisible (components.getFirst());
  50422. }
  50423. resized();
  50424. activeDocumentChanged();
  50425. }
  50426. else
  50427. {
  50428. jassertfalse;
  50429. }
  50430. return true;
  50431. }
  50432. int MultiDocumentPanel::getNumDocuments() const throw()
  50433. {
  50434. return components.size();
  50435. }
  50436. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50437. {
  50438. return components [index];
  50439. }
  50440. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50441. {
  50442. if (mode == FloatingWindows)
  50443. {
  50444. for (int i = getNumChildComponents(); --i >= 0;)
  50445. {
  50446. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50447. if (dw != 0 && dw->isActiveWindow())
  50448. return dw->getContentComponent();
  50449. }
  50450. }
  50451. return components.getLast();
  50452. }
  50453. void MultiDocumentPanel::setActiveDocument (Component* component)
  50454. {
  50455. if (mode == FloatingWindows)
  50456. {
  50457. component = getContainerComp (component);
  50458. if (component != 0)
  50459. component->toFront (true);
  50460. }
  50461. else if (tabComponent != 0)
  50462. {
  50463. jassert (components.indexOf (component) >= 0);
  50464. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50465. {
  50466. if (tabComponent->getTabContentComponent (i) == component)
  50467. {
  50468. tabComponent->setCurrentTabIndex (i);
  50469. break;
  50470. }
  50471. }
  50472. }
  50473. else
  50474. {
  50475. component->grabKeyboardFocus();
  50476. }
  50477. }
  50478. void MultiDocumentPanel::activeDocumentChanged()
  50479. {
  50480. }
  50481. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50482. {
  50483. maximumNumDocuments = newNumber;
  50484. }
  50485. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50486. {
  50487. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50488. }
  50489. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50490. {
  50491. return numDocsBeforeTabsUsed != 0;
  50492. }
  50493. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50494. {
  50495. if (mode != newLayoutMode)
  50496. {
  50497. mode = newLayoutMode;
  50498. if (mode == FloatingWindows)
  50499. {
  50500. tabComponent = 0;
  50501. }
  50502. else
  50503. {
  50504. for (int i = getNumChildComponents(); --i >= 0;)
  50505. {
  50506. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50507. if (dw != 0)
  50508. {
  50509. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50510. dw->setContentComponent (0, false);
  50511. delete dw;
  50512. }
  50513. }
  50514. }
  50515. resized();
  50516. const Array <Component*> tempComps (components);
  50517. components.clear();
  50518. for (int i = 0; i < tempComps.size(); ++i)
  50519. {
  50520. Component* const c = tempComps.getUnchecked(i);
  50521. addDocument (c,
  50522. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50523. shouldDeleteComp (c));
  50524. }
  50525. }
  50526. }
  50527. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50528. {
  50529. if (backgroundColour != newBackgroundColour)
  50530. {
  50531. backgroundColour = newBackgroundColour;
  50532. setOpaque (newBackgroundColour.isOpaque());
  50533. repaint();
  50534. }
  50535. }
  50536. void MultiDocumentPanel::paint (Graphics& g)
  50537. {
  50538. g.fillAll (backgroundColour);
  50539. }
  50540. void MultiDocumentPanel::resized()
  50541. {
  50542. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50543. {
  50544. for (int i = getNumChildComponents(); --i >= 0;)
  50545. getChildComponent (i)->setBounds (getLocalBounds());
  50546. }
  50547. setWantsKeyboardFocus (components.size() == 0);
  50548. }
  50549. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50550. {
  50551. if (mode == FloatingWindows)
  50552. {
  50553. for (int i = 0; i < getNumChildComponents(); ++i)
  50554. {
  50555. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50556. if (dw != 0 && dw->getContentComponent() == c)
  50557. {
  50558. c = dw;
  50559. break;
  50560. }
  50561. }
  50562. }
  50563. return c;
  50564. }
  50565. void MultiDocumentPanel::componentNameChanged (Component&)
  50566. {
  50567. if (mode == FloatingWindows)
  50568. {
  50569. for (int i = 0; i < getNumChildComponents(); ++i)
  50570. {
  50571. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50572. if (dw != 0)
  50573. dw->setName (dw->getContentComponent()->getName());
  50574. }
  50575. }
  50576. else if (tabComponent != 0)
  50577. {
  50578. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50579. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50580. }
  50581. }
  50582. void MultiDocumentPanel::updateOrder()
  50583. {
  50584. const Array <Component*> oldList (components);
  50585. if (mode == FloatingWindows)
  50586. {
  50587. components.clear();
  50588. for (int i = 0; i < getNumChildComponents(); ++i)
  50589. {
  50590. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50591. if (dw != 0)
  50592. components.add (dw->getContentComponent());
  50593. }
  50594. }
  50595. else
  50596. {
  50597. if (tabComponent != 0)
  50598. {
  50599. Component* const current = tabComponent->getCurrentContentComponent();
  50600. if (current != 0)
  50601. {
  50602. components.removeValue (current);
  50603. components.add (current);
  50604. }
  50605. }
  50606. }
  50607. if (components != oldList)
  50608. activeDocumentChanged();
  50609. }
  50610. END_JUCE_NAMESPACE
  50611. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50612. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50613. BEGIN_JUCE_NAMESPACE
  50614. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50615. : zone (zoneFlags)
  50616. {
  50617. }
  50618. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50619. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50620. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50621. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50622. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50623. const BorderSize& border,
  50624. const Point<int>& position)
  50625. {
  50626. int z = 0;
  50627. if (totalSize.contains (position)
  50628. && ! border.subtractedFrom (totalSize).contains (position))
  50629. {
  50630. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50631. if (position.getX() < jmax (border.getLeft(), minW))
  50632. z |= left;
  50633. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50634. z |= right;
  50635. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50636. if (position.getY() < jmax (border.getTop(), minH))
  50637. z |= top;
  50638. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50639. z |= bottom;
  50640. }
  50641. return Zone (z);
  50642. }
  50643. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50644. {
  50645. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50646. switch (zone)
  50647. {
  50648. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50649. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50650. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50651. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50652. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50653. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50654. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50655. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50656. default: break;
  50657. }
  50658. return mc;
  50659. }
  50660. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50661. {
  50662. if (isDraggingWholeObject())
  50663. return b + offset;
  50664. if (isDraggingLeftEdge())
  50665. b.setLeft (b.getX() + offset.getX());
  50666. if (isDraggingRightEdge())
  50667. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50668. if (isDraggingTopEdge())
  50669. b.setTop (b.getY() + offset.getY());
  50670. if (isDraggingBottomEdge())
  50671. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50672. return b;
  50673. }
  50674. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50675. {
  50676. if (isDraggingWholeObject())
  50677. return b + offset;
  50678. if (isDraggingLeftEdge())
  50679. b.setLeft (b.getX() + offset.getX());
  50680. if (isDraggingRightEdge())
  50681. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50682. if (isDraggingTopEdge())
  50683. b.setTop (b.getY() + offset.getY());
  50684. if (isDraggingBottomEdge())
  50685. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50686. return b;
  50687. }
  50688. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50689. ComponentBoundsConstrainer* const constrainer_)
  50690. : component (componentToResize),
  50691. constrainer (constrainer_),
  50692. borderSize (5),
  50693. mouseZone (0)
  50694. {
  50695. }
  50696. ResizableBorderComponent::~ResizableBorderComponent()
  50697. {
  50698. }
  50699. void ResizableBorderComponent::paint (Graphics& g)
  50700. {
  50701. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50702. }
  50703. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50704. {
  50705. updateMouseZone (e);
  50706. }
  50707. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50708. {
  50709. updateMouseZone (e);
  50710. }
  50711. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50712. {
  50713. if (component == 0)
  50714. {
  50715. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50716. return;
  50717. }
  50718. updateMouseZone (e);
  50719. originalBounds = component->getBounds();
  50720. if (constrainer != 0)
  50721. constrainer->resizeStart();
  50722. }
  50723. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50724. {
  50725. if (component == 0)
  50726. {
  50727. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50728. return;
  50729. }
  50730. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50731. if (constrainer != 0)
  50732. constrainer->setBoundsForComponent (component, bounds,
  50733. mouseZone.isDraggingTopEdge(),
  50734. mouseZone.isDraggingLeftEdge(),
  50735. mouseZone.isDraggingBottomEdge(),
  50736. mouseZone.isDraggingRightEdge());
  50737. else
  50738. component->setBounds (bounds);
  50739. }
  50740. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50741. {
  50742. if (constrainer != 0)
  50743. constrainer->resizeEnd();
  50744. }
  50745. bool ResizableBorderComponent::hitTest (int x, int y)
  50746. {
  50747. return x < borderSize.getLeft()
  50748. || x >= getWidth() - borderSize.getRight()
  50749. || y < borderSize.getTop()
  50750. || y >= getHeight() - borderSize.getBottom();
  50751. }
  50752. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50753. {
  50754. if (borderSize != newBorderSize)
  50755. {
  50756. borderSize = newBorderSize;
  50757. repaint();
  50758. }
  50759. }
  50760. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50761. {
  50762. return borderSize;
  50763. }
  50764. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50765. {
  50766. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50767. if (mouseZone != newZone)
  50768. {
  50769. mouseZone = newZone;
  50770. setMouseCursor (newZone.getMouseCursor());
  50771. }
  50772. }
  50773. END_JUCE_NAMESPACE
  50774. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50775. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50776. BEGIN_JUCE_NAMESPACE
  50777. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50778. ComponentBoundsConstrainer* const constrainer_)
  50779. : component (componentToResize),
  50780. constrainer (constrainer_)
  50781. {
  50782. setRepaintsOnMouseActivity (true);
  50783. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50784. }
  50785. ResizableCornerComponent::~ResizableCornerComponent()
  50786. {
  50787. }
  50788. void ResizableCornerComponent::paint (Graphics& g)
  50789. {
  50790. getLookAndFeel()
  50791. .drawCornerResizer (g, getWidth(), getHeight(),
  50792. isMouseOverOrDragging(),
  50793. isMouseButtonDown());
  50794. }
  50795. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50796. {
  50797. if (component == 0)
  50798. {
  50799. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50800. return;
  50801. }
  50802. originalBounds = component->getBounds();
  50803. if (constrainer != 0)
  50804. constrainer->resizeStart();
  50805. }
  50806. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50807. {
  50808. if (component == 0)
  50809. {
  50810. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50811. return;
  50812. }
  50813. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50814. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50815. if (constrainer != 0)
  50816. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50817. else
  50818. component->setBounds (r);
  50819. }
  50820. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50821. {
  50822. if (constrainer != 0)
  50823. constrainer->resizeStart();
  50824. }
  50825. bool ResizableCornerComponent::hitTest (int x, int y)
  50826. {
  50827. if (getWidth() <= 0)
  50828. return false;
  50829. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50830. return y >= yAtX - getHeight() / 4;
  50831. }
  50832. END_JUCE_NAMESPACE
  50833. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50834. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50835. BEGIN_JUCE_NAMESPACE
  50836. class ScrollBar::ScrollbarButton : public Button
  50837. {
  50838. public:
  50839. int direction;
  50840. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50841. : Button (String::empty),
  50842. direction (direction_),
  50843. owner (owner_)
  50844. {
  50845. setWantsKeyboardFocus (false);
  50846. }
  50847. ~ScrollbarButton()
  50848. {
  50849. }
  50850. void paintButton (Graphics& g, bool over, bool down)
  50851. {
  50852. getLookAndFeel()
  50853. .drawScrollbarButton (g, owner,
  50854. getWidth(), getHeight(),
  50855. direction,
  50856. owner.isVertical(),
  50857. over, down);
  50858. }
  50859. void clicked()
  50860. {
  50861. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50862. }
  50863. juce_UseDebuggingNewOperator
  50864. private:
  50865. ScrollBar& owner;
  50866. ScrollbarButton (const ScrollbarButton&);
  50867. ScrollbarButton& operator= (const ScrollbarButton&);
  50868. };
  50869. ScrollBar::ScrollBar (const bool vertical_,
  50870. const bool buttonsAreVisible)
  50871. : totalRange (0.0, 1.0),
  50872. visibleRange (0.0, 0.1),
  50873. singleStepSize (0.1),
  50874. thumbAreaStart (0),
  50875. thumbAreaSize (0),
  50876. thumbStart (0),
  50877. thumbSize (0),
  50878. initialDelayInMillisecs (100),
  50879. repeatDelayInMillisecs (50),
  50880. minimumDelayInMillisecs (10),
  50881. vertical (vertical_),
  50882. isDraggingThumb (false),
  50883. autohides (true)
  50884. {
  50885. setButtonVisibility (buttonsAreVisible);
  50886. setRepaintsOnMouseActivity (true);
  50887. setFocusContainer (true);
  50888. }
  50889. ScrollBar::~ScrollBar()
  50890. {
  50891. upButton = 0;
  50892. downButton = 0;
  50893. }
  50894. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50895. {
  50896. if (totalRange != newRangeLimit)
  50897. {
  50898. totalRange = newRangeLimit;
  50899. setCurrentRange (visibleRange);
  50900. updateThumbPosition();
  50901. }
  50902. }
  50903. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50904. {
  50905. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50906. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50907. }
  50908. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50909. {
  50910. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50911. if (visibleRange != constrainedRange)
  50912. {
  50913. visibleRange = constrainedRange;
  50914. updateThumbPosition();
  50915. triggerAsyncUpdate();
  50916. }
  50917. }
  50918. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50919. {
  50920. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50921. }
  50922. void ScrollBar::setCurrentRangeStart (const double newStart)
  50923. {
  50924. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50925. }
  50926. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50927. {
  50928. singleStepSize = newSingleStepSize;
  50929. }
  50930. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50931. {
  50932. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50933. }
  50934. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50935. {
  50936. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50937. }
  50938. void ScrollBar::scrollToTop()
  50939. {
  50940. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50941. }
  50942. void ScrollBar::scrollToBottom()
  50943. {
  50944. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50945. }
  50946. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50947. const int repeatDelayInMillisecs_,
  50948. const int minimumDelayInMillisecs_)
  50949. {
  50950. initialDelayInMillisecs = initialDelayInMillisecs_;
  50951. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50952. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50953. if (upButton != 0)
  50954. {
  50955. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50956. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50957. }
  50958. }
  50959. void ScrollBar::addListener (Listener* const listener)
  50960. {
  50961. listeners.add (listener);
  50962. }
  50963. void ScrollBar::removeListener (Listener* const listener)
  50964. {
  50965. listeners.remove (listener);
  50966. }
  50967. void ScrollBar::handleAsyncUpdate()
  50968. {
  50969. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50970. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50971. }
  50972. void ScrollBar::updateThumbPosition()
  50973. {
  50974. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50975. : thumbAreaSize);
  50976. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50977. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50978. if (newThumbSize > thumbAreaSize)
  50979. newThumbSize = thumbAreaSize;
  50980. int newThumbStart = thumbAreaStart;
  50981. if (totalRange.getLength() > visibleRange.getLength())
  50982. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50983. / (totalRange.getLength() - visibleRange.getLength()));
  50984. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50985. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50986. {
  50987. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50988. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50989. if (vertical)
  50990. repaint (0, repaintStart, getWidth(), repaintSize);
  50991. else
  50992. repaint (repaintStart, 0, repaintSize, getHeight());
  50993. thumbStart = newThumbStart;
  50994. thumbSize = newThumbSize;
  50995. }
  50996. }
  50997. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50998. {
  50999. if (vertical != shouldBeVertical)
  51000. {
  51001. vertical = shouldBeVertical;
  51002. if (upButton != 0)
  51003. {
  51004. upButton->direction = vertical ? 0 : 3;
  51005. downButton->direction = vertical ? 2 : 1;
  51006. }
  51007. updateThumbPosition();
  51008. }
  51009. }
  51010. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  51011. {
  51012. upButton = 0;
  51013. downButton = 0;
  51014. if (buttonsAreVisible)
  51015. {
  51016. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  51017. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  51018. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  51019. }
  51020. updateThumbPosition();
  51021. }
  51022. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  51023. {
  51024. autohides = shouldHideWhenFullRange;
  51025. updateThumbPosition();
  51026. }
  51027. bool ScrollBar::autoHides() const throw()
  51028. {
  51029. return autohides;
  51030. }
  51031. void ScrollBar::paint (Graphics& g)
  51032. {
  51033. if (thumbAreaSize > 0)
  51034. {
  51035. LookAndFeel& lf = getLookAndFeel();
  51036. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  51037. ? thumbSize : 0;
  51038. if (vertical)
  51039. {
  51040. lf.drawScrollbar (g, *this,
  51041. 0, thumbAreaStart,
  51042. getWidth(), thumbAreaSize,
  51043. vertical,
  51044. thumbStart, thumb,
  51045. isMouseOver(), isMouseButtonDown());
  51046. }
  51047. else
  51048. {
  51049. lf.drawScrollbar (g, *this,
  51050. thumbAreaStart, 0,
  51051. thumbAreaSize, getHeight(),
  51052. vertical,
  51053. thumbStart, thumb,
  51054. isMouseOver(), isMouseButtonDown());
  51055. }
  51056. }
  51057. }
  51058. void ScrollBar::lookAndFeelChanged()
  51059. {
  51060. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  51061. }
  51062. void ScrollBar::resized()
  51063. {
  51064. const int length = ((vertical) ? getHeight() : getWidth());
  51065. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  51066. : 0;
  51067. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51068. {
  51069. thumbAreaStart = length >> 1;
  51070. thumbAreaSize = 0;
  51071. }
  51072. else
  51073. {
  51074. thumbAreaStart = buttonSize;
  51075. thumbAreaSize = length - (buttonSize << 1);
  51076. }
  51077. if (upButton != 0)
  51078. {
  51079. if (vertical)
  51080. {
  51081. upButton->setBounds (0, 0, getWidth(), buttonSize);
  51082. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  51083. }
  51084. else
  51085. {
  51086. upButton->setBounds (0, 0, buttonSize, getHeight());
  51087. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  51088. }
  51089. }
  51090. updateThumbPosition();
  51091. }
  51092. void ScrollBar::mouseDown (const MouseEvent& e)
  51093. {
  51094. isDraggingThumb = false;
  51095. lastMousePos = vertical ? e.y : e.x;
  51096. dragStartMousePos = lastMousePos;
  51097. dragStartRange = visibleRange.getStart();
  51098. if (dragStartMousePos < thumbStart)
  51099. {
  51100. moveScrollbarInPages (-1);
  51101. startTimer (400);
  51102. }
  51103. else if (dragStartMousePos >= thumbStart + thumbSize)
  51104. {
  51105. moveScrollbarInPages (1);
  51106. startTimer (400);
  51107. }
  51108. else
  51109. {
  51110. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51111. && (thumbAreaSize > thumbSize);
  51112. }
  51113. }
  51114. void ScrollBar::mouseDrag (const MouseEvent& e)
  51115. {
  51116. if (isDraggingThumb)
  51117. {
  51118. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  51119. setCurrentRangeStart (dragStartRange
  51120. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  51121. / (thumbAreaSize - thumbSize));
  51122. }
  51123. else
  51124. {
  51125. lastMousePos = (vertical) ? e.y : e.x;
  51126. }
  51127. }
  51128. void ScrollBar::mouseUp (const MouseEvent&)
  51129. {
  51130. isDraggingThumb = false;
  51131. stopTimer();
  51132. repaint();
  51133. }
  51134. void ScrollBar::mouseWheelMove (const MouseEvent&,
  51135. float wheelIncrementX,
  51136. float wheelIncrementY)
  51137. {
  51138. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  51139. if (increment < 0)
  51140. increment = jmin (increment * 10.0f, -1.0f);
  51141. else if (increment > 0)
  51142. increment = jmax (increment * 10.0f, 1.0f);
  51143. setCurrentRange (visibleRange - singleStepSize * increment);
  51144. }
  51145. void ScrollBar::timerCallback()
  51146. {
  51147. if (isMouseButtonDown())
  51148. {
  51149. startTimer (40);
  51150. if (lastMousePos < thumbStart)
  51151. setCurrentRange (visibleRange - visibleRange.getLength());
  51152. else if (lastMousePos > thumbStart + thumbSize)
  51153. setCurrentRangeStart (visibleRange.getEnd());
  51154. }
  51155. else
  51156. {
  51157. stopTimer();
  51158. }
  51159. }
  51160. bool ScrollBar::keyPressed (const KeyPress& key)
  51161. {
  51162. if (! isVisible())
  51163. return false;
  51164. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  51165. moveScrollbarInSteps (-1);
  51166. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  51167. moveScrollbarInSteps (1);
  51168. else if (key.isKeyCode (KeyPress::pageUpKey))
  51169. moveScrollbarInPages (-1);
  51170. else if (key.isKeyCode (KeyPress::pageDownKey))
  51171. moveScrollbarInPages (1);
  51172. else if (key.isKeyCode (KeyPress::homeKey))
  51173. scrollToTop();
  51174. else if (key.isKeyCode (KeyPress::endKey))
  51175. scrollToBottom();
  51176. else
  51177. return false;
  51178. return true;
  51179. }
  51180. END_JUCE_NAMESPACE
  51181. /*** End of inlined file: juce_ScrollBar.cpp ***/
  51182. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  51183. BEGIN_JUCE_NAMESPACE
  51184. StretchableLayoutManager::StretchableLayoutManager()
  51185. : totalSize (0)
  51186. {
  51187. }
  51188. StretchableLayoutManager::~StretchableLayoutManager()
  51189. {
  51190. }
  51191. void StretchableLayoutManager::clearAllItems()
  51192. {
  51193. items.clear();
  51194. totalSize = 0;
  51195. }
  51196. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  51197. const double minimumSize,
  51198. const double maximumSize,
  51199. const double preferredSize)
  51200. {
  51201. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51202. if (layout == 0)
  51203. {
  51204. layout = new ItemLayoutProperties();
  51205. layout->itemIndex = itemIndex;
  51206. int i;
  51207. for (i = 0; i < items.size(); ++i)
  51208. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51209. break;
  51210. items.insert (i, layout);
  51211. }
  51212. layout->minSize = minimumSize;
  51213. layout->maxSize = maximumSize;
  51214. layout->preferredSize = preferredSize;
  51215. layout->currentSize = 0;
  51216. }
  51217. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51218. double& minimumSize,
  51219. double& maximumSize,
  51220. double& preferredSize) const
  51221. {
  51222. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51223. if (layout != 0)
  51224. {
  51225. minimumSize = layout->minSize;
  51226. maximumSize = layout->maxSize;
  51227. preferredSize = layout->preferredSize;
  51228. return true;
  51229. }
  51230. return false;
  51231. }
  51232. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51233. {
  51234. totalSize = newTotalSize;
  51235. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51236. }
  51237. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51238. {
  51239. int pos = 0;
  51240. for (int i = 0; i < itemIndex; ++i)
  51241. {
  51242. const ItemLayoutProperties* const layout = getInfoFor (i);
  51243. if (layout != 0)
  51244. pos += layout->currentSize;
  51245. }
  51246. return pos;
  51247. }
  51248. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51249. {
  51250. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51251. if (layout != 0)
  51252. return layout->currentSize;
  51253. return 0;
  51254. }
  51255. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51256. {
  51257. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51258. if (layout != 0)
  51259. return -layout->currentSize / (double) totalSize;
  51260. return 0;
  51261. }
  51262. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51263. int newPosition)
  51264. {
  51265. for (int i = items.size(); --i >= 0;)
  51266. {
  51267. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51268. if (layout->itemIndex == itemIndex)
  51269. {
  51270. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51271. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51272. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51273. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51274. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51275. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51276. endPos += layout->currentSize;
  51277. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51278. updatePrefSizesToMatchCurrentPositions();
  51279. break;
  51280. }
  51281. }
  51282. }
  51283. void StretchableLayoutManager::layOutComponents (Component** const components,
  51284. int numComponents,
  51285. int x, int y, int w, int h,
  51286. const bool vertically,
  51287. const bool resizeOtherDimension)
  51288. {
  51289. setTotalSize (vertically ? h : w);
  51290. int pos = vertically ? y : x;
  51291. for (int i = 0; i < numComponents; ++i)
  51292. {
  51293. const ItemLayoutProperties* const layout = getInfoFor (i);
  51294. if (layout != 0)
  51295. {
  51296. Component* const c = components[i];
  51297. if (c != 0)
  51298. {
  51299. if (i == numComponents - 1)
  51300. {
  51301. // if it's the last item, crop it to exactly fit the available space..
  51302. if (resizeOtherDimension)
  51303. {
  51304. if (vertically)
  51305. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51306. else
  51307. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51308. }
  51309. else
  51310. {
  51311. if (vertically)
  51312. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51313. else
  51314. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51315. }
  51316. }
  51317. else
  51318. {
  51319. if (resizeOtherDimension)
  51320. {
  51321. if (vertically)
  51322. c->setBounds (x, pos, w, layout->currentSize);
  51323. else
  51324. c->setBounds (pos, y, layout->currentSize, h);
  51325. }
  51326. else
  51327. {
  51328. if (vertically)
  51329. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51330. else
  51331. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51332. }
  51333. }
  51334. }
  51335. pos += layout->currentSize;
  51336. }
  51337. }
  51338. }
  51339. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51340. {
  51341. for (int i = items.size(); --i >= 0;)
  51342. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51343. return items.getUnchecked(i);
  51344. return 0;
  51345. }
  51346. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51347. const int endIndex,
  51348. const int availableSpace,
  51349. int startPos)
  51350. {
  51351. // calculate the total sizes
  51352. int i;
  51353. double totalIdealSize = 0.0;
  51354. int totalMinimums = 0;
  51355. for (i = startIndex; i < endIndex; ++i)
  51356. {
  51357. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51358. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51359. totalMinimums += layout->currentSize;
  51360. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51361. }
  51362. if (totalIdealSize <= 0)
  51363. totalIdealSize = 1.0;
  51364. // now calc the best sizes..
  51365. int extraSpace = availableSpace - totalMinimums;
  51366. while (extraSpace > 0)
  51367. {
  51368. int numWantingMoreSpace = 0;
  51369. int numHavingTakenExtraSpace = 0;
  51370. // first figure out how many comps want a slice of the extra space..
  51371. for (i = startIndex; i < endIndex; ++i)
  51372. {
  51373. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51374. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51375. const int bestSize = jlimit (layout->currentSize,
  51376. jmax (layout->currentSize,
  51377. sizeToRealSize (layout->maxSize, totalSize)),
  51378. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51379. if (bestSize > layout->currentSize)
  51380. ++numWantingMoreSpace;
  51381. }
  51382. // ..share out the extra space..
  51383. for (i = startIndex; i < endIndex; ++i)
  51384. {
  51385. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51386. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51387. int bestSize = jlimit (layout->currentSize,
  51388. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51389. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51390. const int extraWanted = bestSize - layout->currentSize;
  51391. if (extraWanted > 0)
  51392. {
  51393. const int extraAllowed = jmin (extraWanted,
  51394. extraSpace / jmax (1, numWantingMoreSpace));
  51395. if (extraAllowed > 0)
  51396. {
  51397. ++numHavingTakenExtraSpace;
  51398. --numWantingMoreSpace;
  51399. layout->currentSize += extraAllowed;
  51400. extraSpace -= extraAllowed;
  51401. }
  51402. }
  51403. }
  51404. if (numHavingTakenExtraSpace <= 0)
  51405. break;
  51406. }
  51407. // ..and calculate the end position
  51408. for (i = startIndex; i < endIndex; ++i)
  51409. {
  51410. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51411. startPos += layout->currentSize;
  51412. }
  51413. return startPos;
  51414. }
  51415. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51416. const int endIndex) const
  51417. {
  51418. int totalMinimums = 0;
  51419. for (int i = startIndex; i < endIndex; ++i)
  51420. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51421. return totalMinimums;
  51422. }
  51423. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51424. {
  51425. int totalMaximums = 0;
  51426. for (int i = startIndex; i < endIndex; ++i)
  51427. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51428. return totalMaximums;
  51429. }
  51430. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51431. {
  51432. for (int i = 0; i < items.size(); ++i)
  51433. {
  51434. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51435. layout->preferredSize
  51436. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51437. : getItemCurrentAbsoluteSize (i);
  51438. }
  51439. }
  51440. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51441. {
  51442. if (size < 0)
  51443. size *= -totalSpace;
  51444. return roundToInt (size);
  51445. }
  51446. END_JUCE_NAMESPACE
  51447. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51448. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51449. BEGIN_JUCE_NAMESPACE
  51450. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51451. const int itemIndex_,
  51452. const bool isVertical_)
  51453. : layout (layout_),
  51454. itemIndex (itemIndex_),
  51455. isVertical (isVertical_)
  51456. {
  51457. setRepaintsOnMouseActivity (true);
  51458. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51459. : MouseCursor::UpDownResizeCursor));
  51460. }
  51461. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51462. {
  51463. }
  51464. void StretchableLayoutResizerBar::paint (Graphics& g)
  51465. {
  51466. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51467. getWidth(), getHeight(),
  51468. isVertical,
  51469. isMouseOver(),
  51470. isMouseButtonDown());
  51471. }
  51472. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51473. {
  51474. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51475. }
  51476. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51477. {
  51478. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51479. : e.getDistanceFromDragStartY());
  51480. layout->setItemPosition (itemIndex, desiredPos);
  51481. hasBeenMoved();
  51482. }
  51483. void StretchableLayoutResizerBar::hasBeenMoved()
  51484. {
  51485. if (getParentComponent() != 0)
  51486. getParentComponent()->resized();
  51487. }
  51488. END_JUCE_NAMESPACE
  51489. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51490. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51491. BEGIN_JUCE_NAMESPACE
  51492. StretchableObjectResizer::StretchableObjectResizer()
  51493. {
  51494. }
  51495. StretchableObjectResizer::~StretchableObjectResizer()
  51496. {
  51497. }
  51498. void StretchableObjectResizer::addItem (const double size,
  51499. const double minSize, const double maxSize,
  51500. const int order)
  51501. {
  51502. // the order must be >= 0 but less than the maximum integer value.
  51503. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51504. Item* const item = new Item();
  51505. item->size = size;
  51506. item->minSize = minSize;
  51507. item->maxSize = maxSize;
  51508. item->order = order;
  51509. items.add (item);
  51510. }
  51511. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51512. {
  51513. const Item* const it = items [index];
  51514. return it != 0 ? it->size : 0;
  51515. }
  51516. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51517. {
  51518. int order = 0;
  51519. for (;;)
  51520. {
  51521. double currentSize = 0;
  51522. double minSize = 0;
  51523. double maxSize = 0;
  51524. int nextHighestOrder = std::numeric_limits<int>::max();
  51525. for (int i = 0; i < items.size(); ++i)
  51526. {
  51527. const Item* const it = items.getUnchecked(i);
  51528. currentSize += it->size;
  51529. if (it->order <= order)
  51530. {
  51531. minSize += it->minSize;
  51532. maxSize += it->maxSize;
  51533. }
  51534. else
  51535. {
  51536. minSize += it->size;
  51537. maxSize += it->size;
  51538. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51539. }
  51540. }
  51541. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51542. if (thisIterationTarget >= currentSize)
  51543. {
  51544. const double availableExtraSpace = maxSize - currentSize;
  51545. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51546. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51547. for (int i = 0; i < items.size(); ++i)
  51548. {
  51549. Item* const it = items.getUnchecked(i);
  51550. if (it->order <= order)
  51551. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51552. }
  51553. }
  51554. else
  51555. {
  51556. const double amountOfSlack = currentSize - minSize;
  51557. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51558. const double scale = targetAmountOfSlack / amountOfSlack;
  51559. for (int i = 0; i < items.size(); ++i)
  51560. {
  51561. Item* const it = items.getUnchecked(i);
  51562. if (it->order <= order)
  51563. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51564. }
  51565. }
  51566. if (nextHighestOrder < std::numeric_limits<int>::max())
  51567. order = nextHighestOrder;
  51568. else
  51569. break;
  51570. }
  51571. }
  51572. END_JUCE_NAMESPACE
  51573. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51574. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51575. BEGIN_JUCE_NAMESPACE
  51576. TabBarButton::TabBarButton (const String& name,
  51577. TabbedButtonBar* const owner_,
  51578. const int index)
  51579. : Button (name),
  51580. owner (owner_),
  51581. tabIndex (index),
  51582. overlapPixels (0)
  51583. {
  51584. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51585. setComponentEffect (&shadow);
  51586. setWantsKeyboardFocus (false);
  51587. }
  51588. TabBarButton::~TabBarButton()
  51589. {
  51590. }
  51591. void TabBarButton::paintButton (Graphics& g,
  51592. bool isMouseOverButton,
  51593. bool isButtonDown)
  51594. {
  51595. int x, y, w, h;
  51596. getActiveArea (x, y, w, h);
  51597. g.setOrigin (x, y);
  51598. getLookAndFeel()
  51599. .drawTabButton (g, w, h,
  51600. owner->getTabBackgroundColour (tabIndex),
  51601. tabIndex, getButtonText(), *this,
  51602. owner->getOrientation(),
  51603. isMouseOverButton, isButtonDown,
  51604. getToggleState());
  51605. }
  51606. void TabBarButton::clicked (const ModifierKeys& mods)
  51607. {
  51608. if (mods.isPopupMenu())
  51609. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51610. else
  51611. owner->setCurrentTabIndex (tabIndex);
  51612. }
  51613. bool TabBarButton::hitTest (int mx, int my)
  51614. {
  51615. int x, y, w, h;
  51616. getActiveArea (x, y, w, h);
  51617. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51618. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51619. {
  51620. if (((unsigned int) mx) < (unsigned int) getWidth()
  51621. && my >= y + overlapPixels
  51622. && my < y + h - overlapPixels)
  51623. return true;
  51624. }
  51625. else
  51626. {
  51627. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51628. && ((unsigned int) my) < (unsigned int) getHeight())
  51629. return true;
  51630. }
  51631. Path p;
  51632. getLookAndFeel()
  51633. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51634. owner->getOrientation(),
  51635. false, false, getToggleState());
  51636. return p.contains ((float) (mx - x),
  51637. (float) (my - y));
  51638. }
  51639. int TabBarButton::getBestTabLength (const int depth)
  51640. {
  51641. return jlimit (depth * 2,
  51642. depth * 7,
  51643. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51644. }
  51645. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51646. {
  51647. x = 0;
  51648. y = 0;
  51649. int r = getWidth();
  51650. int b = getHeight();
  51651. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51652. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51653. r -= spaceAroundImage;
  51654. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51655. x += spaceAroundImage;
  51656. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51657. y += spaceAroundImage;
  51658. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51659. b -= spaceAroundImage;
  51660. w = r - x;
  51661. h = b - y;
  51662. }
  51663. class TabAreaBehindFrontButtonComponent : public Component
  51664. {
  51665. public:
  51666. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51667. : owner (owner_)
  51668. {
  51669. setInterceptsMouseClicks (false, false);
  51670. }
  51671. ~TabAreaBehindFrontButtonComponent()
  51672. {
  51673. }
  51674. void paint (Graphics& g)
  51675. {
  51676. getLookAndFeel()
  51677. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51678. *owner, owner->getOrientation());
  51679. }
  51680. void enablementChanged()
  51681. {
  51682. repaint();
  51683. }
  51684. private:
  51685. TabbedButtonBar* const owner;
  51686. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51687. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51688. };
  51689. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51690. : orientation (orientation_),
  51691. currentTabIndex (-1)
  51692. {
  51693. setInterceptsMouseClicks (false, true);
  51694. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51695. setFocusContainer (true);
  51696. }
  51697. TabbedButtonBar::~TabbedButtonBar()
  51698. {
  51699. extraTabsButton = 0;
  51700. deleteAllChildren();
  51701. }
  51702. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51703. {
  51704. orientation = newOrientation;
  51705. for (int i = getNumChildComponents(); --i >= 0;)
  51706. getChildComponent (i)->resized();
  51707. resized();
  51708. }
  51709. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51710. {
  51711. return new TabBarButton (name, this, index);
  51712. }
  51713. void TabbedButtonBar::clearTabs()
  51714. {
  51715. tabs.clear();
  51716. tabColours.clear();
  51717. currentTabIndex = -1;
  51718. extraTabsButton = 0;
  51719. removeChildComponent (behindFrontTab);
  51720. deleteAllChildren();
  51721. addChildComponent (behindFrontTab);
  51722. setCurrentTabIndex (-1);
  51723. }
  51724. void TabbedButtonBar::addTab (const String& tabName,
  51725. const Colour& tabBackgroundColour,
  51726. int insertIndex)
  51727. {
  51728. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51729. if (tabName.isNotEmpty())
  51730. {
  51731. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51732. insertIndex = tabs.size();
  51733. for (int i = tabs.size(); --i >= insertIndex;)
  51734. {
  51735. TabBarButton* const tb = getTabButton (i);
  51736. if (tb != 0)
  51737. tb->tabIndex++;
  51738. }
  51739. tabs.insert (insertIndex, tabName);
  51740. tabColours.insert (insertIndex, tabBackgroundColour);
  51741. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51742. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51743. addAndMakeVisible (tb, insertIndex);
  51744. resized();
  51745. if (currentTabIndex < 0)
  51746. setCurrentTabIndex (0);
  51747. }
  51748. }
  51749. void TabbedButtonBar::setTabName (const int tabIndex,
  51750. const String& newName)
  51751. {
  51752. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51753. && tabs[tabIndex] != newName)
  51754. {
  51755. tabs.set (tabIndex, newName);
  51756. TabBarButton* const tb = getTabButton (tabIndex);
  51757. if (tb != 0)
  51758. tb->setButtonText (newName);
  51759. resized();
  51760. }
  51761. }
  51762. void TabbedButtonBar::removeTab (const int tabIndex)
  51763. {
  51764. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51765. {
  51766. const int oldTabIndex = currentTabIndex;
  51767. if (currentTabIndex == tabIndex)
  51768. currentTabIndex = -1;
  51769. tabs.remove (tabIndex);
  51770. tabColours.remove (tabIndex);
  51771. delete getTabButton (tabIndex);
  51772. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51773. {
  51774. TabBarButton* const tb = getTabButton (i);
  51775. if (tb != 0)
  51776. tb->tabIndex--;
  51777. }
  51778. resized();
  51779. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51780. }
  51781. }
  51782. void TabbedButtonBar::moveTab (const int currentIndex,
  51783. const int newIndex)
  51784. {
  51785. tabs.move (currentIndex, newIndex);
  51786. tabColours.move (currentIndex, newIndex);
  51787. resized();
  51788. }
  51789. int TabbedButtonBar::getNumTabs() const
  51790. {
  51791. return tabs.size();
  51792. }
  51793. const StringArray TabbedButtonBar::getTabNames() const
  51794. {
  51795. return tabs;
  51796. }
  51797. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51798. {
  51799. if (currentTabIndex != newIndex)
  51800. {
  51801. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51802. newIndex = -1;
  51803. currentTabIndex = newIndex;
  51804. for (int i = 0; i < getNumChildComponents(); ++i)
  51805. {
  51806. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51807. if (tb != 0)
  51808. tb->setToggleState (tb->tabIndex == newIndex, false);
  51809. }
  51810. resized();
  51811. if (sendChangeMessage_)
  51812. sendChangeMessage (this);
  51813. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51814. }
  51815. }
  51816. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51817. {
  51818. for (int i = getNumChildComponents(); --i >= 0;)
  51819. {
  51820. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51821. if (tb != 0 && tb->tabIndex == index)
  51822. return tb;
  51823. }
  51824. return 0;
  51825. }
  51826. void TabbedButtonBar::lookAndFeelChanged()
  51827. {
  51828. extraTabsButton = 0;
  51829. resized();
  51830. }
  51831. void TabbedButtonBar::resized()
  51832. {
  51833. const double minimumScale = 0.7;
  51834. int depth = getWidth();
  51835. int length = getHeight();
  51836. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51837. swapVariables (depth, length);
  51838. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51839. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51840. int i, totalLength = overlap;
  51841. int numVisibleButtons = tabs.size();
  51842. for (i = 0; i < getNumChildComponents(); ++i)
  51843. {
  51844. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51845. if (tb != 0)
  51846. {
  51847. totalLength += tb->getBestTabLength (depth) - overlap;
  51848. tb->overlapPixels = overlap / 2;
  51849. }
  51850. }
  51851. double scale = 1.0;
  51852. if (totalLength > length)
  51853. scale = jmax (minimumScale, length / (double) totalLength);
  51854. const bool isTooBig = totalLength * scale > length;
  51855. int tabsButtonPos = 0;
  51856. if (isTooBig)
  51857. {
  51858. if (extraTabsButton == 0)
  51859. {
  51860. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51861. extraTabsButton->addButtonListener (this);
  51862. extraTabsButton->setAlwaysOnTop (true);
  51863. extraTabsButton->setTriggeredOnMouseDown (true);
  51864. }
  51865. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51866. extraTabsButton->setSize (buttonSize, buttonSize);
  51867. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51868. {
  51869. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51870. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51871. }
  51872. else
  51873. {
  51874. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51875. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51876. }
  51877. totalLength = 0;
  51878. for (i = 0; i < tabs.size(); ++i)
  51879. {
  51880. TabBarButton* const tb = getTabButton (i);
  51881. if (tb != 0)
  51882. {
  51883. const int newLength = totalLength + tb->getBestTabLength (depth);
  51884. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51885. {
  51886. totalLength += overlap;
  51887. break;
  51888. }
  51889. numVisibleButtons = i + 1;
  51890. totalLength = newLength - overlap;
  51891. }
  51892. }
  51893. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51894. }
  51895. else
  51896. {
  51897. extraTabsButton = 0;
  51898. }
  51899. int pos = 0;
  51900. TabBarButton* frontTab = 0;
  51901. for (i = 0; i < tabs.size(); ++i)
  51902. {
  51903. TabBarButton* const tb = getTabButton (i);
  51904. if (tb != 0)
  51905. {
  51906. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51907. if (i < numVisibleButtons)
  51908. {
  51909. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51910. tb->setBounds (pos, 0, bestLength, getHeight());
  51911. else
  51912. tb->setBounds (0, pos, getWidth(), bestLength);
  51913. tb->toBack();
  51914. if (tb->tabIndex == currentTabIndex)
  51915. frontTab = tb;
  51916. tb->setVisible (true);
  51917. }
  51918. else
  51919. {
  51920. tb->setVisible (false);
  51921. }
  51922. pos += bestLength - overlap;
  51923. }
  51924. }
  51925. behindFrontTab->setBounds (getLocalBounds());
  51926. if (frontTab != 0)
  51927. {
  51928. frontTab->toFront (false);
  51929. behindFrontTab->toBehind (frontTab);
  51930. }
  51931. }
  51932. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51933. {
  51934. return tabColours [tabIndex];
  51935. }
  51936. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51937. {
  51938. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51939. && tabColours [tabIndex] != newColour)
  51940. {
  51941. tabColours.set (tabIndex, newColour);
  51942. repaint();
  51943. }
  51944. }
  51945. void TabbedButtonBar::buttonClicked (Button* button)
  51946. {
  51947. if (button == extraTabsButton)
  51948. {
  51949. PopupMenu m;
  51950. for (int i = 0; i < tabs.size(); ++i)
  51951. {
  51952. TabBarButton* const tb = getTabButton (i);
  51953. if (tb != 0 && ! tb->isVisible())
  51954. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51955. }
  51956. const int res = m.showAt (extraTabsButton);
  51957. if (res != 0)
  51958. setCurrentTabIndex (res - 1);
  51959. }
  51960. }
  51961. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51962. {
  51963. }
  51964. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51965. {
  51966. }
  51967. END_JUCE_NAMESPACE
  51968. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51969. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51970. BEGIN_JUCE_NAMESPACE
  51971. class TabCompButtonBar : public TabbedButtonBar
  51972. {
  51973. public:
  51974. TabCompButtonBar (TabbedComponent* const owner_,
  51975. const TabbedButtonBar::Orientation orientation_)
  51976. : TabbedButtonBar (orientation_),
  51977. owner (owner_)
  51978. {
  51979. }
  51980. ~TabCompButtonBar()
  51981. {
  51982. }
  51983. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51984. {
  51985. owner->changeCallback (newCurrentTabIndex, newTabName);
  51986. }
  51987. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51988. {
  51989. owner->popupMenuClickOnTab (tabIndex, tabName);
  51990. }
  51991. const Colour getTabBackgroundColour (const int tabIndex)
  51992. {
  51993. return owner->tabs->getTabBackgroundColour (tabIndex);
  51994. }
  51995. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51996. {
  51997. return owner->createTabButton (tabName, tabIndex);
  51998. }
  51999. juce_UseDebuggingNewOperator
  52000. private:
  52001. TabbedComponent* const owner;
  52002. TabCompButtonBar (const TabCompButtonBar&);
  52003. TabCompButtonBar& operator= (const TabCompButtonBar&);
  52004. };
  52005. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  52006. : panelComponent (0),
  52007. tabDepth (30),
  52008. outlineThickness (1),
  52009. edgeIndent (0)
  52010. {
  52011. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  52012. }
  52013. TabbedComponent::~TabbedComponent()
  52014. {
  52015. clearTabs();
  52016. delete tabs;
  52017. }
  52018. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  52019. {
  52020. tabs->setOrientation (orientation);
  52021. resized();
  52022. }
  52023. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  52024. {
  52025. return tabs->getOrientation();
  52026. }
  52027. void TabbedComponent::setTabBarDepth (const int newDepth)
  52028. {
  52029. if (tabDepth != newDepth)
  52030. {
  52031. tabDepth = newDepth;
  52032. resized();
  52033. }
  52034. }
  52035. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  52036. {
  52037. return new TabBarButton (tabName, tabs, tabIndex);
  52038. }
  52039. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  52040. void TabbedComponent::clearTabs()
  52041. {
  52042. if (panelComponent != 0)
  52043. {
  52044. panelComponent->setVisible (false);
  52045. removeChildComponent (panelComponent);
  52046. panelComponent = 0;
  52047. }
  52048. tabs->clearTabs();
  52049. for (int i = contentComponents.size(); --i >= 0;)
  52050. {
  52051. Component* const c = contentComponents.getUnchecked(i);
  52052. // be careful not to delete these components until they've been removed from the tab component
  52053. jassert (c == 0 || c->isValidComponent());
  52054. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  52055. delete c;
  52056. }
  52057. contentComponents.clear();
  52058. }
  52059. void TabbedComponent::addTab (const String& tabName,
  52060. const Colour& tabBackgroundColour,
  52061. Component* const contentComponent,
  52062. const bool deleteComponentWhenNotNeeded,
  52063. const int insertIndex)
  52064. {
  52065. contentComponents.insert (insertIndex, contentComponent);
  52066. if (contentComponent != 0)
  52067. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  52068. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  52069. }
  52070. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  52071. {
  52072. tabs->setTabName (tabIndex, newName);
  52073. }
  52074. void TabbedComponent::removeTab (const int tabIndex)
  52075. {
  52076. Component* const c = contentComponents [tabIndex];
  52077. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  52078. {
  52079. if (c == panelComponent)
  52080. panelComponent = 0;
  52081. delete c;
  52082. }
  52083. contentComponents.remove (tabIndex);
  52084. tabs->removeTab (tabIndex);
  52085. }
  52086. int TabbedComponent::getNumTabs() const
  52087. {
  52088. return tabs->getNumTabs();
  52089. }
  52090. const StringArray TabbedComponent::getTabNames() const
  52091. {
  52092. return tabs->getTabNames();
  52093. }
  52094. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  52095. {
  52096. return contentComponents [tabIndex];
  52097. }
  52098. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  52099. {
  52100. return tabs->getTabBackgroundColour (tabIndex);
  52101. }
  52102. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  52103. {
  52104. tabs->setTabBackgroundColour (tabIndex, newColour);
  52105. if (getCurrentTabIndex() == tabIndex)
  52106. repaint();
  52107. }
  52108. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  52109. {
  52110. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  52111. }
  52112. int TabbedComponent::getCurrentTabIndex() const
  52113. {
  52114. return tabs->getCurrentTabIndex();
  52115. }
  52116. const String& TabbedComponent::getCurrentTabName() const
  52117. {
  52118. return tabs->getCurrentTabName();
  52119. }
  52120. void TabbedComponent::setOutline (int thickness)
  52121. {
  52122. outlineThickness = thickness;
  52123. repaint();
  52124. }
  52125. void TabbedComponent::setIndent (const int indentThickness)
  52126. {
  52127. edgeIndent = indentThickness;
  52128. }
  52129. void TabbedComponent::paint (Graphics& g)
  52130. {
  52131. g.fillAll (findColour (backgroundColourId));
  52132. const TabbedButtonBar::Orientation o = getOrientation();
  52133. int x = 0;
  52134. int y = 0;
  52135. int r = getWidth();
  52136. int b = getHeight();
  52137. if (o == TabbedButtonBar::TabsAtTop)
  52138. y += tabDepth;
  52139. else if (o == TabbedButtonBar::TabsAtBottom)
  52140. b -= tabDepth;
  52141. else if (o == TabbedButtonBar::TabsAtLeft)
  52142. x += tabDepth;
  52143. else if (o == TabbedButtonBar::TabsAtRight)
  52144. r -= tabDepth;
  52145. g.reduceClipRegion (x, y, r - x, b - y);
  52146. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  52147. if (outlineThickness > 0)
  52148. {
  52149. if (o == TabbedButtonBar::TabsAtTop)
  52150. --y;
  52151. else if (o == TabbedButtonBar::TabsAtBottom)
  52152. ++b;
  52153. else if (o == TabbedButtonBar::TabsAtLeft)
  52154. --x;
  52155. else if (o == TabbedButtonBar::TabsAtRight)
  52156. ++r;
  52157. g.setColour (findColour (outlineColourId));
  52158. g.drawRect (x, y, r - x, b - y, outlineThickness);
  52159. }
  52160. }
  52161. void TabbedComponent::resized()
  52162. {
  52163. const TabbedButtonBar::Orientation o = getOrientation();
  52164. const int indent = edgeIndent + outlineThickness;
  52165. BorderSize indents (indent);
  52166. if (o == TabbedButtonBar::TabsAtTop)
  52167. {
  52168. tabs->setBounds (0, 0, getWidth(), tabDepth);
  52169. indents.setTop (tabDepth + edgeIndent);
  52170. }
  52171. else if (o == TabbedButtonBar::TabsAtBottom)
  52172. {
  52173. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  52174. indents.setBottom (tabDepth + edgeIndent);
  52175. }
  52176. else if (o == TabbedButtonBar::TabsAtLeft)
  52177. {
  52178. tabs->setBounds (0, 0, tabDepth, getHeight());
  52179. indents.setLeft (tabDepth + edgeIndent);
  52180. }
  52181. else if (o == TabbedButtonBar::TabsAtRight)
  52182. {
  52183. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  52184. indents.setRight (tabDepth + edgeIndent);
  52185. }
  52186. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  52187. for (int i = contentComponents.size(); --i >= 0;)
  52188. if (contentComponents.getUnchecked (i) != 0)
  52189. contentComponents.getUnchecked (i)->setBounds (bounds);
  52190. }
  52191. void TabbedComponent::lookAndFeelChanged()
  52192. {
  52193. for (int i = contentComponents.size(); --i >= 0;)
  52194. if (contentComponents.getUnchecked (i) != 0)
  52195. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  52196. }
  52197. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  52198. const String& newTabName)
  52199. {
  52200. if (panelComponent != 0)
  52201. {
  52202. panelComponent->setVisible (false);
  52203. removeChildComponent (panelComponent);
  52204. panelComponent = 0;
  52205. }
  52206. if (getCurrentTabIndex() >= 0)
  52207. {
  52208. panelComponent = contentComponents [getCurrentTabIndex()];
  52209. if (panelComponent != 0)
  52210. {
  52211. // do these ops as two stages instead of addAndMakeVisible() so that the
  52212. // component has always got a parent when it gets the visibilityChanged() callback
  52213. addChildComponent (panelComponent);
  52214. panelComponent->setVisible (true);
  52215. panelComponent->toFront (true);
  52216. }
  52217. repaint();
  52218. }
  52219. resized();
  52220. currentTabChanged (newCurrentTabIndex, newTabName);
  52221. }
  52222. void TabbedComponent::currentTabChanged (const int, const String&)
  52223. {
  52224. }
  52225. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  52226. {
  52227. }
  52228. END_JUCE_NAMESPACE
  52229. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52230. /*** Start of inlined file: juce_Viewport.cpp ***/
  52231. BEGIN_JUCE_NAMESPACE
  52232. Viewport::Viewport (const String& componentName)
  52233. : Component (componentName),
  52234. scrollBarThickness (0),
  52235. singleStepX (16),
  52236. singleStepY (16),
  52237. showHScrollbar (true),
  52238. showVScrollbar (true),
  52239. verticalScrollBar (true),
  52240. horizontalScrollBar (false)
  52241. {
  52242. // content holder is used to clip the contents so they don't overlap the scrollbars
  52243. addAndMakeVisible (&contentHolder);
  52244. contentHolder.setInterceptsMouseClicks (false, true);
  52245. addChildComponent (&verticalScrollBar);
  52246. addChildComponent (&horizontalScrollBar);
  52247. verticalScrollBar.addListener (this);
  52248. horizontalScrollBar.addListener (this);
  52249. setInterceptsMouseClicks (false, true);
  52250. setWantsKeyboardFocus (true);
  52251. }
  52252. Viewport::~Viewport()
  52253. {
  52254. contentHolder.deleteAllChildren();
  52255. }
  52256. void Viewport::visibleAreaChanged (int, int, int, int)
  52257. {
  52258. }
  52259. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52260. {
  52261. if (contentComp.getComponent() != newViewedComponent)
  52262. {
  52263. {
  52264. ScopedPointer<Component> oldCompDeleter (contentComp);
  52265. contentComp = 0;
  52266. }
  52267. contentComp = newViewedComponent;
  52268. if (contentComp != 0)
  52269. {
  52270. contentComp->setTopLeftPosition (0, 0);
  52271. contentHolder.addAndMakeVisible (contentComp);
  52272. contentComp->addComponentListener (this);
  52273. }
  52274. updateVisibleArea();
  52275. }
  52276. }
  52277. int Viewport::getMaximumVisibleWidth() const
  52278. {
  52279. return contentHolder.getWidth();
  52280. }
  52281. int Viewport::getMaximumVisibleHeight() const
  52282. {
  52283. return contentHolder.getHeight();
  52284. }
  52285. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52286. {
  52287. if (contentComp != 0)
  52288. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52289. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52290. }
  52291. void Viewport::setViewPosition (const Point<int>& newPosition)
  52292. {
  52293. setViewPosition (newPosition.getX(), newPosition.getY());
  52294. }
  52295. void Viewport::setViewPositionProportionately (const double x, const double y)
  52296. {
  52297. if (contentComp != 0)
  52298. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52299. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52300. }
  52301. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52302. {
  52303. if (contentComp != 0)
  52304. {
  52305. int dx = 0, dy = 0;
  52306. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52307. {
  52308. if (mouseX < activeBorderThickness)
  52309. dx = activeBorderThickness - mouseX;
  52310. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52311. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52312. if (dx < 0)
  52313. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52314. else
  52315. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52316. }
  52317. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52318. {
  52319. if (mouseY < activeBorderThickness)
  52320. dy = activeBorderThickness - mouseY;
  52321. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52322. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52323. if (dy < 0)
  52324. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52325. else
  52326. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52327. }
  52328. if (dx != 0 || dy != 0)
  52329. {
  52330. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52331. contentComp->getY() + dy);
  52332. return true;
  52333. }
  52334. }
  52335. return false;
  52336. }
  52337. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52338. {
  52339. updateVisibleArea();
  52340. }
  52341. void Viewport::resized()
  52342. {
  52343. updateVisibleArea();
  52344. }
  52345. void Viewport::updateVisibleArea()
  52346. {
  52347. const int scrollbarWidth = getScrollBarThickness();
  52348. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52349. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52350. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52351. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52352. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52353. Rectangle<int> contentArea (getLocalBounds());
  52354. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52355. {
  52356. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52357. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52358. if (vBarVisible)
  52359. contentArea.setWidth (getWidth() - scrollbarWidth);
  52360. if (hBarVisible)
  52361. contentArea.setHeight (getHeight() - scrollbarWidth);
  52362. if (! contentArea.contains (contentComp->getBounds()))
  52363. {
  52364. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52365. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52366. }
  52367. }
  52368. if (vBarVisible)
  52369. contentArea.setWidth (getWidth() - scrollbarWidth);
  52370. if (hBarVisible)
  52371. contentArea.setHeight (getHeight() - scrollbarWidth);
  52372. contentHolder.setBounds (contentArea);
  52373. Rectangle<int> contentBounds;
  52374. if (contentComp != 0)
  52375. contentBounds = contentComp->getBounds();
  52376. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52377. if (hBarVisible)
  52378. {
  52379. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52380. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52381. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52382. horizontalScrollBar.setSingleStepSize (singleStepX);
  52383. horizontalScrollBar.cancelPendingUpdate();
  52384. }
  52385. if (vBarVisible)
  52386. {
  52387. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52388. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52389. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52390. verticalScrollBar.setSingleStepSize (singleStepY);
  52391. verticalScrollBar.cancelPendingUpdate();
  52392. }
  52393. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52394. horizontalScrollBar.setVisible (hBarVisible);
  52395. verticalScrollBar.setVisible (vBarVisible);
  52396. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52397. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52398. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52399. if (lastVisibleArea != visibleArea)
  52400. {
  52401. lastVisibleArea = visibleArea;
  52402. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52403. }
  52404. horizontalScrollBar.handleUpdateNowIfNeeded();
  52405. verticalScrollBar.handleUpdateNowIfNeeded();
  52406. }
  52407. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52408. {
  52409. if (singleStepX != stepX || singleStepY != stepY)
  52410. {
  52411. singleStepX = stepX;
  52412. singleStepY = stepY;
  52413. updateVisibleArea();
  52414. }
  52415. }
  52416. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52417. const bool showHorizontalScrollbarIfNeeded)
  52418. {
  52419. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52420. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52421. {
  52422. showVScrollbar = showVerticalScrollbarIfNeeded;
  52423. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52424. updateVisibleArea();
  52425. }
  52426. }
  52427. void Viewport::setScrollBarThickness (const int thickness)
  52428. {
  52429. if (scrollBarThickness != thickness)
  52430. {
  52431. scrollBarThickness = thickness;
  52432. updateVisibleArea();
  52433. }
  52434. }
  52435. int Viewport::getScrollBarThickness() const
  52436. {
  52437. return scrollBarThickness > 0 ? scrollBarThickness
  52438. : getLookAndFeel().getDefaultScrollbarWidth();
  52439. }
  52440. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52441. {
  52442. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52443. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52444. }
  52445. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52446. {
  52447. const int newRangeStartInt = roundToInt (newRangeStart);
  52448. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52449. {
  52450. setViewPosition (newRangeStartInt, getViewPositionY());
  52451. }
  52452. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52453. {
  52454. setViewPosition (getViewPositionX(), newRangeStartInt);
  52455. }
  52456. }
  52457. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52458. {
  52459. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52460. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52461. }
  52462. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52463. {
  52464. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52465. {
  52466. const bool hasVertBar = verticalScrollBar.isVisible();
  52467. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52468. if (hasHorzBar || hasVertBar)
  52469. {
  52470. if (wheelIncrementX != 0)
  52471. {
  52472. wheelIncrementX *= 14.0f * singleStepX;
  52473. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52474. : jmax (wheelIncrementX, 1.0f);
  52475. }
  52476. if (wheelIncrementY != 0)
  52477. {
  52478. wheelIncrementY *= 14.0f * singleStepY;
  52479. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52480. : jmax (wheelIncrementY, 1.0f);
  52481. }
  52482. Point<int> pos (getViewPosition());
  52483. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52484. {
  52485. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52486. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52487. }
  52488. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52489. {
  52490. if (wheelIncrementX == 0 && ! hasVertBar)
  52491. wheelIncrementX = wheelIncrementY;
  52492. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52493. }
  52494. else if (hasVertBar && wheelIncrementY != 0)
  52495. {
  52496. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52497. }
  52498. if (pos != getViewPosition())
  52499. {
  52500. setViewPosition (pos);
  52501. return true;
  52502. }
  52503. }
  52504. }
  52505. return false;
  52506. }
  52507. bool Viewport::keyPressed (const KeyPress& key)
  52508. {
  52509. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52510. || key.isKeyCode (KeyPress::downKey)
  52511. || key.isKeyCode (KeyPress::pageUpKey)
  52512. || key.isKeyCode (KeyPress::pageDownKey)
  52513. || key.isKeyCode (KeyPress::homeKey)
  52514. || key.isKeyCode (KeyPress::endKey);
  52515. if (verticalScrollBar.isVisible() && isUpDownKey)
  52516. return verticalScrollBar.keyPressed (key);
  52517. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52518. || key.isKeyCode (KeyPress::rightKey);
  52519. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52520. return horizontalScrollBar.keyPressed (key);
  52521. return false;
  52522. }
  52523. END_JUCE_NAMESPACE
  52524. /*** End of inlined file: juce_Viewport.cpp ***/
  52525. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52526. BEGIN_JUCE_NAMESPACE
  52527. static const Colour createBaseColour (const Colour& buttonColour,
  52528. const bool hasKeyboardFocus,
  52529. const bool isMouseOverButton,
  52530. const bool isButtonDown) throw()
  52531. {
  52532. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52533. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52534. if (isButtonDown)
  52535. return baseColour.contrasting (0.2f);
  52536. else if (isMouseOverButton)
  52537. return baseColour.contrasting (0.1f);
  52538. return baseColour;
  52539. }
  52540. LookAndFeel::LookAndFeel()
  52541. {
  52542. /* if this fails it means you're trying to create a LookAndFeel object before
  52543. the static Colours have been initialised. That ain't gonna work. It probably
  52544. means that you're using a static LookAndFeel object and that your compiler has
  52545. decided to intialise it before the Colours class.
  52546. */
  52547. jassert (Colours::white == Colour (0xffffffff));
  52548. // set up the standard set of colours..
  52549. const int textButtonColour = 0xffbbbbff;
  52550. const int textHighlightColour = 0x401111ee;
  52551. const int standardOutlineColour = 0xb2808080;
  52552. static const int standardColours[] =
  52553. {
  52554. TextButton::buttonColourId, textButtonColour,
  52555. TextButton::buttonOnColourId, 0xff4444ff,
  52556. TextButton::textColourOnId, 0xff000000,
  52557. TextButton::textColourOffId, 0xff000000,
  52558. ComboBox::buttonColourId, 0xffbbbbff,
  52559. ComboBox::outlineColourId, standardOutlineColour,
  52560. ToggleButton::textColourId, 0xff000000,
  52561. TextEditor::backgroundColourId, 0xffffffff,
  52562. TextEditor::textColourId, 0xff000000,
  52563. TextEditor::highlightColourId, textHighlightColour,
  52564. TextEditor::highlightedTextColourId, 0xff000000,
  52565. TextEditor::caretColourId, 0xff000000,
  52566. TextEditor::outlineColourId, 0x00000000,
  52567. TextEditor::focusedOutlineColourId, textButtonColour,
  52568. TextEditor::shadowColourId, 0x38000000,
  52569. Label::backgroundColourId, 0x00000000,
  52570. Label::textColourId, 0xff000000,
  52571. Label::outlineColourId, 0x00000000,
  52572. ScrollBar::backgroundColourId, 0x00000000,
  52573. ScrollBar::thumbColourId, 0xffffffff,
  52574. ScrollBar::trackColourId, 0xffffffff,
  52575. TreeView::linesColourId, 0x4c000000,
  52576. TreeView::backgroundColourId, 0x00000000,
  52577. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52578. PopupMenu::backgroundColourId, 0xffffffff,
  52579. PopupMenu::textColourId, 0xff000000,
  52580. PopupMenu::headerTextColourId, 0xff000000,
  52581. PopupMenu::highlightedTextColourId, 0xffffffff,
  52582. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52583. ComboBox::textColourId, 0xff000000,
  52584. ComboBox::backgroundColourId, 0xffffffff,
  52585. ComboBox::arrowColourId, 0x99000000,
  52586. ListBox::backgroundColourId, 0xffffffff,
  52587. ListBox::outlineColourId, standardOutlineColour,
  52588. ListBox::textColourId, 0xff000000,
  52589. Slider::backgroundColourId, 0x00000000,
  52590. Slider::thumbColourId, textButtonColour,
  52591. Slider::trackColourId, 0x7fffffff,
  52592. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52593. Slider::rotarySliderOutlineColourId, 0x66000000,
  52594. Slider::textBoxTextColourId, 0xff000000,
  52595. Slider::textBoxBackgroundColourId, 0xffffffff,
  52596. Slider::textBoxHighlightColourId, textHighlightColour,
  52597. Slider::textBoxOutlineColourId, standardOutlineColour,
  52598. ResizableWindow::backgroundColourId, 0xff777777,
  52599. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52600. AlertWindow::backgroundColourId, 0xffededed,
  52601. AlertWindow::textColourId, 0xff000000,
  52602. AlertWindow::outlineColourId, 0xff666666,
  52603. ProgressBar::backgroundColourId, 0xffeeeeee,
  52604. ProgressBar::foregroundColourId, 0xffaaaaee,
  52605. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52606. TooltipWindow::textColourId, 0xff000000,
  52607. TooltipWindow::outlineColourId, 0x4c000000,
  52608. TabbedComponent::backgroundColourId, 0x00000000,
  52609. TabbedComponent::outlineColourId, 0xff777777,
  52610. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52611. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52612. Toolbar::backgroundColourId, 0xfff6f8f9,
  52613. Toolbar::separatorColourId, 0x4c000000,
  52614. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52615. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52616. Toolbar::labelTextColourId, 0xff000000,
  52617. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52618. HyperlinkButton::textColourId, 0xcc1111ee,
  52619. GroupComponent::outlineColourId, 0x66000000,
  52620. GroupComponent::textColourId, 0xff000000,
  52621. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52622. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52623. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52624. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52625. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52626. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52627. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52628. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52629. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52630. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52631. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52632. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52633. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52634. CodeEditorComponent::caretColourId, 0xff000000,
  52635. CodeEditorComponent::highlightColourId, textHighlightColour,
  52636. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52637. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52638. ColourSelector::labelTextColourId, 0xff000000,
  52639. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52640. KeyMappingEditorComponent::textColourId, 0xff000000,
  52641. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52642. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52643. DrawableButton::textColourId, 0xff000000,
  52644. };
  52645. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52646. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52647. static String defaultSansName, defaultSerifName, defaultFixedName;
  52648. if (defaultSansName.isEmpty())
  52649. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52650. defaultSans = defaultSansName;
  52651. defaultSerif = defaultSerifName;
  52652. defaultFixed = defaultFixedName;
  52653. }
  52654. LookAndFeel::~LookAndFeel()
  52655. {
  52656. }
  52657. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52658. {
  52659. const int index = colourIds.indexOf (colourId);
  52660. if (index >= 0)
  52661. return colours [index];
  52662. jassertfalse;
  52663. return Colours::black;
  52664. }
  52665. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52666. {
  52667. const int index = colourIds.indexOf (colourId);
  52668. if (index >= 0)
  52669. {
  52670. colours.set (index, colour);
  52671. }
  52672. else
  52673. {
  52674. colourIds.add (colourId);
  52675. colours.add (colour);
  52676. }
  52677. }
  52678. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52679. {
  52680. return colourIds.contains (colourId);
  52681. }
  52682. static LookAndFeel* defaultLF = 0;
  52683. static LookAndFeel* currentDefaultLF = 0;
  52684. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52685. {
  52686. // if this happens, your app hasn't initialised itself properly.. if you're
  52687. // trying to hack your own main() function, have a look at
  52688. // JUCEApplication::initialiseForGUI()
  52689. jassert (currentDefaultLF != 0);
  52690. return *currentDefaultLF;
  52691. }
  52692. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52693. {
  52694. if (newDefaultLookAndFeel == 0)
  52695. {
  52696. if (defaultLF == 0)
  52697. defaultLF = new LookAndFeel();
  52698. newDefaultLookAndFeel = defaultLF;
  52699. }
  52700. currentDefaultLF = newDefaultLookAndFeel;
  52701. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52702. {
  52703. Component* const c = Desktop::getInstance().getComponent (i);
  52704. if (c != 0)
  52705. c->sendLookAndFeelChange();
  52706. }
  52707. }
  52708. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52709. {
  52710. if (currentDefaultLF == defaultLF)
  52711. currentDefaultLF = 0;
  52712. deleteAndZero (defaultLF);
  52713. }
  52714. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52715. {
  52716. String faceName (font.getTypefaceName());
  52717. if (faceName == Font::getDefaultSansSerifFontName())
  52718. faceName = defaultSans;
  52719. else if (faceName == Font::getDefaultSerifFontName())
  52720. faceName = defaultSerif;
  52721. else if (faceName == Font::getDefaultMonospacedFontName())
  52722. faceName = defaultFixed;
  52723. Font f (font);
  52724. f.setTypefaceName (faceName);
  52725. return Typeface::createSystemTypefaceFor (f);
  52726. }
  52727. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52728. {
  52729. defaultSans = newName;
  52730. }
  52731. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52732. {
  52733. return component.getMouseCursor();
  52734. }
  52735. void LookAndFeel::drawButtonBackground (Graphics& g,
  52736. Button& button,
  52737. const Colour& backgroundColour,
  52738. bool isMouseOverButton,
  52739. bool isButtonDown)
  52740. {
  52741. const int width = button.getWidth();
  52742. const int height = button.getHeight();
  52743. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52744. const float halfThickness = outlineThickness * 0.5f;
  52745. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52746. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52747. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52748. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52749. const Colour baseColour (createBaseColour (backgroundColour,
  52750. button.hasKeyboardFocus (true),
  52751. isMouseOverButton, isButtonDown)
  52752. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52753. drawGlassLozenge (g,
  52754. indentL,
  52755. indentT,
  52756. width - indentL - indentR,
  52757. height - indentT - indentB,
  52758. baseColour, outlineThickness, -1.0f,
  52759. button.isConnectedOnLeft(),
  52760. button.isConnectedOnRight(),
  52761. button.isConnectedOnTop(),
  52762. button.isConnectedOnBottom());
  52763. }
  52764. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52765. {
  52766. return button.getFont();
  52767. }
  52768. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52769. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52770. {
  52771. Font font (getFontForTextButton (button));
  52772. g.setFont (font);
  52773. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52774. : TextButton::textColourOffId)
  52775. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52776. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52777. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52778. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52779. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52780. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52781. g.drawFittedText (button.getButtonText(),
  52782. leftIndent,
  52783. yIndent,
  52784. button.getWidth() - leftIndent - rightIndent,
  52785. button.getHeight() - yIndent * 2,
  52786. Justification::centred, 2);
  52787. }
  52788. void LookAndFeel::drawTickBox (Graphics& g,
  52789. Component& component,
  52790. float x, float y, float w, float h,
  52791. const bool ticked,
  52792. const bool isEnabled,
  52793. const bool isMouseOverButton,
  52794. const bool isButtonDown)
  52795. {
  52796. const float boxSize = w * 0.7f;
  52797. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52798. createBaseColour (component.findColour (TextButton::buttonColourId)
  52799. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52800. true,
  52801. isMouseOverButton,
  52802. isButtonDown),
  52803. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52804. if (ticked)
  52805. {
  52806. Path tick;
  52807. tick.startNewSubPath (1.5f, 3.0f);
  52808. tick.lineTo (3.0f, 6.0f);
  52809. tick.lineTo (6.0f, 0.0f);
  52810. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52811. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52812. .translated (x, y));
  52813. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52814. }
  52815. }
  52816. void LookAndFeel::drawToggleButton (Graphics& g,
  52817. ToggleButton& button,
  52818. bool isMouseOverButton,
  52819. bool isButtonDown)
  52820. {
  52821. if (button.hasKeyboardFocus (true))
  52822. {
  52823. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52824. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52825. }
  52826. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52827. const float tickWidth = fontSize * 1.1f;
  52828. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52829. tickWidth, tickWidth,
  52830. button.getToggleState(),
  52831. button.isEnabled(),
  52832. isMouseOverButton,
  52833. isButtonDown);
  52834. g.setColour (button.findColour (ToggleButton::textColourId));
  52835. g.setFont (fontSize);
  52836. if (! button.isEnabled())
  52837. g.setOpacity (0.5f);
  52838. const int textX = (int) tickWidth + 5;
  52839. g.drawFittedText (button.getButtonText(),
  52840. textX, 0,
  52841. button.getWidth() - textX - 2, button.getHeight(),
  52842. Justification::centredLeft, 10);
  52843. }
  52844. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52845. {
  52846. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52847. const int tickWidth = jmin (24, button.getHeight());
  52848. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52849. button.getHeight());
  52850. }
  52851. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52852. const String& message,
  52853. const String& button1,
  52854. const String& button2,
  52855. const String& button3,
  52856. AlertWindow::AlertIconType iconType,
  52857. int numButtons,
  52858. Component* associatedComponent)
  52859. {
  52860. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52861. if (numButtons == 1)
  52862. {
  52863. aw->addButton (button1, 0,
  52864. KeyPress (KeyPress::escapeKey, 0, 0),
  52865. KeyPress (KeyPress::returnKey, 0, 0));
  52866. }
  52867. else
  52868. {
  52869. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52870. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52871. if (button1ShortCut == button2ShortCut)
  52872. button2ShortCut = KeyPress();
  52873. if (numButtons == 2)
  52874. {
  52875. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52876. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52877. }
  52878. else if (numButtons == 3)
  52879. {
  52880. aw->addButton (button1, 1, button1ShortCut);
  52881. aw->addButton (button2, 2, button2ShortCut);
  52882. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52883. }
  52884. }
  52885. return aw;
  52886. }
  52887. void LookAndFeel::drawAlertBox (Graphics& g,
  52888. AlertWindow& alert,
  52889. const Rectangle<int>& textArea,
  52890. TextLayout& textLayout)
  52891. {
  52892. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52893. int iconSpaceUsed = 0;
  52894. Justification alignment (Justification::horizontallyCentred);
  52895. const int iconWidth = 80;
  52896. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52897. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52898. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52899. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52900. iconSize, iconSize);
  52901. if (alert.getAlertType() != AlertWindow::NoIcon)
  52902. {
  52903. Path icon;
  52904. uint32 colour;
  52905. char character;
  52906. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52907. {
  52908. colour = 0x55ff5555;
  52909. character = '!';
  52910. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52911. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52912. (float) iconRect.getX(), (float) iconRect.getBottom());
  52913. icon = icon.createPathWithRoundedCorners (5.0f);
  52914. }
  52915. else
  52916. {
  52917. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52918. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52919. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52920. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52921. }
  52922. GlyphArrangement ga;
  52923. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52924. String::charToString (character),
  52925. (float) iconRect.getX(), (float) iconRect.getY(),
  52926. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52927. Justification::centred, false);
  52928. ga.createPath (icon);
  52929. icon.setUsingNonZeroWinding (false);
  52930. g.setColour (Colour (colour));
  52931. g.fillPath (icon);
  52932. iconSpaceUsed = iconWidth;
  52933. alignment = Justification::left;
  52934. }
  52935. g.setColour (alert.findColour (AlertWindow::textColourId));
  52936. textLayout.drawWithin (g,
  52937. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52938. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52939. alignment.getFlags() | Justification::top);
  52940. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52941. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52942. }
  52943. int LookAndFeel::getAlertBoxWindowFlags()
  52944. {
  52945. return ComponentPeer::windowAppearsOnTaskbar
  52946. | ComponentPeer::windowHasDropShadow;
  52947. }
  52948. int LookAndFeel::getAlertWindowButtonHeight()
  52949. {
  52950. return 28;
  52951. }
  52952. const Font LookAndFeel::getAlertWindowFont()
  52953. {
  52954. return Font (12.0f);
  52955. }
  52956. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52957. int width, int height,
  52958. double progress, const String& textToShow)
  52959. {
  52960. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52961. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52962. g.fillAll (background);
  52963. if (progress >= 0.0f && progress < 1.0f)
  52964. {
  52965. drawGlassLozenge (g, 1.0f, 1.0f,
  52966. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52967. (float) (height - 2),
  52968. foreground,
  52969. 0.5f, 0.0f,
  52970. true, true, true, true);
  52971. }
  52972. else
  52973. {
  52974. // spinning bar..
  52975. g.setColour (foreground);
  52976. const int stripeWidth = height * 2;
  52977. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52978. Path p;
  52979. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52980. p.addQuadrilateral (x, 0.0f,
  52981. x + stripeWidth * 0.5f, 0.0f,
  52982. x, (float) height,
  52983. x - stripeWidth * 0.5f, (float) height);
  52984. Image im (Image::ARGB, width, height, true);
  52985. {
  52986. Graphics g2 (im);
  52987. drawGlassLozenge (g2, 1.0f, 1.0f,
  52988. (float) (width - 2),
  52989. (float) (height - 2),
  52990. foreground,
  52991. 0.5f, 0.0f,
  52992. true, true, true, true);
  52993. }
  52994. g.setTiledImageFill (im, 0, 0, 0.85f);
  52995. g.fillPath (p);
  52996. }
  52997. if (textToShow.isNotEmpty())
  52998. {
  52999. g.setColour (Colour::contrasting (background, foreground));
  53000. g.setFont (height * 0.6f);
  53001. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  53002. }
  53003. }
  53004. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  53005. {
  53006. const float radius = jmin (w, h) * 0.4f;
  53007. const float thickness = radius * 0.15f;
  53008. Path p;
  53009. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  53010. radius * 0.6f, thickness,
  53011. thickness * 0.5f);
  53012. const float cx = x + w * 0.5f;
  53013. const float cy = y + h * 0.5f;
  53014. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  53015. for (int i = 0; i < 12; ++i)
  53016. {
  53017. const int n = (i + 12 - animationIndex) % 12;
  53018. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  53019. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  53020. .translated (cx, cy));
  53021. }
  53022. }
  53023. void LookAndFeel::drawScrollbarButton (Graphics& g,
  53024. ScrollBar& scrollbar,
  53025. int width, int height,
  53026. int buttonDirection,
  53027. bool /*isScrollbarVertical*/,
  53028. bool /*isMouseOverButton*/,
  53029. bool isButtonDown)
  53030. {
  53031. Path p;
  53032. if (buttonDirection == 0)
  53033. p.addTriangle (width * 0.5f, height * 0.2f,
  53034. width * 0.1f, height * 0.7f,
  53035. width * 0.9f, height * 0.7f);
  53036. else if (buttonDirection == 1)
  53037. p.addTriangle (width * 0.8f, height * 0.5f,
  53038. width * 0.3f, height * 0.1f,
  53039. width * 0.3f, height * 0.9f);
  53040. else if (buttonDirection == 2)
  53041. p.addTriangle (width * 0.5f, height * 0.8f,
  53042. width * 0.1f, height * 0.3f,
  53043. width * 0.9f, height * 0.3f);
  53044. else if (buttonDirection == 3)
  53045. p.addTriangle (width * 0.2f, height * 0.5f,
  53046. width * 0.7f, height * 0.1f,
  53047. width * 0.7f, height * 0.9f);
  53048. if (isButtonDown)
  53049. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  53050. else
  53051. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  53052. g.fillPath (p);
  53053. g.setColour (Colour (0x80000000));
  53054. g.strokePath (p, PathStrokeType (0.5f));
  53055. }
  53056. void LookAndFeel::drawScrollbar (Graphics& g,
  53057. ScrollBar& scrollbar,
  53058. int x, int y,
  53059. int width, int height,
  53060. bool isScrollbarVertical,
  53061. int thumbStartPosition,
  53062. int thumbSize,
  53063. bool /*isMouseOver*/,
  53064. bool /*isMouseDown*/)
  53065. {
  53066. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  53067. Path slotPath, thumbPath;
  53068. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  53069. const float slotIndentx2 = slotIndent * 2.0f;
  53070. const float thumbIndent = slotIndent + 1.0f;
  53071. const float thumbIndentx2 = thumbIndent * 2.0f;
  53072. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  53073. if (isScrollbarVertical)
  53074. {
  53075. slotPath.addRoundedRectangle (x + slotIndent,
  53076. y + slotIndent,
  53077. width - slotIndentx2,
  53078. height - slotIndentx2,
  53079. (width - slotIndentx2) * 0.5f);
  53080. if (thumbSize > 0)
  53081. thumbPath.addRoundedRectangle (x + thumbIndent,
  53082. thumbStartPosition + thumbIndent,
  53083. width - thumbIndentx2,
  53084. thumbSize - thumbIndentx2,
  53085. (width - thumbIndentx2) * 0.5f);
  53086. gx1 = (float) x;
  53087. gx2 = x + width * 0.7f;
  53088. }
  53089. else
  53090. {
  53091. slotPath.addRoundedRectangle (x + slotIndent,
  53092. y + slotIndent,
  53093. width - slotIndentx2,
  53094. height - slotIndentx2,
  53095. (height - slotIndentx2) * 0.5f);
  53096. if (thumbSize > 0)
  53097. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  53098. y + thumbIndent,
  53099. thumbSize - thumbIndentx2,
  53100. height - thumbIndentx2,
  53101. (height - thumbIndentx2) * 0.5f);
  53102. gy1 = (float) y;
  53103. gy2 = y + height * 0.7f;
  53104. }
  53105. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  53106. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  53107. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  53108. g.fillPath (slotPath);
  53109. if (isScrollbarVertical)
  53110. {
  53111. gx1 = x + width * 0.6f;
  53112. gx2 = (float) x + width;
  53113. }
  53114. else
  53115. {
  53116. gy1 = y + height * 0.6f;
  53117. gy2 = (float) y + height;
  53118. }
  53119. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  53120. Colour (0x19000000), gx2, gy2, false));
  53121. g.fillPath (slotPath);
  53122. g.setColour (thumbColour);
  53123. g.fillPath (thumbPath);
  53124. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  53125. Colours::transparentBlack, gx2, gy2, false));
  53126. g.saveState();
  53127. if (isScrollbarVertical)
  53128. g.reduceClipRegion (x + width / 2, y, width, height);
  53129. else
  53130. g.reduceClipRegion (x, y + height / 2, width, height);
  53131. g.fillPath (thumbPath);
  53132. g.restoreState();
  53133. g.setColour (Colour (0x4c000000));
  53134. g.strokePath (thumbPath, PathStrokeType (0.4f));
  53135. }
  53136. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  53137. {
  53138. return 0;
  53139. }
  53140. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  53141. {
  53142. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  53143. }
  53144. int LookAndFeel::getDefaultScrollbarWidth()
  53145. {
  53146. return 18;
  53147. }
  53148. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  53149. {
  53150. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  53151. : scrollbar.getHeight());
  53152. }
  53153. const Path LookAndFeel::getTickShape (const float height)
  53154. {
  53155. static const unsigned char tickShapeData[] =
  53156. {
  53157. 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,
  53158. 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,
  53159. 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,
  53160. 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,
  53161. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  53162. };
  53163. Path p;
  53164. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  53165. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53166. return p;
  53167. }
  53168. const Path LookAndFeel::getCrossShape (const float height)
  53169. {
  53170. static const unsigned char crossShapeData[] =
  53171. {
  53172. 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,
  53173. 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,
  53174. 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,
  53175. 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,
  53176. 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,
  53177. 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,
  53178. 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
  53179. };
  53180. Path p;
  53181. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  53182. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53183. return p;
  53184. }
  53185. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  53186. {
  53187. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  53188. x += (w - boxSize) >> 1;
  53189. y += (h - boxSize) >> 1;
  53190. w = boxSize;
  53191. h = boxSize;
  53192. g.setColour (Colour (0xe5ffffff));
  53193. g.fillRect (x, y, w, h);
  53194. g.setColour (Colour (0x80000000));
  53195. g.drawRect (x, y, w, h);
  53196. const float size = boxSize / 2 + 1.0f;
  53197. const float centre = (float) (boxSize / 2);
  53198. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53199. if (isPlus)
  53200. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53201. }
  53202. void LookAndFeel::drawBubble (Graphics& g,
  53203. float tipX, float tipY,
  53204. float boxX, float boxY,
  53205. float boxW, float boxH)
  53206. {
  53207. int side = 0;
  53208. if (tipX < boxX)
  53209. side = 1;
  53210. else if (tipX > boxX + boxW)
  53211. side = 3;
  53212. else if (tipY > boxY + boxH)
  53213. side = 2;
  53214. const float indent = 2.0f;
  53215. Path p;
  53216. p.addBubble (boxX + indent,
  53217. boxY + indent,
  53218. boxW - indent * 2.0f,
  53219. boxH - indent * 2.0f,
  53220. 5.0f,
  53221. tipX, tipY,
  53222. side,
  53223. 0.5f,
  53224. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53225. //xxx need to take comp as param for colour
  53226. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53227. g.fillPath (p);
  53228. //xxx as above
  53229. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53230. g.strokePath (p, PathStrokeType (1.33f));
  53231. }
  53232. const Font LookAndFeel::getPopupMenuFont()
  53233. {
  53234. return Font (17.0f);
  53235. }
  53236. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53237. const bool isSeparator,
  53238. int standardMenuItemHeight,
  53239. int& idealWidth,
  53240. int& idealHeight)
  53241. {
  53242. if (isSeparator)
  53243. {
  53244. idealWidth = 50;
  53245. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53246. }
  53247. else
  53248. {
  53249. Font font (getPopupMenuFont());
  53250. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53251. font.setHeight (standardMenuItemHeight / 1.3f);
  53252. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53253. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53254. }
  53255. }
  53256. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53257. {
  53258. const Colour background (findColour (PopupMenu::backgroundColourId));
  53259. g.fillAll (background);
  53260. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53261. for (int i = 0; i < height; i += 3)
  53262. g.fillRect (0, i, width, 1);
  53263. #if ! JUCE_MAC
  53264. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53265. g.drawRect (0, 0, width, height);
  53266. #endif
  53267. }
  53268. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53269. int width, int height,
  53270. bool isScrollUpArrow)
  53271. {
  53272. const Colour background (findColour (PopupMenu::backgroundColourId));
  53273. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53274. background.withAlpha (0.0f),
  53275. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53276. false));
  53277. g.fillRect (1, 1, width - 2, height - 2);
  53278. const float hw = width * 0.5f;
  53279. const float arrowW = height * 0.3f;
  53280. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53281. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53282. Path p;
  53283. p.addTriangle (hw - arrowW, y1,
  53284. hw + arrowW, y1,
  53285. hw, y2);
  53286. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53287. g.fillPath (p);
  53288. }
  53289. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53290. int width, int height,
  53291. const bool isSeparator,
  53292. const bool isActive,
  53293. const bool isHighlighted,
  53294. const bool isTicked,
  53295. const bool hasSubMenu,
  53296. const String& text,
  53297. const String& shortcutKeyText,
  53298. Image* image,
  53299. const Colour* const textColourToUse)
  53300. {
  53301. const float halfH = height * 0.5f;
  53302. if (isSeparator)
  53303. {
  53304. const float separatorIndent = 5.5f;
  53305. g.setColour (Colour (0x33000000));
  53306. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53307. g.setColour (Colour (0x66ffffff));
  53308. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53309. }
  53310. else
  53311. {
  53312. Colour textColour (findColour (PopupMenu::textColourId));
  53313. if (textColourToUse != 0)
  53314. textColour = *textColourToUse;
  53315. if (isHighlighted)
  53316. {
  53317. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53318. g.fillRect (1, 1, width - 2, height - 2);
  53319. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53320. }
  53321. else
  53322. {
  53323. g.setColour (textColour);
  53324. }
  53325. if (! isActive)
  53326. g.setOpacity (0.3f);
  53327. Font font (getPopupMenuFont());
  53328. if (font.getHeight() > height / 1.3f)
  53329. font.setHeight (height / 1.3f);
  53330. g.setFont (font);
  53331. const int leftBorder = (height * 5) / 4;
  53332. const int rightBorder = 4;
  53333. if (image != 0)
  53334. {
  53335. g.drawImageWithin (*image,
  53336. 2, 1, leftBorder - 4, height - 2,
  53337. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53338. }
  53339. else if (isTicked)
  53340. {
  53341. const Path tick (getTickShape (1.0f));
  53342. const float th = font.getAscent();
  53343. const float ty = halfH - th * 0.5f;
  53344. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53345. th, true));
  53346. }
  53347. g.drawFittedText (text,
  53348. leftBorder, 0,
  53349. width - (leftBorder + rightBorder), height,
  53350. Justification::centredLeft, 1);
  53351. if (shortcutKeyText.isNotEmpty())
  53352. {
  53353. Font f2 (font);
  53354. f2.setHeight (f2.getHeight() * 0.75f);
  53355. f2.setHorizontalScale (0.95f);
  53356. g.setFont (f2);
  53357. g.drawText (shortcutKeyText,
  53358. leftBorder,
  53359. 0,
  53360. width - (leftBorder + rightBorder + 4),
  53361. height,
  53362. Justification::centredRight,
  53363. true);
  53364. }
  53365. if (hasSubMenu)
  53366. {
  53367. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53368. const float x = width - height * 0.6f;
  53369. Path p;
  53370. p.addTriangle (x, halfH - arrowH * 0.5f,
  53371. x, halfH + arrowH * 0.5f,
  53372. x + arrowH * 0.6f, halfH);
  53373. g.fillPath (p);
  53374. }
  53375. }
  53376. }
  53377. int LookAndFeel::getMenuWindowFlags()
  53378. {
  53379. return ComponentPeer::windowHasDropShadow;
  53380. }
  53381. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53382. bool, MenuBarComponent& menuBar)
  53383. {
  53384. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53385. if (menuBar.isEnabled())
  53386. {
  53387. drawShinyButtonShape (g,
  53388. -4.0f, 0.0f,
  53389. width + 8.0f, (float) height,
  53390. 0.0f,
  53391. baseColour,
  53392. 0.4f,
  53393. true, true, true, true);
  53394. }
  53395. else
  53396. {
  53397. g.fillAll (baseColour);
  53398. }
  53399. }
  53400. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53401. {
  53402. return Font (menuBar.getHeight() * 0.7f);
  53403. }
  53404. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53405. {
  53406. return getMenuBarFont (menuBar, itemIndex, itemText)
  53407. .getStringWidth (itemText) + menuBar.getHeight();
  53408. }
  53409. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53410. int width, int height,
  53411. int itemIndex,
  53412. const String& itemText,
  53413. bool isMouseOverItem,
  53414. bool isMenuOpen,
  53415. bool /*isMouseOverBar*/,
  53416. MenuBarComponent& menuBar)
  53417. {
  53418. if (! menuBar.isEnabled())
  53419. {
  53420. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53421. .withMultipliedAlpha (0.5f));
  53422. }
  53423. else if (isMenuOpen || isMouseOverItem)
  53424. {
  53425. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53426. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53427. }
  53428. else
  53429. {
  53430. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53431. }
  53432. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53433. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53434. }
  53435. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53436. TextEditor& textEditor)
  53437. {
  53438. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53439. }
  53440. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53441. {
  53442. if (textEditor.isEnabled())
  53443. {
  53444. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53445. {
  53446. const int border = 2;
  53447. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53448. g.drawRect (0, 0, width, height, border);
  53449. g.setOpacity (1.0f);
  53450. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53451. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53452. }
  53453. else
  53454. {
  53455. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53456. g.drawRect (0, 0, width, height);
  53457. g.setOpacity (1.0f);
  53458. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53459. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53460. }
  53461. }
  53462. }
  53463. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53464. const bool isButtonDown,
  53465. int buttonX, int buttonY,
  53466. int buttonW, int buttonH,
  53467. ComboBox& box)
  53468. {
  53469. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53470. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53471. {
  53472. g.setColour (box.findColour (TextButton::buttonColourId));
  53473. g.drawRect (0, 0, width, height, 2);
  53474. }
  53475. else
  53476. {
  53477. g.setColour (box.findColour (ComboBox::outlineColourId));
  53478. g.drawRect (0, 0, width, height);
  53479. }
  53480. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53481. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  53482. box.hasKeyboardFocus (true),
  53483. false, isButtonDown)
  53484. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53485. drawGlassLozenge (g,
  53486. buttonX + outlineThickness, buttonY + outlineThickness,
  53487. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53488. baseColour, outlineThickness, -1.0f,
  53489. true, true, true, true);
  53490. if (box.isEnabled())
  53491. {
  53492. const float arrowX = 0.3f;
  53493. const float arrowH = 0.2f;
  53494. Path p;
  53495. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53496. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53497. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53498. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53499. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53500. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53501. g.setColour (box.findColour (ComboBox::arrowColourId));
  53502. g.fillPath (p);
  53503. }
  53504. }
  53505. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53506. {
  53507. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53508. }
  53509. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53510. {
  53511. return new Label (String::empty, String::empty);
  53512. }
  53513. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53514. {
  53515. label.setBounds (1, 1,
  53516. box.getWidth() + 3 - box.getHeight(),
  53517. box.getHeight() - 2);
  53518. label.setFont (getComboBoxFont (box));
  53519. }
  53520. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53521. {
  53522. g.fillAll (label.findColour (Label::backgroundColourId));
  53523. if (! label.isBeingEdited())
  53524. {
  53525. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53526. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53527. g.setFont (label.getFont());
  53528. g.drawFittedText (label.getText(),
  53529. label.getHorizontalBorderSize(),
  53530. label.getVerticalBorderSize(),
  53531. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53532. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53533. label.getJustificationType(),
  53534. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53535. label.getMinimumHorizontalScale());
  53536. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53537. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53538. }
  53539. else if (label.isEnabled())
  53540. {
  53541. g.setColour (label.findColour (Label::outlineColourId));
  53542. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53543. }
  53544. }
  53545. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53546. int x, int y,
  53547. int width, int height,
  53548. float /*sliderPos*/,
  53549. float /*minSliderPos*/,
  53550. float /*maxSliderPos*/,
  53551. const Slider::SliderStyle /*style*/,
  53552. Slider& slider)
  53553. {
  53554. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53555. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53556. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53557. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53558. Path indent;
  53559. if (slider.isHorizontal())
  53560. {
  53561. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53562. const float ih = sliderRadius;
  53563. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53564. gradCol2, 0.0f, iy + ih, false));
  53565. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53566. width + sliderRadius, ih,
  53567. 5.0f);
  53568. g.fillPath (indent);
  53569. }
  53570. else
  53571. {
  53572. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53573. const float iw = sliderRadius;
  53574. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53575. gradCol2, ix + iw, 0.0f, false));
  53576. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53577. iw, height + sliderRadius,
  53578. 5.0f);
  53579. g.fillPath (indent);
  53580. }
  53581. g.setColour (Colour (0x4c000000));
  53582. g.strokePath (indent, PathStrokeType (0.5f));
  53583. }
  53584. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53585. int x, int y,
  53586. int width, int height,
  53587. float sliderPos,
  53588. float minSliderPos,
  53589. float maxSliderPos,
  53590. const Slider::SliderStyle style,
  53591. Slider& slider)
  53592. {
  53593. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53594. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  53595. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53596. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53597. slider.isMouseButtonDown() && slider.isEnabled()));
  53598. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53599. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53600. {
  53601. float kx, ky;
  53602. if (style == Slider::LinearVertical)
  53603. {
  53604. kx = x + width * 0.5f;
  53605. ky = sliderPos;
  53606. }
  53607. else
  53608. {
  53609. kx = sliderPos;
  53610. ky = y + height * 0.5f;
  53611. }
  53612. drawGlassSphere (g,
  53613. kx - sliderRadius,
  53614. ky - sliderRadius,
  53615. sliderRadius * 2.0f,
  53616. knobColour, outlineThickness);
  53617. }
  53618. else
  53619. {
  53620. if (style == Slider::ThreeValueVertical)
  53621. {
  53622. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53623. sliderPos - sliderRadius,
  53624. sliderRadius * 2.0f,
  53625. knobColour, outlineThickness);
  53626. }
  53627. else if (style == Slider::ThreeValueHorizontal)
  53628. {
  53629. drawGlassSphere (g,sliderPos - sliderRadius,
  53630. y + height * 0.5f - sliderRadius,
  53631. sliderRadius * 2.0f,
  53632. knobColour, outlineThickness);
  53633. }
  53634. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53635. {
  53636. const float sr = jmin (sliderRadius, width * 0.4f);
  53637. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53638. minSliderPos - sliderRadius,
  53639. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53640. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53641. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53642. }
  53643. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53644. {
  53645. const float sr = jmin (sliderRadius, height * 0.4f);
  53646. drawGlassPointer (g, minSliderPos - sr,
  53647. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53648. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53649. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53650. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53651. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53652. }
  53653. }
  53654. }
  53655. void LookAndFeel::drawLinearSlider (Graphics& g,
  53656. int x, int y,
  53657. int width, int height,
  53658. float sliderPos,
  53659. float minSliderPos,
  53660. float maxSliderPos,
  53661. const Slider::SliderStyle style,
  53662. Slider& slider)
  53663. {
  53664. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53665. if (style == Slider::LinearBar)
  53666. {
  53667. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53668. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  53669. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53670. false,
  53671. isMouseOver,
  53672. isMouseOver || slider.isMouseButtonDown()));
  53673. drawShinyButtonShape (g,
  53674. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53675. baseColour,
  53676. slider.isEnabled() ? 0.9f : 0.3f,
  53677. true, true, true, true);
  53678. }
  53679. else
  53680. {
  53681. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53682. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53683. }
  53684. }
  53685. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53686. {
  53687. return jmin (7,
  53688. slider.getHeight() / 2,
  53689. slider.getWidth() / 2) + 2;
  53690. }
  53691. void LookAndFeel::drawRotarySlider (Graphics& g,
  53692. int x, int y,
  53693. int width, int height,
  53694. float sliderPos,
  53695. const float rotaryStartAngle,
  53696. const float rotaryEndAngle,
  53697. Slider& slider)
  53698. {
  53699. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53700. const float centreX = x + width * 0.5f;
  53701. const float centreY = y + height * 0.5f;
  53702. const float rx = centreX - radius;
  53703. const float ry = centreY - radius;
  53704. const float rw = radius * 2.0f;
  53705. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53706. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53707. if (radius > 12.0f)
  53708. {
  53709. if (slider.isEnabled())
  53710. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53711. else
  53712. g.setColour (Colour (0x80808080));
  53713. const float thickness = 0.7f;
  53714. {
  53715. Path filledArc;
  53716. filledArc.addPieSegment (rx, ry, rw, rw,
  53717. rotaryStartAngle,
  53718. angle,
  53719. thickness);
  53720. g.fillPath (filledArc);
  53721. }
  53722. if (thickness > 0)
  53723. {
  53724. const float innerRadius = radius * 0.2f;
  53725. Path p;
  53726. p.addTriangle (-innerRadius, 0.0f,
  53727. 0.0f, -radius * thickness * 1.1f,
  53728. innerRadius, 0.0f);
  53729. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53730. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53731. }
  53732. if (slider.isEnabled())
  53733. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53734. else
  53735. g.setColour (Colour (0x80808080));
  53736. Path outlineArc;
  53737. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53738. outlineArc.closeSubPath();
  53739. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53740. }
  53741. else
  53742. {
  53743. if (slider.isEnabled())
  53744. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53745. else
  53746. g.setColour (Colour (0x80808080));
  53747. Path p;
  53748. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53749. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53750. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53751. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53752. }
  53753. }
  53754. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53755. {
  53756. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53757. }
  53758. class SliderLabelComp : public Label
  53759. {
  53760. public:
  53761. SliderLabelComp() : Label (String::empty, String::empty) {}
  53762. ~SliderLabelComp() {}
  53763. void mouseWheelMove (const MouseEvent&, float, float) {}
  53764. };
  53765. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53766. {
  53767. Label* const l = new SliderLabelComp();
  53768. l->setJustificationType (Justification::centred);
  53769. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53770. l->setColour (Label::backgroundColourId,
  53771. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53772. : slider.findColour (Slider::textBoxBackgroundColourId));
  53773. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53774. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53775. l->setColour (TextEditor::backgroundColourId,
  53776. slider.findColour (Slider::textBoxBackgroundColourId)
  53777. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53778. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53779. return l;
  53780. }
  53781. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53782. {
  53783. return 0;
  53784. }
  53785. static const TextLayout layoutTooltipText (const String& text) throw()
  53786. {
  53787. const float tooltipFontSize = 12.0f;
  53788. const int maxToolTipWidth = 400;
  53789. const Font f (tooltipFontSize, Font::bold);
  53790. TextLayout tl (text, f);
  53791. tl.layout (maxToolTipWidth, Justification::left, true);
  53792. return tl;
  53793. }
  53794. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53795. {
  53796. const TextLayout tl (layoutTooltipText (tipText));
  53797. width = tl.getWidth() + 14;
  53798. height = tl.getHeight() + 6;
  53799. }
  53800. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53801. {
  53802. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53803. const Colour textCol (findColour (TooltipWindow::textColourId));
  53804. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53805. g.setColour (findColour (TooltipWindow::outlineColourId));
  53806. g.drawRect (0, 0, width, height, 1);
  53807. #endif
  53808. const TextLayout tl (layoutTooltipText (text));
  53809. g.setColour (findColour (TooltipWindow::textColourId));
  53810. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53811. }
  53812. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53813. {
  53814. return new TextButton (text, TRANS("click to browse for a different file"));
  53815. }
  53816. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53817. ComboBox* filenameBox,
  53818. Button* browseButton)
  53819. {
  53820. browseButton->setSize (80, filenameComp.getHeight());
  53821. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53822. if (tb != 0)
  53823. tb->changeWidthToFitText();
  53824. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53825. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53826. }
  53827. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53828. int imageX, int imageY, int imageW, int imageH,
  53829. const Colour& overlayColour,
  53830. float imageOpacity,
  53831. ImageButton& button)
  53832. {
  53833. if (! button.isEnabled())
  53834. imageOpacity *= 0.3f;
  53835. if (! overlayColour.isOpaque())
  53836. {
  53837. g.setOpacity (imageOpacity);
  53838. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53839. 0, 0, image->getWidth(), image->getHeight(), false);
  53840. }
  53841. if (! overlayColour.isTransparent())
  53842. {
  53843. g.setColour (overlayColour);
  53844. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53845. 0, 0, image->getWidth(), image->getHeight(), true);
  53846. }
  53847. }
  53848. void LookAndFeel::drawCornerResizer (Graphics& g,
  53849. int w, int h,
  53850. bool /*isMouseOver*/,
  53851. bool /*isMouseDragging*/)
  53852. {
  53853. const float lineThickness = jmin (w, h) * 0.075f;
  53854. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53855. {
  53856. g.setColour (Colours::lightgrey);
  53857. g.drawLine (w * i,
  53858. h + 1.0f,
  53859. w + 1.0f,
  53860. h * i,
  53861. lineThickness);
  53862. g.setColour (Colours::darkgrey);
  53863. g.drawLine (w * i + lineThickness,
  53864. h + 1.0f,
  53865. w + 1.0f,
  53866. h * i + lineThickness,
  53867. lineThickness);
  53868. }
  53869. }
  53870. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  53871. const BorderSize& /*borders*/)
  53872. {
  53873. }
  53874. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53875. const BorderSize& /*border*/, ResizableWindow& window)
  53876. {
  53877. g.fillAll (window.getBackgroundColour());
  53878. }
  53879. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  53880. const BorderSize& border, ResizableWindow&)
  53881. {
  53882. g.setColour (Colour (0x80000000));
  53883. g.drawRect (0, 0, w, h);
  53884. g.setColour (Colour (0x19000000));
  53885. g.drawRect (border.getLeft() - 1,
  53886. border.getTop() - 1,
  53887. w + 2 - border.getLeftAndRight(),
  53888. h + 2 - border.getTopAndBottom());
  53889. }
  53890. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53891. Graphics& g, int w, int h,
  53892. int titleSpaceX, int titleSpaceW,
  53893. const Image* icon,
  53894. bool drawTitleTextOnLeft)
  53895. {
  53896. const bool isActive = window.isActiveWindow();
  53897. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53898. 0.0f, 0.0f,
  53899. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53900. 0.0f, (float) h, false));
  53901. g.fillAll();
  53902. Font font (h * 0.65f, Font::bold);
  53903. g.setFont (font);
  53904. int textW = font.getStringWidth (window.getName());
  53905. int iconW = 0;
  53906. int iconH = 0;
  53907. if (icon != 0)
  53908. {
  53909. iconH = (int) font.getHeight();
  53910. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53911. }
  53912. textW = jmin (titleSpaceW, textW + iconW);
  53913. int textX = drawTitleTextOnLeft ? titleSpaceX
  53914. : jmax (titleSpaceX, (w - textW) / 2);
  53915. if (textX + textW > titleSpaceX + titleSpaceW)
  53916. textX = titleSpaceX + titleSpaceW - textW;
  53917. if (icon != 0)
  53918. {
  53919. g.setOpacity (isActive ? 1.0f : 0.6f);
  53920. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53921. RectanglePlacement::centred, false);
  53922. textX += iconW;
  53923. textW -= iconW;
  53924. }
  53925. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53926. g.setColour (findColour (DocumentWindow::textColourId));
  53927. else
  53928. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53929. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53930. }
  53931. class GlassWindowButton : public Button
  53932. {
  53933. public:
  53934. GlassWindowButton (const String& name, const Colour& col,
  53935. const Path& normalShape_,
  53936. const Path& toggledShape_) throw()
  53937. : Button (name),
  53938. colour (col),
  53939. normalShape (normalShape_),
  53940. toggledShape (toggledShape_)
  53941. {
  53942. }
  53943. ~GlassWindowButton()
  53944. {
  53945. }
  53946. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53947. {
  53948. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53949. if (! isEnabled())
  53950. alpha *= 0.5f;
  53951. float x = 0, y = 0, diam;
  53952. if (getWidth() < getHeight())
  53953. {
  53954. diam = (float) getWidth();
  53955. y = (getHeight() - getWidth()) * 0.5f;
  53956. }
  53957. else
  53958. {
  53959. diam = (float) getHeight();
  53960. y = (getWidth() - getHeight()) * 0.5f;
  53961. }
  53962. x += diam * 0.05f;
  53963. y += diam * 0.05f;
  53964. diam *= 0.9f;
  53965. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53966. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53967. g.fillEllipse (x, y, diam, diam);
  53968. x += 2.0f;
  53969. y += 2.0f;
  53970. diam -= 4.0f;
  53971. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53972. Path& p = getToggleState() ? toggledShape : normalShape;
  53973. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53974. diam * 0.4f, diam * 0.4f, true));
  53975. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53976. g.fillPath (p, t);
  53977. }
  53978. juce_UseDebuggingNewOperator
  53979. private:
  53980. Colour colour;
  53981. Path normalShape, toggledShape;
  53982. GlassWindowButton (const GlassWindowButton&);
  53983. GlassWindowButton& operator= (const GlassWindowButton&);
  53984. };
  53985. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53986. {
  53987. Path shape;
  53988. const float crossThickness = 0.25f;
  53989. if (buttonType == DocumentWindow::closeButton)
  53990. {
  53991. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53992. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53993. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53994. }
  53995. else if (buttonType == DocumentWindow::minimiseButton)
  53996. {
  53997. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53998. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53999. }
  54000. else if (buttonType == DocumentWindow::maximiseButton)
  54001. {
  54002. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  54003. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  54004. Path fullscreenShape;
  54005. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  54006. fullscreenShape.lineTo (0.0f, 100.0f);
  54007. fullscreenShape.lineTo (0.0f, 0.0f);
  54008. fullscreenShape.lineTo (100.0f, 0.0f);
  54009. fullscreenShape.lineTo (100.0f, 45.0f);
  54010. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  54011. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  54012. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  54013. }
  54014. jassertfalse;
  54015. return 0;
  54016. }
  54017. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54018. int titleBarX,
  54019. int titleBarY,
  54020. int titleBarW,
  54021. int titleBarH,
  54022. Button* minimiseButton,
  54023. Button* maximiseButton,
  54024. Button* closeButton,
  54025. bool positionTitleBarButtonsOnLeft)
  54026. {
  54027. const int buttonW = titleBarH - titleBarH / 8;
  54028. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54029. : titleBarX + titleBarW - buttonW - buttonW / 4;
  54030. if (closeButton != 0)
  54031. {
  54032. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54033. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  54034. }
  54035. if (positionTitleBarButtonsOnLeft)
  54036. swapVariables (minimiseButton, maximiseButton);
  54037. if (maximiseButton != 0)
  54038. {
  54039. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54040. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54041. }
  54042. if (minimiseButton != 0)
  54043. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54044. }
  54045. int LookAndFeel::getDefaultMenuBarHeight()
  54046. {
  54047. return 24;
  54048. }
  54049. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  54050. {
  54051. return new DropShadower (0.4f, 1, 5, 10);
  54052. }
  54053. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  54054. int w, int h,
  54055. bool /*isVerticalBar*/,
  54056. bool isMouseOver,
  54057. bool isMouseDragging)
  54058. {
  54059. float alpha = 0.5f;
  54060. if (isMouseOver || isMouseDragging)
  54061. {
  54062. g.fillAll (Colour (0x190000ff));
  54063. alpha = 1.0f;
  54064. }
  54065. const float cx = w * 0.5f;
  54066. const float cy = h * 0.5f;
  54067. const float cr = jmin (w, h) * 0.4f;
  54068. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  54069. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  54070. true));
  54071. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  54072. }
  54073. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  54074. const String& text,
  54075. const Justification& position,
  54076. GroupComponent& group)
  54077. {
  54078. const float textH = 15.0f;
  54079. const float indent = 3.0f;
  54080. const float textEdgeGap = 4.0f;
  54081. float cs = 5.0f;
  54082. Font f (textH);
  54083. Path p;
  54084. float x = indent;
  54085. float y = f.getAscent() - 3.0f;
  54086. float w = jmax (0.0f, width - x * 2.0f);
  54087. float h = jmax (0.0f, height - y - indent);
  54088. cs = jmin (cs, w * 0.5f, h * 0.5f);
  54089. const float cs2 = 2.0f * cs;
  54090. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  54091. float textX = cs + textEdgeGap;
  54092. if (position.testFlags (Justification::horizontallyCentred))
  54093. textX = cs + (w - cs2 - textW) * 0.5f;
  54094. else if (position.testFlags (Justification::right))
  54095. textX = w - cs - textW - textEdgeGap;
  54096. p.startNewSubPath (x + textX + textW, y);
  54097. p.lineTo (x + w - cs, y);
  54098. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  54099. p.lineTo (x + w, y + h - cs);
  54100. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54101. p.lineTo (x + cs, y + h);
  54102. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54103. p.lineTo (x, y + cs);
  54104. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54105. p.lineTo (x + textX, y);
  54106. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  54107. g.setColour (group.findColour (GroupComponent::outlineColourId)
  54108. .withMultipliedAlpha (alpha));
  54109. g.strokePath (p, PathStrokeType (2.0f));
  54110. g.setColour (group.findColour (GroupComponent::textColourId)
  54111. .withMultipliedAlpha (alpha));
  54112. g.setFont (f);
  54113. g.drawText (text,
  54114. roundToInt (x + textX), 0,
  54115. roundToInt (textW),
  54116. roundToInt (textH),
  54117. Justification::centred, true);
  54118. }
  54119. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  54120. {
  54121. return 1 + tabDepth / 3;
  54122. }
  54123. int LookAndFeel::getTabButtonSpaceAroundImage()
  54124. {
  54125. return 4;
  54126. }
  54127. void LookAndFeel::createTabButtonShape (Path& p,
  54128. int width, int height,
  54129. int /*tabIndex*/,
  54130. const String& /*text*/,
  54131. Button& /*button*/,
  54132. TabbedButtonBar::Orientation orientation,
  54133. const bool /*isMouseOver*/,
  54134. const bool /*isMouseDown*/,
  54135. const bool /*isFrontTab*/)
  54136. {
  54137. const float w = (float) width;
  54138. const float h = (float) height;
  54139. float length = w;
  54140. float depth = h;
  54141. if (orientation == TabbedButtonBar::TabsAtLeft
  54142. || orientation == TabbedButtonBar::TabsAtRight)
  54143. {
  54144. swapVariables (length, depth);
  54145. }
  54146. const float indent = (float) getTabButtonOverlap ((int) depth);
  54147. const float overhang = 4.0f;
  54148. if (orientation == TabbedButtonBar::TabsAtLeft)
  54149. {
  54150. p.startNewSubPath (w, 0.0f);
  54151. p.lineTo (0.0f, indent);
  54152. p.lineTo (0.0f, h - indent);
  54153. p.lineTo (w, h);
  54154. p.lineTo (w + overhang, h + overhang);
  54155. p.lineTo (w + overhang, -overhang);
  54156. }
  54157. else if (orientation == TabbedButtonBar::TabsAtRight)
  54158. {
  54159. p.startNewSubPath (0.0f, 0.0f);
  54160. p.lineTo (w, indent);
  54161. p.lineTo (w, h - indent);
  54162. p.lineTo (0.0f, h);
  54163. p.lineTo (-overhang, h + overhang);
  54164. p.lineTo (-overhang, -overhang);
  54165. }
  54166. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54167. {
  54168. p.startNewSubPath (0.0f, 0.0f);
  54169. p.lineTo (indent, h);
  54170. p.lineTo (w - indent, h);
  54171. p.lineTo (w, 0.0f);
  54172. p.lineTo (w + overhang, -overhang);
  54173. p.lineTo (-overhang, -overhang);
  54174. }
  54175. else
  54176. {
  54177. p.startNewSubPath (0.0f, h);
  54178. p.lineTo (indent, 0.0f);
  54179. p.lineTo (w - indent, 0.0f);
  54180. p.lineTo (w, h);
  54181. p.lineTo (w + overhang, h + overhang);
  54182. p.lineTo (-overhang, h + overhang);
  54183. }
  54184. p.closeSubPath();
  54185. p = p.createPathWithRoundedCorners (3.0f);
  54186. }
  54187. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54188. const Path& path,
  54189. const Colour& preferredColour,
  54190. int /*tabIndex*/,
  54191. const String& /*text*/,
  54192. Button& button,
  54193. TabbedButtonBar::Orientation /*orientation*/,
  54194. const bool /*isMouseOver*/,
  54195. const bool /*isMouseDown*/,
  54196. const bool isFrontTab)
  54197. {
  54198. g.setColour (isFrontTab ? preferredColour
  54199. : preferredColour.withMultipliedAlpha (0.9f));
  54200. g.fillPath (path);
  54201. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54202. : TabbedButtonBar::tabOutlineColourId, false)
  54203. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54204. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54205. }
  54206. void LookAndFeel::drawTabButtonText (Graphics& g,
  54207. int x, int y, int w, int h,
  54208. const Colour& preferredBackgroundColour,
  54209. int /*tabIndex*/,
  54210. const String& text,
  54211. Button& button,
  54212. TabbedButtonBar::Orientation orientation,
  54213. const bool isMouseOver,
  54214. const bool isMouseDown,
  54215. const bool isFrontTab)
  54216. {
  54217. int length = w;
  54218. int depth = h;
  54219. if (orientation == TabbedButtonBar::TabsAtLeft
  54220. || orientation == TabbedButtonBar::TabsAtRight)
  54221. {
  54222. swapVariables (length, depth);
  54223. }
  54224. Font font (depth * 0.6f);
  54225. font.setUnderline (button.hasKeyboardFocus (false));
  54226. GlyphArrangement textLayout;
  54227. textLayout.addFittedText (font, text.trim(),
  54228. 0.0f, 0.0f, (float) length, (float) depth,
  54229. Justification::centred,
  54230. jmax (1, depth / 12));
  54231. AffineTransform transform;
  54232. if (orientation == TabbedButtonBar::TabsAtLeft)
  54233. {
  54234. transform = transform.rotated (float_Pi * -0.5f)
  54235. .translated ((float) x, (float) (y + h));
  54236. }
  54237. else if (orientation == TabbedButtonBar::TabsAtRight)
  54238. {
  54239. transform = transform.rotated (float_Pi * 0.5f)
  54240. .translated ((float) (x + w), (float) y);
  54241. }
  54242. else
  54243. {
  54244. transform = transform.translated ((float) x, (float) y);
  54245. }
  54246. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54247. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54248. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54249. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54250. else
  54251. g.setColour (preferredBackgroundColour.contrasting());
  54252. if (! (isMouseOver || isMouseDown))
  54253. g.setOpacity (0.8f);
  54254. if (! button.isEnabled())
  54255. g.setOpacity (0.3f);
  54256. textLayout.draw (g, transform);
  54257. }
  54258. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54259. const String& text,
  54260. int tabDepth,
  54261. Button&)
  54262. {
  54263. Font f (tabDepth * 0.6f);
  54264. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54265. }
  54266. void LookAndFeel::drawTabButton (Graphics& g,
  54267. int w, int h,
  54268. const Colour& preferredColour,
  54269. int tabIndex,
  54270. const String& text,
  54271. Button& button,
  54272. TabbedButtonBar::Orientation orientation,
  54273. const bool isMouseOver,
  54274. const bool isMouseDown,
  54275. const bool isFrontTab)
  54276. {
  54277. int length = w;
  54278. int depth = h;
  54279. if (orientation == TabbedButtonBar::TabsAtLeft
  54280. || orientation == TabbedButtonBar::TabsAtRight)
  54281. {
  54282. swapVariables (length, depth);
  54283. }
  54284. Path tabShape;
  54285. createTabButtonShape (tabShape, w, h,
  54286. tabIndex, text, button, orientation,
  54287. isMouseOver, isMouseDown, isFrontTab);
  54288. fillTabButtonShape (g, tabShape, preferredColour,
  54289. tabIndex, text, button, orientation,
  54290. isMouseOver, isMouseDown, isFrontTab);
  54291. const int indent = getTabButtonOverlap (depth);
  54292. int x = 0, y = 0;
  54293. if (orientation == TabbedButtonBar::TabsAtLeft
  54294. || orientation == TabbedButtonBar::TabsAtRight)
  54295. {
  54296. y += indent;
  54297. h -= indent * 2;
  54298. }
  54299. else
  54300. {
  54301. x += indent;
  54302. w -= indent * 2;
  54303. }
  54304. drawTabButtonText (g, x, y, w, h, preferredColour,
  54305. tabIndex, text, button, orientation,
  54306. isMouseOver, isMouseDown, isFrontTab);
  54307. }
  54308. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54309. int w, int h,
  54310. TabbedButtonBar& tabBar,
  54311. TabbedButtonBar::Orientation orientation)
  54312. {
  54313. const float shadowSize = 0.2f;
  54314. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54315. Rectangle<int> shadowRect;
  54316. if (orientation == TabbedButtonBar::TabsAtLeft)
  54317. {
  54318. x1 = (float) w;
  54319. x2 = w * (1.0f - shadowSize);
  54320. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54321. }
  54322. else if (orientation == TabbedButtonBar::TabsAtRight)
  54323. {
  54324. x2 = w * shadowSize;
  54325. shadowRect.setBounds (0, 0, (int) x2, h);
  54326. }
  54327. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54328. {
  54329. y2 = h * shadowSize;
  54330. shadowRect.setBounds (0, 0, w, (int) y2);
  54331. }
  54332. else
  54333. {
  54334. y1 = (float) h;
  54335. y2 = h * (1.0f - shadowSize);
  54336. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54337. }
  54338. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54339. Colours::transparentBlack, x2, y2, false));
  54340. shadowRect.expand (2, 2);
  54341. g.fillRect (shadowRect);
  54342. g.setColour (Colour (0x80000000));
  54343. if (orientation == TabbedButtonBar::TabsAtLeft)
  54344. {
  54345. g.fillRect (w - 1, 0, 1, h);
  54346. }
  54347. else if (orientation == TabbedButtonBar::TabsAtRight)
  54348. {
  54349. g.fillRect (0, 0, 1, h);
  54350. }
  54351. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54352. {
  54353. g.fillRect (0, 0, w, 1);
  54354. }
  54355. else
  54356. {
  54357. g.fillRect (0, h - 1, w, 1);
  54358. }
  54359. }
  54360. Button* LookAndFeel::createTabBarExtrasButton()
  54361. {
  54362. const float thickness = 7.0f;
  54363. const float indent = 22.0f;
  54364. Path p;
  54365. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54366. DrawablePath ellipse;
  54367. ellipse.setPath (p);
  54368. ellipse.setFill (Colour (0x99ffffff));
  54369. p.clear();
  54370. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54371. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54372. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54373. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54374. p.setUsingNonZeroWinding (false);
  54375. DrawablePath dp;
  54376. dp.setPath (p);
  54377. dp.setFill (Colour (0x59000000));
  54378. DrawableComposite normalImage;
  54379. normalImage.insertDrawable (ellipse);
  54380. normalImage.insertDrawable (dp);
  54381. dp.setFill (Colour (0xcc000000));
  54382. DrawableComposite overImage;
  54383. overImage.insertDrawable (ellipse);
  54384. overImage.insertDrawable (dp);
  54385. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54386. db->setImages (&normalImage, &overImage, 0);
  54387. return db;
  54388. }
  54389. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54390. {
  54391. g.fillAll (Colours::white);
  54392. const int w = header.getWidth();
  54393. const int h = header.getHeight();
  54394. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54395. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54396. false));
  54397. g.fillRect (0, h / 2, w, h);
  54398. g.setColour (Colour (0x33000000));
  54399. g.fillRect (0, h - 1, w, 1);
  54400. for (int i = header.getNumColumns (true); --i >= 0;)
  54401. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54402. }
  54403. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54404. int width, int height,
  54405. bool isMouseOver, bool isMouseDown,
  54406. int columnFlags)
  54407. {
  54408. if (isMouseDown)
  54409. g.fillAll (Colour (0x8899aadd));
  54410. else if (isMouseOver)
  54411. g.fillAll (Colour (0x5599aadd));
  54412. int rightOfText = width - 4;
  54413. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54414. {
  54415. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54416. const float bottom = height - top;
  54417. const float w = height * 0.5f;
  54418. const float x = rightOfText - (w * 1.25f);
  54419. rightOfText = (int) x;
  54420. Path sortArrow;
  54421. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54422. g.setColour (Colour (0x99000000));
  54423. g.fillPath (sortArrow);
  54424. }
  54425. g.setColour (Colours::black);
  54426. g.setFont (height * 0.5f, Font::bold);
  54427. const int textX = 4;
  54428. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54429. }
  54430. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54431. {
  54432. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54433. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54434. background.darker (0.1f),
  54435. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54436. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54437. false));
  54438. g.fillAll();
  54439. }
  54440. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54441. {
  54442. return createTabBarExtrasButton();
  54443. }
  54444. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54445. bool isMouseOver, bool isMouseDown,
  54446. ToolbarItemComponent& component)
  54447. {
  54448. if (isMouseDown)
  54449. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54450. else if (isMouseOver)
  54451. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54452. }
  54453. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54454. const String& text, ToolbarItemComponent& component)
  54455. {
  54456. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54457. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54458. const float fontHeight = jmin (14.0f, height * 0.85f);
  54459. g.setFont (fontHeight);
  54460. g.drawFittedText (text,
  54461. x, y, width, height,
  54462. Justification::centred,
  54463. jmax (1, height / (int) fontHeight));
  54464. }
  54465. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54466. bool isOpen, int width, int height)
  54467. {
  54468. const int buttonSize = (height * 3) / 4;
  54469. const int buttonIndent = (height - buttonSize) / 2;
  54470. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54471. const int textX = buttonIndent * 2 + buttonSize + 2;
  54472. g.setColour (Colours::black);
  54473. g.setFont (height * 0.7f, Font::bold);
  54474. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54475. }
  54476. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54477. PropertyComponent&)
  54478. {
  54479. g.setColour (Colour (0x66ffffff));
  54480. g.fillRect (0, 0, width, height - 1);
  54481. }
  54482. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54483. PropertyComponent& component)
  54484. {
  54485. g.setColour (Colours::black);
  54486. if (! component.isEnabled())
  54487. g.setOpacity (0.6f);
  54488. g.setFont (jmin (height, 24) * 0.65f);
  54489. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54490. g.drawFittedText (component.getName(),
  54491. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54492. Justification::centredLeft, 2);
  54493. }
  54494. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54495. {
  54496. return Rectangle<int> (component.getWidth() / 3, 1,
  54497. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54498. }
  54499. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54500. {
  54501. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54502. {
  54503. Graphics g2 (content);
  54504. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54505. g2.fillPath (path);
  54506. g2.setColour (Colours::white.withAlpha (0.8f));
  54507. g2.strokePath (path, PathStrokeType (2.0f));
  54508. }
  54509. DropShadowEffect shadow;
  54510. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54511. shadow.applyEffect (content, g);
  54512. }
  54513. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54514. const String& instructions,
  54515. GlyphArrangement& text,
  54516. int width)
  54517. {
  54518. text.clear();
  54519. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54520. 8.0f, 22.0f, width - 16.0f,
  54521. Justification::centred);
  54522. text.addJustifiedText (Font (14.0f), instructions,
  54523. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54524. Justification::centred);
  54525. }
  54526. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54527. const String& filename, Image* icon,
  54528. const String& fileSizeDescription,
  54529. const String& fileTimeDescription,
  54530. const bool isDirectory,
  54531. const bool isItemSelected,
  54532. const int /*itemIndex*/)
  54533. {
  54534. if (isItemSelected)
  54535. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54536. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54537. g.setFont (height * 0.7f);
  54538. Image im;
  54539. if (icon != 0)
  54540. im = *icon;
  54541. if (im.isNull())
  54542. im = isDirectory ? getDefaultFolderImage()
  54543. : getDefaultDocumentFileImage();
  54544. const int x = 32;
  54545. if (im.isValid())
  54546. {
  54547. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  54548. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54549. false);
  54550. }
  54551. if (width > 450 && ! isDirectory)
  54552. {
  54553. const int sizeX = roundToInt (width * 0.7f);
  54554. const int dateX = roundToInt (width * 0.8f);
  54555. g.drawFittedText (filename,
  54556. x, 0, sizeX - x, height,
  54557. Justification::centredLeft, 1);
  54558. g.setFont (height * 0.5f);
  54559. g.setColour (Colours::darkgrey);
  54560. if (! isDirectory)
  54561. {
  54562. g.drawFittedText (fileSizeDescription,
  54563. sizeX, 0, dateX - sizeX - 8, height,
  54564. Justification::centredRight, 1);
  54565. g.drawFittedText (fileTimeDescription,
  54566. dateX, 0, width - 8 - dateX, height,
  54567. Justification::centredRight, 1);
  54568. }
  54569. }
  54570. else
  54571. {
  54572. g.drawFittedText (filename,
  54573. x, 0, width - x, height,
  54574. Justification::centredLeft, 1);
  54575. }
  54576. }
  54577. Button* LookAndFeel::createFileBrowserGoUpButton()
  54578. {
  54579. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54580. Path arrowPath;
  54581. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54582. DrawablePath arrowImage;
  54583. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54584. arrowImage.setPath (arrowPath);
  54585. goUpButton->setImages (&arrowImage);
  54586. return goUpButton;
  54587. }
  54588. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54589. DirectoryContentsDisplayComponent* fileListComponent,
  54590. FilePreviewComponent* previewComp,
  54591. ComboBox* currentPathBox,
  54592. TextEditor* filenameBox,
  54593. Button* goUpButton)
  54594. {
  54595. const int x = 8;
  54596. int w = browserComp.getWidth() - x - x;
  54597. if (previewComp != 0)
  54598. {
  54599. const int previewWidth = w / 3;
  54600. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54601. w -= previewWidth + 4;
  54602. }
  54603. int y = 4;
  54604. const int controlsHeight = 22;
  54605. const int bottomSectionHeight = controlsHeight + 8;
  54606. const int upButtonWidth = 50;
  54607. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54608. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54609. y += controlsHeight + 4;
  54610. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54611. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54612. y = listAsComp->getBottom() + 4;
  54613. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54614. }
  54615. const Image LookAndFeel::getDefaultFolderImage()
  54616. {
  54617. 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,
  54618. 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,
  54619. 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,
  54620. 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,
  54621. 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,
  54622. 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,
  54623. 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,
  54624. 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,
  54625. 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,
  54626. 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,
  54627. 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,
  54628. 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,
  54629. 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,
  54630. 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,
  54631. 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,
  54632. 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,
  54633. 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,
  54634. 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,
  54635. 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,
  54636. 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,
  54637. 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,
  54638. 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,
  54639. 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,
  54640. 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,
  54641. 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,
  54642. 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,
  54643. 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,
  54644. 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,
  54645. 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,
  54646. 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,
  54647. 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,
  54648. 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,
  54649. 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,
  54650. 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,
  54651. 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,
  54652. 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,
  54653. 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,
  54654. 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,
  54655. 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,
  54656. 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,
  54657. 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,
  54658. 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,
  54659. 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,
  54660. 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};
  54661. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  54662. }
  54663. const Image LookAndFeel::getDefaultDocumentFileImage()
  54664. {
  54665. 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,
  54666. 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,
  54667. 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,
  54668. 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,
  54669. 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,
  54670. 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,
  54671. 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,
  54672. 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,
  54673. 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,
  54674. 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,
  54675. 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,
  54676. 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,
  54677. 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,
  54678. 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,
  54679. 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,
  54680. 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,
  54681. 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,
  54682. 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,
  54683. 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,
  54684. 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,
  54685. 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,
  54686. 174,66,96,130,0,0};
  54687. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  54688. }
  54689. void LookAndFeel::playAlertSound()
  54690. {
  54691. PlatformUtilities::beep();
  54692. }
  54693. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54694. {
  54695. g.setColour (Colours::white.withAlpha (0.7f));
  54696. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54697. g.setColour (Colours::black.withAlpha (0.2f));
  54698. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54699. const int totalBlocks = 7;
  54700. const int numBlocks = roundToInt (totalBlocks * level);
  54701. const float w = (width - 6.0f) / (float) totalBlocks;
  54702. for (int i = 0; i < totalBlocks; ++i)
  54703. {
  54704. if (i >= numBlocks)
  54705. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54706. else
  54707. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54708. : Colours::red);
  54709. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54710. }
  54711. }
  54712. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54713. {
  54714. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54715. if (keyDescription.isNotEmpty())
  54716. {
  54717. if (button.isEnabled())
  54718. {
  54719. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54720. g.fillAll (textColour.withAlpha (alpha));
  54721. g.setOpacity (0.3f);
  54722. g.drawBevel (0, 0, width, height, 2);
  54723. }
  54724. g.setColour (textColour);
  54725. g.setFont (height * 0.6f);
  54726. g.drawFittedText (keyDescription,
  54727. 3, 0, width - 6, height,
  54728. Justification::centred, 1);
  54729. }
  54730. else
  54731. {
  54732. const float thickness = 7.0f;
  54733. const float indent = 22.0f;
  54734. Path p;
  54735. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54736. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54737. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54738. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54739. p.setUsingNonZeroWinding (false);
  54740. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54741. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54742. }
  54743. if (button.hasKeyboardFocus (false))
  54744. {
  54745. g.setColour (textColour.withAlpha (0.4f));
  54746. g.drawRect (0, 0, width, height);
  54747. }
  54748. }
  54749. static void createRoundedPath (Path& p,
  54750. const float x, const float y,
  54751. const float w, const float h,
  54752. const float cs,
  54753. const bool curveTopLeft, const bool curveTopRight,
  54754. const bool curveBottomLeft, const bool curveBottomRight) throw()
  54755. {
  54756. const float cs2 = 2.0f * cs;
  54757. if (curveTopLeft)
  54758. {
  54759. p.startNewSubPath (x, y + cs);
  54760. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54761. }
  54762. else
  54763. {
  54764. p.startNewSubPath (x, y);
  54765. }
  54766. if (curveTopRight)
  54767. {
  54768. p.lineTo (x + w - cs, y);
  54769. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  54770. }
  54771. else
  54772. {
  54773. p.lineTo (x + w, y);
  54774. }
  54775. if (curveBottomRight)
  54776. {
  54777. p.lineTo (x + w, y + h - cs);
  54778. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54779. }
  54780. else
  54781. {
  54782. p.lineTo (x + w, y + h);
  54783. }
  54784. if (curveBottomLeft)
  54785. {
  54786. p.lineTo (x + cs, y + h);
  54787. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54788. }
  54789. else
  54790. {
  54791. p.lineTo (x, y + h);
  54792. }
  54793. p.closeSubPath();
  54794. }
  54795. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54796. float x, float y, float w, float h,
  54797. float maxCornerSize,
  54798. const Colour& baseColour,
  54799. const float strokeWidth,
  54800. const bool flatOnLeft,
  54801. const bool flatOnRight,
  54802. const bool flatOnTop,
  54803. const bool flatOnBottom) throw()
  54804. {
  54805. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54806. return;
  54807. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54808. Path outline;
  54809. createRoundedPath (outline, x, y, w, h, cs,
  54810. ! (flatOnLeft || flatOnTop),
  54811. ! (flatOnRight || flatOnTop),
  54812. ! (flatOnLeft || flatOnBottom),
  54813. ! (flatOnRight || flatOnBottom));
  54814. ColourGradient cg (baseColour, 0.0f, y,
  54815. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54816. false);
  54817. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54818. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54819. g.setGradientFill (cg);
  54820. g.fillPath (outline);
  54821. g.setColour (Colour (0x80000000));
  54822. g.strokePath (outline, PathStrokeType (strokeWidth));
  54823. }
  54824. void LookAndFeel::drawGlassSphere (Graphics& g,
  54825. const float x, const float y,
  54826. const float diameter,
  54827. const Colour& colour,
  54828. const float outlineThickness) throw()
  54829. {
  54830. if (diameter <= outlineThickness)
  54831. return;
  54832. Path p;
  54833. p.addEllipse (x, y, diameter, diameter);
  54834. {
  54835. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54836. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54837. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54838. g.setGradientFill (cg);
  54839. g.fillPath (p);
  54840. }
  54841. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54842. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54843. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54844. ColourGradient cg (Colours::transparentBlack,
  54845. x + diameter * 0.5f, y + diameter * 0.5f,
  54846. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54847. x, y + diameter * 0.5f, true);
  54848. cg.addColour (0.7, Colours::transparentBlack);
  54849. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54850. g.setGradientFill (cg);
  54851. g.fillPath (p);
  54852. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54853. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54854. }
  54855. void LookAndFeel::drawGlassPointer (Graphics& g,
  54856. const float x, const float y,
  54857. const float diameter,
  54858. const Colour& colour, const float outlineThickness,
  54859. const int direction) throw()
  54860. {
  54861. if (diameter <= outlineThickness)
  54862. return;
  54863. Path p;
  54864. p.startNewSubPath (x + diameter * 0.5f, y);
  54865. p.lineTo (x + diameter, y + diameter * 0.6f);
  54866. p.lineTo (x + diameter, y + diameter);
  54867. p.lineTo (x, y + diameter);
  54868. p.lineTo (x, y + diameter * 0.6f);
  54869. p.closeSubPath();
  54870. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54871. {
  54872. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54873. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54874. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54875. g.setGradientFill (cg);
  54876. g.fillPath (p);
  54877. }
  54878. ColourGradient cg (Colours::transparentBlack,
  54879. x + diameter * 0.5f, y + diameter * 0.5f,
  54880. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54881. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54882. cg.addColour (0.5, Colours::transparentBlack);
  54883. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54884. g.setGradientFill (cg);
  54885. g.fillPath (p);
  54886. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54887. g.strokePath (p, PathStrokeType (outlineThickness));
  54888. }
  54889. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54890. const float x, const float y,
  54891. const float width, const float height,
  54892. const Colour& colour,
  54893. const float outlineThickness,
  54894. const float cornerSize,
  54895. const bool flatOnLeft,
  54896. const bool flatOnRight,
  54897. const bool flatOnTop,
  54898. const bool flatOnBottom) throw()
  54899. {
  54900. if (width <= outlineThickness || height <= outlineThickness)
  54901. return;
  54902. const int intX = (int) x;
  54903. const int intY = (int) y;
  54904. const int intW = (int) width;
  54905. const int intH = (int) height;
  54906. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54907. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54908. const int intEdge = (int) edgeBlurRadius;
  54909. Path outline;
  54910. createRoundedPath (outline, x, y, width, height, cs,
  54911. ! (flatOnLeft || flatOnTop),
  54912. ! (flatOnRight || flatOnTop),
  54913. ! (flatOnLeft || flatOnBottom),
  54914. ! (flatOnRight || flatOnBottom));
  54915. {
  54916. ColourGradient cg (colour.darker (0.2f), 0, y,
  54917. colour.darker (0.2f), 0, y + height, false);
  54918. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54919. cg.addColour (0.4, colour);
  54920. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54921. g.setGradientFill (cg);
  54922. g.fillPath (outline);
  54923. }
  54924. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54925. colour.darker (0.2f), x, y + height * 0.5f, true);
  54926. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54927. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54928. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54929. {
  54930. g.saveState();
  54931. g.setGradientFill (cg);
  54932. g.reduceClipRegion (intX, intY, intEdge, intH);
  54933. g.fillPath (outline);
  54934. g.restoreState();
  54935. }
  54936. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54937. {
  54938. cg.point1.setX (x + width - edgeBlurRadius);
  54939. cg.point2.setX (x + width);
  54940. g.saveState();
  54941. g.setGradientFill (cg);
  54942. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54943. g.fillPath (outline);
  54944. g.restoreState();
  54945. }
  54946. {
  54947. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54948. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54949. Path highlight;
  54950. createRoundedPath (highlight,
  54951. x + leftIndent,
  54952. y + cs * 0.1f,
  54953. width - (leftIndent + rightIndent),
  54954. height * 0.4f, cs * 0.4f,
  54955. ! (flatOnLeft || flatOnTop),
  54956. ! (flatOnRight || flatOnTop),
  54957. ! (flatOnLeft || flatOnBottom),
  54958. ! (flatOnRight || flatOnBottom));
  54959. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54960. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54961. g.fillPath (highlight);
  54962. }
  54963. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54964. g.strokePath (outline, PathStrokeType (outlineThickness));
  54965. }
  54966. END_JUCE_NAMESPACE
  54967. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54968. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54969. BEGIN_JUCE_NAMESPACE
  54970. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54971. {
  54972. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54973. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54974. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54975. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54976. setColour (Slider::thumbColourId, Colours::white);
  54977. setColour (Slider::trackColourId, Colour (0x7f000000));
  54978. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54979. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54980. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54981. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54982. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54983. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54984. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54985. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54986. }
  54987. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54988. {
  54989. }
  54990. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54991. Button& button,
  54992. const Colour& backgroundColour,
  54993. bool isMouseOverButton,
  54994. bool isButtonDown)
  54995. {
  54996. const int width = button.getWidth();
  54997. const int height = button.getHeight();
  54998. const float indent = 2.0f;
  54999. const int cornerSize = jmin (roundToInt (width * 0.4f),
  55000. roundToInt (height * 0.4f));
  55001. Path p;
  55002. p.addRoundedRectangle (indent, indent,
  55003. width - indent * 2.0f,
  55004. height - indent * 2.0f,
  55005. (float) cornerSize);
  55006. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  55007. if (isMouseOverButton)
  55008. {
  55009. if (isButtonDown)
  55010. bc = bc.brighter();
  55011. else if (bc.getBrightness() > 0.5f)
  55012. bc = bc.darker (0.1f);
  55013. else
  55014. bc = bc.brighter (0.1f);
  55015. }
  55016. g.setColour (bc);
  55017. g.fillPath (p);
  55018. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  55019. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  55020. }
  55021. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  55022. Component& /*component*/,
  55023. float x, float y, float w, float h,
  55024. const bool ticked,
  55025. const bool isEnabled,
  55026. const bool /*isMouseOverButton*/,
  55027. const bool isButtonDown)
  55028. {
  55029. Path box;
  55030. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  55031. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  55032. : Colours::lightgrey.withAlpha (0.1f));
  55033. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  55034. g.fillPath (box, trans);
  55035. g.setColour (Colours::black.withAlpha (0.6f));
  55036. g.strokePath (box, PathStrokeType (0.9f), trans);
  55037. if (ticked)
  55038. {
  55039. Path tick;
  55040. tick.startNewSubPath (1.5f, 3.0f);
  55041. tick.lineTo (3.0f, 6.0f);
  55042. tick.lineTo (6.0f, 0.0f);
  55043. g.setColour (isEnabled ? Colours::black : Colours::grey);
  55044. g.strokePath (tick, PathStrokeType (2.5f), trans);
  55045. }
  55046. }
  55047. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  55048. ToggleButton& button,
  55049. bool isMouseOverButton,
  55050. bool isButtonDown)
  55051. {
  55052. if (button.hasKeyboardFocus (true))
  55053. {
  55054. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  55055. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  55056. }
  55057. const int tickWidth = jmin (20, button.getHeight() - 4);
  55058. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  55059. (float) tickWidth, (float) tickWidth,
  55060. button.getToggleState(),
  55061. button.isEnabled(),
  55062. isMouseOverButton,
  55063. isButtonDown);
  55064. g.setColour (button.findColour (ToggleButton::textColourId));
  55065. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  55066. if (! button.isEnabled())
  55067. g.setOpacity (0.5f);
  55068. const int textX = tickWidth + 5;
  55069. g.drawFittedText (button.getButtonText(),
  55070. textX, 4,
  55071. button.getWidth() - textX - 2, button.getHeight() - 8,
  55072. Justification::centredLeft, 10);
  55073. }
  55074. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  55075. int width, int height,
  55076. double progress, const String& textToShow)
  55077. {
  55078. if (progress < 0 || progress >= 1.0)
  55079. {
  55080. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  55081. }
  55082. else
  55083. {
  55084. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  55085. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  55086. g.fillAll (background);
  55087. g.setColour (foreground);
  55088. g.fillRect (1, 1,
  55089. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  55090. height - 2);
  55091. if (textToShow.isNotEmpty())
  55092. {
  55093. g.setColour (Colour::contrasting (background, foreground));
  55094. g.setFont (height * 0.6f);
  55095. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  55096. }
  55097. }
  55098. }
  55099. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  55100. ScrollBar& bar,
  55101. int width, int height,
  55102. int buttonDirection,
  55103. bool isScrollbarVertical,
  55104. bool isMouseOverButton,
  55105. bool isButtonDown)
  55106. {
  55107. if (isScrollbarVertical)
  55108. width -= 2;
  55109. else
  55110. height -= 2;
  55111. Path p;
  55112. if (buttonDirection == 0)
  55113. p.addTriangle (width * 0.5f, height * 0.2f,
  55114. width * 0.1f, height * 0.7f,
  55115. width * 0.9f, height * 0.7f);
  55116. else if (buttonDirection == 1)
  55117. p.addTriangle (width * 0.8f, height * 0.5f,
  55118. width * 0.3f, height * 0.1f,
  55119. width * 0.3f, height * 0.9f);
  55120. else if (buttonDirection == 2)
  55121. p.addTriangle (width * 0.5f, height * 0.8f,
  55122. width * 0.1f, height * 0.3f,
  55123. width * 0.9f, height * 0.3f);
  55124. else if (buttonDirection == 3)
  55125. p.addTriangle (width * 0.2f, height * 0.5f,
  55126. width * 0.7f, height * 0.1f,
  55127. width * 0.7f, height * 0.9f);
  55128. if (isButtonDown)
  55129. g.setColour (Colours::white);
  55130. else if (isMouseOverButton)
  55131. g.setColour (Colours::white.withAlpha (0.7f));
  55132. else
  55133. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  55134. g.fillPath (p);
  55135. g.setColour (Colours::black.withAlpha (0.5f));
  55136. g.strokePath (p, PathStrokeType (0.5f));
  55137. }
  55138. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  55139. ScrollBar& bar,
  55140. int x, int y,
  55141. int width, int height,
  55142. bool isScrollbarVertical,
  55143. int thumbStartPosition,
  55144. int thumbSize,
  55145. bool isMouseOver,
  55146. bool isMouseDown)
  55147. {
  55148. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  55149. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55150. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  55151. if (thumbSize > 0.0f)
  55152. {
  55153. Rectangle<int> thumb;
  55154. if (isScrollbarVertical)
  55155. {
  55156. width -= 2;
  55157. g.fillRect (x + roundToInt (width * 0.35f), y,
  55158. roundToInt (width * 0.3f), height);
  55159. thumb.setBounds (x + 1, thumbStartPosition,
  55160. width - 2, thumbSize);
  55161. }
  55162. else
  55163. {
  55164. height -= 2;
  55165. g.fillRect (x, y + roundToInt (height * 0.35f),
  55166. width, roundToInt (height * 0.3f));
  55167. thumb.setBounds (thumbStartPosition, y + 1,
  55168. thumbSize, height - 2);
  55169. }
  55170. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55171. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  55172. g.fillRect (thumb);
  55173. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  55174. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  55175. if (thumbSize > 16)
  55176. {
  55177. for (int i = 3; --i >= 0;)
  55178. {
  55179. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  55180. g.setColour (Colours::black.withAlpha (0.15f));
  55181. if (isScrollbarVertical)
  55182. {
  55183. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  55184. g.setColour (Colours::white.withAlpha (0.15f));
  55185. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  55186. }
  55187. else
  55188. {
  55189. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  55190. g.setColour (Colours::white.withAlpha (0.15f));
  55191. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  55192. }
  55193. }
  55194. }
  55195. }
  55196. }
  55197. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55198. {
  55199. return &scrollbarShadow;
  55200. }
  55201. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55202. {
  55203. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55204. g.setColour (Colours::black.withAlpha (0.6f));
  55205. g.drawRect (0, 0, width, height);
  55206. }
  55207. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55208. bool, MenuBarComponent& menuBar)
  55209. {
  55210. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55211. }
  55212. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55213. {
  55214. if (textEditor.isEnabled())
  55215. {
  55216. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55217. g.drawRect (0, 0, width, height);
  55218. }
  55219. }
  55220. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55221. const bool isButtonDown,
  55222. int buttonX, int buttonY,
  55223. int buttonW, int buttonH,
  55224. ComboBox& box)
  55225. {
  55226. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55227. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55228. : ComboBox::backgroundColourId));
  55229. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55230. g.setColour (box.findColour (ComboBox::outlineColourId));
  55231. g.drawRect (0, 0, width, height);
  55232. const float arrowX = 0.2f;
  55233. const float arrowH = 0.3f;
  55234. if (box.isEnabled())
  55235. {
  55236. Path p;
  55237. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55238. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55239. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55240. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55241. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55242. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55243. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55244. : ComboBox::buttonColourId));
  55245. g.fillPath (p);
  55246. }
  55247. }
  55248. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55249. {
  55250. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55251. f.setHorizontalScale (0.9f);
  55252. return f;
  55253. }
  55254. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55255. {
  55256. Path p;
  55257. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55258. g.setColour (fill);
  55259. g.fillPath (p);
  55260. g.setColour (outline);
  55261. g.strokePath (p, PathStrokeType (0.3f));
  55262. }
  55263. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55264. int x, int y,
  55265. int w, int h,
  55266. float sliderPos,
  55267. float minSliderPos,
  55268. float maxSliderPos,
  55269. const Slider::SliderStyle style,
  55270. Slider& slider)
  55271. {
  55272. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55273. if (style == Slider::LinearBar)
  55274. {
  55275. g.setColour (slider.findColour (Slider::thumbColourId));
  55276. g.fillRect (x, y, (int) sliderPos - x, h);
  55277. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55278. g.drawRect (x, y, (int) sliderPos - x, h);
  55279. }
  55280. else
  55281. {
  55282. g.setColour (slider.findColour (Slider::trackColourId)
  55283. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55284. if (slider.isHorizontal())
  55285. {
  55286. g.fillRect (x, y + roundToInt (h * 0.6f),
  55287. w, roundToInt (h * 0.2f));
  55288. }
  55289. else
  55290. {
  55291. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55292. jmin (4, roundToInt (w * 0.2f)), h);
  55293. }
  55294. float alpha = 0.35f;
  55295. if (slider.isEnabled())
  55296. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55297. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55298. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55299. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55300. {
  55301. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55302. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55303. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55304. fill, outline);
  55305. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55306. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55307. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55308. fill, outline);
  55309. }
  55310. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55311. {
  55312. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55313. minSliderPos - 7.0f, y + h * 0.9f ,
  55314. minSliderPos, y + h * 0.9f,
  55315. fill, outline);
  55316. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55317. maxSliderPos, y + h * 0.9f,
  55318. maxSliderPos + 7.0f, y + h * 0.9f,
  55319. fill, outline);
  55320. }
  55321. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55322. {
  55323. drawTriangle (g, sliderPos, y + h * 0.9f,
  55324. sliderPos - 7.0f, y + h * 0.2f,
  55325. sliderPos + 7.0f, y + h * 0.2f,
  55326. fill, outline);
  55327. }
  55328. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55329. {
  55330. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55331. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55332. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55333. fill, outline);
  55334. }
  55335. }
  55336. }
  55337. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55338. {
  55339. if (isIncrement)
  55340. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55341. else
  55342. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55343. }
  55344. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55345. {
  55346. return &scrollbarShadow;
  55347. }
  55348. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55349. {
  55350. return 8;
  55351. }
  55352. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55353. int w, int h,
  55354. bool isMouseOver,
  55355. bool isMouseDragging)
  55356. {
  55357. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55358. : Colours::darkgrey);
  55359. const float lineThickness = jmin (w, h) * 0.1f;
  55360. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55361. {
  55362. g.drawLine (w * i,
  55363. h + 1.0f,
  55364. w + 1.0f,
  55365. h * i,
  55366. lineThickness);
  55367. }
  55368. }
  55369. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55370. {
  55371. Path shape;
  55372. if (buttonType == DocumentWindow::closeButton)
  55373. {
  55374. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55375. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55376. ShapeButton* const b = new ShapeButton ("close",
  55377. Colour (0x7fff3333),
  55378. Colour (0xd7ff3333),
  55379. Colour (0xf7ff3333));
  55380. b->setShape (shape, true, true, true);
  55381. return b;
  55382. }
  55383. else if (buttonType == DocumentWindow::minimiseButton)
  55384. {
  55385. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55386. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55387. DrawablePath dp;
  55388. dp.setPath (shape);
  55389. dp.setFill (Colours::black.withAlpha (0.3f));
  55390. b->setImages (&dp);
  55391. return b;
  55392. }
  55393. else if (buttonType == DocumentWindow::maximiseButton)
  55394. {
  55395. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55396. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55397. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55398. DrawablePath dp;
  55399. dp.setPath (shape);
  55400. dp.setFill (Colours::black.withAlpha (0.3f));
  55401. b->setImages (&dp);
  55402. return b;
  55403. }
  55404. jassertfalse;
  55405. return 0;
  55406. }
  55407. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55408. int titleBarX,
  55409. int titleBarY,
  55410. int titleBarW,
  55411. int titleBarH,
  55412. Button* minimiseButton,
  55413. Button* maximiseButton,
  55414. Button* closeButton,
  55415. bool positionTitleBarButtonsOnLeft)
  55416. {
  55417. titleBarY += titleBarH / 8;
  55418. titleBarH -= titleBarH / 4;
  55419. const int buttonW = titleBarH;
  55420. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55421. : titleBarX + titleBarW - buttonW - 4;
  55422. if (closeButton != 0)
  55423. {
  55424. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55425. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55426. : -(buttonW + buttonW / 5);
  55427. }
  55428. if (positionTitleBarButtonsOnLeft)
  55429. swapVariables (minimiseButton, maximiseButton);
  55430. if (maximiseButton != 0)
  55431. {
  55432. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55433. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55434. }
  55435. if (minimiseButton != 0)
  55436. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55437. }
  55438. END_JUCE_NAMESPACE
  55439. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55440. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55441. BEGIN_JUCE_NAMESPACE
  55442. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55443. : model (0),
  55444. itemUnderMouse (-1),
  55445. currentPopupIndex (-1),
  55446. topLevelIndexClicked (0),
  55447. lastMouseX (0),
  55448. lastMouseY (0)
  55449. {
  55450. setRepaintsOnMouseActivity (true);
  55451. setWantsKeyboardFocus (false);
  55452. setMouseClickGrabsKeyboardFocus (false);
  55453. setModel (model_);
  55454. }
  55455. MenuBarComponent::~MenuBarComponent()
  55456. {
  55457. setModel (0);
  55458. Desktop::getInstance().removeGlobalMouseListener (this);
  55459. }
  55460. MenuBarModel* MenuBarComponent::getModel() const throw()
  55461. {
  55462. return model;
  55463. }
  55464. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55465. {
  55466. if (model != newModel)
  55467. {
  55468. if (model != 0)
  55469. model->removeListener (this);
  55470. model = newModel;
  55471. if (model != 0)
  55472. model->addListener (this);
  55473. repaint();
  55474. menuBarItemsChanged (0);
  55475. }
  55476. }
  55477. void MenuBarComponent::paint (Graphics& g)
  55478. {
  55479. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55480. getLookAndFeel().drawMenuBarBackground (g,
  55481. getWidth(),
  55482. getHeight(),
  55483. isMouseOverBar,
  55484. *this);
  55485. if (model != 0)
  55486. {
  55487. for (int i = 0; i < menuNames.size(); ++i)
  55488. {
  55489. g.saveState();
  55490. g.setOrigin (xPositions [i], 0);
  55491. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55492. getLookAndFeel().drawMenuBarItem (g,
  55493. xPositions[i + 1] - xPositions[i],
  55494. getHeight(),
  55495. i,
  55496. menuNames[i],
  55497. i == itemUnderMouse,
  55498. i == currentPopupIndex,
  55499. isMouseOverBar,
  55500. *this);
  55501. g.restoreState();
  55502. }
  55503. }
  55504. }
  55505. void MenuBarComponent::resized()
  55506. {
  55507. xPositions.clear();
  55508. int x = 2;
  55509. xPositions.add (x);
  55510. for (int i = 0; i < menuNames.size(); ++i)
  55511. {
  55512. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55513. xPositions.add (x);
  55514. }
  55515. }
  55516. int MenuBarComponent::getItemAt (const int x, const int y)
  55517. {
  55518. for (int i = 0; i < xPositions.size(); ++i)
  55519. if (x >= xPositions[i] && x < xPositions[i + 1])
  55520. return reallyContains (x, y, true) ? i : -1;
  55521. return -1;
  55522. }
  55523. void MenuBarComponent::repaintMenuItem (int index)
  55524. {
  55525. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55526. {
  55527. const int x1 = xPositions [index];
  55528. const int x2 = xPositions [index + 1];
  55529. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55530. }
  55531. }
  55532. void MenuBarComponent::setItemUnderMouse (const int index)
  55533. {
  55534. if (itemUnderMouse != index)
  55535. {
  55536. repaintMenuItem (itemUnderMouse);
  55537. itemUnderMouse = index;
  55538. repaintMenuItem (itemUnderMouse);
  55539. }
  55540. }
  55541. void MenuBarComponent::setOpenItem (int index)
  55542. {
  55543. if (currentPopupIndex != index)
  55544. {
  55545. repaintMenuItem (currentPopupIndex);
  55546. currentPopupIndex = index;
  55547. repaintMenuItem (currentPopupIndex);
  55548. if (index >= 0)
  55549. Desktop::getInstance().addGlobalMouseListener (this);
  55550. else
  55551. Desktop::getInstance().removeGlobalMouseListener (this);
  55552. }
  55553. }
  55554. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55555. {
  55556. setItemUnderMouse (getItemAt (x, y));
  55557. }
  55558. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55559. {
  55560. public:
  55561. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55562. : bar (bar_), topLevelIndex (topLevelIndex_)
  55563. {
  55564. }
  55565. ~AsyncCallback() {}
  55566. void modalStateFinished (int returnValue)
  55567. {
  55568. if (bar != 0)
  55569. bar->menuDismissed (topLevelIndex, returnValue);
  55570. }
  55571. private:
  55572. Component::SafePointer<MenuBarComponent> bar;
  55573. const int topLevelIndex;
  55574. AsyncCallback (const AsyncCallback&);
  55575. AsyncCallback& operator= (const AsyncCallback&);
  55576. };
  55577. void MenuBarComponent::showMenu (int index)
  55578. {
  55579. if (index != currentPopupIndex)
  55580. {
  55581. PopupMenu::dismissAllActiveMenus();
  55582. menuBarItemsChanged (0);
  55583. setOpenItem (index);
  55584. setItemUnderMouse (index);
  55585. if (index >= 0)
  55586. {
  55587. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55588. menuNames [itemUnderMouse]));
  55589. if (m.lookAndFeel == 0)
  55590. m.setLookAndFeel (&getLookAndFeel());
  55591. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55592. m.showMenu (itemPos + getScreenPosition(),
  55593. 0, itemPos.getWidth(), 0, 0, true, this,
  55594. new AsyncCallback (this, index));
  55595. }
  55596. }
  55597. }
  55598. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55599. {
  55600. topLevelIndexClicked = topLevelIndex;
  55601. postCommandMessage (itemId);
  55602. }
  55603. void MenuBarComponent::handleCommandMessage (int commandId)
  55604. {
  55605. const Point<int> mousePos (getMouseXYRelative());
  55606. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55607. if (! isCurrentlyBlockedByAnotherModalComponent())
  55608. setOpenItem (-1);
  55609. if (commandId != 0 && model != 0)
  55610. model->menuItemSelected (commandId, topLevelIndexClicked);
  55611. }
  55612. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55613. {
  55614. if (e.eventComponent == this)
  55615. updateItemUnderMouse (e.x, e.y);
  55616. }
  55617. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55618. {
  55619. if (e.eventComponent == this)
  55620. updateItemUnderMouse (e.x, e.y);
  55621. }
  55622. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55623. {
  55624. if (currentPopupIndex < 0)
  55625. {
  55626. const MouseEvent e2 (e.getEventRelativeTo (this));
  55627. updateItemUnderMouse (e2.x, e2.y);
  55628. currentPopupIndex = -2;
  55629. showMenu (itemUnderMouse);
  55630. }
  55631. }
  55632. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55633. {
  55634. const MouseEvent e2 (e.getEventRelativeTo (this));
  55635. const int item = getItemAt (e2.x, e2.y);
  55636. if (item >= 0)
  55637. showMenu (item);
  55638. }
  55639. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55640. {
  55641. const MouseEvent e2 (e.getEventRelativeTo (this));
  55642. updateItemUnderMouse (e2.x, e2.y);
  55643. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55644. {
  55645. setOpenItem (-1);
  55646. PopupMenu::dismissAllActiveMenus();
  55647. }
  55648. }
  55649. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55650. {
  55651. const MouseEvent e2 (e.getEventRelativeTo (this));
  55652. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55653. {
  55654. if (currentPopupIndex >= 0)
  55655. {
  55656. const int item = getItemAt (e2.x, e2.y);
  55657. if (item >= 0)
  55658. showMenu (item);
  55659. }
  55660. else
  55661. {
  55662. updateItemUnderMouse (e2.x, e2.y);
  55663. }
  55664. lastMouseX = e2.x;
  55665. lastMouseY = e2.y;
  55666. }
  55667. }
  55668. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55669. {
  55670. bool used = false;
  55671. const int numMenus = menuNames.size();
  55672. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55673. if (key.isKeyCode (KeyPress::leftKey))
  55674. {
  55675. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55676. used = true;
  55677. }
  55678. else if (key.isKeyCode (KeyPress::rightKey))
  55679. {
  55680. showMenu ((currentIndex + 1) % numMenus);
  55681. used = true;
  55682. }
  55683. return used;
  55684. }
  55685. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55686. {
  55687. StringArray newNames;
  55688. if (model != 0)
  55689. newNames = model->getMenuBarNames();
  55690. if (newNames != menuNames)
  55691. {
  55692. menuNames = newNames;
  55693. repaint();
  55694. resized();
  55695. }
  55696. }
  55697. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55698. const ApplicationCommandTarget::InvocationInfo& info)
  55699. {
  55700. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55701. return;
  55702. for (int i = 0; i < menuNames.size(); ++i)
  55703. {
  55704. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55705. if (menu.containsCommandItem (info.commandID))
  55706. {
  55707. setItemUnderMouse (i);
  55708. startTimer (200);
  55709. break;
  55710. }
  55711. }
  55712. }
  55713. void MenuBarComponent::timerCallback()
  55714. {
  55715. stopTimer();
  55716. const Point<int> mousePos (getMouseXYRelative());
  55717. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55718. }
  55719. END_JUCE_NAMESPACE
  55720. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55721. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55722. BEGIN_JUCE_NAMESPACE
  55723. MenuBarModel::MenuBarModel() throw()
  55724. : manager (0)
  55725. {
  55726. }
  55727. MenuBarModel::~MenuBarModel()
  55728. {
  55729. setApplicationCommandManagerToWatch (0);
  55730. }
  55731. void MenuBarModel::menuItemsChanged()
  55732. {
  55733. triggerAsyncUpdate();
  55734. }
  55735. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55736. {
  55737. if (manager != newManager)
  55738. {
  55739. if (manager != 0)
  55740. manager->removeListener (this);
  55741. manager = newManager;
  55742. if (manager != 0)
  55743. manager->addListener (this);
  55744. }
  55745. }
  55746. void MenuBarModel::addListener (Listener* const newListener) throw()
  55747. {
  55748. listeners.add (newListener);
  55749. }
  55750. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55751. {
  55752. // Trying to remove a listener that isn't on the list!
  55753. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55754. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55755. jassert (listeners.contains (listenerToRemove));
  55756. listeners.remove (listenerToRemove);
  55757. }
  55758. void MenuBarModel::handleAsyncUpdate()
  55759. {
  55760. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55761. }
  55762. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55763. {
  55764. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55765. }
  55766. void MenuBarModel::applicationCommandListChanged()
  55767. {
  55768. menuItemsChanged();
  55769. }
  55770. END_JUCE_NAMESPACE
  55771. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55772. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55773. BEGIN_JUCE_NAMESPACE
  55774. class PopupMenu::Item
  55775. {
  55776. public:
  55777. Item()
  55778. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55779. usesColour (false), customComp (0), commandManager (0)
  55780. {
  55781. }
  55782. Item (const int itemId_,
  55783. const String& text_,
  55784. const bool active_,
  55785. const bool isTicked_,
  55786. const Image& im,
  55787. const Colour& textColour_,
  55788. const bool usesColour_,
  55789. PopupMenuCustomComponent* const customComp_,
  55790. const PopupMenu* const subMenu_,
  55791. ApplicationCommandManager* const commandManager_)
  55792. : itemId (itemId_), text (text_), textColour (textColour_),
  55793. active (active_), isSeparator (false), isTicked (isTicked_),
  55794. usesColour (usesColour_), image (im), customComp (customComp_),
  55795. commandManager (commandManager_)
  55796. {
  55797. if (subMenu_ != 0)
  55798. subMenu = new PopupMenu (*subMenu_);
  55799. if (commandManager_ != 0 && itemId_ != 0)
  55800. {
  55801. String shortcutKey;
  55802. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55803. ->getKeyPressesAssignedToCommand (itemId_));
  55804. for (int i = 0; i < keyPresses.size(); ++i)
  55805. {
  55806. const String key (keyPresses.getReference(i).getTextDescription());
  55807. if (shortcutKey.isNotEmpty())
  55808. shortcutKey << ", ";
  55809. if (key.length() == 1)
  55810. shortcutKey << "shortcut: '" << key << '\'';
  55811. else
  55812. shortcutKey << key;
  55813. }
  55814. shortcutKey = shortcutKey.trim();
  55815. if (shortcutKey.isNotEmpty())
  55816. text << "<end>" << shortcutKey;
  55817. }
  55818. }
  55819. Item (const Item& other)
  55820. : itemId (other.itemId),
  55821. text (other.text),
  55822. textColour (other.textColour),
  55823. active (other.active),
  55824. isSeparator (other.isSeparator),
  55825. isTicked (other.isTicked),
  55826. usesColour (other.usesColour),
  55827. image (other.image),
  55828. customComp (other.customComp),
  55829. commandManager (other.commandManager)
  55830. {
  55831. if (other.subMenu != 0)
  55832. subMenu = new PopupMenu (*(other.subMenu));
  55833. }
  55834. ~Item()
  55835. {
  55836. customComp = 0;
  55837. }
  55838. bool canBeTriggered() const throw()
  55839. {
  55840. return active && ! (isSeparator || (subMenu != 0));
  55841. }
  55842. bool hasActiveSubMenu() const throw()
  55843. {
  55844. return active && (subMenu != 0);
  55845. }
  55846. const int itemId;
  55847. String text;
  55848. const Colour textColour;
  55849. const bool active, isSeparator, isTicked, usesColour;
  55850. Image image;
  55851. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55852. ScopedPointer <PopupMenu> subMenu;
  55853. ApplicationCommandManager* const commandManager;
  55854. juce_UseDebuggingNewOperator
  55855. private:
  55856. Item& operator= (const Item&);
  55857. };
  55858. class PopupMenu::ItemComponent : public Component
  55859. {
  55860. public:
  55861. ItemComponent (const PopupMenu::Item& itemInfo_)
  55862. : itemInfo (itemInfo_),
  55863. isHighlighted (false)
  55864. {
  55865. if (itemInfo.customComp != 0)
  55866. addAndMakeVisible (itemInfo.customComp);
  55867. }
  55868. ~ItemComponent()
  55869. {
  55870. if (itemInfo.customComp != 0)
  55871. removeChildComponent (itemInfo.customComp);
  55872. }
  55873. void getIdealSize (int& idealWidth,
  55874. int& idealHeight,
  55875. const int standardItemHeight)
  55876. {
  55877. if (itemInfo.customComp != 0)
  55878. {
  55879. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55880. }
  55881. else
  55882. {
  55883. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55884. itemInfo.isSeparator,
  55885. standardItemHeight,
  55886. idealWidth,
  55887. idealHeight);
  55888. }
  55889. }
  55890. void paint (Graphics& g)
  55891. {
  55892. if (itemInfo.customComp == 0)
  55893. {
  55894. String mainText (itemInfo.text);
  55895. String endText;
  55896. const int endIndex = mainText.indexOf ("<end>");
  55897. if (endIndex >= 0)
  55898. {
  55899. endText = mainText.substring (endIndex + 5).trim();
  55900. mainText = mainText.substring (0, endIndex);
  55901. }
  55902. getLookAndFeel()
  55903. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55904. itemInfo.isSeparator,
  55905. itemInfo.active,
  55906. isHighlighted,
  55907. itemInfo.isTicked,
  55908. itemInfo.subMenu != 0,
  55909. mainText, endText,
  55910. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55911. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55912. }
  55913. }
  55914. void resized()
  55915. {
  55916. if (getNumChildComponents() > 0)
  55917. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55918. }
  55919. void setHighlighted (bool shouldBeHighlighted)
  55920. {
  55921. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55922. if (isHighlighted != shouldBeHighlighted)
  55923. {
  55924. isHighlighted = shouldBeHighlighted;
  55925. if (itemInfo.customComp != 0)
  55926. {
  55927. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55928. itemInfo.customComp->repaint();
  55929. }
  55930. repaint();
  55931. }
  55932. }
  55933. PopupMenu::Item itemInfo;
  55934. juce_UseDebuggingNewOperator
  55935. private:
  55936. bool isHighlighted;
  55937. ItemComponent (const ItemComponent&);
  55938. ItemComponent& operator= (const ItemComponent&);
  55939. };
  55940. namespace PopupMenuSettings
  55941. {
  55942. static const int scrollZone = 24;
  55943. static const int borderSize = 2;
  55944. static const int timerInterval = 50;
  55945. static const int dismissCommandId = 0x6287345f;
  55946. }
  55947. class PopupMenu::Window : public Component,
  55948. private Timer
  55949. {
  55950. public:
  55951. Window()
  55952. : Component ("menu"),
  55953. owner (0),
  55954. currentChild (0),
  55955. activeSubMenu (0),
  55956. managerOfChosenCommand (0),
  55957. minimumWidth (0),
  55958. maximumNumColumns (7),
  55959. standardItemHeight (0),
  55960. isOver (false),
  55961. hasBeenOver (false),
  55962. isDown (false),
  55963. needsToScroll (false),
  55964. hideOnExit (false),
  55965. disableMouseMoves (false),
  55966. hasAnyJuceCompHadFocus (false),
  55967. numColumns (0),
  55968. contentHeight (0),
  55969. childYOffset (0),
  55970. timeEnteredCurrentChildComp (0),
  55971. scrollAcceleration (1.0)
  55972. {
  55973. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55974. setWantsKeyboardFocus (true);
  55975. setMouseClickGrabsKeyboardFocus (false);
  55976. setOpaque (true);
  55977. setAlwaysOnTop (true);
  55978. Desktop::getInstance().addGlobalMouseListener (this);
  55979. getActiveWindows().add (this);
  55980. }
  55981. ~Window()
  55982. {
  55983. getActiveWindows().removeValue (this);
  55984. Desktop::getInstance().removeGlobalMouseListener (this);
  55985. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55986. activeSubMenu = 0;
  55987. deleteAllChildren();
  55988. }
  55989. static Window* create (const PopupMenu& menu,
  55990. const bool dismissOnMouseUp,
  55991. Window* const owner_,
  55992. const Rectangle<int>& target,
  55993. const int minimumWidth,
  55994. const int maximumNumColumns,
  55995. const int standardItemHeight,
  55996. const bool alignToRectangle,
  55997. const int itemIdThatMustBeVisible,
  55998. ApplicationCommandManager** managerOfChosenCommand,
  55999. Component* const componentAttachedTo)
  56000. {
  56001. if (menu.items.size() > 0)
  56002. {
  56003. int totalItems = 0;
  56004. ScopedPointer <Window> mw (new Window());
  56005. mw->setLookAndFeel (menu.lookAndFeel);
  56006. mw->setWantsKeyboardFocus (false);
  56007. mw->minimumWidth = minimumWidth;
  56008. mw->maximumNumColumns = maximumNumColumns;
  56009. mw->standardItemHeight = standardItemHeight;
  56010. mw->dismissOnMouseUp = dismissOnMouseUp;
  56011. for (int i = 0; i < menu.items.size(); ++i)
  56012. {
  56013. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  56014. mw->addItem (*item);
  56015. ++totalItems;
  56016. }
  56017. if (totalItems > 0)
  56018. {
  56019. mw->owner = owner_;
  56020. mw->managerOfChosenCommand = managerOfChosenCommand;
  56021. mw->componentAttachedTo = componentAttachedTo;
  56022. mw->componentAttachedToOriginal = componentAttachedTo;
  56023. mw->calculateWindowPos (target, alignToRectangle);
  56024. mw->setTopLeftPosition (mw->windowPos.getX(),
  56025. mw->windowPos.getY());
  56026. mw->updateYPositions();
  56027. if (itemIdThatMustBeVisible != 0)
  56028. {
  56029. const int y = target.getY() - mw->windowPos.getY();
  56030. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  56031. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  56032. }
  56033. mw->resizeToBestWindowPos();
  56034. mw->addToDesktop (ComponentPeer::windowIsTemporary
  56035. | mw->getLookAndFeel().getMenuWindowFlags());
  56036. return mw.release();
  56037. }
  56038. }
  56039. return 0;
  56040. }
  56041. void paint (Graphics& g)
  56042. {
  56043. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  56044. }
  56045. void paintOverChildren (Graphics& g)
  56046. {
  56047. if (isScrolling())
  56048. {
  56049. LookAndFeel& lf = getLookAndFeel();
  56050. if (isScrollZoneActive (false))
  56051. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  56052. if (isScrollZoneActive (true))
  56053. {
  56054. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  56055. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  56056. }
  56057. }
  56058. }
  56059. bool isScrollZoneActive (bool bottomOne) const
  56060. {
  56061. return isScrolling()
  56062. && (bottomOne
  56063. ? childYOffset < contentHeight - windowPos.getHeight()
  56064. : childYOffset > 0);
  56065. }
  56066. void addItem (const PopupMenu::Item& item)
  56067. {
  56068. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  56069. addAndMakeVisible (mic);
  56070. int itemW = 80;
  56071. int itemH = 16;
  56072. mic->getIdealSize (itemW, itemH, standardItemHeight);
  56073. mic->setSize (itemW, jlimit (2, 600, itemH));
  56074. mic->addMouseListener (this, false);
  56075. }
  56076. // hide this and all sub-comps
  56077. void hide (const PopupMenu::Item* const item)
  56078. {
  56079. if (isVisible())
  56080. {
  56081. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56082. activeSubMenu = 0;
  56083. currentChild = 0;
  56084. exitModalState (item != 0 ? item->itemId : 0);
  56085. setVisible (false);
  56086. if (item != 0
  56087. && item->commandManager != 0
  56088. && item->itemId != 0)
  56089. {
  56090. *managerOfChosenCommand = item->commandManager;
  56091. }
  56092. }
  56093. }
  56094. void dismissMenu (const PopupMenu::Item* const item)
  56095. {
  56096. if (owner != 0)
  56097. {
  56098. owner->dismissMenu (item);
  56099. }
  56100. else
  56101. {
  56102. if (item != 0)
  56103. {
  56104. // need a copy of this on the stack as the one passed in will get deleted during this call
  56105. const PopupMenu::Item mi (*item);
  56106. hide (&mi);
  56107. }
  56108. else
  56109. {
  56110. hide (0);
  56111. }
  56112. }
  56113. }
  56114. void mouseMove (const MouseEvent&)
  56115. {
  56116. timerCallback();
  56117. }
  56118. void mouseDown (const MouseEvent&)
  56119. {
  56120. timerCallback();
  56121. }
  56122. void mouseDrag (const MouseEvent&)
  56123. {
  56124. timerCallback();
  56125. }
  56126. void mouseUp (const MouseEvent&)
  56127. {
  56128. timerCallback();
  56129. }
  56130. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  56131. {
  56132. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  56133. lastMouse = Point<int> (-1, -1);
  56134. }
  56135. bool keyPressed (const KeyPress& key)
  56136. {
  56137. if (key.isKeyCode (KeyPress::downKey))
  56138. {
  56139. selectNextItem (1);
  56140. }
  56141. else if (key.isKeyCode (KeyPress::upKey))
  56142. {
  56143. selectNextItem (-1);
  56144. }
  56145. else if (key.isKeyCode (KeyPress::leftKey))
  56146. {
  56147. if (owner != 0)
  56148. {
  56149. Component::SafePointer<Window> parentWindow (owner);
  56150. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  56151. hide (0);
  56152. if (parentWindow != 0)
  56153. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  56154. disableTimerUntilMouseMoves();
  56155. }
  56156. else if (componentAttachedTo != 0)
  56157. {
  56158. componentAttachedTo->keyPressed (key);
  56159. }
  56160. }
  56161. else if (key.isKeyCode (KeyPress::rightKey))
  56162. {
  56163. disableTimerUntilMouseMoves();
  56164. if (showSubMenuFor (currentChild))
  56165. {
  56166. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56167. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  56168. activeSubMenu->selectNextItem (1);
  56169. }
  56170. else if (componentAttachedTo != 0)
  56171. {
  56172. componentAttachedTo->keyPressed (key);
  56173. }
  56174. }
  56175. else if (key.isKeyCode (KeyPress::returnKey))
  56176. {
  56177. triggerCurrentlyHighlightedItem();
  56178. }
  56179. else if (key.isKeyCode (KeyPress::escapeKey))
  56180. {
  56181. dismissMenu (0);
  56182. }
  56183. else
  56184. {
  56185. return false;
  56186. }
  56187. return true;
  56188. }
  56189. void inputAttemptWhenModal()
  56190. {
  56191. Component::SafePointer<Component> deletionChecker (this);
  56192. timerCallback();
  56193. if (deletionChecker != 0 && ! isOverAnyMenu())
  56194. {
  56195. if (componentAttachedTo != 0)
  56196. {
  56197. // we want to dismiss the menu, but if we do it synchronously, then
  56198. // the mouse-click will be allowed to pass through. That's good, except
  56199. // when the user clicks on the button that orginally popped the menu up,
  56200. // as they'll expect the menu to go away, and in fact it'll just
  56201. // come back. So only dismiss synchronously if they're not on the original
  56202. // comp that we're attached to.
  56203. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56204. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  56205. {
  56206. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56207. return;
  56208. }
  56209. }
  56210. dismissMenu (0);
  56211. }
  56212. }
  56213. void handleCommandMessage (int commandId)
  56214. {
  56215. Component::handleCommandMessage (commandId);
  56216. if (commandId == PopupMenuSettings::dismissCommandId)
  56217. dismissMenu (0);
  56218. }
  56219. void timerCallback()
  56220. {
  56221. if (! isVisible())
  56222. return;
  56223. if (componentAttachedTo != componentAttachedToOriginal)
  56224. {
  56225. dismissMenu (0);
  56226. return;
  56227. }
  56228. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56229. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56230. return;
  56231. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56232. // move rather than a real timer callback
  56233. const Point<int> globalMousePos (Desktop::getMousePosition());
  56234. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  56235. const uint32 now = Time::getMillisecondCounter();
  56236. if (now > timeEnteredCurrentChildComp + 100
  56237. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  56238. && currentChild->isValidComponent()
  56239. && (! disableMouseMoves)
  56240. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56241. {
  56242. showSubMenuFor (currentChild);
  56243. }
  56244. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56245. {
  56246. highlightItemUnderMouse (globalMousePos, localMousePos);
  56247. }
  56248. bool overScrollArea = false;
  56249. if (isScrolling()
  56250. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  56251. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56252. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56253. {
  56254. if (now > lastScroll + 20)
  56255. {
  56256. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56257. int amount = 0;
  56258. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  56259. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  56260. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56261. lastScroll = now;
  56262. }
  56263. overScrollArea = true;
  56264. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56265. }
  56266. else
  56267. {
  56268. scrollAcceleration = 1.0;
  56269. }
  56270. const bool wasDown = isDown;
  56271. bool isOverAny = isOverAnyMenu();
  56272. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56273. {
  56274. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56275. isOverAny = isOverAnyMenu();
  56276. }
  56277. if (hideOnExit && hasBeenOver && ! isOverAny)
  56278. {
  56279. hide (0);
  56280. }
  56281. else
  56282. {
  56283. isDown = hasBeenOver
  56284. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56285. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56286. bool anyFocused = Process::isForegroundProcess();
  56287. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56288. {
  56289. // because no component at all may have focus, our test here will
  56290. // only be triggered when something has focus and then loses it.
  56291. anyFocused = ! hasAnyJuceCompHadFocus;
  56292. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56293. {
  56294. if (ComponentPeer::getPeer (i)->isFocused())
  56295. {
  56296. anyFocused = true;
  56297. hasAnyJuceCompHadFocus = true;
  56298. break;
  56299. }
  56300. }
  56301. }
  56302. if (! anyFocused)
  56303. {
  56304. if (now > lastFocused + 10)
  56305. {
  56306. wasHiddenBecauseOfAppChange() = true;
  56307. dismissMenu (0);
  56308. return; // may have been deleted by the previous call..
  56309. }
  56310. }
  56311. else if (wasDown && now > menuCreationTime + 250
  56312. && ! (isDown || overScrollArea))
  56313. {
  56314. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56315. if (isOver)
  56316. {
  56317. triggerCurrentlyHighlightedItem();
  56318. }
  56319. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56320. {
  56321. dismissMenu (0);
  56322. }
  56323. return; // may have been deleted by the previous calls..
  56324. }
  56325. else
  56326. {
  56327. lastFocused = now;
  56328. }
  56329. }
  56330. }
  56331. static Array<Window*>& getActiveWindows()
  56332. {
  56333. static Array<Window*> activeMenuWindows;
  56334. return activeMenuWindows;
  56335. }
  56336. static bool& wasHiddenBecauseOfAppChange() throw()
  56337. {
  56338. static bool b = false;
  56339. return b;
  56340. }
  56341. juce_UseDebuggingNewOperator
  56342. private:
  56343. Window* owner;
  56344. PopupMenu::ItemComponent* currentChild;
  56345. ScopedPointer <Window> activeSubMenu;
  56346. ApplicationCommandManager** managerOfChosenCommand;
  56347. Component::SafePointer<Component> componentAttachedTo;
  56348. Component* componentAttachedToOriginal;
  56349. Rectangle<int> windowPos;
  56350. Point<int> lastMouse;
  56351. int minimumWidth, maximumNumColumns, standardItemHeight;
  56352. bool isOver, hasBeenOver, isDown, needsToScroll;
  56353. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56354. int numColumns, contentHeight, childYOffset;
  56355. Array <int> columnWidths;
  56356. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56357. double scrollAcceleration;
  56358. bool overlaps (const Rectangle<int>& r) const
  56359. {
  56360. return r.intersects (getBounds())
  56361. || (owner != 0 && owner->overlaps (r));
  56362. }
  56363. bool isOverAnyMenu() const
  56364. {
  56365. return (owner != 0) ? owner->isOverAnyMenu()
  56366. : isOverChildren();
  56367. }
  56368. bool isOverChildren() const
  56369. {
  56370. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56371. return isVisible()
  56372. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56373. }
  56374. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56375. {
  56376. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56377. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56378. if (activeSubMenu != 0)
  56379. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56380. }
  56381. bool treeContains (const Window* const window) const throw()
  56382. {
  56383. const Window* mw = this;
  56384. while (mw->owner != 0)
  56385. mw = mw->owner;
  56386. while (mw != 0)
  56387. {
  56388. if (mw == window)
  56389. return true;
  56390. mw = mw->activeSubMenu;
  56391. }
  56392. return false;
  56393. }
  56394. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56395. {
  56396. const Rectangle<int> mon (Desktop::getInstance()
  56397. .getMonitorAreaContaining (target.getCentre(),
  56398. #if JUCE_MAC
  56399. true));
  56400. #else
  56401. false)); // on windows, don't stop the menu overlapping the taskbar
  56402. #endif
  56403. int x, y, widthToUse, heightToUse;
  56404. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56405. if (alignToRectangle)
  56406. {
  56407. x = target.getX();
  56408. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56409. const int spaceOver = target.getY() - mon.getY();
  56410. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56411. y = target.getBottom();
  56412. else
  56413. y = target.getY() - heightToUse;
  56414. }
  56415. else
  56416. {
  56417. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56418. if (owner != 0)
  56419. {
  56420. if (owner->owner != 0)
  56421. {
  56422. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56423. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56424. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56425. tendTowardsRight = true;
  56426. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56427. tendTowardsRight = false;
  56428. }
  56429. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56430. {
  56431. tendTowardsRight = true;
  56432. }
  56433. }
  56434. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56435. target.getX() - mon.getX()) - 32;
  56436. if (biggestSpace < widthToUse)
  56437. {
  56438. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56439. if (numColumns > 1)
  56440. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56441. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56442. }
  56443. if (tendTowardsRight)
  56444. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56445. else
  56446. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56447. y = target.getY();
  56448. if (target.getCentreY() > mon.getCentreY())
  56449. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56450. }
  56451. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56452. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56453. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56454. // sets this flag if it's big enough to obscure any of its parent menus
  56455. hideOnExit = (owner != 0)
  56456. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56457. }
  56458. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56459. {
  56460. numColumns = 0;
  56461. contentHeight = 0;
  56462. const int maxMenuH = getParentHeight() - 24;
  56463. int totalW;
  56464. do
  56465. {
  56466. ++numColumns;
  56467. totalW = workOutBestSize (maxMenuW);
  56468. if (totalW > maxMenuW)
  56469. {
  56470. numColumns = jmax (1, numColumns - 1);
  56471. totalW = workOutBestSize (maxMenuW); // to update col widths
  56472. break;
  56473. }
  56474. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56475. {
  56476. break;
  56477. }
  56478. } while (numColumns < maximumNumColumns);
  56479. const int actualH = jmin (contentHeight, maxMenuH);
  56480. needsToScroll = contentHeight > actualH;
  56481. width = updateYPositions();
  56482. height = actualH + PopupMenuSettings::borderSize * 2;
  56483. }
  56484. int workOutBestSize (const int maxMenuW)
  56485. {
  56486. int totalW = 0;
  56487. contentHeight = 0;
  56488. int childNum = 0;
  56489. for (int col = 0; col < numColumns; ++col)
  56490. {
  56491. int i, colW = 50, colH = 0;
  56492. const int numChildren = jmin (getNumChildComponents() - childNum,
  56493. (getNumChildComponents() + numColumns - 1) / numColumns);
  56494. for (i = numChildren; --i >= 0;)
  56495. {
  56496. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56497. colH += getChildComponent (childNum + i)->getHeight();
  56498. }
  56499. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56500. columnWidths.set (col, colW);
  56501. totalW += colW;
  56502. contentHeight = jmax (contentHeight, colH);
  56503. childNum += numChildren;
  56504. }
  56505. if (totalW < minimumWidth)
  56506. {
  56507. totalW = minimumWidth;
  56508. for (int col = 0; col < numColumns; ++col)
  56509. columnWidths.set (0, totalW / numColumns);
  56510. }
  56511. return totalW;
  56512. }
  56513. void ensureItemIsVisible (const int itemId, int wantedY)
  56514. {
  56515. jassert (itemId != 0)
  56516. for (int i = getNumChildComponents(); --i >= 0;)
  56517. {
  56518. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56519. if (m != 0
  56520. && m->itemInfo.itemId == itemId
  56521. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56522. {
  56523. const int currentY = m->getY();
  56524. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56525. {
  56526. if (wantedY < 0)
  56527. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56528. jmax (PopupMenuSettings::scrollZone,
  56529. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56530. currentY);
  56531. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56532. int deltaY = wantedY - currentY;
  56533. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56534. jmin (windowPos.getHeight(), mon.getHeight()));
  56535. const int newY = jlimit (mon.getY(),
  56536. mon.getBottom() - windowPos.getHeight(),
  56537. windowPos.getY() + deltaY);
  56538. deltaY -= newY - windowPos.getY();
  56539. childYOffset -= deltaY;
  56540. windowPos.setPosition (windowPos.getX(), newY);
  56541. updateYPositions();
  56542. }
  56543. break;
  56544. }
  56545. }
  56546. }
  56547. void resizeToBestWindowPos()
  56548. {
  56549. Rectangle<int> r (windowPos);
  56550. if (childYOffset < 0)
  56551. {
  56552. r.setBounds (r.getX(), r.getY() - childYOffset,
  56553. r.getWidth(), r.getHeight() + childYOffset);
  56554. }
  56555. else if (childYOffset > 0)
  56556. {
  56557. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56558. if (spaceAtBottom > 0)
  56559. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56560. }
  56561. setBounds (r);
  56562. updateYPositions();
  56563. }
  56564. void alterChildYPos (const int delta)
  56565. {
  56566. if (isScrolling())
  56567. {
  56568. childYOffset += delta;
  56569. if (delta < 0)
  56570. {
  56571. childYOffset = jmax (childYOffset, 0);
  56572. }
  56573. else if (delta > 0)
  56574. {
  56575. childYOffset = jmin (childYOffset,
  56576. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56577. }
  56578. updateYPositions();
  56579. }
  56580. else
  56581. {
  56582. childYOffset = 0;
  56583. }
  56584. resizeToBestWindowPos();
  56585. repaint();
  56586. }
  56587. int updateYPositions()
  56588. {
  56589. int x = 0;
  56590. int childNum = 0;
  56591. for (int col = 0; col < numColumns; ++col)
  56592. {
  56593. const int numChildren = jmin (getNumChildComponents() - childNum,
  56594. (getNumChildComponents() + numColumns - 1) / numColumns);
  56595. const int colW = columnWidths [col];
  56596. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56597. for (int i = 0; i < numChildren; ++i)
  56598. {
  56599. Component* const c = getChildComponent (childNum + i);
  56600. c->setBounds (x, y, colW, c->getHeight());
  56601. y += c->getHeight();
  56602. }
  56603. x += colW;
  56604. childNum += numChildren;
  56605. }
  56606. return x;
  56607. }
  56608. bool isScrolling() const throw()
  56609. {
  56610. return childYOffset != 0 || needsToScroll;
  56611. }
  56612. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56613. {
  56614. if (currentChild->isValidComponent())
  56615. currentChild->setHighlighted (false);
  56616. currentChild = child;
  56617. if (currentChild != 0)
  56618. {
  56619. currentChild->setHighlighted (true);
  56620. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56621. }
  56622. }
  56623. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56624. {
  56625. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56626. activeSubMenu = 0;
  56627. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56628. {
  56629. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56630. dismissOnMouseUp,
  56631. this,
  56632. childComp->getScreenBounds(),
  56633. 0, maximumNumColumns,
  56634. standardItemHeight,
  56635. false, 0, managerOfChosenCommand,
  56636. componentAttachedTo);
  56637. if (activeSubMenu != 0)
  56638. {
  56639. activeSubMenu->setVisible (true);
  56640. activeSubMenu->enterModalState (false);
  56641. activeSubMenu->toFront (false);
  56642. return true;
  56643. }
  56644. }
  56645. return false;
  56646. }
  56647. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56648. {
  56649. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56650. if (isOver)
  56651. hasBeenOver = true;
  56652. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56653. {
  56654. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56655. if (disableMouseMoves && isOver)
  56656. disableMouseMoves = false;
  56657. }
  56658. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56659. return;
  56660. bool isMovingTowardsMenu = false;
  56661. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56662. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56663. {
  56664. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56665. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56666. // extends from the last mouse pos to the submenu's rectangle..
  56667. float subX = (float) activeSubMenu->getScreenX();
  56668. if (activeSubMenu->getX() > getX())
  56669. {
  56670. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56671. }
  56672. else
  56673. {
  56674. lastMouse += Point<int> (2, 0);
  56675. subX += activeSubMenu->getWidth();
  56676. }
  56677. Path areaTowardsSubMenu;
  56678. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56679. (float) lastMouse.getY(),
  56680. subX,
  56681. (float) activeSubMenu->getScreenY(),
  56682. subX,
  56683. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56684. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56685. }
  56686. lastMouse = globalMousePos;
  56687. if (! isMovingTowardsMenu)
  56688. {
  56689. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56690. if (c == this)
  56691. c = 0;
  56692. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56693. if (mic == 0 && c != 0)
  56694. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56695. if (mic != currentChild
  56696. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56697. {
  56698. if (isOver && (c != 0) && (activeSubMenu != 0))
  56699. {
  56700. activeSubMenu->hide (0);
  56701. }
  56702. if (! isOver)
  56703. mic = 0;
  56704. setCurrentlyHighlightedChild (mic);
  56705. }
  56706. }
  56707. }
  56708. void triggerCurrentlyHighlightedItem()
  56709. {
  56710. if (currentChild->isValidComponent()
  56711. && currentChild->itemInfo.canBeTriggered()
  56712. && (currentChild->itemInfo.customComp == 0
  56713. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56714. {
  56715. dismissMenu (&currentChild->itemInfo);
  56716. }
  56717. }
  56718. void selectNextItem (const int delta)
  56719. {
  56720. disableTimerUntilMouseMoves();
  56721. PopupMenu::ItemComponent* mic = 0;
  56722. bool wasLastOne = (currentChild == 0);
  56723. const int numItems = getNumChildComponents();
  56724. for (int i = 0; i < numItems + 1; ++i)
  56725. {
  56726. int index = (delta > 0) ? i : (numItems - 1 - i);
  56727. index = (index + numItems) % numItems;
  56728. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56729. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56730. && wasLastOne)
  56731. break;
  56732. if (mic == currentChild)
  56733. wasLastOne = true;
  56734. }
  56735. setCurrentlyHighlightedChild (mic);
  56736. }
  56737. void disableTimerUntilMouseMoves()
  56738. {
  56739. disableMouseMoves = true;
  56740. if (owner != 0)
  56741. owner->disableTimerUntilMouseMoves();
  56742. }
  56743. Window (const Window&);
  56744. Window& operator= (const Window&);
  56745. };
  56746. PopupMenu::PopupMenu()
  56747. : lookAndFeel (0),
  56748. separatorPending (false)
  56749. {
  56750. }
  56751. PopupMenu::PopupMenu (const PopupMenu& other)
  56752. : lookAndFeel (other.lookAndFeel),
  56753. separatorPending (false)
  56754. {
  56755. items.addCopiesOf (other.items);
  56756. }
  56757. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56758. {
  56759. if (this != &other)
  56760. {
  56761. lookAndFeel = other.lookAndFeel;
  56762. clear();
  56763. items.addCopiesOf (other.items);
  56764. }
  56765. return *this;
  56766. }
  56767. PopupMenu::~PopupMenu()
  56768. {
  56769. clear();
  56770. }
  56771. void PopupMenu::clear()
  56772. {
  56773. items.clear();
  56774. separatorPending = false;
  56775. }
  56776. void PopupMenu::addSeparatorIfPending()
  56777. {
  56778. if (separatorPending)
  56779. {
  56780. separatorPending = false;
  56781. if (items.size() > 0)
  56782. items.add (new Item());
  56783. }
  56784. }
  56785. void PopupMenu::addItem (const int itemResultId,
  56786. const String& itemText,
  56787. const bool isActive,
  56788. const bool isTicked,
  56789. const Image& iconToUse)
  56790. {
  56791. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56792. // didn't pick anything, so you shouldn't use it as the id
  56793. // for an item..
  56794. addSeparatorIfPending();
  56795. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56796. Colours::black, false, 0, 0, 0));
  56797. }
  56798. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56799. const int commandID,
  56800. const String& displayName)
  56801. {
  56802. jassert (commandManager != 0 && commandID != 0);
  56803. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56804. if (registeredInfo != 0)
  56805. {
  56806. ApplicationCommandInfo info (*registeredInfo);
  56807. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56808. addSeparatorIfPending();
  56809. items.add (new Item (commandID,
  56810. displayName.isNotEmpty() ? displayName
  56811. : info.shortName,
  56812. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56813. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56814. Image::null,
  56815. Colours::black,
  56816. false,
  56817. 0, 0,
  56818. commandManager));
  56819. }
  56820. }
  56821. void PopupMenu::addColouredItem (const int itemResultId,
  56822. const String& itemText,
  56823. const Colour& itemTextColour,
  56824. const bool isActive,
  56825. const bool isTicked,
  56826. const Image& iconToUse)
  56827. {
  56828. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56829. // didn't pick anything, so you shouldn't use it as the id
  56830. // for an item..
  56831. addSeparatorIfPending();
  56832. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56833. itemTextColour, true, 0, 0, 0));
  56834. }
  56835. void PopupMenu::addCustomItem (const int itemResultId,
  56836. PopupMenuCustomComponent* const customComponent)
  56837. {
  56838. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56839. // didn't pick anything, so you shouldn't use it as the id
  56840. // for an item..
  56841. addSeparatorIfPending();
  56842. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56843. Colours::black, false, customComponent, 0, 0));
  56844. }
  56845. class NormalComponentWrapper : public PopupMenuCustomComponent
  56846. {
  56847. public:
  56848. NormalComponentWrapper (Component* const comp,
  56849. const int w, const int h,
  56850. const bool triggerMenuItemAutomaticallyWhenClicked)
  56851. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56852. width (w),
  56853. height (h)
  56854. {
  56855. addAndMakeVisible (comp);
  56856. }
  56857. ~NormalComponentWrapper() {}
  56858. void getIdealSize (int& idealWidth, int& idealHeight)
  56859. {
  56860. idealWidth = width;
  56861. idealHeight = height;
  56862. }
  56863. void resized()
  56864. {
  56865. if (getChildComponent(0) != 0)
  56866. getChildComponent(0)->setBounds (getLocalBounds());
  56867. }
  56868. juce_UseDebuggingNewOperator
  56869. private:
  56870. const int width, height;
  56871. NormalComponentWrapper (const NormalComponentWrapper&);
  56872. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56873. };
  56874. void PopupMenu::addCustomItem (const int itemResultId,
  56875. Component* customComponent,
  56876. int idealWidth, int idealHeight,
  56877. const bool triggerMenuItemAutomaticallyWhenClicked)
  56878. {
  56879. addCustomItem (itemResultId,
  56880. new NormalComponentWrapper (customComponent,
  56881. idealWidth, idealHeight,
  56882. triggerMenuItemAutomaticallyWhenClicked));
  56883. }
  56884. void PopupMenu::addSubMenu (const String& subMenuName,
  56885. const PopupMenu& subMenu,
  56886. const bool isActive,
  56887. const Image& iconToUse,
  56888. const bool isTicked)
  56889. {
  56890. addSeparatorIfPending();
  56891. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56892. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56893. }
  56894. void PopupMenu::addSeparator()
  56895. {
  56896. separatorPending = true;
  56897. }
  56898. class HeaderItemComponent : public PopupMenuCustomComponent
  56899. {
  56900. public:
  56901. HeaderItemComponent (const String& name)
  56902. : PopupMenuCustomComponent (false)
  56903. {
  56904. setName (name);
  56905. }
  56906. ~HeaderItemComponent()
  56907. {
  56908. }
  56909. void paint (Graphics& g)
  56910. {
  56911. Font f (getLookAndFeel().getPopupMenuFont());
  56912. f.setBold (true);
  56913. g.setFont (f);
  56914. g.setColour (findColour (PopupMenu::headerTextColourId));
  56915. g.drawFittedText (getName(),
  56916. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56917. Justification::bottomLeft, 1);
  56918. }
  56919. void getIdealSize (int& idealWidth,
  56920. int& idealHeight)
  56921. {
  56922. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56923. idealHeight += idealHeight / 2;
  56924. idealWidth += idealWidth / 4;
  56925. }
  56926. juce_UseDebuggingNewOperator
  56927. };
  56928. void PopupMenu::addSectionHeader (const String& title)
  56929. {
  56930. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56931. }
  56932. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56933. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56934. {
  56935. public:
  56936. PopupMenuCompletionCallback()
  56937. : managerOfChosenCommand (0)
  56938. {
  56939. }
  56940. ~PopupMenuCompletionCallback() {}
  56941. void modalStateFinished (int result)
  56942. {
  56943. if (managerOfChosenCommand != 0 && result != 0)
  56944. {
  56945. ApplicationCommandTarget::InvocationInfo info (result);
  56946. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56947. managerOfChosenCommand->invoke (info, true);
  56948. }
  56949. }
  56950. ApplicationCommandManager* managerOfChosenCommand;
  56951. ScopedPointer<Component> component;
  56952. private:
  56953. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56954. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56955. };
  56956. int PopupMenu::showMenu (const Rectangle<int>& target,
  56957. const int itemIdThatMustBeVisible,
  56958. const int minimumWidth,
  56959. const int maximumNumColumns,
  56960. const int standardItemHeight,
  56961. const bool alignToRectangle,
  56962. Component* const componentAttachedTo,
  56963. ModalComponentManager::Callback* userCallback)
  56964. {
  56965. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56966. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56967. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56968. Window::wasHiddenBecauseOfAppChange() = false;
  56969. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56970. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56971. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56972. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56973. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56974. &callback->managerOfChosenCommand, componentAttachedTo);
  56975. if (callback->component == 0)
  56976. return 0;
  56977. callbackDeleter.release();
  56978. callback->component->enterModalState (false, userCallbackDeleter.release());
  56979. callback->component->toFront (false); // need to do this after making it modal, or it could
  56980. // be stuck behind other comps that are already modal..
  56981. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56982. if (userCallback != 0)
  56983. return 0;
  56984. const int result = callback->component->runModalLoop();
  56985. if (! Window::wasHiddenBecauseOfAppChange())
  56986. {
  56987. if (prevTopLevel != 0)
  56988. prevTopLevel->toFront (true);
  56989. if (prevFocused != 0)
  56990. prevFocused->grabKeyboardFocus();
  56991. }
  56992. return result;
  56993. }
  56994. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56995. const int minimumWidth,
  56996. const int maximumNumColumns,
  56997. const int standardItemHeight,
  56998. ModalComponentManager::Callback* callback)
  56999. {
  57000. const Point<int> mousePos (Desktop::getMousePosition());
  57001. return showAt (mousePos.getX(), mousePos.getY(),
  57002. itemIdThatMustBeVisible,
  57003. minimumWidth,
  57004. maximumNumColumns,
  57005. standardItemHeight,
  57006. callback);
  57007. }
  57008. int PopupMenu::showAt (const int screenX,
  57009. const int screenY,
  57010. const int itemIdThatMustBeVisible,
  57011. const int minimumWidth,
  57012. const int maximumNumColumns,
  57013. const int standardItemHeight,
  57014. ModalComponentManager::Callback* callback)
  57015. {
  57016. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  57017. itemIdThatMustBeVisible,
  57018. minimumWidth, maximumNumColumns,
  57019. standardItemHeight,
  57020. false, 0, callback);
  57021. }
  57022. int PopupMenu::showAt (Component* componentToAttachTo,
  57023. const int itemIdThatMustBeVisible,
  57024. const int minimumWidth,
  57025. const int maximumNumColumns,
  57026. const int standardItemHeight,
  57027. ModalComponentManager::Callback* callback)
  57028. {
  57029. if (componentToAttachTo != 0)
  57030. {
  57031. return showMenu (componentToAttachTo->getScreenBounds(),
  57032. itemIdThatMustBeVisible,
  57033. minimumWidth,
  57034. maximumNumColumns,
  57035. standardItemHeight,
  57036. true, componentToAttachTo, callback);
  57037. }
  57038. else
  57039. {
  57040. return show (itemIdThatMustBeVisible,
  57041. minimumWidth,
  57042. maximumNumColumns,
  57043. standardItemHeight,
  57044. callback);
  57045. }
  57046. }
  57047. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  57048. {
  57049. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  57050. {
  57051. Window* const pmw = Window::getActiveWindows()[i];
  57052. if (pmw != 0)
  57053. pmw->dismissMenu (0);
  57054. }
  57055. }
  57056. int PopupMenu::getNumItems() const throw()
  57057. {
  57058. int num = 0;
  57059. for (int i = items.size(); --i >= 0;)
  57060. if (! (items.getUnchecked(i))->isSeparator)
  57061. ++num;
  57062. return num;
  57063. }
  57064. bool PopupMenu::containsCommandItem (const int commandID) const
  57065. {
  57066. for (int i = items.size(); --i >= 0;)
  57067. {
  57068. const Item* mi = items.getUnchecked (i);
  57069. if ((mi->itemId == commandID && mi->commandManager != 0)
  57070. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  57071. {
  57072. return true;
  57073. }
  57074. }
  57075. return false;
  57076. }
  57077. bool PopupMenu::containsAnyActiveItems() const throw()
  57078. {
  57079. for (int i = items.size(); --i >= 0;)
  57080. {
  57081. const Item* const mi = items.getUnchecked (i);
  57082. if (mi->subMenu != 0)
  57083. {
  57084. if (mi->subMenu->containsAnyActiveItems())
  57085. return true;
  57086. }
  57087. else if (mi->active)
  57088. {
  57089. return true;
  57090. }
  57091. }
  57092. return false;
  57093. }
  57094. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  57095. {
  57096. lookAndFeel = newLookAndFeel;
  57097. }
  57098. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  57099. : isHighlighted (false),
  57100. isTriggeredAutomatically (isTriggeredAutomatically_)
  57101. {
  57102. }
  57103. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  57104. {
  57105. }
  57106. void PopupMenuCustomComponent::triggerMenuItem()
  57107. {
  57108. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  57109. if (mic != 0)
  57110. {
  57111. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  57112. if (pmw != 0)
  57113. {
  57114. pmw->dismissMenu (&mic->itemInfo);
  57115. }
  57116. else
  57117. {
  57118. // something must have gone wrong with the component hierarchy if this happens..
  57119. jassertfalse;
  57120. }
  57121. }
  57122. else
  57123. {
  57124. // why isn't this component inside a menu? Not much point triggering the item if
  57125. // there's no menu.
  57126. jassertfalse;
  57127. }
  57128. }
  57129. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  57130. : subMenu (0),
  57131. itemId (0),
  57132. isSeparator (false),
  57133. isTicked (false),
  57134. isEnabled (false),
  57135. isCustomComponent (false),
  57136. isSectionHeader (false),
  57137. customColour (0),
  57138. customImage (0),
  57139. menu (menu_),
  57140. index (0)
  57141. {
  57142. }
  57143. PopupMenu::MenuItemIterator::~MenuItemIterator()
  57144. {
  57145. }
  57146. bool PopupMenu::MenuItemIterator::next()
  57147. {
  57148. if (index >= menu.items.size())
  57149. return false;
  57150. const Item* const item = menu.items.getUnchecked (index);
  57151. ++index;
  57152. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  57153. subMenu = item->subMenu;
  57154. itemId = item->itemId;
  57155. isSeparator = item->isSeparator;
  57156. isTicked = item->isTicked;
  57157. isEnabled = item->active;
  57158. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  57159. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  57160. customColour = item->usesColour ? &(item->textColour) : 0;
  57161. customImage = item->image;
  57162. commandManager = item->commandManager;
  57163. return true;
  57164. }
  57165. END_JUCE_NAMESPACE
  57166. /*** End of inlined file: juce_PopupMenu.cpp ***/
  57167. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  57168. BEGIN_JUCE_NAMESPACE
  57169. ComponentDragger::ComponentDragger()
  57170. : constrainer (0)
  57171. {
  57172. }
  57173. ComponentDragger::~ComponentDragger()
  57174. {
  57175. }
  57176. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  57177. ComponentBoundsConstrainer* const constrainer_)
  57178. {
  57179. jassert (componentToDrag->isValidComponent());
  57180. if (componentToDrag != 0)
  57181. {
  57182. constrainer = constrainer_;
  57183. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  57184. }
  57185. }
  57186. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  57187. {
  57188. jassert (componentToDrag->isValidComponent());
  57189. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  57190. if (componentToDrag != 0)
  57191. {
  57192. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  57193. const Component* const parentComp = componentToDrag->getParentComponent();
  57194. if (parentComp != 0)
  57195. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  57196. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  57197. if (constrainer != 0)
  57198. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57199. else
  57200. componentToDrag->setBounds (bounds);
  57201. }
  57202. }
  57203. END_JUCE_NAMESPACE
  57204. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57205. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57206. BEGIN_JUCE_NAMESPACE
  57207. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57208. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57209. class DragImageComponent : public Component,
  57210. public Timer
  57211. {
  57212. public:
  57213. DragImageComponent (const Image& im,
  57214. const String& desc,
  57215. Component* const sourceComponent,
  57216. Component* const mouseDragSource_,
  57217. DragAndDropContainer* const o,
  57218. const Point<int>& imageOffset_)
  57219. : image (im),
  57220. source (sourceComponent),
  57221. mouseDragSource (mouseDragSource_),
  57222. owner (o),
  57223. dragDesc (desc),
  57224. imageOffset (imageOffset_),
  57225. hasCheckedForExternalDrag (false),
  57226. drawImage (true)
  57227. {
  57228. setSize (im.getWidth(), im.getHeight());
  57229. if (mouseDragSource == 0)
  57230. mouseDragSource = source;
  57231. mouseDragSource->addMouseListener (this, false);
  57232. startTimer (200);
  57233. setInterceptsMouseClicks (false, false);
  57234. setAlwaysOnTop (true);
  57235. }
  57236. ~DragImageComponent()
  57237. {
  57238. if (owner->dragImageComponent == this)
  57239. owner->dragImageComponent.release();
  57240. if (mouseDragSource != 0)
  57241. {
  57242. mouseDragSource->removeMouseListener (this);
  57243. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57244. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57245. }
  57246. }
  57247. void paint (Graphics& g)
  57248. {
  57249. if (isOpaque())
  57250. g.fillAll (Colours::white);
  57251. if (drawImage)
  57252. {
  57253. g.setOpacity (1.0f);
  57254. g.drawImageAt (image, 0, 0);
  57255. }
  57256. }
  57257. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57258. {
  57259. Component* hit = getParentComponent();
  57260. if (hit == 0)
  57261. {
  57262. hit = Desktop::getInstance().findComponentAt (screenPos);
  57263. }
  57264. else
  57265. {
  57266. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  57267. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57268. }
  57269. // (note: use a local copy of the dragDesc member in case the callback runs
  57270. // a modal loop and deletes this object before the method completes)
  57271. const String dragDescLocal (dragDesc);
  57272. while (hit != 0)
  57273. {
  57274. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57275. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57276. {
  57277. relativePos = hit->globalPositionToRelative (screenPos);
  57278. return ddt;
  57279. }
  57280. hit = hit->getParentComponent();
  57281. }
  57282. return 0;
  57283. }
  57284. void mouseUp (const MouseEvent& e)
  57285. {
  57286. if (e.originalComponent != this)
  57287. {
  57288. if (mouseDragSource != 0)
  57289. mouseDragSource->removeMouseListener (this);
  57290. bool dropAccepted = false;
  57291. DragAndDropTarget* ddt = 0;
  57292. Point<int> relPos;
  57293. if (isVisible())
  57294. {
  57295. setVisible (false);
  57296. ddt = findTarget (e.getScreenPosition(), relPos);
  57297. // fade this component and remove it - it'll be deleted later by the timer callback
  57298. dropAccepted = ddt != 0;
  57299. setVisible (true);
  57300. if (dropAccepted || source == 0)
  57301. {
  57302. fadeOutComponent (120);
  57303. }
  57304. else
  57305. {
  57306. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  57307. source->getHeight() / 2)));
  57308. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  57309. getHeight() / 2)));
  57310. fadeOutComponent (120,
  57311. target.getX() - ourCentre.getX(),
  57312. target.getY() - ourCentre.getY());
  57313. }
  57314. }
  57315. if (getParentComponent() != 0)
  57316. getParentComponent()->removeChildComponent (this);
  57317. if (dropAccepted && ddt != 0)
  57318. {
  57319. // (note: use a local copy of the dragDesc member in case the callback runs
  57320. // a modal loop and deletes this object before the method completes)
  57321. const String dragDescLocal (dragDesc);
  57322. currentlyOverComp = 0;
  57323. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57324. }
  57325. // careful - this object could now be deleted..
  57326. }
  57327. }
  57328. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57329. {
  57330. // (note: use a local copy of the dragDesc member in case the callback runs
  57331. // a modal loop and deletes this object before it returns)
  57332. const String dragDescLocal (dragDesc);
  57333. Point<int> newPos (screenPos + imageOffset);
  57334. if (getParentComponent() != 0)
  57335. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57336. //if (newX != getX() || newY != getY())
  57337. {
  57338. setTopLeftPosition (newPos.getX(), newPos.getY());
  57339. Point<int> relPos;
  57340. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57341. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57342. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57343. if (ddtComp != currentlyOverComp)
  57344. {
  57345. if (currentlyOverComp != 0 && source != 0
  57346. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57347. {
  57348. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57349. }
  57350. currentlyOverComp = ddtComp;
  57351. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57352. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57353. }
  57354. DragAndDropTarget* target = getCurrentlyOver();
  57355. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57356. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57357. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57358. {
  57359. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57360. {
  57361. hasCheckedForExternalDrag = true;
  57362. StringArray files;
  57363. bool canMoveFiles = false;
  57364. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57365. && files.size() > 0)
  57366. {
  57367. Component::SafePointer<Component> cdw (this);
  57368. setVisible (false);
  57369. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57370. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57371. if (cdw != 0)
  57372. delete this;
  57373. return;
  57374. }
  57375. }
  57376. }
  57377. }
  57378. }
  57379. void mouseDrag (const MouseEvent& e)
  57380. {
  57381. if (e.originalComponent != this)
  57382. updateLocation (true, e.getScreenPosition());
  57383. }
  57384. void timerCallback()
  57385. {
  57386. if (source == 0)
  57387. {
  57388. delete this;
  57389. }
  57390. else if (! isMouseButtonDownAnywhere())
  57391. {
  57392. if (mouseDragSource != 0)
  57393. mouseDragSource->removeMouseListener (this);
  57394. delete this;
  57395. }
  57396. }
  57397. private:
  57398. Image image;
  57399. Component::SafePointer<Component> source;
  57400. Component::SafePointer<Component> mouseDragSource;
  57401. DragAndDropContainer* const owner;
  57402. Component::SafePointer<Component> currentlyOverComp;
  57403. DragAndDropTarget* getCurrentlyOver()
  57404. {
  57405. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57406. }
  57407. String dragDesc;
  57408. const Point<int> imageOffset;
  57409. bool hasCheckedForExternalDrag, drawImage;
  57410. DragImageComponent (const DragImageComponent&);
  57411. DragImageComponent& operator= (const DragImageComponent&);
  57412. };
  57413. DragAndDropContainer::DragAndDropContainer()
  57414. {
  57415. }
  57416. DragAndDropContainer::~DragAndDropContainer()
  57417. {
  57418. dragImageComponent = 0;
  57419. }
  57420. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57421. Component* sourceComponent,
  57422. const Image& dragImage_,
  57423. const bool allowDraggingToExternalWindows,
  57424. const Point<int>* imageOffsetFromMouse)
  57425. {
  57426. Image dragImage (dragImage_);
  57427. if (dragImageComponent == 0)
  57428. {
  57429. Component* const thisComp = dynamic_cast <Component*> (this);
  57430. if (thisComp == 0)
  57431. {
  57432. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57433. return;
  57434. }
  57435. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57436. if (draggingSource == 0 || ! draggingSource->isDragging())
  57437. {
  57438. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57439. return;
  57440. }
  57441. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57442. Point<int> imageOffset;
  57443. if (dragImage.isNull())
  57444. {
  57445. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57446. .convertedToFormat (Image::ARGB);
  57447. dragImage.multiplyAllAlphas (0.6f);
  57448. const int lo = 150;
  57449. const int hi = 400;
  57450. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57451. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57452. for (int y = dragImage.getHeight(); --y >= 0;)
  57453. {
  57454. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57455. for (int x = dragImage.getWidth(); --x >= 0;)
  57456. {
  57457. const int dx = x - clipped.getX();
  57458. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57459. if (distance > lo)
  57460. {
  57461. const float alpha = (distance > hi) ? 0
  57462. : (hi - distance) / (float) (hi - lo)
  57463. + Random::getSystemRandom().nextFloat() * 0.008f;
  57464. dragImage.multiplyAlphaAt (x, y, alpha);
  57465. }
  57466. }
  57467. }
  57468. imageOffset = -clipped;
  57469. }
  57470. else
  57471. {
  57472. if (imageOffsetFromMouse == 0)
  57473. imageOffset = -dragImage.getBounds().getCentre();
  57474. else
  57475. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57476. }
  57477. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57478. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57479. currentDragDesc = sourceDescription;
  57480. if (allowDraggingToExternalWindows)
  57481. {
  57482. if (! Desktop::canUseSemiTransparentWindows())
  57483. dragImageComponent->setOpaque (true);
  57484. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57485. | ComponentPeer::windowIsTemporary
  57486. | ComponentPeer::windowIgnoresKeyPresses);
  57487. }
  57488. else
  57489. thisComp->addChildComponent (dragImageComponent);
  57490. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57491. dragImageComponent->setVisible (true);
  57492. }
  57493. }
  57494. bool DragAndDropContainer::isDragAndDropActive() const
  57495. {
  57496. return dragImageComponent != 0;
  57497. }
  57498. const String DragAndDropContainer::getCurrentDragDescription() const
  57499. {
  57500. return (dragImageComponent != 0) ? currentDragDesc
  57501. : String::empty;
  57502. }
  57503. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57504. {
  57505. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57506. }
  57507. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57508. {
  57509. return false;
  57510. }
  57511. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57512. {
  57513. }
  57514. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57515. {
  57516. }
  57517. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57518. {
  57519. }
  57520. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57521. {
  57522. return true;
  57523. }
  57524. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57525. {
  57526. }
  57527. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57528. {
  57529. }
  57530. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57531. {
  57532. }
  57533. END_JUCE_NAMESPACE
  57534. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57535. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57536. BEGIN_JUCE_NAMESPACE
  57537. class MouseCursor::SharedCursorHandle
  57538. {
  57539. public:
  57540. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57541. : handle (createStandardMouseCursor (type)),
  57542. refCount (1),
  57543. standardType (type),
  57544. isStandard (true)
  57545. {
  57546. }
  57547. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57548. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57549. refCount (1),
  57550. standardType (MouseCursor::NormalCursor),
  57551. isStandard (false)
  57552. {
  57553. }
  57554. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57555. {
  57556. const ScopedLock sl (getLock());
  57557. for (int i = 0; i < getCursors().size(); ++i)
  57558. {
  57559. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57560. if (sc->standardType == type)
  57561. return sc->retain();
  57562. }
  57563. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57564. getCursors().add (sc);
  57565. return sc;
  57566. }
  57567. SharedCursorHandle* retain() throw()
  57568. {
  57569. ++refCount;
  57570. return this;
  57571. }
  57572. void release()
  57573. {
  57574. if (--refCount == 0)
  57575. {
  57576. if (isStandard)
  57577. {
  57578. const ScopedLock sl (getLock());
  57579. getCursors().removeValue (this);
  57580. }
  57581. delete this;
  57582. }
  57583. }
  57584. void* getHandle() const throw() { return handle; }
  57585. juce_UseDebuggingNewOperator
  57586. private:
  57587. void* const handle;
  57588. Atomic <int> refCount;
  57589. const MouseCursor::StandardCursorType standardType;
  57590. const bool isStandard;
  57591. static CriticalSection& getLock()
  57592. {
  57593. static CriticalSection lock;
  57594. return lock;
  57595. }
  57596. static Array <SharedCursorHandle*>& getCursors()
  57597. {
  57598. static Array <SharedCursorHandle*> cursors;
  57599. return cursors;
  57600. }
  57601. ~SharedCursorHandle()
  57602. {
  57603. deleteMouseCursor (handle, isStandard);
  57604. }
  57605. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57606. };
  57607. MouseCursor::MouseCursor()
  57608. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57609. {
  57610. jassert (cursorHandle != 0);
  57611. }
  57612. MouseCursor::MouseCursor (const StandardCursorType type)
  57613. : cursorHandle (SharedCursorHandle::createStandard (type))
  57614. {
  57615. jassert (cursorHandle != 0);
  57616. }
  57617. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57618. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57619. {
  57620. }
  57621. MouseCursor::MouseCursor (const MouseCursor& other)
  57622. : cursorHandle (other.cursorHandle->retain())
  57623. {
  57624. }
  57625. MouseCursor::~MouseCursor()
  57626. {
  57627. cursorHandle->release();
  57628. }
  57629. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57630. {
  57631. other.cursorHandle->retain();
  57632. cursorHandle->release();
  57633. cursorHandle = other.cursorHandle;
  57634. return *this;
  57635. }
  57636. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57637. {
  57638. return getHandle() == other.getHandle();
  57639. }
  57640. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57641. {
  57642. return getHandle() != other.getHandle();
  57643. }
  57644. void* MouseCursor::getHandle() const throw()
  57645. {
  57646. return cursorHandle->getHandle();
  57647. }
  57648. void MouseCursor::showWaitCursor()
  57649. {
  57650. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57651. }
  57652. void MouseCursor::hideWaitCursor()
  57653. {
  57654. Desktop::getInstance().getMainMouseSource().revealCursor();
  57655. }
  57656. END_JUCE_NAMESPACE
  57657. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57658. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57659. BEGIN_JUCE_NAMESPACE
  57660. MouseEvent::MouseEvent (MouseInputSource& source_,
  57661. const Point<int>& position,
  57662. const ModifierKeys& mods_,
  57663. Component* const eventComponent_,
  57664. Component* const originator,
  57665. const Time& eventTime_,
  57666. const Point<int> mouseDownPos_,
  57667. const Time& mouseDownTime_,
  57668. const int numberOfClicks_,
  57669. const bool mouseWasDragged) throw()
  57670. : x (position.getX()),
  57671. y (position.getY()),
  57672. mods (mods_),
  57673. eventComponent (eventComponent_),
  57674. originalComponent (originator),
  57675. eventTime (eventTime_),
  57676. source (source_),
  57677. mouseDownPos (mouseDownPos_),
  57678. mouseDownTime (mouseDownTime_),
  57679. numberOfClicks (numberOfClicks_),
  57680. wasMovedSinceMouseDown (mouseWasDragged)
  57681. {
  57682. }
  57683. MouseEvent::~MouseEvent() throw()
  57684. {
  57685. }
  57686. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57687. {
  57688. if (otherComponent == 0)
  57689. {
  57690. jassertfalse;
  57691. return *this;
  57692. }
  57693. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57694. mods, otherComponent, originalComponent, eventTime,
  57695. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57696. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57697. }
  57698. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57699. {
  57700. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57701. eventTime, mouseDownPos, mouseDownTime,
  57702. numberOfClicks, wasMovedSinceMouseDown);
  57703. }
  57704. bool MouseEvent::mouseWasClicked() const throw()
  57705. {
  57706. return ! wasMovedSinceMouseDown;
  57707. }
  57708. int MouseEvent::getMouseDownX() const throw()
  57709. {
  57710. return mouseDownPos.getX();
  57711. }
  57712. int MouseEvent::getMouseDownY() const throw()
  57713. {
  57714. return mouseDownPos.getY();
  57715. }
  57716. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57717. {
  57718. return mouseDownPos;
  57719. }
  57720. int MouseEvent::getDistanceFromDragStartX() const throw()
  57721. {
  57722. return x - mouseDownPos.getX();
  57723. }
  57724. int MouseEvent::getDistanceFromDragStartY() const throw()
  57725. {
  57726. return y - mouseDownPos.getY();
  57727. }
  57728. int MouseEvent::getDistanceFromDragStart() const throw()
  57729. {
  57730. return mouseDownPos.getDistanceFrom (getPosition());
  57731. }
  57732. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57733. {
  57734. return getPosition() - mouseDownPos;
  57735. }
  57736. int MouseEvent::getLengthOfMousePress() const throw()
  57737. {
  57738. if (mouseDownTime.toMilliseconds() > 0)
  57739. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57740. return 0;
  57741. }
  57742. const Point<int> MouseEvent::getPosition() const throw()
  57743. {
  57744. return Point<int> (x, y);
  57745. }
  57746. int MouseEvent::getScreenX() const
  57747. {
  57748. return getScreenPosition().getX();
  57749. }
  57750. int MouseEvent::getScreenY() const
  57751. {
  57752. return getScreenPosition().getY();
  57753. }
  57754. const Point<int> MouseEvent::getScreenPosition() const
  57755. {
  57756. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57757. }
  57758. int MouseEvent::getMouseDownScreenX() const
  57759. {
  57760. return getMouseDownScreenPosition().getX();
  57761. }
  57762. int MouseEvent::getMouseDownScreenY() const
  57763. {
  57764. return getMouseDownScreenPosition().getY();
  57765. }
  57766. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57767. {
  57768. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57769. }
  57770. int MouseEvent::doubleClickTimeOutMs = 400;
  57771. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57772. {
  57773. doubleClickTimeOutMs = newTime;
  57774. }
  57775. int MouseEvent::getDoubleClickTimeout() throw()
  57776. {
  57777. return doubleClickTimeOutMs;
  57778. }
  57779. END_JUCE_NAMESPACE
  57780. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57781. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57782. BEGIN_JUCE_NAMESPACE
  57783. class MouseInputSourceInternal : public AsyncUpdater
  57784. {
  57785. public:
  57786. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57787. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  57788. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57789. mouseEventCounter (0)
  57790. {
  57791. zerostruct (mouseDowns);
  57792. }
  57793. ~MouseInputSourceInternal()
  57794. {
  57795. }
  57796. bool isDragging() const throw()
  57797. {
  57798. return buttonState.isAnyMouseButtonDown();
  57799. }
  57800. Component* getComponentUnderMouse() const
  57801. {
  57802. return static_cast <Component*> (componentUnderMouse);
  57803. }
  57804. const ModifierKeys getCurrentModifiers() const
  57805. {
  57806. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57807. }
  57808. ComponentPeer* getPeer()
  57809. {
  57810. if (! ComponentPeer::isValidPeer (lastPeer))
  57811. lastPeer = 0;
  57812. return lastPeer;
  57813. }
  57814. Component* findComponentAt (const Point<int>& screenPos)
  57815. {
  57816. ComponentPeer* const peer = getPeer();
  57817. if (peer != 0)
  57818. {
  57819. Component* const comp = peer->getComponent();
  57820. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57821. // (the contains() call is needed to test for overlapping desktop windows)
  57822. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57823. return comp->getComponentAt (relativePos);
  57824. }
  57825. return 0;
  57826. }
  57827. const Point<int> getScreenPosition() const throw()
  57828. {
  57829. return lastScreenPos + unboundedMouseOffset;
  57830. }
  57831. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57832. {
  57833. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57834. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57835. }
  57836. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57837. {
  57838. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57839. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57840. }
  57841. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57842. {
  57843. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57844. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57845. }
  57846. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57847. {
  57848. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57849. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57850. }
  57851. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57852. {
  57853. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57854. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57855. }
  57856. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57857. {
  57858. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57859. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57860. }
  57861. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57862. {
  57863. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57864. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57865. }
  57866. // (returns true if the button change caused a modal event loop)
  57867. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57868. {
  57869. if (buttonState == newButtonState)
  57870. return false;
  57871. setScreenPos (screenPos, time, false);
  57872. // (ignore secondary clicks when there's already a button down)
  57873. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57874. {
  57875. buttonState = newButtonState;
  57876. return false;
  57877. }
  57878. const int lastCounter = mouseEventCounter;
  57879. if (buttonState.isAnyMouseButtonDown())
  57880. {
  57881. Component* const current = getComponentUnderMouse();
  57882. if (current != 0)
  57883. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57884. enableUnboundedMouseMovement (false, false);
  57885. }
  57886. buttonState = newButtonState;
  57887. if (buttonState.isAnyMouseButtonDown())
  57888. {
  57889. Desktop::getInstance().incrementMouseClickCounter();
  57890. Component* const current = getComponentUnderMouse();
  57891. if (current != 0)
  57892. {
  57893. registerMouseDown (screenPos, time, current);
  57894. sendMouseDown (current, screenPos, time);
  57895. }
  57896. }
  57897. return lastCounter != mouseEventCounter;
  57898. }
  57899. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57900. {
  57901. Component* current = getComponentUnderMouse();
  57902. if (newComponent != current)
  57903. {
  57904. Component::SafePointer<Component> safeNewComp (newComponent);
  57905. const ModifierKeys originalButtonState (buttonState);
  57906. if (current != 0)
  57907. {
  57908. setButtons (screenPos, time, ModifierKeys());
  57909. sendMouseExit (current, screenPos, time);
  57910. buttonState = originalButtonState;
  57911. }
  57912. componentUnderMouse = safeNewComp;
  57913. current = getComponentUnderMouse();
  57914. if (current != 0)
  57915. sendMouseEnter (current, screenPos, time);
  57916. revealCursor (false);
  57917. setButtons (screenPos, time, originalButtonState);
  57918. }
  57919. }
  57920. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57921. {
  57922. ModifierKeys::updateCurrentModifiers();
  57923. if (newPeer != lastPeer)
  57924. {
  57925. setComponentUnderMouse (0, screenPos, time);
  57926. lastPeer = newPeer;
  57927. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57928. }
  57929. }
  57930. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57931. {
  57932. if (! isDragging())
  57933. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57934. if (newScreenPos != lastScreenPos || forceUpdate)
  57935. {
  57936. cancelPendingUpdate();
  57937. lastScreenPos = newScreenPos;
  57938. Component* const current = getComponentUnderMouse();
  57939. if (current != 0)
  57940. {
  57941. if (isDragging())
  57942. {
  57943. registerMouseDrag (newScreenPos);
  57944. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57945. if (isUnboundedMouseModeOn)
  57946. handleUnboundedDrag (current);
  57947. }
  57948. else
  57949. {
  57950. sendMouseMove (current, newScreenPos, time);
  57951. }
  57952. }
  57953. revealCursor (false);
  57954. }
  57955. }
  57956. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57957. {
  57958. jassert (newPeer != 0);
  57959. lastTime = time;
  57960. ++mouseEventCounter;
  57961. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57962. if (isDragging() && newMods.isAnyMouseButtonDown())
  57963. {
  57964. setScreenPos (screenPos, time, false);
  57965. }
  57966. else
  57967. {
  57968. setPeer (newPeer, screenPos, time);
  57969. ComponentPeer* peer = getPeer();
  57970. if (peer != 0)
  57971. {
  57972. if (setButtons (screenPos, time, newMods))
  57973. return; // some modal events have been dispatched, so the current event is now out-of-date
  57974. peer = getPeer();
  57975. if (peer != 0)
  57976. setScreenPos (screenPos, time, false);
  57977. }
  57978. }
  57979. }
  57980. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57981. {
  57982. jassert (peer != 0);
  57983. lastTime = time;
  57984. ++mouseEventCounter;
  57985. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57986. setPeer (peer, screenPos, time);
  57987. setScreenPos (screenPos, time, false);
  57988. triggerFakeMove();
  57989. if (! isDragging())
  57990. {
  57991. Component* current = getComponentUnderMouse();
  57992. if (current != 0)
  57993. sendMouseWheel (current, screenPos, time, x, y);
  57994. }
  57995. }
  57996. const Time getLastMouseDownTime() const throw()
  57997. {
  57998. return Time (mouseDowns[0].time);
  57999. }
  58000. const Point<int> getLastMouseDownPosition() const throw()
  58001. {
  58002. return mouseDowns[0].position;
  58003. }
  58004. int getNumberOfMultipleClicks() const throw()
  58005. {
  58006. int numClicks = 0;
  58007. if (mouseDowns[0].time != 0)
  58008. {
  58009. if (! mouseMovedSignificantlySincePressed)
  58010. ++numClicks;
  58011. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  58012. {
  58013. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  58014. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  58015. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  58016. {
  58017. ++numClicks;
  58018. }
  58019. else
  58020. {
  58021. break;
  58022. }
  58023. }
  58024. }
  58025. return numClicks;
  58026. }
  58027. bool hasMouseMovedSignificantlySincePressed() const throw()
  58028. {
  58029. return mouseMovedSignificantlySincePressed
  58030. || lastTime > mouseDowns[0].time + 300;
  58031. }
  58032. void triggerFakeMove()
  58033. {
  58034. triggerAsyncUpdate();
  58035. }
  58036. void handleAsyncUpdate()
  58037. {
  58038. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  58039. }
  58040. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  58041. {
  58042. enable = enable && isDragging();
  58043. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  58044. if (enable != isUnboundedMouseModeOn)
  58045. {
  58046. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  58047. {
  58048. // when released, return the mouse to within the component's bounds
  58049. Component* current = getComponentUnderMouse();
  58050. if (current != 0)
  58051. Desktop::setMousePosition (current->getScreenBounds()
  58052. .getConstrainedPoint (lastScreenPos));
  58053. }
  58054. isUnboundedMouseModeOn = enable;
  58055. unboundedMouseOffset = Point<int>();
  58056. revealCursor (true);
  58057. }
  58058. }
  58059. void handleUnboundedDrag (Component* current)
  58060. {
  58061. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  58062. if (! screenArea.contains (lastScreenPos))
  58063. {
  58064. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  58065. unboundedMouseOffset += (lastScreenPos - componentCentre);
  58066. Desktop::setMousePosition (componentCentre);
  58067. }
  58068. else if (isCursorVisibleUntilOffscreen
  58069. && (! unboundedMouseOffset.isOrigin())
  58070. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  58071. {
  58072. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  58073. unboundedMouseOffset = Point<int>();
  58074. }
  58075. }
  58076. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  58077. {
  58078. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  58079. {
  58080. cursor = MouseCursor::NoCursor;
  58081. forcedUpdate = true;
  58082. }
  58083. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  58084. {
  58085. currentCursorHandle = cursor.getHandle();
  58086. cursor.showInWindow (getPeer());
  58087. }
  58088. }
  58089. void hideCursor()
  58090. {
  58091. showMouseCursor (MouseCursor::NoCursor, true);
  58092. }
  58093. void revealCursor (bool forcedUpdate)
  58094. {
  58095. MouseCursor mc (MouseCursor::NormalCursor);
  58096. Component* current = getComponentUnderMouse();
  58097. if (current != 0)
  58098. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  58099. showMouseCursor (mc, forcedUpdate);
  58100. }
  58101. int index;
  58102. bool isMouseDevice;
  58103. Point<int> lastScreenPos;
  58104. ModifierKeys buttonState;
  58105. private:
  58106. MouseInputSource& source;
  58107. Component::SafePointer<Component> componentUnderMouse;
  58108. ComponentPeer* lastPeer;
  58109. Point<int> unboundedMouseOffset;
  58110. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  58111. void* currentCursorHandle;
  58112. int mouseEventCounter;
  58113. struct RecentMouseDown
  58114. {
  58115. Point<int> position;
  58116. int64 time;
  58117. Component* component;
  58118. };
  58119. RecentMouseDown mouseDowns[4];
  58120. bool mouseMovedSignificantlySincePressed;
  58121. int64 lastTime;
  58122. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  58123. {
  58124. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  58125. mouseDowns[i] = mouseDowns[i - 1];
  58126. mouseDowns[0].position = screenPos;
  58127. mouseDowns[0].time = time;
  58128. mouseDowns[0].component = component;
  58129. mouseMovedSignificantlySincePressed = false;
  58130. }
  58131. void registerMouseDrag (const Point<int>& screenPos) throw()
  58132. {
  58133. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  58134. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  58135. }
  58136. MouseInputSourceInternal (const MouseInputSourceInternal&);
  58137. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  58138. };
  58139. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  58140. {
  58141. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  58142. }
  58143. MouseInputSource::~MouseInputSource()
  58144. {
  58145. }
  58146. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  58147. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  58148. bool MouseInputSource::canHover() const { return isMouse(); }
  58149. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  58150. int MouseInputSource::getIndex() const { return pimpl->index; }
  58151. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  58152. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  58153. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  58154. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  58155. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  58156. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  58157. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  58158. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  58159. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  58160. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  58161. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  58162. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  58163. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  58164. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  58165. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  58166. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  58167. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  58168. {
  58169. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  58170. }
  58171. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  58172. {
  58173. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  58174. }
  58175. END_JUCE_NAMESPACE
  58176. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  58177. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  58178. BEGIN_JUCE_NAMESPACE
  58179. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  58180. : source (0),
  58181. hoverTimeMillisecs (hoverTimeMillisecs_),
  58182. hasJustHovered (false)
  58183. {
  58184. internalTimer.owner = this;
  58185. }
  58186. MouseHoverDetector::~MouseHoverDetector()
  58187. {
  58188. setHoverComponent (0);
  58189. }
  58190. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  58191. {
  58192. hoverTimeMillisecs = newTimeInMillisecs;
  58193. }
  58194. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  58195. {
  58196. if (source != newSourceComponent)
  58197. {
  58198. internalTimer.stopTimer();
  58199. hasJustHovered = false;
  58200. if (source != 0)
  58201. {
  58202. // ! you need to delete the hover detector before deleting its component
  58203. jassert (source->isValidComponent());
  58204. source->removeMouseListener (&internalTimer);
  58205. }
  58206. source = newSourceComponent;
  58207. if (newSourceComponent != 0)
  58208. newSourceComponent->addMouseListener (&internalTimer, false);
  58209. }
  58210. }
  58211. void MouseHoverDetector::hoverTimerCallback()
  58212. {
  58213. internalTimer.stopTimer();
  58214. if (source != 0)
  58215. {
  58216. const Point<int> pos (source->getMouseXYRelative());
  58217. if (source->reallyContains (pos.getX(), pos.getY(), false))
  58218. {
  58219. hasJustHovered = true;
  58220. mouseHovered (pos.getX(), pos.getY());
  58221. }
  58222. }
  58223. }
  58224. void MouseHoverDetector::checkJustHoveredCallback()
  58225. {
  58226. if (hasJustHovered)
  58227. {
  58228. hasJustHovered = false;
  58229. mouseMovedAfterHover();
  58230. }
  58231. }
  58232. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  58233. {
  58234. owner->hoverTimerCallback();
  58235. }
  58236. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  58237. {
  58238. stopTimer();
  58239. owner->checkJustHoveredCallback();
  58240. }
  58241. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  58242. {
  58243. stopTimer();
  58244. owner->checkJustHoveredCallback();
  58245. }
  58246. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  58247. {
  58248. stopTimer();
  58249. owner->checkJustHoveredCallback();
  58250. }
  58251. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  58252. {
  58253. stopTimer();
  58254. owner->checkJustHoveredCallback();
  58255. }
  58256. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  58257. {
  58258. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  58259. {
  58260. lastX = e.x;
  58261. lastY = e.y;
  58262. if (owner->source != 0)
  58263. startTimer (owner->hoverTimeMillisecs);
  58264. owner->checkJustHoveredCallback();
  58265. }
  58266. }
  58267. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  58268. {
  58269. stopTimer();
  58270. owner->checkJustHoveredCallback();
  58271. }
  58272. END_JUCE_NAMESPACE
  58273. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  58274. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58275. BEGIN_JUCE_NAMESPACE
  58276. void MouseListener::mouseEnter (const MouseEvent&)
  58277. {
  58278. }
  58279. void MouseListener::mouseExit (const MouseEvent&)
  58280. {
  58281. }
  58282. void MouseListener::mouseDown (const MouseEvent&)
  58283. {
  58284. }
  58285. void MouseListener::mouseUp (const MouseEvent&)
  58286. {
  58287. }
  58288. void MouseListener::mouseDrag (const MouseEvent&)
  58289. {
  58290. }
  58291. void MouseListener::mouseMove (const MouseEvent&)
  58292. {
  58293. }
  58294. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58295. {
  58296. }
  58297. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58298. {
  58299. }
  58300. END_JUCE_NAMESPACE
  58301. /*** End of inlined file: juce_MouseListener.cpp ***/
  58302. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58303. BEGIN_JUCE_NAMESPACE
  58304. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58305. const String& buttonTextWhenTrue,
  58306. const String& buttonTextWhenFalse)
  58307. : PropertyComponent (name),
  58308. onText (buttonTextWhenTrue),
  58309. offText (buttonTextWhenFalse)
  58310. {
  58311. addAndMakeVisible (&button);
  58312. button.setClickingTogglesState (false);
  58313. button.addButtonListener (this);
  58314. }
  58315. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58316. const String& name,
  58317. const String& buttonText)
  58318. : PropertyComponent (name),
  58319. onText (buttonText),
  58320. offText (buttonText)
  58321. {
  58322. addAndMakeVisible (&button);
  58323. button.setClickingTogglesState (false);
  58324. button.setButtonText (buttonText);
  58325. button.getToggleStateValue().referTo (valueToControl);
  58326. button.setClickingTogglesState (true);
  58327. }
  58328. BooleanPropertyComponent::~BooleanPropertyComponent()
  58329. {
  58330. }
  58331. void BooleanPropertyComponent::setState (const bool newState)
  58332. {
  58333. button.setToggleState (newState, true);
  58334. }
  58335. bool BooleanPropertyComponent::getState() const
  58336. {
  58337. return button.getToggleState();
  58338. }
  58339. void BooleanPropertyComponent::paint (Graphics& g)
  58340. {
  58341. PropertyComponent::paint (g);
  58342. g.setColour (Colours::white);
  58343. g.fillRect (button.getBounds());
  58344. g.setColour (findColour (ComboBox::outlineColourId));
  58345. g.drawRect (button.getBounds());
  58346. }
  58347. void BooleanPropertyComponent::refresh()
  58348. {
  58349. button.setToggleState (getState(), false);
  58350. button.setButtonText (button.getToggleState() ? onText : offText);
  58351. }
  58352. void BooleanPropertyComponent::buttonClicked (Button*)
  58353. {
  58354. setState (! getState());
  58355. }
  58356. END_JUCE_NAMESPACE
  58357. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58358. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58359. BEGIN_JUCE_NAMESPACE
  58360. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58361. const bool triggerOnMouseDown)
  58362. : PropertyComponent (name)
  58363. {
  58364. addAndMakeVisible (&button);
  58365. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58366. button.addButtonListener (this);
  58367. }
  58368. ButtonPropertyComponent::~ButtonPropertyComponent()
  58369. {
  58370. }
  58371. void ButtonPropertyComponent::refresh()
  58372. {
  58373. button.setButtonText (getButtonText());
  58374. }
  58375. void ButtonPropertyComponent::buttonClicked (Button*)
  58376. {
  58377. buttonClicked();
  58378. }
  58379. END_JUCE_NAMESPACE
  58380. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58381. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58382. BEGIN_JUCE_NAMESPACE
  58383. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58384. public Value::Listener
  58385. {
  58386. public:
  58387. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58388. : sourceValue (sourceValue_),
  58389. mappings (mappings_)
  58390. {
  58391. sourceValue.addListener (this);
  58392. }
  58393. ~RemapperValueSource() {}
  58394. const var getValue() const
  58395. {
  58396. return mappings.indexOf (sourceValue.getValue()) + 1;
  58397. }
  58398. void setValue (const var& newValue)
  58399. {
  58400. const var remappedVal (mappings [(int) newValue - 1]);
  58401. if (remappedVal != sourceValue)
  58402. sourceValue = remappedVal;
  58403. }
  58404. void valueChanged (Value&)
  58405. {
  58406. sendChangeMessage (true);
  58407. }
  58408. juce_UseDebuggingNewOperator
  58409. protected:
  58410. Value sourceValue;
  58411. Array<var> mappings;
  58412. RemapperValueSource (const RemapperValueSource&);
  58413. const RemapperValueSource& operator= (const RemapperValueSource&);
  58414. };
  58415. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58416. : PropertyComponent (name),
  58417. isCustomClass (true)
  58418. {
  58419. }
  58420. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58421. const String& name,
  58422. const StringArray& choices_,
  58423. const Array <var>& correspondingValues)
  58424. : PropertyComponent (name),
  58425. choices (choices_),
  58426. isCustomClass (false)
  58427. {
  58428. // The array of corresponding values must contain one value for each of the items in
  58429. // the choices array!
  58430. jassert (correspondingValues.size() == choices.size());
  58431. createComboBox();
  58432. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58433. }
  58434. ChoicePropertyComponent::~ChoicePropertyComponent()
  58435. {
  58436. }
  58437. void ChoicePropertyComponent::createComboBox()
  58438. {
  58439. addAndMakeVisible (&comboBox);
  58440. for (int i = 0; i < choices.size(); ++i)
  58441. {
  58442. if (choices[i].isNotEmpty())
  58443. comboBox.addItem (choices[i], i + 1);
  58444. else
  58445. comboBox.addSeparator();
  58446. }
  58447. comboBox.setEditableText (false);
  58448. }
  58449. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58450. {
  58451. jassertfalse; // you need to override this method in your subclass!
  58452. }
  58453. int ChoicePropertyComponent::getIndex() const
  58454. {
  58455. jassertfalse; // you need to override this method in your subclass!
  58456. return -1;
  58457. }
  58458. const StringArray& ChoicePropertyComponent::getChoices() const
  58459. {
  58460. return choices;
  58461. }
  58462. void ChoicePropertyComponent::refresh()
  58463. {
  58464. if (isCustomClass)
  58465. {
  58466. if (! comboBox.isVisible())
  58467. {
  58468. createComboBox();
  58469. comboBox.addListener (this);
  58470. }
  58471. comboBox.setSelectedId (getIndex() + 1, true);
  58472. }
  58473. }
  58474. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58475. {
  58476. if (isCustomClass)
  58477. {
  58478. const int newIndex = comboBox.getSelectedId() - 1;
  58479. if (newIndex != getIndex())
  58480. setIndex (newIndex);
  58481. }
  58482. }
  58483. END_JUCE_NAMESPACE
  58484. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58485. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58486. BEGIN_JUCE_NAMESPACE
  58487. PropertyComponent::PropertyComponent (const String& name,
  58488. const int preferredHeight_)
  58489. : Component (name),
  58490. preferredHeight (preferredHeight_)
  58491. {
  58492. jassert (name.isNotEmpty());
  58493. }
  58494. PropertyComponent::~PropertyComponent()
  58495. {
  58496. }
  58497. void PropertyComponent::paint (Graphics& g)
  58498. {
  58499. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58500. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58501. }
  58502. void PropertyComponent::resized()
  58503. {
  58504. if (getNumChildComponents() > 0)
  58505. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58506. }
  58507. void PropertyComponent::enablementChanged()
  58508. {
  58509. repaint();
  58510. }
  58511. END_JUCE_NAMESPACE
  58512. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58513. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58514. BEGIN_JUCE_NAMESPACE
  58515. class PropertyPanel::PropertyHolderComponent : public Component
  58516. {
  58517. public:
  58518. PropertyHolderComponent()
  58519. {
  58520. }
  58521. ~PropertyHolderComponent()
  58522. {
  58523. deleteAllChildren();
  58524. }
  58525. void paint (Graphics&)
  58526. {
  58527. }
  58528. void updateLayout (int width);
  58529. void refreshAll() const;
  58530. private:
  58531. PropertyHolderComponent (const PropertyHolderComponent&);
  58532. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58533. };
  58534. class PropertySectionComponent : public Component
  58535. {
  58536. public:
  58537. PropertySectionComponent (const String& sectionTitle,
  58538. const Array <PropertyComponent*>& newProperties,
  58539. const bool open)
  58540. : Component (sectionTitle),
  58541. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58542. isOpen_ (open)
  58543. {
  58544. for (int i = newProperties.size(); --i >= 0;)
  58545. {
  58546. addAndMakeVisible (newProperties.getUnchecked(i));
  58547. newProperties.getUnchecked(i)->refresh();
  58548. }
  58549. }
  58550. ~PropertySectionComponent()
  58551. {
  58552. deleteAllChildren();
  58553. }
  58554. void paint (Graphics& g)
  58555. {
  58556. if (titleHeight > 0)
  58557. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58558. }
  58559. void resized()
  58560. {
  58561. int y = titleHeight;
  58562. for (int i = getNumChildComponents(); --i >= 0;)
  58563. {
  58564. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58565. if (pec != 0)
  58566. {
  58567. const int prefH = pec->getPreferredHeight();
  58568. pec->setBounds (1, y, getWidth() - 2, prefH);
  58569. y += prefH;
  58570. }
  58571. }
  58572. }
  58573. int getPreferredHeight() const
  58574. {
  58575. int y = titleHeight;
  58576. if (isOpen())
  58577. {
  58578. for (int i = 0; i < getNumChildComponents(); ++i)
  58579. {
  58580. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58581. if (pec != 0)
  58582. y += pec->getPreferredHeight();
  58583. }
  58584. }
  58585. return y;
  58586. }
  58587. void setOpen (const bool open)
  58588. {
  58589. if (isOpen_ != open)
  58590. {
  58591. isOpen_ = open;
  58592. for (int i = 0; i < getNumChildComponents(); ++i)
  58593. {
  58594. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58595. if (pec != 0)
  58596. pec->setVisible (open);
  58597. }
  58598. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58599. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58600. if (pp != 0)
  58601. pp->resized();
  58602. }
  58603. }
  58604. bool isOpen() const
  58605. {
  58606. return isOpen_;
  58607. }
  58608. void refreshAll() const
  58609. {
  58610. for (int i = 0; i < getNumChildComponents(); ++i)
  58611. {
  58612. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58613. if (pec != 0)
  58614. pec->refresh();
  58615. }
  58616. }
  58617. void mouseDown (const MouseEvent&)
  58618. {
  58619. }
  58620. void mouseUp (const MouseEvent& e)
  58621. {
  58622. if (e.getMouseDownX() < titleHeight
  58623. && e.x < titleHeight
  58624. && e.y < titleHeight
  58625. && e.getNumberOfClicks() != 2)
  58626. {
  58627. setOpen (! isOpen());
  58628. }
  58629. }
  58630. void mouseDoubleClick (const MouseEvent& e)
  58631. {
  58632. if (e.y < titleHeight)
  58633. setOpen (! isOpen());
  58634. }
  58635. private:
  58636. int titleHeight;
  58637. bool isOpen_;
  58638. PropertySectionComponent (const PropertySectionComponent&);
  58639. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58640. };
  58641. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58642. {
  58643. int y = 0;
  58644. for (int i = getNumChildComponents(); --i >= 0;)
  58645. {
  58646. PropertySectionComponent* const section
  58647. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58648. if (section != 0)
  58649. {
  58650. const int prefH = section->getPreferredHeight();
  58651. section->setBounds (0, y, width, prefH);
  58652. y += prefH;
  58653. }
  58654. }
  58655. setSize (width, y);
  58656. repaint();
  58657. }
  58658. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58659. {
  58660. for (int i = getNumChildComponents(); --i >= 0;)
  58661. {
  58662. PropertySectionComponent* const section
  58663. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58664. if (section != 0)
  58665. section->refreshAll();
  58666. }
  58667. }
  58668. PropertyPanel::PropertyPanel()
  58669. {
  58670. messageWhenEmpty = TRANS("(nothing selected)");
  58671. addAndMakeVisible (&viewport);
  58672. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58673. viewport.setFocusContainer (true);
  58674. }
  58675. PropertyPanel::~PropertyPanel()
  58676. {
  58677. clear();
  58678. }
  58679. void PropertyPanel::paint (Graphics& g)
  58680. {
  58681. if (propertyHolderComponent->getNumChildComponents() == 0)
  58682. {
  58683. g.setColour (Colours::black.withAlpha (0.5f));
  58684. g.setFont (14.0f);
  58685. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58686. Justification::centred, true);
  58687. }
  58688. }
  58689. void PropertyPanel::resized()
  58690. {
  58691. viewport.setBounds (getLocalBounds());
  58692. updatePropHolderLayout();
  58693. }
  58694. void PropertyPanel::clear()
  58695. {
  58696. if (propertyHolderComponent->getNumChildComponents() > 0)
  58697. {
  58698. propertyHolderComponent->deleteAllChildren();
  58699. repaint();
  58700. }
  58701. }
  58702. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58703. {
  58704. if (propertyHolderComponent->getNumChildComponents() == 0)
  58705. repaint();
  58706. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58707. newProperties,
  58708. true), 0);
  58709. updatePropHolderLayout();
  58710. }
  58711. void PropertyPanel::addSection (const String& sectionTitle,
  58712. const Array <PropertyComponent*>& newProperties,
  58713. const bool shouldBeOpen)
  58714. {
  58715. jassert (sectionTitle.isNotEmpty());
  58716. if (propertyHolderComponent->getNumChildComponents() == 0)
  58717. repaint();
  58718. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58719. newProperties,
  58720. shouldBeOpen), 0);
  58721. updatePropHolderLayout();
  58722. }
  58723. void PropertyPanel::updatePropHolderLayout() const
  58724. {
  58725. const int maxWidth = viewport.getMaximumVisibleWidth();
  58726. propertyHolderComponent->updateLayout (maxWidth);
  58727. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58728. if (maxWidth != newMaxWidth)
  58729. {
  58730. // need to do this twice because of scrollbars changing the size, etc.
  58731. propertyHolderComponent->updateLayout (newMaxWidth);
  58732. }
  58733. }
  58734. void PropertyPanel::refreshAll() const
  58735. {
  58736. propertyHolderComponent->refreshAll();
  58737. }
  58738. const StringArray PropertyPanel::getSectionNames() const
  58739. {
  58740. StringArray s;
  58741. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58742. {
  58743. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58744. if (section != 0 && section->getName().isNotEmpty())
  58745. s.add (section->getName());
  58746. }
  58747. return s;
  58748. }
  58749. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58750. {
  58751. int index = 0;
  58752. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58753. {
  58754. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58755. if (section != 0 && section->getName().isNotEmpty())
  58756. {
  58757. if (index == sectionIndex)
  58758. return section->isOpen();
  58759. ++index;
  58760. }
  58761. }
  58762. return false;
  58763. }
  58764. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58765. {
  58766. int index = 0;
  58767. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58768. {
  58769. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58770. if (section != 0 && section->getName().isNotEmpty())
  58771. {
  58772. if (index == sectionIndex)
  58773. {
  58774. section->setOpen (shouldBeOpen);
  58775. break;
  58776. }
  58777. ++index;
  58778. }
  58779. }
  58780. }
  58781. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58782. {
  58783. int index = 0;
  58784. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58785. {
  58786. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58787. if (section != 0 && section->getName().isNotEmpty())
  58788. {
  58789. if (index == sectionIndex)
  58790. {
  58791. section->setEnabled (shouldBeEnabled);
  58792. break;
  58793. }
  58794. ++index;
  58795. }
  58796. }
  58797. }
  58798. XmlElement* PropertyPanel::getOpennessState() const
  58799. {
  58800. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58801. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58802. const StringArray sections (getSectionNames());
  58803. for (int i = 0; i < sections.size(); ++i)
  58804. {
  58805. if (sections[i].isNotEmpty())
  58806. {
  58807. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58808. e->setAttribute ("name", sections[i]);
  58809. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58810. }
  58811. }
  58812. return xml;
  58813. }
  58814. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58815. {
  58816. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58817. {
  58818. const StringArray sections (getSectionNames());
  58819. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58820. {
  58821. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58822. e->getBoolAttribute ("open"));
  58823. }
  58824. viewport.setViewPosition (viewport.getViewPositionX(),
  58825. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58826. }
  58827. }
  58828. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58829. {
  58830. if (messageWhenEmpty != newMessage)
  58831. {
  58832. messageWhenEmpty = newMessage;
  58833. repaint();
  58834. }
  58835. }
  58836. const String& PropertyPanel::getMessageWhenEmpty() const
  58837. {
  58838. return messageWhenEmpty;
  58839. }
  58840. END_JUCE_NAMESPACE
  58841. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58842. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58843. BEGIN_JUCE_NAMESPACE
  58844. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58845. const double rangeMin,
  58846. const double rangeMax,
  58847. const double interval,
  58848. const double skewFactor)
  58849. : PropertyComponent (name)
  58850. {
  58851. addAndMakeVisible (&slider);
  58852. slider.setRange (rangeMin, rangeMax, interval);
  58853. slider.setSkewFactor (skewFactor);
  58854. slider.setSliderStyle (Slider::LinearBar);
  58855. slider.addListener (this);
  58856. }
  58857. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58858. const String& name,
  58859. const double rangeMin,
  58860. const double rangeMax,
  58861. const double interval,
  58862. const double skewFactor)
  58863. : PropertyComponent (name)
  58864. {
  58865. addAndMakeVisible (&slider);
  58866. slider.setRange (rangeMin, rangeMax, interval);
  58867. slider.setSkewFactor (skewFactor);
  58868. slider.setSliderStyle (Slider::LinearBar);
  58869. slider.getValueObject().referTo (valueToControl);
  58870. }
  58871. SliderPropertyComponent::~SliderPropertyComponent()
  58872. {
  58873. }
  58874. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58875. {
  58876. }
  58877. double SliderPropertyComponent::getValue() const
  58878. {
  58879. return slider.getValue();
  58880. }
  58881. void SliderPropertyComponent::refresh()
  58882. {
  58883. slider.setValue (getValue(), false);
  58884. }
  58885. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58886. {
  58887. if (getValue() != slider.getValue())
  58888. setValue (slider.getValue());
  58889. }
  58890. END_JUCE_NAMESPACE
  58891. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58892. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58893. BEGIN_JUCE_NAMESPACE
  58894. class TextPropLabel : public Label
  58895. {
  58896. TextPropertyComponent& owner;
  58897. int maxChars;
  58898. bool isMultiline;
  58899. public:
  58900. TextPropLabel (TextPropertyComponent& owner_,
  58901. const int maxChars_, const bool isMultiline_)
  58902. : Label (String::empty, String::empty),
  58903. owner (owner_),
  58904. maxChars (maxChars_),
  58905. isMultiline (isMultiline_)
  58906. {
  58907. setEditable (true, true, false);
  58908. setColour (backgroundColourId, Colours::white);
  58909. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58910. }
  58911. ~TextPropLabel()
  58912. {
  58913. }
  58914. TextEditor* createEditorComponent()
  58915. {
  58916. TextEditor* const textEditor = Label::createEditorComponent();
  58917. textEditor->setInputRestrictions (maxChars);
  58918. if (isMultiline)
  58919. {
  58920. textEditor->setMultiLine (true, true);
  58921. textEditor->setReturnKeyStartsNewLine (true);
  58922. }
  58923. return textEditor;
  58924. }
  58925. void textWasEdited()
  58926. {
  58927. owner.textWasEdited();
  58928. }
  58929. };
  58930. TextPropertyComponent::TextPropertyComponent (const String& name,
  58931. const int maxNumChars,
  58932. const bool isMultiLine)
  58933. : PropertyComponent (name)
  58934. {
  58935. createEditor (maxNumChars, isMultiLine);
  58936. }
  58937. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58938. const String& name,
  58939. const int maxNumChars,
  58940. const bool isMultiLine)
  58941. : PropertyComponent (name)
  58942. {
  58943. createEditor (maxNumChars, isMultiLine);
  58944. textEditor->getTextValue().referTo (valueToControl);
  58945. }
  58946. TextPropertyComponent::~TextPropertyComponent()
  58947. {
  58948. deleteAllChildren();
  58949. }
  58950. void TextPropertyComponent::setText (const String& newText)
  58951. {
  58952. textEditor->setText (newText, true);
  58953. }
  58954. const String TextPropertyComponent::getText() const
  58955. {
  58956. return textEditor->getText();
  58957. }
  58958. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58959. {
  58960. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58961. if (isMultiLine)
  58962. {
  58963. textEditor->setJustificationType (Justification::topLeft);
  58964. preferredHeight = 120;
  58965. }
  58966. }
  58967. void TextPropertyComponent::refresh()
  58968. {
  58969. textEditor->setText (getText(), false);
  58970. }
  58971. void TextPropertyComponent::textWasEdited()
  58972. {
  58973. const String newText (textEditor->getText());
  58974. if (getText() != newText)
  58975. setText (newText);
  58976. }
  58977. END_JUCE_NAMESPACE
  58978. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58979. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58980. BEGIN_JUCE_NAMESPACE
  58981. class SimpleDeviceManagerInputLevelMeter : public Component,
  58982. public Timer
  58983. {
  58984. public:
  58985. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58986. : manager (manager_),
  58987. level (0)
  58988. {
  58989. startTimer (50);
  58990. manager->enableInputLevelMeasurement (true);
  58991. }
  58992. ~SimpleDeviceManagerInputLevelMeter()
  58993. {
  58994. manager->enableInputLevelMeasurement (false);
  58995. }
  58996. void timerCallback()
  58997. {
  58998. const float newLevel = (float) manager->getCurrentInputLevel();
  58999. if (std::abs (level - newLevel) > 0.005f)
  59000. {
  59001. level = newLevel;
  59002. repaint();
  59003. }
  59004. }
  59005. void paint (Graphics& g)
  59006. {
  59007. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  59008. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  59009. }
  59010. private:
  59011. AudioDeviceManager* const manager;
  59012. float level;
  59013. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  59014. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  59015. };
  59016. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  59017. public ListBoxModel
  59018. {
  59019. public:
  59020. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  59021. const String& noItemsMessage_,
  59022. const int minNumber_,
  59023. const int maxNumber_)
  59024. : ListBox (String::empty, 0),
  59025. deviceManager (deviceManager_),
  59026. noItemsMessage (noItemsMessage_),
  59027. minNumber (minNumber_),
  59028. maxNumber (maxNumber_)
  59029. {
  59030. items = MidiInput::getDevices();
  59031. setModel (this);
  59032. setOutlineThickness (1);
  59033. }
  59034. ~MidiInputSelectorComponentListBox()
  59035. {
  59036. }
  59037. int getNumRows()
  59038. {
  59039. return items.size();
  59040. }
  59041. void paintListBoxItem (int row,
  59042. Graphics& g,
  59043. int width, int height,
  59044. bool rowIsSelected)
  59045. {
  59046. if (((unsigned int) row) < (unsigned int) items.size())
  59047. {
  59048. if (rowIsSelected)
  59049. g.fillAll (findColour (TextEditor::highlightColourId)
  59050. .withMultipliedAlpha (0.3f));
  59051. const String item (items [row]);
  59052. bool enabled = deviceManager.isMidiInputEnabled (item);
  59053. const int x = getTickX();
  59054. const float tickW = height * 0.75f;
  59055. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59056. enabled, true, true, false);
  59057. g.setFont (height * 0.6f);
  59058. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59059. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59060. }
  59061. }
  59062. void listBoxItemClicked (int row, const MouseEvent& e)
  59063. {
  59064. selectRow (row);
  59065. if (e.x < getTickX())
  59066. flipEnablement (row);
  59067. }
  59068. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59069. {
  59070. flipEnablement (row);
  59071. }
  59072. void returnKeyPressed (int row)
  59073. {
  59074. flipEnablement (row);
  59075. }
  59076. void paint (Graphics& g)
  59077. {
  59078. ListBox::paint (g);
  59079. if (items.size() == 0)
  59080. {
  59081. g.setColour (Colours::grey);
  59082. g.setFont (13.0f);
  59083. g.drawText (noItemsMessage,
  59084. 0, 0, getWidth(), getHeight() / 2,
  59085. Justification::centred, true);
  59086. }
  59087. }
  59088. int getBestHeight (const int preferredHeight)
  59089. {
  59090. const int extra = getOutlineThickness() * 2;
  59091. return jmax (getRowHeight() * 2 + extra,
  59092. jmin (getRowHeight() * getNumRows() + extra,
  59093. preferredHeight));
  59094. }
  59095. juce_UseDebuggingNewOperator
  59096. private:
  59097. AudioDeviceManager& deviceManager;
  59098. const String noItemsMessage;
  59099. StringArray items;
  59100. int minNumber, maxNumber;
  59101. void flipEnablement (const int row)
  59102. {
  59103. if (((unsigned int) row) < (unsigned int) items.size())
  59104. {
  59105. const String item (items [row]);
  59106. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  59107. }
  59108. }
  59109. int getTickX() const
  59110. {
  59111. return getRowHeight() + 5;
  59112. }
  59113. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  59114. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  59115. };
  59116. class AudioDeviceSettingsPanel : public Component,
  59117. public ChangeListener,
  59118. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  59119. public ButtonListener
  59120. {
  59121. public:
  59122. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  59123. AudioIODeviceType::DeviceSetupDetails& setup_,
  59124. const bool hideAdvancedOptionsWithButton)
  59125. : type (type_),
  59126. setup (setup_)
  59127. {
  59128. if (hideAdvancedOptionsWithButton)
  59129. {
  59130. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  59131. showAdvancedSettingsButton->addButtonListener (this);
  59132. }
  59133. type->scanForDevices();
  59134. setup.manager->addChangeListener (this);
  59135. changeListenerCallback (0);
  59136. }
  59137. ~AudioDeviceSettingsPanel()
  59138. {
  59139. setup.manager->removeChangeListener (this);
  59140. }
  59141. void resized()
  59142. {
  59143. const int lx = proportionOfWidth (0.35f);
  59144. const int w = proportionOfWidth (0.4f);
  59145. const int h = 24;
  59146. const int space = 6;
  59147. const int dh = h + space;
  59148. int y = 0;
  59149. if (outputDeviceDropDown != 0)
  59150. {
  59151. outputDeviceDropDown->setBounds (lx, y, w, h);
  59152. if (testButton != 0)
  59153. testButton->setBounds (proportionOfWidth (0.77f),
  59154. outputDeviceDropDown->getY(),
  59155. proportionOfWidth (0.18f),
  59156. h);
  59157. y += dh;
  59158. }
  59159. if (inputDeviceDropDown != 0)
  59160. {
  59161. inputDeviceDropDown->setBounds (lx, y, w, h);
  59162. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  59163. inputDeviceDropDown->getY(),
  59164. proportionOfWidth (0.18f),
  59165. h);
  59166. y += dh;
  59167. }
  59168. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  59169. if (outputChanList != 0)
  59170. {
  59171. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  59172. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59173. y += bh + space;
  59174. }
  59175. if (inputChanList != 0)
  59176. {
  59177. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  59178. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59179. y += bh + space;
  59180. }
  59181. y += space * 2;
  59182. if (showAdvancedSettingsButton != 0)
  59183. {
  59184. showAdvancedSettingsButton->changeWidthToFitText (h);
  59185. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  59186. }
  59187. if (sampleRateDropDown != 0)
  59188. {
  59189. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  59190. || ! showAdvancedSettingsButton->isVisible());
  59191. sampleRateDropDown->setBounds (lx, y, w, h);
  59192. y += dh;
  59193. }
  59194. if (bufferSizeDropDown != 0)
  59195. {
  59196. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  59197. || ! showAdvancedSettingsButton->isVisible());
  59198. bufferSizeDropDown->setBounds (lx, y, w, h);
  59199. y += dh;
  59200. }
  59201. if (showUIButton != 0)
  59202. {
  59203. showUIButton->setVisible (showAdvancedSettingsButton == 0
  59204. || ! showAdvancedSettingsButton->isVisible());
  59205. showUIButton->changeWidthToFitText (h);
  59206. showUIButton->setTopLeftPosition (lx, y);
  59207. }
  59208. }
  59209. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59210. {
  59211. if (comboBoxThatHasChanged == 0)
  59212. return;
  59213. AudioDeviceManager::AudioDeviceSetup config;
  59214. setup.manager->getAudioDeviceSetup (config);
  59215. String error;
  59216. if (comboBoxThatHasChanged == outputDeviceDropDown
  59217. || comboBoxThatHasChanged == inputDeviceDropDown)
  59218. {
  59219. if (outputDeviceDropDown != 0)
  59220. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59221. : outputDeviceDropDown->getText();
  59222. if (inputDeviceDropDown != 0)
  59223. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59224. : inputDeviceDropDown->getText();
  59225. if (! type->hasSeparateInputsAndOutputs())
  59226. config.inputDeviceName = config.outputDeviceName;
  59227. if (comboBoxThatHasChanged == inputDeviceDropDown)
  59228. config.useDefaultInputChannels = true;
  59229. else
  59230. config.useDefaultOutputChannels = true;
  59231. error = setup.manager->setAudioDeviceSetup (config, true);
  59232. showCorrectDeviceName (inputDeviceDropDown, true);
  59233. showCorrectDeviceName (outputDeviceDropDown, false);
  59234. updateControlPanelButton();
  59235. resized();
  59236. }
  59237. else if (comboBoxThatHasChanged == sampleRateDropDown)
  59238. {
  59239. if (sampleRateDropDown->getSelectedId() > 0)
  59240. {
  59241. config.sampleRate = sampleRateDropDown->getSelectedId();
  59242. error = setup.manager->setAudioDeviceSetup (config, true);
  59243. }
  59244. }
  59245. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  59246. {
  59247. if (bufferSizeDropDown->getSelectedId() > 0)
  59248. {
  59249. config.bufferSize = bufferSizeDropDown->getSelectedId();
  59250. error = setup.manager->setAudioDeviceSetup (config, true);
  59251. }
  59252. }
  59253. if (error.isNotEmpty())
  59254. {
  59255. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  59256. "Error when trying to open audio device!",
  59257. error);
  59258. }
  59259. }
  59260. void buttonClicked (Button* button)
  59261. {
  59262. if (button == showAdvancedSettingsButton)
  59263. {
  59264. showAdvancedSettingsButton->setVisible (false);
  59265. resized();
  59266. }
  59267. else if (button == showUIButton)
  59268. {
  59269. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59270. if (device != 0 && device->showControlPanel())
  59271. {
  59272. setup.manager->closeAudioDevice();
  59273. setup.manager->restartLastAudioDevice();
  59274. getTopLevelComponent()->toFront (true);
  59275. }
  59276. }
  59277. else if (button == testButton && testButton != 0)
  59278. {
  59279. setup.manager->playTestSound();
  59280. }
  59281. }
  59282. void updateControlPanelButton()
  59283. {
  59284. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59285. showUIButton = 0;
  59286. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59287. {
  59288. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59289. TRANS ("opens the device's own control panel")));
  59290. showUIButton->addButtonListener (this);
  59291. }
  59292. resized();
  59293. }
  59294. void changeListenerCallback (void*)
  59295. {
  59296. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59297. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59298. {
  59299. if (outputDeviceDropDown == 0)
  59300. {
  59301. outputDeviceDropDown = new ComboBox (String::empty);
  59302. outputDeviceDropDown->addListener (this);
  59303. addAndMakeVisible (outputDeviceDropDown);
  59304. outputDeviceLabel = new Label (String::empty,
  59305. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59306. : TRANS ("device:"));
  59307. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59308. if (setup.maxNumOutputChannels > 0)
  59309. {
  59310. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59311. testButton->addButtonListener (this);
  59312. }
  59313. }
  59314. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59315. }
  59316. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59317. {
  59318. if (inputDeviceDropDown == 0)
  59319. {
  59320. inputDeviceDropDown = new ComboBox (String::empty);
  59321. inputDeviceDropDown->addListener (this);
  59322. addAndMakeVisible (inputDeviceDropDown);
  59323. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59324. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59325. addAndMakeVisible (inputLevelMeter
  59326. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59327. }
  59328. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59329. }
  59330. updateControlPanelButton();
  59331. showCorrectDeviceName (inputDeviceDropDown, true);
  59332. showCorrectDeviceName (outputDeviceDropDown, false);
  59333. if (currentDevice != 0)
  59334. {
  59335. if (setup.maxNumOutputChannels > 0
  59336. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59337. {
  59338. if (outputChanList == 0)
  59339. {
  59340. addAndMakeVisible (outputChanList
  59341. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59342. TRANS ("(no audio output channels found)")));
  59343. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59344. outputChanLabel->attachToComponent (outputChanList, true);
  59345. }
  59346. outputChanList->refresh();
  59347. }
  59348. else
  59349. {
  59350. outputChanLabel = 0;
  59351. outputChanList = 0;
  59352. }
  59353. if (setup.maxNumInputChannels > 0
  59354. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59355. {
  59356. if (inputChanList == 0)
  59357. {
  59358. addAndMakeVisible (inputChanList
  59359. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59360. TRANS ("(no audio input channels found)")));
  59361. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59362. inputChanLabel->attachToComponent (inputChanList, true);
  59363. }
  59364. inputChanList->refresh();
  59365. }
  59366. else
  59367. {
  59368. inputChanLabel = 0;
  59369. inputChanList = 0;
  59370. }
  59371. // sample rate..
  59372. {
  59373. if (sampleRateDropDown == 0)
  59374. {
  59375. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59376. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59377. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59378. }
  59379. else
  59380. {
  59381. sampleRateDropDown->clear();
  59382. sampleRateDropDown->removeListener (this);
  59383. }
  59384. const int numRates = currentDevice->getNumSampleRates();
  59385. for (int i = 0; i < numRates; ++i)
  59386. {
  59387. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59388. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59389. }
  59390. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59391. sampleRateDropDown->addListener (this);
  59392. }
  59393. // buffer size
  59394. {
  59395. if (bufferSizeDropDown == 0)
  59396. {
  59397. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59398. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59399. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59400. }
  59401. else
  59402. {
  59403. bufferSizeDropDown->clear();
  59404. bufferSizeDropDown->removeListener (this);
  59405. }
  59406. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59407. double currentRate = currentDevice->getCurrentSampleRate();
  59408. if (currentRate == 0)
  59409. currentRate = 48000.0;
  59410. for (int i = 0; i < numBufferSizes; ++i)
  59411. {
  59412. const int bs = currentDevice->getBufferSizeSamples (i);
  59413. bufferSizeDropDown->addItem (String (bs)
  59414. + " samples ("
  59415. + String (bs * 1000.0 / currentRate, 1)
  59416. + " ms)",
  59417. bs);
  59418. }
  59419. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59420. bufferSizeDropDown->addListener (this);
  59421. }
  59422. }
  59423. else
  59424. {
  59425. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59426. sampleRateLabel = 0;
  59427. bufferSizeLabel = 0;
  59428. sampleRateDropDown = 0;
  59429. bufferSizeDropDown = 0;
  59430. if (outputDeviceDropDown != 0)
  59431. outputDeviceDropDown->setSelectedId (-1, true);
  59432. if (inputDeviceDropDown != 0)
  59433. inputDeviceDropDown->setSelectedId (-1, true);
  59434. }
  59435. resized();
  59436. setSize (getWidth(), getLowestY() + 4);
  59437. }
  59438. private:
  59439. AudioIODeviceType* const type;
  59440. const AudioIODeviceType::DeviceSetupDetails setup;
  59441. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59442. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59443. ScopedPointer<TextButton> testButton;
  59444. ScopedPointer<Component> inputLevelMeter;
  59445. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59446. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59447. {
  59448. if (box != 0)
  59449. {
  59450. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59451. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59452. box->setSelectedId (index + 1, true);
  59453. if (testButton != 0 && ! isInput)
  59454. testButton->setEnabled (index >= 0);
  59455. }
  59456. }
  59457. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59458. {
  59459. const StringArray devs (type->getDeviceNames (isInputs));
  59460. combo.clear (true);
  59461. for (int i = 0; i < devs.size(); ++i)
  59462. combo.addItem (devs[i], i + 1);
  59463. combo.addItem (TRANS("<< none >>"), -1);
  59464. combo.setSelectedId (-1, true);
  59465. }
  59466. int getLowestY() const
  59467. {
  59468. int y = 0;
  59469. for (int i = getNumChildComponents(); --i >= 0;)
  59470. y = jmax (y, getChildComponent (i)->getBottom());
  59471. return y;
  59472. }
  59473. public:
  59474. class ChannelSelectorListBox : public ListBox,
  59475. public ListBoxModel
  59476. {
  59477. public:
  59478. enum BoxType
  59479. {
  59480. audioInputType,
  59481. audioOutputType
  59482. };
  59483. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59484. const BoxType type_,
  59485. const String& noItemsMessage_)
  59486. : ListBox (String::empty, 0),
  59487. setup (setup_),
  59488. type (type_),
  59489. noItemsMessage (noItemsMessage_)
  59490. {
  59491. refresh();
  59492. setModel (this);
  59493. setOutlineThickness (1);
  59494. }
  59495. ~ChannelSelectorListBox()
  59496. {
  59497. }
  59498. void refresh()
  59499. {
  59500. items.clear();
  59501. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59502. if (currentDevice != 0)
  59503. {
  59504. if (type == audioInputType)
  59505. items = currentDevice->getInputChannelNames();
  59506. else if (type == audioOutputType)
  59507. items = currentDevice->getOutputChannelNames();
  59508. if (setup.useStereoPairs)
  59509. {
  59510. StringArray pairs;
  59511. for (int i = 0; i < items.size(); i += 2)
  59512. {
  59513. const String name (items[i]);
  59514. const String name2 (items[i + 1]);
  59515. String commonBit;
  59516. for (int j = 0; j < name.length(); ++j)
  59517. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59518. commonBit = name.substring (0, j);
  59519. // Make sure we only split the name at a space, because otherwise, things
  59520. // like "input 11" + "input 12" would become "input 11 + 2"
  59521. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59522. commonBit = commonBit.dropLastCharacters (1);
  59523. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59524. }
  59525. items = pairs;
  59526. }
  59527. }
  59528. updateContent();
  59529. repaint();
  59530. }
  59531. int getNumRows()
  59532. {
  59533. return items.size();
  59534. }
  59535. void paintListBoxItem (int row,
  59536. Graphics& g,
  59537. int width, int height,
  59538. bool rowIsSelected)
  59539. {
  59540. if (((unsigned int) row) < (unsigned int) items.size())
  59541. {
  59542. if (rowIsSelected)
  59543. g.fillAll (findColour (TextEditor::highlightColourId)
  59544. .withMultipliedAlpha (0.3f));
  59545. const String item (items [row]);
  59546. bool enabled = false;
  59547. AudioDeviceManager::AudioDeviceSetup config;
  59548. setup.manager->getAudioDeviceSetup (config);
  59549. if (setup.useStereoPairs)
  59550. {
  59551. if (type == audioInputType)
  59552. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59553. else if (type == audioOutputType)
  59554. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59555. }
  59556. else
  59557. {
  59558. if (type == audioInputType)
  59559. enabled = config.inputChannels [row];
  59560. else if (type == audioOutputType)
  59561. enabled = config.outputChannels [row];
  59562. }
  59563. const int x = getTickX();
  59564. const float tickW = height * 0.75f;
  59565. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59566. enabled, true, true, false);
  59567. g.setFont (height * 0.6f);
  59568. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59569. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59570. }
  59571. }
  59572. void listBoxItemClicked (int row, const MouseEvent& e)
  59573. {
  59574. selectRow (row);
  59575. if (e.x < getTickX())
  59576. flipEnablement (row);
  59577. }
  59578. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59579. {
  59580. flipEnablement (row);
  59581. }
  59582. void returnKeyPressed (int row)
  59583. {
  59584. flipEnablement (row);
  59585. }
  59586. void paint (Graphics& g)
  59587. {
  59588. ListBox::paint (g);
  59589. if (items.size() == 0)
  59590. {
  59591. g.setColour (Colours::grey);
  59592. g.setFont (13.0f);
  59593. g.drawText (noItemsMessage,
  59594. 0, 0, getWidth(), getHeight() / 2,
  59595. Justification::centred, true);
  59596. }
  59597. }
  59598. int getBestHeight (int maxHeight)
  59599. {
  59600. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59601. getNumRows())
  59602. + getOutlineThickness() * 2;
  59603. }
  59604. juce_UseDebuggingNewOperator
  59605. private:
  59606. const AudioIODeviceType::DeviceSetupDetails setup;
  59607. const BoxType type;
  59608. const String noItemsMessage;
  59609. StringArray items;
  59610. void flipEnablement (const int row)
  59611. {
  59612. jassert (type == audioInputType || type == audioOutputType);
  59613. if (((unsigned int) row) < (unsigned int) items.size())
  59614. {
  59615. AudioDeviceManager::AudioDeviceSetup config;
  59616. setup.manager->getAudioDeviceSetup (config);
  59617. if (setup.useStereoPairs)
  59618. {
  59619. BigInteger bits;
  59620. BigInteger& original = (type == audioInputType ? config.inputChannels
  59621. : config.outputChannels);
  59622. int i;
  59623. for (i = 0; i < 256; i += 2)
  59624. bits.setBit (i / 2, original [i] || original [i + 1]);
  59625. if (type == audioInputType)
  59626. {
  59627. config.useDefaultInputChannels = false;
  59628. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59629. }
  59630. else
  59631. {
  59632. config.useDefaultOutputChannels = false;
  59633. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59634. }
  59635. for (i = 0; i < 256; ++i)
  59636. original.setBit (i, bits [i / 2]);
  59637. }
  59638. else
  59639. {
  59640. if (type == audioInputType)
  59641. {
  59642. config.useDefaultInputChannels = false;
  59643. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59644. }
  59645. else
  59646. {
  59647. config.useDefaultOutputChannels = false;
  59648. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59649. }
  59650. }
  59651. String error (setup.manager->setAudioDeviceSetup (config, true));
  59652. if (! error.isEmpty())
  59653. {
  59654. //xxx
  59655. }
  59656. }
  59657. }
  59658. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59659. {
  59660. const int numActive = chans.countNumberOfSetBits();
  59661. if (chans [index])
  59662. {
  59663. if (numActive > minNumber)
  59664. chans.setBit (index, false);
  59665. }
  59666. else
  59667. {
  59668. if (numActive >= maxNumber)
  59669. {
  59670. const int firstActiveChan = chans.findNextSetBit();
  59671. chans.setBit (index > firstActiveChan
  59672. ? firstActiveChan : chans.getHighestBit(),
  59673. false);
  59674. }
  59675. chans.setBit (index, true);
  59676. }
  59677. }
  59678. int getTickX() const
  59679. {
  59680. return getRowHeight() + 5;
  59681. }
  59682. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59683. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59684. };
  59685. private:
  59686. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59687. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59688. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59689. };
  59690. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59691. const int minInputChannels_,
  59692. const int maxInputChannels_,
  59693. const int minOutputChannels_,
  59694. const int maxOutputChannels_,
  59695. const bool showMidiInputOptions,
  59696. const bool showMidiOutputSelector,
  59697. const bool showChannelsAsStereoPairs_,
  59698. const bool hideAdvancedOptionsWithButton_)
  59699. : deviceManager (deviceManager_),
  59700. deviceTypeDropDown (0),
  59701. deviceTypeDropDownLabel (0),
  59702. minOutputChannels (minOutputChannels_),
  59703. maxOutputChannels (maxOutputChannels_),
  59704. minInputChannels (minInputChannels_),
  59705. maxInputChannels (maxInputChannels_),
  59706. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59707. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59708. {
  59709. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59710. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59711. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59712. {
  59713. deviceTypeDropDown = new ComboBox (String::empty);
  59714. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59715. {
  59716. deviceTypeDropDown
  59717. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59718. i + 1);
  59719. }
  59720. addAndMakeVisible (deviceTypeDropDown);
  59721. deviceTypeDropDown->addListener (this);
  59722. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59723. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59724. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59725. }
  59726. if (showMidiInputOptions)
  59727. {
  59728. addAndMakeVisible (midiInputsList
  59729. = new MidiInputSelectorComponentListBox (deviceManager,
  59730. TRANS("(no midi inputs available)"),
  59731. 0, 0));
  59732. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59733. midiInputsLabel->setJustificationType (Justification::topRight);
  59734. midiInputsLabel->attachToComponent (midiInputsList, true);
  59735. }
  59736. else
  59737. {
  59738. midiInputsList = 0;
  59739. midiInputsLabel = 0;
  59740. }
  59741. if (showMidiOutputSelector)
  59742. {
  59743. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59744. midiOutputSelector->addListener (this);
  59745. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59746. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59747. }
  59748. else
  59749. {
  59750. midiOutputSelector = 0;
  59751. midiOutputLabel = 0;
  59752. }
  59753. deviceManager_.addChangeListener (this);
  59754. changeListenerCallback (0);
  59755. }
  59756. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59757. {
  59758. deviceManager.removeChangeListener (this);
  59759. }
  59760. void AudioDeviceSelectorComponent::resized()
  59761. {
  59762. const int lx = proportionOfWidth (0.35f);
  59763. const int w = proportionOfWidth (0.4f);
  59764. const int h = 24;
  59765. const int space = 6;
  59766. const int dh = h + space;
  59767. int y = 15;
  59768. if (deviceTypeDropDown != 0)
  59769. {
  59770. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59771. y += dh + space * 2;
  59772. }
  59773. if (audioDeviceSettingsComp != 0)
  59774. {
  59775. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59776. y += audioDeviceSettingsComp->getHeight() + space;
  59777. }
  59778. if (midiInputsList != 0)
  59779. {
  59780. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59781. midiInputsList->setBounds (lx, y, w, bh);
  59782. y += bh + space;
  59783. }
  59784. if (midiOutputSelector != 0)
  59785. midiOutputSelector->setBounds (lx, y, w, h);
  59786. }
  59787. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59788. {
  59789. if (child == audioDeviceSettingsComp)
  59790. resized();
  59791. }
  59792. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59793. {
  59794. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59795. if (device != 0 && device->hasControlPanel())
  59796. {
  59797. if (device->showControlPanel())
  59798. deviceManager.restartLastAudioDevice();
  59799. getTopLevelComponent()->toFront (true);
  59800. }
  59801. }
  59802. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59803. {
  59804. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59805. {
  59806. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59807. if (type != 0)
  59808. {
  59809. audioDeviceSettingsComp = 0;
  59810. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59811. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59812. }
  59813. }
  59814. else if (comboBoxThatHasChanged == midiOutputSelector)
  59815. {
  59816. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59817. }
  59818. }
  59819. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59820. {
  59821. if (deviceTypeDropDown != 0)
  59822. {
  59823. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59824. }
  59825. if (audioDeviceSettingsComp == 0
  59826. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59827. {
  59828. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59829. audioDeviceSettingsComp = 0;
  59830. AudioIODeviceType* const type
  59831. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59832. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59833. if (type != 0)
  59834. {
  59835. AudioIODeviceType::DeviceSetupDetails details;
  59836. details.manager = &deviceManager;
  59837. details.minNumInputChannels = minInputChannels;
  59838. details.maxNumInputChannels = maxInputChannels;
  59839. details.minNumOutputChannels = minOutputChannels;
  59840. details.maxNumOutputChannels = maxOutputChannels;
  59841. details.useStereoPairs = showChannelsAsStereoPairs;
  59842. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59843. if (audioDeviceSettingsComp != 0)
  59844. {
  59845. addAndMakeVisible (audioDeviceSettingsComp);
  59846. audioDeviceSettingsComp->resized();
  59847. }
  59848. }
  59849. }
  59850. if (midiInputsList != 0)
  59851. {
  59852. midiInputsList->updateContent();
  59853. midiInputsList->repaint();
  59854. }
  59855. if (midiOutputSelector != 0)
  59856. {
  59857. midiOutputSelector->clear();
  59858. const StringArray midiOuts (MidiOutput::getDevices());
  59859. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59860. midiOutputSelector->addSeparator();
  59861. for (int i = 0; i < midiOuts.size(); ++i)
  59862. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59863. int current = -1;
  59864. if (deviceManager.getDefaultMidiOutput() != 0)
  59865. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59866. midiOutputSelector->setSelectedId (current, true);
  59867. }
  59868. resized();
  59869. }
  59870. END_JUCE_NAMESPACE
  59871. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59872. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59873. BEGIN_JUCE_NAMESPACE
  59874. BubbleComponent::BubbleComponent()
  59875. : side (0),
  59876. allowablePlacements (above | below | left | right),
  59877. arrowTipX (0.0f),
  59878. arrowTipY (0.0f)
  59879. {
  59880. setInterceptsMouseClicks (false, false);
  59881. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59882. setComponentEffect (&shadow);
  59883. }
  59884. BubbleComponent::~BubbleComponent()
  59885. {
  59886. }
  59887. void BubbleComponent::paint (Graphics& g)
  59888. {
  59889. int x = content.getX();
  59890. int y = content.getY();
  59891. int w = content.getWidth();
  59892. int h = content.getHeight();
  59893. int cw, ch;
  59894. getContentSize (cw, ch);
  59895. if (side == 3)
  59896. x += w - cw;
  59897. else if (side != 1)
  59898. x += (w - cw) / 2;
  59899. w = cw;
  59900. if (side == 2)
  59901. y += h - ch;
  59902. else if (side != 0)
  59903. y += (h - ch) / 2;
  59904. h = ch;
  59905. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59906. (float) x, (float) y,
  59907. (float) w, (float) h);
  59908. const int cx = x + (w - cw) / 2;
  59909. const int cy = y + (h - ch) / 2;
  59910. const int indent = 3;
  59911. g.setOrigin (cx + indent, cy + indent);
  59912. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59913. paintContent (g, cw - indent * 2, ch - indent * 2);
  59914. }
  59915. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59916. {
  59917. allowablePlacements = newPlacement;
  59918. }
  59919. void BubbleComponent::setPosition (Component* componentToPointTo)
  59920. {
  59921. jassert (componentToPointTo->isValidComponent());
  59922. Point<int> pos;
  59923. if (getParentComponent() != 0)
  59924. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59925. else
  59926. pos = componentToPointTo->relativePositionToGlobal (pos);
  59927. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59928. }
  59929. void BubbleComponent::setPosition (const int arrowTipX_,
  59930. const int arrowTipY_)
  59931. {
  59932. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59933. }
  59934. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59935. {
  59936. Rectangle<int> availableSpace;
  59937. if (getParentComponent() != 0)
  59938. {
  59939. availableSpace.setSize (getParentComponent()->getWidth(),
  59940. getParentComponent()->getHeight());
  59941. }
  59942. else
  59943. {
  59944. availableSpace = getParentMonitorArea();
  59945. }
  59946. int x = 0;
  59947. int y = 0;
  59948. int w = 150;
  59949. int h = 30;
  59950. getContentSize (w, h);
  59951. w += 30;
  59952. h += 30;
  59953. const float edgeIndent = 2.0f;
  59954. const int arrowLength = jmin (10, h / 3, w / 3);
  59955. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59956. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59957. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59958. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59959. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59960. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59961. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59962. {
  59963. spaceLeft = spaceRight = 0;
  59964. }
  59965. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59966. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59967. {
  59968. spaceAbove = spaceBelow = 0;
  59969. }
  59970. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59971. {
  59972. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59973. arrowTipX = w * 0.5f;
  59974. content.setSize (w, h - arrowLength);
  59975. if (spaceAbove >= spaceBelow)
  59976. {
  59977. // above
  59978. y = rectangleToPointTo.getY() - h;
  59979. content.setPosition (0, 0);
  59980. arrowTipY = h - edgeIndent;
  59981. side = 2;
  59982. }
  59983. else
  59984. {
  59985. // below
  59986. y = rectangleToPointTo.getBottom();
  59987. content.setPosition (0, arrowLength);
  59988. arrowTipY = edgeIndent;
  59989. side = 0;
  59990. }
  59991. }
  59992. else
  59993. {
  59994. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59995. arrowTipY = h * 0.5f;
  59996. content.setSize (w - arrowLength, h);
  59997. if (spaceLeft > spaceRight)
  59998. {
  59999. // on the left
  60000. x = rectangleToPointTo.getX() - w;
  60001. content.setPosition (0, 0);
  60002. arrowTipX = w - edgeIndent;
  60003. side = 3;
  60004. }
  60005. else
  60006. {
  60007. // on the right
  60008. x = rectangleToPointTo.getRight();
  60009. content.setPosition (arrowLength, 0);
  60010. arrowTipX = edgeIndent;
  60011. side = 1;
  60012. }
  60013. }
  60014. setBounds (x, y, w, h);
  60015. }
  60016. END_JUCE_NAMESPACE
  60017. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  60018. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  60019. BEGIN_JUCE_NAMESPACE
  60020. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  60021. : fadeOutLength (fadeOutLengthMs),
  60022. deleteAfterUse (false)
  60023. {
  60024. }
  60025. BubbleMessageComponent::~BubbleMessageComponent()
  60026. {
  60027. fadeOutComponent (fadeOutLength);
  60028. }
  60029. void BubbleMessageComponent::showAt (int x, int y,
  60030. const String& text,
  60031. const int numMillisecondsBeforeRemoving,
  60032. const bool removeWhenMouseClicked,
  60033. const bool deleteSelfAfterUse)
  60034. {
  60035. textLayout.clear();
  60036. textLayout.setText (text, Font (14.0f));
  60037. textLayout.layout (256, Justification::centredLeft, true);
  60038. setPosition (x, y);
  60039. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  60040. }
  60041. void BubbleMessageComponent::showAt (Component* const component,
  60042. const String& text,
  60043. const int numMillisecondsBeforeRemoving,
  60044. const bool removeWhenMouseClicked,
  60045. const bool deleteSelfAfterUse)
  60046. {
  60047. textLayout.clear();
  60048. textLayout.setText (text, Font (14.0f));
  60049. textLayout.layout (256, Justification::centredLeft, true);
  60050. setPosition (component);
  60051. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  60052. }
  60053. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  60054. const bool removeWhenMouseClicked,
  60055. const bool deleteSelfAfterUse)
  60056. {
  60057. setVisible (true);
  60058. deleteAfterUse = deleteSelfAfterUse;
  60059. if (numMillisecondsBeforeRemoving > 0)
  60060. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  60061. else
  60062. expiryTime = 0;
  60063. startTimer (77);
  60064. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  60065. if (! (removeWhenMouseClicked && isShowing()))
  60066. mouseClickCounter += 0xfffff;
  60067. repaint();
  60068. }
  60069. void BubbleMessageComponent::getContentSize (int& w, int& h)
  60070. {
  60071. w = textLayout.getWidth() + 16;
  60072. h = textLayout.getHeight() + 16;
  60073. }
  60074. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  60075. {
  60076. g.setColour (findColour (TooltipWindow::textColourId));
  60077. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  60078. }
  60079. void BubbleMessageComponent::timerCallback()
  60080. {
  60081. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  60082. {
  60083. stopTimer();
  60084. setVisible (false);
  60085. if (deleteAfterUse)
  60086. delete this;
  60087. }
  60088. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  60089. {
  60090. stopTimer();
  60091. fadeOutComponent (fadeOutLength);
  60092. if (deleteAfterUse)
  60093. delete this;
  60094. }
  60095. }
  60096. END_JUCE_NAMESPACE
  60097. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  60098. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  60099. BEGIN_JUCE_NAMESPACE
  60100. class ColourComponentSlider : public Slider
  60101. {
  60102. public:
  60103. ColourComponentSlider (const String& name)
  60104. : Slider (name)
  60105. {
  60106. setRange (0.0, 255.0, 1.0);
  60107. }
  60108. ~ColourComponentSlider()
  60109. {
  60110. }
  60111. const String getTextFromValue (double value)
  60112. {
  60113. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  60114. }
  60115. double getValueFromText (const String& text)
  60116. {
  60117. return (double) text.getHexValue32();
  60118. }
  60119. private:
  60120. ColourComponentSlider (const ColourComponentSlider&);
  60121. ColourComponentSlider& operator= (const ColourComponentSlider&);
  60122. };
  60123. class ColourSpaceMarker : public Component
  60124. {
  60125. public:
  60126. ColourSpaceMarker()
  60127. {
  60128. setInterceptsMouseClicks (false, false);
  60129. }
  60130. ~ColourSpaceMarker()
  60131. {
  60132. }
  60133. void paint (Graphics& g)
  60134. {
  60135. g.setColour (Colour::greyLevel (0.1f));
  60136. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  60137. g.setColour (Colour::greyLevel (0.9f));
  60138. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  60139. }
  60140. private:
  60141. ColourSpaceMarker (const ColourSpaceMarker&);
  60142. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  60143. };
  60144. class ColourSelector::ColourSpaceView : public Component
  60145. {
  60146. public:
  60147. ColourSpaceView (ColourSelector* owner_,
  60148. float& h_, float& s_, float& v_,
  60149. const int edgeSize)
  60150. : owner (owner_),
  60151. h (h_), s (s_), v (v_),
  60152. lastHue (0.0f),
  60153. edge (edgeSize)
  60154. {
  60155. addAndMakeVisible (&marker);
  60156. setMouseCursor (MouseCursor::CrosshairCursor);
  60157. }
  60158. ~ColourSpaceView()
  60159. {
  60160. }
  60161. void paint (Graphics& g)
  60162. {
  60163. if (colours.isNull())
  60164. {
  60165. const int width = getWidth() / 2;
  60166. const int height = getHeight() / 2;
  60167. colours = Image (Image::RGB, width, height, false);
  60168. Image::BitmapData pixels (colours, true);
  60169. for (int y = 0; y < height; ++y)
  60170. {
  60171. const float val = 1.0f - y / (float) height;
  60172. for (int x = 0; x < width; ++x)
  60173. {
  60174. const float sat = x / (float) width;
  60175. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  60176. }
  60177. }
  60178. }
  60179. g.setOpacity (1.0f);
  60180. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  60181. 0, 0, colours.getWidth(), colours.getHeight());
  60182. }
  60183. void mouseDown (const MouseEvent& e)
  60184. {
  60185. mouseDrag (e);
  60186. }
  60187. void mouseDrag (const MouseEvent& e)
  60188. {
  60189. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  60190. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  60191. owner->setSV (sat, val);
  60192. }
  60193. void updateIfNeeded()
  60194. {
  60195. if (lastHue != h)
  60196. {
  60197. lastHue = h;
  60198. colours = Image::null;
  60199. repaint();
  60200. }
  60201. updateMarker();
  60202. }
  60203. void resized()
  60204. {
  60205. colours = Image::null;
  60206. updateMarker();
  60207. }
  60208. private:
  60209. ColourSelector* const owner;
  60210. float& h;
  60211. float& s;
  60212. float& v;
  60213. float lastHue;
  60214. ColourSpaceMarker marker;
  60215. const int edge;
  60216. Image colours;
  60217. void updateMarker()
  60218. {
  60219. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  60220. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  60221. edge * 2, edge * 2);
  60222. }
  60223. ColourSpaceView (const ColourSpaceView&);
  60224. ColourSpaceView& operator= (const ColourSpaceView&);
  60225. };
  60226. class HueSelectorMarker : public Component
  60227. {
  60228. public:
  60229. HueSelectorMarker()
  60230. {
  60231. setInterceptsMouseClicks (false, false);
  60232. }
  60233. ~HueSelectorMarker()
  60234. {
  60235. }
  60236. void paint (Graphics& g)
  60237. {
  60238. Path p;
  60239. p.addTriangle (1.0f, 1.0f,
  60240. getWidth() * 0.3f, getHeight() * 0.5f,
  60241. 1.0f, getHeight() - 1.0f);
  60242. p.addTriangle (getWidth() - 1.0f, 1.0f,
  60243. getWidth() * 0.7f, getHeight() * 0.5f,
  60244. getWidth() - 1.0f, getHeight() - 1.0f);
  60245. g.setColour (Colours::white.withAlpha (0.75f));
  60246. g.fillPath (p);
  60247. g.setColour (Colours::black.withAlpha (0.75f));
  60248. g.strokePath (p, PathStrokeType (1.2f));
  60249. }
  60250. private:
  60251. HueSelectorMarker (const HueSelectorMarker&);
  60252. HueSelectorMarker& operator= (const HueSelectorMarker&);
  60253. };
  60254. class ColourSelector::HueSelectorComp : public Component
  60255. {
  60256. public:
  60257. HueSelectorComp (ColourSelector* owner_,
  60258. float& h_, float& s_, float& v_,
  60259. const int edgeSize)
  60260. : owner (owner_),
  60261. h (h_), s (s_), v (v_),
  60262. lastHue (0.0f),
  60263. edge (edgeSize)
  60264. {
  60265. addAndMakeVisible (&marker);
  60266. }
  60267. ~HueSelectorComp()
  60268. {
  60269. }
  60270. void paint (Graphics& g)
  60271. {
  60272. const float yScale = 1.0f / (getHeight() - edge * 2);
  60273. const Rectangle<int> clip (g.getClipBounds());
  60274. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  60275. {
  60276. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60277. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60278. }
  60279. }
  60280. void resized()
  60281. {
  60282. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60283. getWidth(), edge * 2);
  60284. }
  60285. void mouseDown (const MouseEvent& e)
  60286. {
  60287. mouseDrag (e);
  60288. }
  60289. void mouseDrag (const MouseEvent& e)
  60290. {
  60291. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60292. owner->setHue (hue);
  60293. }
  60294. void updateIfNeeded()
  60295. {
  60296. resized();
  60297. }
  60298. private:
  60299. ColourSelector* const owner;
  60300. float& h;
  60301. float& s;
  60302. float& v;
  60303. float lastHue;
  60304. HueSelectorMarker marker;
  60305. const int edge;
  60306. HueSelectorComp (const HueSelectorComp&);
  60307. HueSelectorComp& operator= (const HueSelectorComp&);
  60308. };
  60309. class ColourSelector::SwatchComponent : public Component
  60310. {
  60311. public:
  60312. SwatchComponent (ColourSelector* owner_, int index_)
  60313. : owner (owner_),
  60314. index (index_)
  60315. {
  60316. }
  60317. ~SwatchComponent()
  60318. {
  60319. }
  60320. void paint (Graphics& g)
  60321. {
  60322. const Colour colour (owner->getSwatchColour (index));
  60323. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60324. Colour (0xffdddddd).overlaidWith (colour),
  60325. Colour (0xffffffff).overlaidWith (colour));
  60326. }
  60327. void mouseDown (const MouseEvent&)
  60328. {
  60329. PopupMenu m;
  60330. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60331. m.addSeparator();
  60332. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60333. const int r = m.showAt (this);
  60334. if (r == 1)
  60335. {
  60336. owner->setCurrentColour (owner->getSwatchColour (index));
  60337. }
  60338. else if (r == 2)
  60339. {
  60340. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  60341. {
  60342. owner->setSwatchColour (index, owner->getCurrentColour());
  60343. repaint();
  60344. }
  60345. }
  60346. }
  60347. private:
  60348. ColourSelector* const owner;
  60349. const int index;
  60350. SwatchComponent (const SwatchComponent&);
  60351. SwatchComponent& operator= (const SwatchComponent&);
  60352. };
  60353. ColourSelector::ColourSelector (const int flags_,
  60354. const int edgeGap_,
  60355. const int gapAroundColourSpaceComponent)
  60356. : colour (Colours::white),
  60357. colourSpace (0),
  60358. hueSelector (0),
  60359. flags (flags_),
  60360. edgeGap (edgeGap_)
  60361. {
  60362. // not much point having a selector with no components in it!
  60363. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60364. updateHSV();
  60365. if ((flags & showSliders) != 0)
  60366. {
  60367. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60368. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60369. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60370. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60371. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60372. for (int i = 4; --i >= 0;)
  60373. sliders[i]->addListener (this);
  60374. }
  60375. else
  60376. {
  60377. zeromem (sliders, sizeof (sliders));
  60378. }
  60379. if ((flags & showColourspace) != 0)
  60380. {
  60381. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  60382. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  60383. }
  60384. update();
  60385. }
  60386. ColourSelector::~ColourSelector()
  60387. {
  60388. dispatchPendingMessages();
  60389. swatchComponents.clear();
  60390. deleteAllChildren();
  60391. }
  60392. const Colour ColourSelector::getCurrentColour() const
  60393. {
  60394. return ((flags & showAlphaChannel) != 0) ? colour
  60395. : colour.withAlpha ((uint8) 0xff);
  60396. }
  60397. void ColourSelector::setCurrentColour (const Colour& c)
  60398. {
  60399. if (c != colour)
  60400. {
  60401. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60402. updateHSV();
  60403. update();
  60404. }
  60405. }
  60406. void ColourSelector::setHue (float newH)
  60407. {
  60408. newH = jlimit (0.0f, 1.0f, newH);
  60409. if (h != newH)
  60410. {
  60411. h = newH;
  60412. colour = Colour (h, s, v, colour.getFloatAlpha());
  60413. update();
  60414. }
  60415. }
  60416. void ColourSelector::setSV (float newS, float newV)
  60417. {
  60418. newS = jlimit (0.0f, 1.0f, newS);
  60419. newV = jlimit (0.0f, 1.0f, newV);
  60420. if (s != newS || v != newV)
  60421. {
  60422. s = newS;
  60423. v = newV;
  60424. colour = Colour (h, s, v, colour.getFloatAlpha());
  60425. update();
  60426. }
  60427. }
  60428. void ColourSelector::updateHSV()
  60429. {
  60430. colour.getHSB (h, s, v);
  60431. }
  60432. void ColourSelector::update()
  60433. {
  60434. if (sliders[0] != 0)
  60435. {
  60436. sliders[0]->setValue ((int) colour.getRed());
  60437. sliders[1]->setValue ((int) colour.getGreen());
  60438. sliders[2]->setValue ((int) colour.getBlue());
  60439. sliders[3]->setValue ((int) colour.getAlpha());
  60440. }
  60441. if (colourSpace != 0)
  60442. {
  60443. colourSpace->updateIfNeeded();
  60444. hueSelector->updateIfNeeded();
  60445. }
  60446. if ((flags & showColourAtTop) != 0)
  60447. repaint (previewArea);
  60448. sendChangeMessage (this);
  60449. }
  60450. void ColourSelector::paint (Graphics& g)
  60451. {
  60452. g.fillAll (findColour (backgroundColourId));
  60453. if ((flags & showColourAtTop) != 0)
  60454. {
  60455. const Colour currentColour (getCurrentColour());
  60456. g.fillCheckerBoard (previewArea, 10, 10,
  60457. Colour (0xffdddddd).overlaidWith (currentColour),
  60458. Colour (0xffffffff).overlaidWith (currentColour));
  60459. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60460. g.setFont (14.0f, true);
  60461. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60462. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60463. Justification::centred, false);
  60464. }
  60465. if ((flags & showSliders) != 0)
  60466. {
  60467. g.setColour (findColour (labelTextColourId));
  60468. g.setFont (11.0f);
  60469. for (int i = 4; --i >= 0;)
  60470. {
  60471. if (sliders[i]->isVisible())
  60472. g.drawText (sliders[i]->getName() + ":",
  60473. 0, sliders[i]->getY(),
  60474. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60475. Justification::centredRight, false);
  60476. }
  60477. }
  60478. }
  60479. void ColourSelector::resized()
  60480. {
  60481. const int swatchesPerRow = 8;
  60482. const int swatchHeight = 22;
  60483. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60484. const int numSwatches = getNumSwatches();
  60485. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60486. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60487. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60488. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60489. int y = topSpace;
  60490. if ((flags & showColourspace) != 0)
  60491. {
  60492. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60493. colourSpace->setBounds (edgeGap, y,
  60494. getWidth() - hueWidth - edgeGap - 4,
  60495. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60496. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60497. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60498. colourSpace->getHeight());
  60499. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60500. }
  60501. if ((flags & showSliders) != 0)
  60502. {
  60503. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60504. for (int i = 0; i < numSliders; ++i)
  60505. {
  60506. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60507. proportionOfWidth (0.72f), sliderHeight - 2);
  60508. y += sliderHeight;
  60509. }
  60510. }
  60511. if (numSwatches > 0)
  60512. {
  60513. const int startX = 8;
  60514. const int xGap = 4;
  60515. const int yGap = 4;
  60516. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60517. y += edgeGap;
  60518. if (swatchComponents.size() != numSwatches)
  60519. {
  60520. swatchComponents.clear();
  60521. for (int i = 0; i < numSwatches; ++i)
  60522. {
  60523. SwatchComponent* const sc = new SwatchComponent (this, i);
  60524. swatchComponents.add (sc);
  60525. addAndMakeVisible (sc);
  60526. }
  60527. }
  60528. int x = startX;
  60529. for (int i = 0; i < swatchComponents.size(); ++i)
  60530. {
  60531. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60532. sc->setBounds (x + xGap / 2,
  60533. y + yGap / 2,
  60534. swatchWidth - xGap,
  60535. swatchHeight - yGap);
  60536. if (((i + 1) % swatchesPerRow) == 0)
  60537. {
  60538. x = startX;
  60539. y += swatchHeight;
  60540. }
  60541. else
  60542. {
  60543. x += swatchWidth;
  60544. }
  60545. }
  60546. }
  60547. }
  60548. void ColourSelector::sliderValueChanged (Slider*)
  60549. {
  60550. if (sliders[0] != 0)
  60551. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60552. (uint8) sliders[1]->getValue(),
  60553. (uint8) sliders[2]->getValue(),
  60554. (uint8) sliders[3]->getValue()));
  60555. }
  60556. int ColourSelector::getNumSwatches() const
  60557. {
  60558. return 0;
  60559. }
  60560. const Colour ColourSelector::getSwatchColour (const int) const
  60561. {
  60562. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60563. return Colours::black;
  60564. }
  60565. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60566. {
  60567. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60568. }
  60569. END_JUCE_NAMESPACE
  60570. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60571. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60572. BEGIN_JUCE_NAMESPACE
  60573. class ShadowWindow : public Component
  60574. {
  60575. Component* owner;
  60576. Image shadowImageSections [12];
  60577. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60578. public:
  60579. ShadowWindow (Component* const owner_,
  60580. const int type_,
  60581. const Image shadowImageSections_ [12])
  60582. : owner (owner_),
  60583. type (type_)
  60584. {
  60585. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60586. shadowImageSections [i] = shadowImageSections_ [i];
  60587. setInterceptsMouseClicks (false, false);
  60588. if (owner_->isOnDesktop())
  60589. {
  60590. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60591. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60592. | ComponentPeer::windowIsTemporary
  60593. | ComponentPeer::windowIgnoresKeyPresses);
  60594. }
  60595. else if (owner_->getParentComponent() != 0)
  60596. {
  60597. owner_->getParentComponent()->addChildComponent (this);
  60598. }
  60599. }
  60600. ~ShadowWindow()
  60601. {
  60602. }
  60603. void paint (Graphics& g)
  60604. {
  60605. const Image& topLeft = shadowImageSections [type * 3];
  60606. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60607. const Image& filler = shadowImageSections [type * 3 + 2];
  60608. g.setOpacity (1.0f);
  60609. if (type < 2)
  60610. {
  60611. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60612. g.drawImage (topLeft,
  60613. 0, 0, topLeft.getWidth(), imH,
  60614. 0, 0, topLeft.getWidth(), imH);
  60615. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60616. g.drawImage (bottomRight,
  60617. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60618. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60619. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60620. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60621. }
  60622. else
  60623. {
  60624. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60625. g.drawImage (topLeft,
  60626. 0, 0, imW, topLeft.getHeight(),
  60627. 0, 0, imW, topLeft.getHeight());
  60628. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60629. g.drawImage (bottomRight,
  60630. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60631. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60632. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60633. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60634. }
  60635. }
  60636. void resized()
  60637. {
  60638. repaint(); // (needed for correct repainting)
  60639. }
  60640. private:
  60641. ShadowWindow (const ShadowWindow&);
  60642. ShadowWindow& operator= (const ShadowWindow&);
  60643. };
  60644. DropShadower::DropShadower (const float alpha_,
  60645. const int xOffset_,
  60646. const int yOffset_,
  60647. const float blurRadius_)
  60648. : owner (0),
  60649. numShadows (0),
  60650. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60651. xOffset (xOffset_),
  60652. yOffset (yOffset_),
  60653. alpha (alpha_),
  60654. blurRadius (blurRadius_),
  60655. inDestructor (false),
  60656. reentrant (false)
  60657. {
  60658. }
  60659. DropShadower::~DropShadower()
  60660. {
  60661. if (owner != 0)
  60662. owner->removeComponentListener (this);
  60663. inDestructor = true;
  60664. deleteShadowWindows();
  60665. }
  60666. void DropShadower::deleteShadowWindows()
  60667. {
  60668. if (numShadows > 0)
  60669. {
  60670. int i;
  60671. for (i = numShadows; --i >= 0;)
  60672. delete shadowWindows[i];
  60673. numShadows = 0;
  60674. }
  60675. }
  60676. void DropShadower::setOwner (Component* componentToFollow)
  60677. {
  60678. if (componentToFollow != owner)
  60679. {
  60680. if (owner != 0)
  60681. owner->removeComponentListener (this);
  60682. // (the component can't be null)
  60683. jassert (componentToFollow != 0);
  60684. owner = componentToFollow;
  60685. jassert (owner != 0);
  60686. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60687. owner->addComponentListener (this);
  60688. updateShadows();
  60689. }
  60690. }
  60691. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60692. {
  60693. updateShadows();
  60694. }
  60695. void DropShadower::componentBroughtToFront (Component&)
  60696. {
  60697. bringShadowWindowsToFront();
  60698. }
  60699. void DropShadower::componentChildrenChanged (Component&)
  60700. {
  60701. }
  60702. void DropShadower::componentParentHierarchyChanged (Component&)
  60703. {
  60704. deleteShadowWindows();
  60705. updateShadows();
  60706. }
  60707. void DropShadower::componentVisibilityChanged (Component&)
  60708. {
  60709. updateShadows();
  60710. }
  60711. void DropShadower::updateShadows()
  60712. {
  60713. if (reentrant || inDestructor || (owner == 0))
  60714. return;
  60715. reentrant = true;
  60716. ComponentPeer* const nw = owner->getPeer();
  60717. const bool isOwnerVisible = owner->isVisible()
  60718. && (nw == 0 || ! nw->isMinimised());
  60719. const bool createShadowWindows = numShadows == 0
  60720. && owner->getWidth() > 0
  60721. && owner->getHeight() > 0
  60722. && isOwnerVisible
  60723. && (Desktop::canUseSemiTransparentWindows()
  60724. || owner->getParentComponent() != 0);
  60725. if (createShadowWindows)
  60726. {
  60727. // keep a cached version of the image to save doing the gaussian too often
  60728. String imageId;
  60729. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60730. const int hash = imageId.hashCode();
  60731. Image bigIm (ImageCache::getFromHashCode (hash));
  60732. if (bigIm.isNull())
  60733. {
  60734. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60735. Graphics bigG (bigIm);
  60736. bigG.setColour (Colours::black.withAlpha (alpha));
  60737. bigG.fillRect (shadowEdge + xOffset,
  60738. shadowEdge + yOffset,
  60739. bigIm.getWidth() - (shadowEdge * 2),
  60740. bigIm.getHeight() - (shadowEdge * 2));
  60741. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60742. blurKernel.createGaussianBlur (blurRadius);
  60743. blurKernel.applyToImage (bigIm, bigIm,
  60744. Rectangle<int> (xOffset, yOffset,
  60745. bigIm.getWidth(), bigIm.getHeight()));
  60746. ImageCache::addImageToCache (bigIm, hash);
  60747. }
  60748. const int iw = bigIm.getWidth();
  60749. const int ih = bigIm.getHeight();
  60750. const int shadowEdge2 = shadowEdge * 2;
  60751. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60752. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60753. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60754. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60755. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60756. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60757. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60758. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60759. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60760. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60761. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60762. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60763. for (int i = 0; i < 4; ++i)
  60764. {
  60765. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60766. ++numShadows;
  60767. }
  60768. }
  60769. if (numShadows > 0)
  60770. {
  60771. for (int i = numShadows; --i >= 0;)
  60772. {
  60773. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60774. shadowWindows[i]->setVisible (isOwnerVisible);
  60775. }
  60776. const int x = owner->getX();
  60777. const int y = owner->getY() - shadowEdge;
  60778. const int w = owner->getWidth();
  60779. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60780. shadowWindows[0]->setBounds (x - shadowEdge,
  60781. y,
  60782. shadowEdge,
  60783. h);
  60784. shadowWindows[1]->setBounds (x + w,
  60785. y,
  60786. shadowEdge,
  60787. h);
  60788. shadowWindows[2]->setBounds (x,
  60789. y,
  60790. w,
  60791. shadowEdge);
  60792. shadowWindows[3]->setBounds (x,
  60793. owner->getBottom(),
  60794. w,
  60795. shadowEdge);
  60796. }
  60797. reentrant = false;
  60798. if (createShadowWindows)
  60799. bringShadowWindowsToFront();
  60800. }
  60801. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60802. const int sx, const int sy)
  60803. {
  60804. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60805. Graphics g (shadowImageSections[num]);
  60806. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60807. }
  60808. void DropShadower::bringShadowWindowsToFront()
  60809. {
  60810. if (! (inDestructor || reentrant))
  60811. {
  60812. updateShadows();
  60813. reentrant = true;
  60814. for (int i = numShadows; --i >= 0;)
  60815. shadowWindows[i]->toBehind (owner);
  60816. reentrant = false;
  60817. }
  60818. }
  60819. END_JUCE_NAMESPACE
  60820. /*** End of inlined file: juce_DropShadower.cpp ***/
  60821. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60822. BEGIN_JUCE_NAMESPACE
  60823. class MagnifyingPeer : public ComponentPeer
  60824. {
  60825. public:
  60826. MagnifyingPeer (Component* const component_,
  60827. MagnifierComponent* const magnifierComp_)
  60828. : ComponentPeer (component_, 0),
  60829. magnifierComp (magnifierComp_)
  60830. {
  60831. }
  60832. ~MagnifyingPeer()
  60833. {
  60834. }
  60835. void* getNativeHandle() const { return 0; }
  60836. void setVisible (bool) {}
  60837. void setTitle (const String&) {}
  60838. void setPosition (int, int) {}
  60839. void setSize (int, int) {}
  60840. void setBounds (int, int, int, int, bool) {}
  60841. void setMinimised (bool) {}
  60842. bool isMinimised() const { return false; }
  60843. void setFullScreen (bool) {}
  60844. bool isFullScreen() const { return false; }
  60845. const BorderSize getFrameSize() const { return BorderSize (0); }
  60846. bool setAlwaysOnTop (bool) { return true; }
  60847. void toFront (bool) {}
  60848. void toBehind (ComponentPeer*) {}
  60849. void setIcon (const Image&) {}
  60850. bool isFocused() const
  60851. {
  60852. return magnifierComp->hasKeyboardFocus (true);
  60853. }
  60854. void grabFocus()
  60855. {
  60856. ComponentPeer* peer = magnifierComp->getPeer();
  60857. if (peer != 0)
  60858. peer->grabFocus();
  60859. }
  60860. void textInputRequired (const Point<int>& position)
  60861. {
  60862. ComponentPeer* peer = magnifierComp->getPeer();
  60863. if (peer != 0)
  60864. peer->textInputRequired (position);
  60865. }
  60866. const Rectangle<int> getBounds() const
  60867. {
  60868. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60869. component->getWidth(), component->getHeight());
  60870. }
  60871. const Point<int> getScreenPosition() const
  60872. {
  60873. return magnifierComp->getScreenPosition();
  60874. }
  60875. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60876. {
  60877. const double zoom = magnifierComp->getScaleFactor();
  60878. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60879. roundToInt (relativePosition.getY() * zoom)));
  60880. }
  60881. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60882. {
  60883. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60884. const double zoom = magnifierComp->getScaleFactor();
  60885. return Point<int> (roundToInt (p.getX() / zoom),
  60886. roundToInt (p.getY() / zoom));
  60887. }
  60888. bool contains (const Point<int>& position, bool) const
  60889. {
  60890. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60891. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60892. }
  60893. void repaint (const Rectangle<int>& area)
  60894. {
  60895. const double zoom = magnifierComp->getScaleFactor();
  60896. magnifierComp->repaint ((int) (area.getX() * zoom),
  60897. (int) (area.getY() * zoom),
  60898. roundToInt (area.getWidth() * zoom) + 1,
  60899. roundToInt (area.getHeight() * zoom) + 1);
  60900. }
  60901. void performAnyPendingRepaintsNow()
  60902. {
  60903. }
  60904. juce_UseDebuggingNewOperator
  60905. private:
  60906. MagnifierComponent* const magnifierComp;
  60907. MagnifyingPeer (const MagnifyingPeer&);
  60908. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60909. };
  60910. class PeerHolderComp : public Component
  60911. {
  60912. public:
  60913. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60914. : magnifierComp (magnifierComp_)
  60915. {
  60916. setVisible (true);
  60917. }
  60918. ~PeerHolderComp()
  60919. {
  60920. }
  60921. ComponentPeer* createNewPeer (int, void*)
  60922. {
  60923. return new MagnifyingPeer (this, magnifierComp);
  60924. }
  60925. void childBoundsChanged (Component* c)
  60926. {
  60927. if (c != 0)
  60928. {
  60929. setSize (c->getWidth(), c->getHeight());
  60930. magnifierComp->childBoundsChanged (this);
  60931. }
  60932. }
  60933. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60934. {
  60935. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60936. Component* const p = magnifierComp->getParentComponent();
  60937. if (p != 0)
  60938. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60939. }
  60940. private:
  60941. MagnifierComponent* const magnifierComp;
  60942. PeerHolderComp (const PeerHolderComp&);
  60943. PeerHolderComp& operator= (const PeerHolderComp&);
  60944. };
  60945. MagnifierComponent::MagnifierComponent (Component* const content_,
  60946. const bool deleteContentCompWhenNoLongerNeeded)
  60947. : content (content_),
  60948. scaleFactor (0.0),
  60949. peer (0),
  60950. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60951. quality (Graphics::lowResamplingQuality),
  60952. mouseSource (0, true)
  60953. {
  60954. holderComp = new PeerHolderComp (this);
  60955. setScaleFactor (1.0);
  60956. }
  60957. MagnifierComponent::~MagnifierComponent()
  60958. {
  60959. delete holderComp;
  60960. if (deleteContent)
  60961. delete content;
  60962. }
  60963. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60964. {
  60965. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60966. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60967. if (scaleFactor != newScaleFactor)
  60968. {
  60969. scaleFactor = newScaleFactor;
  60970. if (scaleFactor == 1.0)
  60971. {
  60972. holderComp->removeFromDesktop();
  60973. peer = 0;
  60974. addChildComponent (content);
  60975. childBoundsChanged (content);
  60976. }
  60977. else
  60978. {
  60979. holderComp->addAndMakeVisible (content);
  60980. holderComp->childBoundsChanged (content);
  60981. childBoundsChanged (holderComp);
  60982. holderComp->addToDesktop (0);
  60983. peer = holderComp->getPeer();
  60984. }
  60985. repaint();
  60986. }
  60987. }
  60988. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60989. {
  60990. quality = newQuality;
  60991. }
  60992. void MagnifierComponent::paint (Graphics& g)
  60993. {
  60994. const int w = holderComp->getWidth();
  60995. const int h = holderComp->getHeight();
  60996. if (w == 0 || h == 0)
  60997. return;
  60998. const Rectangle<int> r (g.getClipBounds());
  60999. const int srcX = (int) (r.getX() / scaleFactor);
  61000. const int srcY = (int) (r.getY() / scaleFactor);
  61001. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  61002. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  61003. if (scaleFactor >= 1.0)
  61004. {
  61005. ++srcW;
  61006. ++srcH;
  61007. }
  61008. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  61009. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  61010. {
  61011. Graphics g2 (temp);
  61012. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  61013. holderComp->paintEntireComponent (g2);
  61014. }
  61015. g.setImageResamplingQuality (quality);
  61016. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  61017. }
  61018. void MagnifierComponent::childBoundsChanged (Component* c)
  61019. {
  61020. if (c != 0)
  61021. setSize (roundToInt (c->getWidth() * scaleFactor),
  61022. roundToInt (c->getHeight() * scaleFactor));
  61023. }
  61024. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  61025. {
  61026. if (peer != 0)
  61027. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  61028. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  61029. }
  61030. void MagnifierComponent::mouseDown (const MouseEvent& e)
  61031. {
  61032. passOnMouseEventToPeer (e);
  61033. }
  61034. void MagnifierComponent::mouseUp (const MouseEvent& e)
  61035. {
  61036. passOnMouseEventToPeer (e);
  61037. }
  61038. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  61039. {
  61040. passOnMouseEventToPeer (e);
  61041. }
  61042. void MagnifierComponent::mouseMove (const MouseEvent& e)
  61043. {
  61044. passOnMouseEventToPeer (e);
  61045. }
  61046. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  61047. {
  61048. passOnMouseEventToPeer (e);
  61049. }
  61050. void MagnifierComponent::mouseExit (const MouseEvent& e)
  61051. {
  61052. passOnMouseEventToPeer (e);
  61053. }
  61054. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  61055. {
  61056. if (peer != 0)
  61057. peer->handleMouseWheel (e.source.getIndex(),
  61058. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  61059. ix * 256.0f, iy * 256.0f);
  61060. else
  61061. Component::mouseWheelMove (e, ix, iy);
  61062. }
  61063. int MagnifierComponent::scaleInt (const int n) const
  61064. {
  61065. return roundToInt (n / scaleFactor);
  61066. }
  61067. END_JUCE_NAMESPACE
  61068. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  61069. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61070. BEGIN_JUCE_NAMESPACE
  61071. class MidiKeyboardUpDownButton : public Button
  61072. {
  61073. public:
  61074. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  61075. const int delta_)
  61076. : Button (String::empty),
  61077. owner (owner_),
  61078. delta (delta_)
  61079. {
  61080. setOpaque (true);
  61081. }
  61082. ~MidiKeyboardUpDownButton()
  61083. {
  61084. }
  61085. void clicked()
  61086. {
  61087. int note = owner->getLowestVisibleKey();
  61088. if (delta < 0)
  61089. note = (note - 1) / 12;
  61090. else
  61091. note = note / 12 + 1;
  61092. owner->setLowestVisibleKey (note * 12);
  61093. }
  61094. void paintButton (Graphics& g,
  61095. bool isMouseOverButton,
  61096. bool isButtonDown)
  61097. {
  61098. owner->drawUpDownButton (g, getWidth(), getHeight(),
  61099. isMouseOverButton, isButtonDown,
  61100. delta > 0);
  61101. }
  61102. private:
  61103. MidiKeyboardComponent* const owner;
  61104. const int delta;
  61105. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  61106. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  61107. };
  61108. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  61109. const Orientation orientation_)
  61110. : state (state_),
  61111. xOffset (0),
  61112. blackNoteLength (1),
  61113. keyWidth (16.0f),
  61114. orientation (orientation_),
  61115. midiChannel (1),
  61116. midiInChannelMask (0xffff),
  61117. velocity (1.0f),
  61118. noteUnderMouse (-1),
  61119. mouseDownNote (-1),
  61120. rangeStart (0),
  61121. rangeEnd (127),
  61122. firstKey (12 * 4),
  61123. canScroll (true),
  61124. mouseDragging (false),
  61125. useMousePositionForVelocity (true),
  61126. keyMappingOctave (6),
  61127. octaveNumForMiddleC (3)
  61128. {
  61129. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  61130. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  61131. // initialise with a default set of querty key-mappings..
  61132. const char* const keymap = "awsedftgyhujkolp;";
  61133. for (int i = String (keymap).length(); --i >= 0;)
  61134. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  61135. setOpaque (true);
  61136. setWantsKeyboardFocus (true);
  61137. state.addListener (this);
  61138. }
  61139. MidiKeyboardComponent::~MidiKeyboardComponent()
  61140. {
  61141. state.removeListener (this);
  61142. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  61143. deleteAllChildren();
  61144. }
  61145. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  61146. {
  61147. keyWidth = widthInPixels;
  61148. resized();
  61149. }
  61150. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  61151. {
  61152. if (orientation != newOrientation)
  61153. {
  61154. orientation = newOrientation;
  61155. resized();
  61156. }
  61157. }
  61158. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  61159. const int highestNote)
  61160. {
  61161. jassert (lowestNote >= 0 && lowestNote <= 127);
  61162. jassert (highestNote >= 0 && highestNote <= 127);
  61163. jassert (lowestNote <= highestNote);
  61164. if (rangeStart != lowestNote || rangeEnd != highestNote)
  61165. {
  61166. rangeStart = jlimit (0, 127, lowestNote);
  61167. rangeEnd = jlimit (0, 127, highestNote);
  61168. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  61169. resized();
  61170. }
  61171. }
  61172. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  61173. {
  61174. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  61175. if (noteNumber != firstKey)
  61176. {
  61177. firstKey = noteNumber;
  61178. sendChangeMessage (this);
  61179. resized();
  61180. }
  61181. }
  61182. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  61183. {
  61184. if (canScroll != canScroll_)
  61185. {
  61186. canScroll = canScroll_;
  61187. resized();
  61188. }
  61189. }
  61190. void MidiKeyboardComponent::colourChanged()
  61191. {
  61192. repaint();
  61193. }
  61194. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  61195. {
  61196. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  61197. if (midiChannel != midiChannelNumber)
  61198. {
  61199. resetAnyKeysInUse();
  61200. midiChannel = jlimit (1, 16, midiChannelNumber);
  61201. }
  61202. }
  61203. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  61204. {
  61205. midiInChannelMask = midiChannelMask;
  61206. triggerAsyncUpdate();
  61207. }
  61208. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  61209. {
  61210. velocity = jlimit (0.0f, 1.0f, velocity_);
  61211. useMousePositionForVelocity = useMousePositionForVelocity_;
  61212. }
  61213. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  61214. {
  61215. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  61216. static const float blackNoteWidth = 0.7f;
  61217. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  61218. 1.0f, 2 - blackNoteWidth * 0.4f,
  61219. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  61220. 4.0f, 5 - blackNoteWidth * 0.5f,
  61221. 5.0f, 6 - blackNoteWidth * 0.3f,
  61222. 6.0f };
  61223. static const float widths[] = { 1.0f, blackNoteWidth,
  61224. 1.0f, blackNoteWidth,
  61225. 1.0f, 1.0f, blackNoteWidth,
  61226. 1.0f, blackNoteWidth,
  61227. 1.0f, blackNoteWidth,
  61228. 1.0f };
  61229. const int octave = midiNoteNumber / 12;
  61230. const int note = midiNoteNumber % 12;
  61231. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  61232. w = roundToInt (widths [note] * keyWidth_);
  61233. }
  61234. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  61235. {
  61236. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  61237. int rx, rw;
  61238. getKeyPosition (rangeStart, keyWidth, rx, rw);
  61239. x -= xOffset + rx;
  61240. }
  61241. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  61242. {
  61243. int x, y;
  61244. getKeyPos (midiNoteNumber, x, y);
  61245. return x;
  61246. }
  61247. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  61248. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  61249. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  61250. {
  61251. if (! reallyContains (pos.getX(), pos.getY(), false))
  61252. return -1;
  61253. Point<int> p (pos);
  61254. if (orientation != horizontalKeyboard)
  61255. {
  61256. p = Point<int> (p.getY(), p.getX());
  61257. if (orientation == verticalKeyboardFacingLeft)
  61258. p = Point<int> (p.getX(), getWidth() - p.getY());
  61259. else
  61260. p = Point<int> (getHeight() - p.getX(), p.getY());
  61261. }
  61262. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  61263. }
  61264. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  61265. {
  61266. if (pos.getY() < blackNoteLength)
  61267. {
  61268. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61269. {
  61270. for (int i = 0; i < 5; ++i)
  61271. {
  61272. const int note = octaveStart + blackNotes [i];
  61273. if (note >= rangeStart && note <= rangeEnd)
  61274. {
  61275. int kx, kw;
  61276. getKeyPos (note, kx, kw);
  61277. kx += xOffset;
  61278. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61279. {
  61280. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61281. return note;
  61282. }
  61283. }
  61284. }
  61285. }
  61286. }
  61287. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61288. {
  61289. for (int i = 0; i < 7; ++i)
  61290. {
  61291. const int note = octaveStart + whiteNotes [i];
  61292. if (note >= rangeStart && note <= rangeEnd)
  61293. {
  61294. int kx, kw;
  61295. getKeyPos (note, kx, kw);
  61296. kx += xOffset;
  61297. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61298. {
  61299. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61300. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61301. return note;
  61302. }
  61303. }
  61304. }
  61305. }
  61306. mousePositionVelocity = 0;
  61307. return -1;
  61308. }
  61309. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61310. {
  61311. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61312. {
  61313. int x, w;
  61314. getKeyPos (noteNum, x, w);
  61315. if (orientation == horizontalKeyboard)
  61316. repaint (x, 0, w, getHeight());
  61317. else if (orientation == verticalKeyboardFacingLeft)
  61318. repaint (0, x, getWidth(), w);
  61319. else if (orientation == verticalKeyboardFacingRight)
  61320. repaint (0, getHeight() - x - w, getWidth(), w);
  61321. }
  61322. }
  61323. void MidiKeyboardComponent::paint (Graphics& g)
  61324. {
  61325. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61326. const Colour lineColour (findColour (keySeparatorLineColourId));
  61327. const Colour textColour (findColour (textLabelColourId));
  61328. int x, w, octave;
  61329. for (octave = 0; octave < 128; octave += 12)
  61330. {
  61331. for (int white = 0; white < 7; ++white)
  61332. {
  61333. const int noteNum = octave + whiteNotes [white];
  61334. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61335. {
  61336. getKeyPos (noteNum, x, w);
  61337. if (orientation == horizontalKeyboard)
  61338. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61339. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61340. noteUnderMouse == noteNum,
  61341. lineColour, textColour);
  61342. else if (orientation == verticalKeyboardFacingLeft)
  61343. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61344. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61345. noteUnderMouse == noteNum,
  61346. lineColour, textColour);
  61347. else if (orientation == verticalKeyboardFacingRight)
  61348. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61349. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61350. noteUnderMouse == noteNum,
  61351. lineColour, textColour);
  61352. }
  61353. }
  61354. }
  61355. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61356. if (orientation == verticalKeyboardFacingLeft)
  61357. {
  61358. x1 = getWidth() - 1.0f;
  61359. x2 = getWidth() - 5.0f;
  61360. }
  61361. else if (orientation == verticalKeyboardFacingRight)
  61362. x2 = 5.0f;
  61363. else
  61364. y2 = 5.0f;
  61365. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61366. Colours::transparentBlack, x2, y2, false));
  61367. getKeyPos (rangeEnd, x, w);
  61368. x += w;
  61369. if (orientation == verticalKeyboardFacingLeft)
  61370. g.fillRect (getWidth() - 5, 0, 5, x);
  61371. else if (orientation == verticalKeyboardFacingRight)
  61372. g.fillRect (0, 0, 5, x);
  61373. else
  61374. g.fillRect (0, 0, x, 5);
  61375. g.setColour (lineColour);
  61376. if (orientation == verticalKeyboardFacingLeft)
  61377. g.fillRect (0, 0, 1, x);
  61378. else if (orientation == verticalKeyboardFacingRight)
  61379. g.fillRect (getWidth() - 1, 0, 1, x);
  61380. else
  61381. g.fillRect (0, getHeight() - 1, x, 1);
  61382. const Colour blackNoteColour (findColour (blackNoteColourId));
  61383. for (octave = 0; octave < 128; octave += 12)
  61384. {
  61385. for (int black = 0; black < 5; ++black)
  61386. {
  61387. const int noteNum = octave + blackNotes [black];
  61388. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61389. {
  61390. getKeyPos (noteNum, x, w);
  61391. if (orientation == horizontalKeyboard)
  61392. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61393. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61394. noteUnderMouse == noteNum,
  61395. blackNoteColour);
  61396. else if (orientation == verticalKeyboardFacingLeft)
  61397. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61398. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61399. noteUnderMouse == noteNum,
  61400. blackNoteColour);
  61401. else if (orientation == verticalKeyboardFacingRight)
  61402. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61403. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61404. noteUnderMouse == noteNum,
  61405. blackNoteColour);
  61406. }
  61407. }
  61408. }
  61409. }
  61410. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61411. Graphics& g, int x, int y, int w, int h,
  61412. bool isDown, bool isOver,
  61413. const Colour& lineColour,
  61414. const Colour& textColour)
  61415. {
  61416. Colour c (Colours::transparentWhite);
  61417. if (isDown)
  61418. c = findColour (keyDownOverlayColourId);
  61419. if (isOver)
  61420. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61421. g.setColour (c);
  61422. g.fillRect (x, y, w, h);
  61423. const String text (getWhiteNoteText (midiNoteNumber));
  61424. if (! text.isEmpty())
  61425. {
  61426. g.setColour (textColour);
  61427. Font f (jmin (12.0f, keyWidth * 0.9f));
  61428. f.setHorizontalScale (0.8f);
  61429. g.setFont (f);
  61430. Justification justification (Justification::centredBottom);
  61431. if (orientation == verticalKeyboardFacingLeft)
  61432. justification = Justification::centredLeft;
  61433. else if (orientation == verticalKeyboardFacingRight)
  61434. justification = Justification::centredRight;
  61435. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61436. }
  61437. g.setColour (lineColour);
  61438. if (orientation == horizontalKeyboard)
  61439. g.fillRect (x, y, 1, h);
  61440. else if (orientation == verticalKeyboardFacingLeft)
  61441. g.fillRect (x, y, w, 1);
  61442. else if (orientation == verticalKeyboardFacingRight)
  61443. g.fillRect (x, y + h - 1, w, 1);
  61444. if (midiNoteNumber == rangeEnd)
  61445. {
  61446. if (orientation == horizontalKeyboard)
  61447. g.fillRect (x + w, y, 1, h);
  61448. else if (orientation == verticalKeyboardFacingLeft)
  61449. g.fillRect (x, y + h, w, 1);
  61450. else if (orientation == verticalKeyboardFacingRight)
  61451. g.fillRect (x, y - 1, w, 1);
  61452. }
  61453. }
  61454. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61455. Graphics& g, int x, int y, int w, int h,
  61456. bool isDown, bool isOver,
  61457. const Colour& noteFillColour)
  61458. {
  61459. Colour c (noteFillColour);
  61460. if (isDown)
  61461. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61462. if (isOver)
  61463. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61464. g.setColour (c);
  61465. g.fillRect (x, y, w, h);
  61466. if (isDown)
  61467. {
  61468. g.setColour (noteFillColour);
  61469. g.drawRect (x, y, w, h);
  61470. }
  61471. else
  61472. {
  61473. const int xIndent = jmax (1, jmin (w, h) / 8);
  61474. g.setColour (c.brighter());
  61475. if (orientation == horizontalKeyboard)
  61476. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61477. else if (orientation == verticalKeyboardFacingLeft)
  61478. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61479. else if (orientation == verticalKeyboardFacingRight)
  61480. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61481. }
  61482. }
  61483. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61484. {
  61485. octaveNumForMiddleC = octaveNumForMiddleC_;
  61486. repaint();
  61487. }
  61488. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61489. {
  61490. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61491. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61492. return String::empty;
  61493. }
  61494. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61495. const bool isMouseOver_,
  61496. const bool isButtonDown,
  61497. const bool movesOctavesUp)
  61498. {
  61499. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61500. float angle;
  61501. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61502. angle = movesOctavesUp ? 0.0f : 0.5f;
  61503. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61504. angle = movesOctavesUp ? 0.25f : 0.75f;
  61505. else
  61506. angle = movesOctavesUp ? 0.75f : 0.25f;
  61507. Path path;
  61508. path.lineTo (0.0f, 1.0f);
  61509. path.lineTo (1.0f, 0.5f);
  61510. path.closeSubPath();
  61511. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61512. g.setColour (findColour (upDownButtonArrowColourId)
  61513. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61514. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61515. w - 2.0f,
  61516. h - 2.0f,
  61517. true));
  61518. }
  61519. void MidiKeyboardComponent::resized()
  61520. {
  61521. int w = getWidth();
  61522. int h = getHeight();
  61523. if (w > 0 && h > 0)
  61524. {
  61525. if (orientation != horizontalKeyboard)
  61526. swapVariables (w, h);
  61527. blackNoteLength = roundToInt (h * 0.7f);
  61528. int kx2, kw2;
  61529. getKeyPos (rangeEnd, kx2, kw2);
  61530. kx2 += kw2;
  61531. if (firstKey != rangeStart)
  61532. {
  61533. int kx1, kw1;
  61534. getKeyPos (rangeStart, kx1, kw1);
  61535. if (kx2 - kx1 <= w)
  61536. {
  61537. firstKey = rangeStart;
  61538. sendChangeMessage (this);
  61539. repaint();
  61540. }
  61541. }
  61542. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61543. scrollDown->setVisible (showScrollButtons);
  61544. scrollUp->setVisible (showScrollButtons);
  61545. xOffset = 0;
  61546. if (showScrollButtons)
  61547. {
  61548. const int scrollButtonW = jmin (12, w / 2);
  61549. if (orientation == horizontalKeyboard)
  61550. {
  61551. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61552. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61553. }
  61554. else if (orientation == verticalKeyboardFacingLeft)
  61555. {
  61556. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61557. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61558. }
  61559. else if (orientation == verticalKeyboardFacingRight)
  61560. {
  61561. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61562. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61563. }
  61564. int endOfLastKey, kw;
  61565. getKeyPos (rangeEnd, endOfLastKey, kw);
  61566. endOfLastKey += kw;
  61567. float mousePositionVelocity;
  61568. const int spaceAvailable = w - scrollButtonW * 2;
  61569. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61570. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61571. {
  61572. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61573. sendChangeMessage (this);
  61574. }
  61575. int newOffset = 0;
  61576. getKeyPos (firstKey, newOffset, kw);
  61577. xOffset = newOffset - scrollButtonW;
  61578. }
  61579. else
  61580. {
  61581. firstKey = rangeStart;
  61582. }
  61583. timerCallback();
  61584. repaint();
  61585. }
  61586. }
  61587. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61588. {
  61589. triggerAsyncUpdate();
  61590. }
  61591. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61592. {
  61593. triggerAsyncUpdate();
  61594. }
  61595. void MidiKeyboardComponent::handleAsyncUpdate()
  61596. {
  61597. for (int i = rangeStart; i <= rangeEnd; ++i)
  61598. {
  61599. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61600. {
  61601. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61602. repaintNote (i);
  61603. }
  61604. }
  61605. }
  61606. void MidiKeyboardComponent::resetAnyKeysInUse()
  61607. {
  61608. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61609. {
  61610. state.allNotesOff (midiChannel);
  61611. keysPressed.clear();
  61612. mouseDownNote = -1;
  61613. }
  61614. }
  61615. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61616. {
  61617. float mousePositionVelocity = 0.0f;
  61618. const int newNote = (mouseDragging || isMouseOver())
  61619. ? xyToNote (pos, mousePositionVelocity) : -1;
  61620. if (noteUnderMouse != newNote)
  61621. {
  61622. if (mouseDownNote >= 0)
  61623. {
  61624. state.noteOff (midiChannel, mouseDownNote);
  61625. mouseDownNote = -1;
  61626. }
  61627. if (mouseDragging && newNote >= 0)
  61628. {
  61629. if (! useMousePositionForVelocity)
  61630. mousePositionVelocity = 1.0f;
  61631. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61632. mouseDownNote = newNote;
  61633. }
  61634. repaintNote (noteUnderMouse);
  61635. noteUnderMouse = newNote;
  61636. repaintNote (noteUnderMouse);
  61637. }
  61638. else if (mouseDownNote >= 0 && ! mouseDragging)
  61639. {
  61640. state.noteOff (midiChannel, mouseDownNote);
  61641. mouseDownNote = -1;
  61642. }
  61643. }
  61644. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61645. {
  61646. updateNoteUnderMouse (e.getPosition());
  61647. stopTimer();
  61648. }
  61649. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61650. {
  61651. float mousePositionVelocity;
  61652. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61653. if (newNote >= 0)
  61654. mouseDraggedToKey (newNote, e);
  61655. updateNoteUnderMouse (e.getPosition());
  61656. }
  61657. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61658. {
  61659. return true;
  61660. }
  61661. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61662. {
  61663. }
  61664. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61665. {
  61666. float mousePositionVelocity;
  61667. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61668. mouseDragging = false;
  61669. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61670. {
  61671. repaintNote (noteUnderMouse);
  61672. noteUnderMouse = -1;
  61673. mouseDragging = true;
  61674. updateNoteUnderMouse (e.getPosition());
  61675. startTimer (500);
  61676. }
  61677. }
  61678. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61679. {
  61680. mouseDragging = false;
  61681. updateNoteUnderMouse (e.getPosition());
  61682. stopTimer();
  61683. }
  61684. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61685. {
  61686. updateNoteUnderMouse (e.getPosition());
  61687. }
  61688. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61689. {
  61690. updateNoteUnderMouse (e.getPosition());
  61691. }
  61692. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61693. {
  61694. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61695. }
  61696. void MidiKeyboardComponent::timerCallback()
  61697. {
  61698. updateNoteUnderMouse (getMouseXYRelative());
  61699. }
  61700. void MidiKeyboardComponent::clearKeyMappings()
  61701. {
  61702. resetAnyKeysInUse();
  61703. keyPressNotes.clear();
  61704. keyPresses.clear();
  61705. }
  61706. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61707. const int midiNoteOffsetFromC)
  61708. {
  61709. removeKeyPressForNote (midiNoteOffsetFromC);
  61710. keyPressNotes.add (midiNoteOffsetFromC);
  61711. keyPresses.add (key);
  61712. }
  61713. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61714. {
  61715. for (int i = keyPressNotes.size(); --i >= 0;)
  61716. {
  61717. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61718. {
  61719. keyPressNotes.remove (i);
  61720. keyPresses.remove (i);
  61721. }
  61722. }
  61723. }
  61724. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61725. {
  61726. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61727. keyMappingOctave = newOctaveNumber;
  61728. }
  61729. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61730. {
  61731. bool keyPressUsed = false;
  61732. for (int i = keyPresses.size(); --i >= 0;)
  61733. {
  61734. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61735. if (keyPresses.getReference(i).isCurrentlyDown())
  61736. {
  61737. if (! keysPressed [note])
  61738. {
  61739. keysPressed.setBit (note);
  61740. state.noteOn (midiChannel, note, velocity);
  61741. keyPressUsed = true;
  61742. }
  61743. }
  61744. else
  61745. {
  61746. if (keysPressed [note])
  61747. {
  61748. keysPressed.clearBit (note);
  61749. state.noteOff (midiChannel, note);
  61750. keyPressUsed = true;
  61751. }
  61752. }
  61753. }
  61754. return keyPressUsed;
  61755. }
  61756. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61757. {
  61758. resetAnyKeysInUse();
  61759. }
  61760. END_JUCE_NAMESPACE
  61761. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61762. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61763. #if JUCE_OPENGL
  61764. BEGIN_JUCE_NAMESPACE
  61765. extern void juce_glViewport (const int w, const int h);
  61766. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61767. const int alphaBits_,
  61768. const int depthBufferBits_,
  61769. const int stencilBufferBits_)
  61770. : redBits (bitsPerRGBComponent),
  61771. greenBits (bitsPerRGBComponent),
  61772. blueBits (bitsPerRGBComponent),
  61773. alphaBits (alphaBits_),
  61774. depthBufferBits (depthBufferBits_),
  61775. stencilBufferBits (stencilBufferBits_),
  61776. accumulationBufferRedBits (0),
  61777. accumulationBufferGreenBits (0),
  61778. accumulationBufferBlueBits (0),
  61779. accumulationBufferAlphaBits (0),
  61780. fullSceneAntiAliasingNumSamples (0)
  61781. {
  61782. }
  61783. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61784. : redBits (other.redBits),
  61785. greenBits (other.greenBits),
  61786. blueBits (other.blueBits),
  61787. alphaBits (other.alphaBits),
  61788. depthBufferBits (other.depthBufferBits),
  61789. stencilBufferBits (other.stencilBufferBits),
  61790. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61791. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61792. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61793. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61794. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61795. {
  61796. }
  61797. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61798. {
  61799. redBits = other.redBits;
  61800. greenBits = other.greenBits;
  61801. blueBits = other.blueBits;
  61802. alphaBits = other.alphaBits;
  61803. depthBufferBits = other.depthBufferBits;
  61804. stencilBufferBits = other.stencilBufferBits;
  61805. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61806. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61807. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61808. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61809. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61810. return *this;
  61811. }
  61812. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61813. {
  61814. return redBits == other.redBits
  61815. && greenBits == other.greenBits
  61816. && blueBits == other.blueBits
  61817. && alphaBits == other.alphaBits
  61818. && depthBufferBits == other.depthBufferBits
  61819. && stencilBufferBits == other.stencilBufferBits
  61820. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61821. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61822. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61823. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61824. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61825. }
  61826. static Array<OpenGLContext*> knownContexts;
  61827. OpenGLContext::OpenGLContext() throw()
  61828. {
  61829. knownContexts.add (this);
  61830. }
  61831. OpenGLContext::~OpenGLContext()
  61832. {
  61833. knownContexts.removeValue (this);
  61834. }
  61835. OpenGLContext* OpenGLContext::getCurrentContext()
  61836. {
  61837. for (int i = knownContexts.size(); --i >= 0;)
  61838. {
  61839. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61840. if (oglc->isActive())
  61841. return oglc;
  61842. }
  61843. return 0;
  61844. }
  61845. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61846. {
  61847. public:
  61848. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61849. : ComponentMovementWatcher (owner_),
  61850. owner (owner_),
  61851. wasShowing (false)
  61852. {
  61853. }
  61854. ~OpenGLComponentWatcher() {}
  61855. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61856. {
  61857. owner->updateContextPosition();
  61858. }
  61859. void componentPeerChanged()
  61860. {
  61861. const ScopedLock sl (owner->getContextLock());
  61862. owner->deleteContext();
  61863. }
  61864. void componentVisibilityChanged (Component&)
  61865. {
  61866. const bool isShowingNow = owner->isShowing();
  61867. if (wasShowing != isShowingNow)
  61868. {
  61869. wasShowing = isShowingNow;
  61870. if (! isShowingNow)
  61871. {
  61872. const ScopedLock sl (owner->getContextLock());
  61873. owner->deleteContext();
  61874. }
  61875. }
  61876. }
  61877. juce_UseDebuggingNewOperator
  61878. private:
  61879. OpenGLComponent* const owner;
  61880. bool wasShowing;
  61881. };
  61882. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61883. : type (type_),
  61884. contextToShareListsWith (0),
  61885. needToUpdateViewport (true)
  61886. {
  61887. setOpaque (true);
  61888. componentWatcher = new OpenGLComponentWatcher (this);
  61889. }
  61890. OpenGLComponent::~OpenGLComponent()
  61891. {
  61892. deleteContext();
  61893. componentWatcher = 0;
  61894. }
  61895. void OpenGLComponent::deleteContext()
  61896. {
  61897. const ScopedLock sl (contextLock);
  61898. context = 0;
  61899. }
  61900. void OpenGLComponent::updateContextPosition()
  61901. {
  61902. needToUpdateViewport = true;
  61903. if (getWidth() > 0 && getHeight() > 0)
  61904. {
  61905. Component* const topComp = getTopLevelComponent();
  61906. if (topComp->getPeer() != 0)
  61907. {
  61908. const ScopedLock sl (contextLock);
  61909. if (context != 0)
  61910. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61911. getScreenY() - topComp->getScreenY(),
  61912. getWidth(),
  61913. getHeight(),
  61914. topComp->getHeight());
  61915. }
  61916. }
  61917. }
  61918. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61919. {
  61920. OpenGLPixelFormat pf;
  61921. const ScopedLock sl (contextLock);
  61922. if (context != 0)
  61923. pf = context->getPixelFormat();
  61924. return pf;
  61925. }
  61926. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61927. {
  61928. if (! (preferredPixelFormat == formatToUse))
  61929. {
  61930. const ScopedLock sl (contextLock);
  61931. deleteContext();
  61932. preferredPixelFormat = formatToUse;
  61933. }
  61934. }
  61935. void OpenGLComponent::shareWith (OpenGLContext* c)
  61936. {
  61937. if (contextToShareListsWith != c)
  61938. {
  61939. const ScopedLock sl (contextLock);
  61940. deleteContext();
  61941. contextToShareListsWith = c;
  61942. }
  61943. }
  61944. bool OpenGLComponent::makeCurrentContextActive()
  61945. {
  61946. if (context == 0)
  61947. {
  61948. const ScopedLock sl (contextLock);
  61949. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61950. {
  61951. context = createContext();
  61952. if (context != 0)
  61953. {
  61954. updateContextPosition();
  61955. if (context->makeActive())
  61956. newOpenGLContextCreated();
  61957. }
  61958. }
  61959. }
  61960. return context != 0 && context->makeActive();
  61961. }
  61962. void OpenGLComponent::makeCurrentContextInactive()
  61963. {
  61964. if (context != 0)
  61965. context->makeInactive();
  61966. }
  61967. bool OpenGLComponent::isActiveContext() const throw()
  61968. {
  61969. return context != 0 && context->isActive();
  61970. }
  61971. void OpenGLComponent::swapBuffers()
  61972. {
  61973. if (context != 0)
  61974. context->swapBuffers();
  61975. }
  61976. void OpenGLComponent::paint (Graphics&)
  61977. {
  61978. if (renderAndSwapBuffers())
  61979. {
  61980. ComponentPeer* const peer = getPeer();
  61981. if (peer != 0)
  61982. {
  61983. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61984. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61985. }
  61986. }
  61987. }
  61988. bool OpenGLComponent::renderAndSwapBuffers()
  61989. {
  61990. const ScopedLock sl (contextLock);
  61991. if (! makeCurrentContextActive())
  61992. return false;
  61993. if (needToUpdateViewport)
  61994. {
  61995. needToUpdateViewport = false;
  61996. juce_glViewport (getWidth(), getHeight());
  61997. }
  61998. renderOpenGL();
  61999. swapBuffers();
  62000. return true;
  62001. }
  62002. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  62003. {
  62004. Component::internalRepaint (x, y, w, h);
  62005. if (context != 0)
  62006. context->repaint();
  62007. }
  62008. END_JUCE_NAMESPACE
  62009. #endif
  62010. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  62011. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  62012. BEGIN_JUCE_NAMESPACE
  62013. PreferencesPanel::PreferencesPanel()
  62014. : buttonSize (70)
  62015. {
  62016. }
  62017. PreferencesPanel::~PreferencesPanel()
  62018. {
  62019. currentPage = 0;
  62020. deleteAllChildren();
  62021. }
  62022. void PreferencesPanel::addSettingsPage (const String& title,
  62023. const Drawable* icon,
  62024. const Drawable* overIcon,
  62025. const Drawable* downIcon)
  62026. {
  62027. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  62028. button->setImages (icon, overIcon, downIcon);
  62029. button->setRadioGroupId (1);
  62030. button->addButtonListener (this);
  62031. button->setClickingTogglesState (true);
  62032. button->setWantsKeyboardFocus (false);
  62033. addAndMakeVisible (button);
  62034. resized();
  62035. if (currentPage == 0)
  62036. setCurrentPage (title);
  62037. }
  62038. void PreferencesPanel::addSettingsPage (const String& title,
  62039. const void* imageData,
  62040. const int imageDataSize)
  62041. {
  62042. DrawableImage icon, iconOver, iconDown;
  62043. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  62044. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  62045. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  62046. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  62047. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  62048. addSettingsPage (title, &icon, &iconOver, &iconDown);
  62049. }
  62050. class PrefsDialogWindow : public DialogWindow
  62051. {
  62052. public:
  62053. PrefsDialogWindow (const String& dialogtitle,
  62054. const Colour& backgroundColour)
  62055. : DialogWindow (dialogtitle, backgroundColour, true)
  62056. {
  62057. }
  62058. ~PrefsDialogWindow()
  62059. {
  62060. }
  62061. void closeButtonPressed()
  62062. {
  62063. exitModalState (0);
  62064. }
  62065. private:
  62066. PrefsDialogWindow (const PrefsDialogWindow&);
  62067. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  62068. };
  62069. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  62070. int dialogWidth,
  62071. int dialogHeight,
  62072. const Colour& backgroundColour)
  62073. {
  62074. setSize (dialogWidth, dialogHeight);
  62075. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  62076. dw.setContentComponent (this, true, true);
  62077. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  62078. dw.runModalLoop();
  62079. dw.setContentComponent (0, false, false);
  62080. }
  62081. void PreferencesPanel::resized()
  62082. {
  62083. int x = 0;
  62084. for (int i = 0; i < getNumChildComponents(); ++i)
  62085. {
  62086. Component* c = getChildComponent (i);
  62087. if (dynamic_cast <DrawableButton*> (c) == 0)
  62088. {
  62089. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  62090. }
  62091. else
  62092. {
  62093. c->setBounds (x, 0, buttonSize, buttonSize);
  62094. x += buttonSize;
  62095. }
  62096. }
  62097. }
  62098. void PreferencesPanel::paint (Graphics& g)
  62099. {
  62100. g.setColour (Colours::grey);
  62101. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  62102. }
  62103. void PreferencesPanel::setCurrentPage (const String& pageName)
  62104. {
  62105. if (currentPageName != pageName)
  62106. {
  62107. currentPageName = pageName;
  62108. currentPage = 0;
  62109. currentPage = createComponentForPage (pageName);
  62110. if (currentPage != 0)
  62111. {
  62112. addAndMakeVisible (currentPage);
  62113. currentPage->toBack();
  62114. resized();
  62115. }
  62116. for (int i = 0; i < getNumChildComponents(); ++i)
  62117. {
  62118. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  62119. if (db != 0 && db->getName() == pageName)
  62120. {
  62121. db->setToggleState (true, false);
  62122. break;
  62123. }
  62124. }
  62125. }
  62126. }
  62127. void PreferencesPanel::buttonClicked (Button*)
  62128. {
  62129. for (int i = 0; i < getNumChildComponents(); ++i)
  62130. {
  62131. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  62132. if (db != 0 && db->getToggleState())
  62133. {
  62134. setCurrentPage (db->getName());
  62135. break;
  62136. }
  62137. }
  62138. }
  62139. END_JUCE_NAMESPACE
  62140. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  62141. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62142. #if JUCE_WINDOWS || JUCE_LINUX
  62143. BEGIN_JUCE_NAMESPACE
  62144. SystemTrayIconComponent::SystemTrayIconComponent()
  62145. {
  62146. addToDesktop (0);
  62147. }
  62148. SystemTrayIconComponent::~SystemTrayIconComponent()
  62149. {
  62150. }
  62151. END_JUCE_NAMESPACE
  62152. #endif
  62153. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62154. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  62155. BEGIN_JUCE_NAMESPACE
  62156. class AlertWindowTextEditor : public TextEditor
  62157. {
  62158. public:
  62159. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  62160. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  62161. {
  62162. setSelectAllWhenFocused (true);
  62163. }
  62164. ~AlertWindowTextEditor()
  62165. {
  62166. }
  62167. void returnPressed()
  62168. {
  62169. // pass these up the component hierarchy to be trigger the buttons
  62170. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  62171. }
  62172. void escapePressed()
  62173. {
  62174. // pass these up the component hierarchy to be trigger the buttons
  62175. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  62176. }
  62177. private:
  62178. AlertWindowTextEditor (const AlertWindowTextEditor&);
  62179. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  62180. static juce_wchar getDefaultPasswordChar() throw()
  62181. {
  62182. #if JUCE_LINUX
  62183. return 0x2022;
  62184. #else
  62185. return 0x25cf;
  62186. #endif
  62187. }
  62188. };
  62189. AlertWindow::AlertWindow (const String& title,
  62190. const String& message,
  62191. AlertIconType iconType,
  62192. Component* associatedComponent_)
  62193. : TopLevelWindow (title, true),
  62194. alertIconType (iconType),
  62195. associatedComponent (associatedComponent_)
  62196. {
  62197. if (message.isEmpty())
  62198. text = " "; // to force an update if the message is empty
  62199. setMessage (message);
  62200. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  62201. {
  62202. Component* const c = Desktop::getInstance().getComponent (i);
  62203. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  62204. {
  62205. setAlwaysOnTop (true);
  62206. break;
  62207. }
  62208. }
  62209. if (! JUCEApplication::isStandaloneApp())
  62210. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62211. lookAndFeelChanged();
  62212. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  62213. }
  62214. AlertWindow::~AlertWindow()
  62215. {
  62216. for (int i = customComps.size(); --i >= 0;)
  62217. removeChildComponent ((Component*) customComps[i]);
  62218. deleteAllChildren();
  62219. }
  62220. void AlertWindow::userTriedToCloseWindow()
  62221. {
  62222. exitModalState (0);
  62223. }
  62224. void AlertWindow::setMessage (const String& message)
  62225. {
  62226. const String newMessage (message.substring (0, 2048));
  62227. if (text != newMessage)
  62228. {
  62229. text = newMessage;
  62230. font.setHeight (15.0f);
  62231. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  62232. textLayout.setText (getName() + "\n\n", titleFont);
  62233. textLayout.appendText (text, font);
  62234. updateLayout (true);
  62235. repaint();
  62236. }
  62237. }
  62238. void AlertWindow::buttonClicked (Button* button)
  62239. {
  62240. for (int i = 0; i < buttons.size(); i++)
  62241. {
  62242. TextButton* const c = (TextButton*) buttons[i];
  62243. if (button->getName() == c->getName())
  62244. {
  62245. if (c->getParentComponent() != 0)
  62246. c->getParentComponent()->exitModalState (c->getCommandID());
  62247. break;
  62248. }
  62249. }
  62250. }
  62251. void AlertWindow::addButton (const String& name,
  62252. const int returnValue,
  62253. const KeyPress& shortcutKey1,
  62254. const KeyPress& shortcutKey2)
  62255. {
  62256. TextButton* const b = new TextButton (name, String::empty);
  62257. b->setWantsKeyboardFocus (true);
  62258. b->setMouseClickGrabsKeyboardFocus (false);
  62259. b->setCommandToTrigger (0, returnValue, false);
  62260. b->addShortcut (shortcutKey1);
  62261. b->addShortcut (shortcutKey2);
  62262. b->addButtonListener (this);
  62263. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  62264. addAndMakeVisible (b, 0);
  62265. buttons.add (b);
  62266. updateLayout (false);
  62267. }
  62268. int AlertWindow::getNumButtons() const
  62269. {
  62270. return buttons.size();
  62271. }
  62272. void AlertWindow::triggerButtonClick (const String& buttonName)
  62273. {
  62274. for (int i = buttons.size(); --i >= 0;)
  62275. {
  62276. TextButton* const b = (TextButton*) buttons[i];
  62277. if (buttonName == b->getName())
  62278. {
  62279. b->triggerClick();
  62280. break;
  62281. }
  62282. }
  62283. }
  62284. void AlertWindow::addTextEditor (const String& name,
  62285. const String& initialContents,
  62286. const String& onScreenLabel,
  62287. const bool isPasswordBox)
  62288. {
  62289. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62290. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62291. tc->setFont (font);
  62292. tc->setText (initialContents);
  62293. tc->setCaretPosition (initialContents.length());
  62294. addAndMakeVisible (tc);
  62295. textBoxes.add (tc);
  62296. allComps.add (tc);
  62297. textboxNames.add (onScreenLabel);
  62298. updateLayout (false);
  62299. }
  62300. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62301. {
  62302. for (int i = textBoxes.size(); --i >= 0;)
  62303. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  62304. return ((TextEditor*)textBoxes[i])->getText();
  62305. return String::empty;
  62306. }
  62307. void AlertWindow::addComboBox (const String& name,
  62308. const StringArray& items,
  62309. const String& onScreenLabel)
  62310. {
  62311. ComboBox* const cb = new ComboBox (name);
  62312. for (int i = 0; i < items.size(); ++i)
  62313. cb->addItem (items[i], i + 1);
  62314. addAndMakeVisible (cb);
  62315. cb->setSelectedItemIndex (0);
  62316. comboBoxes.add (cb);
  62317. allComps.add (cb);
  62318. comboBoxNames.add (onScreenLabel);
  62319. updateLayout (false);
  62320. }
  62321. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62322. {
  62323. for (int i = comboBoxes.size(); --i >= 0;)
  62324. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62325. return (ComboBox*) comboBoxes[i];
  62326. return 0;
  62327. }
  62328. class AlertTextComp : public TextEditor
  62329. {
  62330. public:
  62331. AlertTextComp (const String& message,
  62332. const Font& font)
  62333. {
  62334. setReadOnly (true);
  62335. setMultiLine (true, true);
  62336. setCaretVisible (false);
  62337. setScrollbarsShown (true);
  62338. lookAndFeelChanged();
  62339. setWantsKeyboardFocus (false);
  62340. setFont (font);
  62341. setText (message, false);
  62342. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62343. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62344. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62345. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62346. }
  62347. ~AlertTextComp()
  62348. {
  62349. }
  62350. int getPreferredWidth() const throw() { return bestWidth; }
  62351. void updateLayout (const int width)
  62352. {
  62353. TextLayout text;
  62354. text.appendText (getText(), getFont());
  62355. text.layout (width - 8, Justification::topLeft, true);
  62356. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62357. }
  62358. private:
  62359. int bestWidth;
  62360. AlertTextComp (const AlertTextComp&);
  62361. AlertTextComp& operator= (const AlertTextComp&);
  62362. };
  62363. void AlertWindow::addTextBlock (const String& textBlock)
  62364. {
  62365. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62366. textBlocks.add (c);
  62367. allComps.add (c);
  62368. addAndMakeVisible (c);
  62369. updateLayout (false);
  62370. }
  62371. void AlertWindow::addProgressBarComponent (double& progressValue)
  62372. {
  62373. ProgressBar* const pb = new ProgressBar (progressValue);
  62374. progressBars.add (pb);
  62375. allComps.add (pb);
  62376. addAndMakeVisible (pb);
  62377. updateLayout (false);
  62378. }
  62379. void AlertWindow::addCustomComponent (Component* const component)
  62380. {
  62381. customComps.add (component);
  62382. allComps.add (component);
  62383. addAndMakeVisible (component);
  62384. updateLayout (false);
  62385. }
  62386. int AlertWindow::getNumCustomComponents() const
  62387. {
  62388. return customComps.size();
  62389. }
  62390. Component* AlertWindow::getCustomComponent (const int index) const
  62391. {
  62392. return (Component*) customComps [index];
  62393. }
  62394. Component* AlertWindow::removeCustomComponent (const int index)
  62395. {
  62396. Component* const c = getCustomComponent (index);
  62397. if (c != 0)
  62398. {
  62399. customComps.removeValue (c);
  62400. allComps.removeValue (c);
  62401. removeChildComponent (c);
  62402. updateLayout (false);
  62403. }
  62404. return c;
  62405. }
  62406. void AlertWindow::paint (Graphics& g)
  62407. {
  62408. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62409. g.setColour (findColour (textColourId));
  62410. g.setFont (getLookAndFeel().getAlertWindowFont());
  62411. int i;
  62412. for (i = textBoxes.size(); --i >= 0;)
  62413. {
  62414. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62415. g.drawFittedText (textboxNames[i],
  62416. te->getX(), te->getY() - 14,
  62417. te->getWidth(), 14,
  62418. Justification::centredLeft, 1);
  62419. }
  62420. for (i = comboBoxNames.size(); --i >= 0;)
  62421. {
  62422. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62423. g.drawFittedText (comboBoxNames[i],
  62424. cb->getX(), cb->getY() - 14,
  62425. cb->getWidth(), 14,
  62426. Justification::centredLeft, 1);
  62427. }
  62428. for (i = customComps.size(); --i >= 0;)
  62429. {
  62430. const Component* const c = (Component*) customComps[i];
  62431. g.drawFittedText (c->getName(),
  62432. c->getX(), c->getY() - 14,
  62433. c->getWidth(), 14,
  62434. Justification::centredLeft, 1);
  62435. }
  62436. }
  62437. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62438. {
  62439. const int titleH = 24;
  62440. const int iconWidth = 80;
  62441. const int wid = jmax (font.getStringWidth (text),
  62442. font.getStringWidth (getName()));
  62443. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62444. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62445. const int edgeGap = 10;
  62446. const int labelHeight = 18;
  62447. int iconSpace;
  62448. if (alertIconType == NoIcon)
  62449. {
  62450. textLayout.layout (w, Justification::horizontallyCentred, true);
  62451. iconSpace = 0;
  62452. }
  62453. else
  62454. {
  62455. textLayout.layout (w, Justification::left, true);
  62456. iconSpace = iconWidth;
  62457. }
  62458. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62459. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62460. const int textLayoutH = textLayout.getHeight();
  62461. const int textBottom = 16 + titleH + textLayoutH;
  62462. int h = textBottom;
  62463. int buttonW = 40;
  62464. int i;
  62465. for (i = 0; i < buttons.size(); ++i)
  62466. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62467. w = jmax (buttonW, w);
  62468. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62469. if (buttons.size() > 0)
  62470. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62471. for (i = customComps.size(); --i >= 0;)
  62472. {
  62473. Component* c = (Component*) customComps[i];
  62474. w = jmax (w, (c->getWidth() * 100) / 80);
  62475. h += 10 + c->getHeight();
  62476. if (c->getName().isNotEmpty())
  62477. h += labelHeight;
  62478. }
  62479. for (i = textBlocks.size(); --i >= 0;)
  62480. {
  62481. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62482. w = jmax (w, ac->getPreferredWidth());
  62483. }
  62484. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62485. for (i = textBlocks.size(); --i >= 0;)
  62486. {
  62487. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62488. ac->updateLayout ((int) (w * 0.8f));
  62489. h += ac->getHeight() + 10;
  62490. }
  62491. h = jmin (getParentHeight() - 50, h);
  62492. if (onlyIncreaseSize)
  62493. {
  62494. w = jmax (w, getWidth());
  62495. h = jmax (h, getHeight());
  62496. }
  62497. if (! isVisible())
  62498. {
  62499. centreAroundComponent (associatedComponent, w, h);
  62500. }
  62501. else
  62502. {
  62503. const int cx = getX() + getWidth() / 2;
  62504. const int cy = getY() + getHeight() / 2;
  62505. setBounds (cx - w / 2,
  62506. cy - h / 2,
  62507. w, h);
  62508. }
  62509. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62510. const int spacer = 16;
  62511. int totalWidth = -spacer;
  62512. for (i = buttons.size(); --i >= 0;)
  62513. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62514. int x = (w - totalWidth) / 2;
  62515. int y = (int) (getHeight() * 0.95f);
  62516. for (i = 0; i < buttons.size(); ++i)
  62517. {
  62518. TextButton* const c = (TextButton*) buttons[i];
  62519. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62520. c->setTopLeftPosition (x, ny);
  62521. if (ny < y)
  62522. y = ny;
  62523. x += c->getWidth() + spacer;
  62524. c->toFront (false);
  62525. }
  62526. y = textBottom;
  62527. for (i = 0; i < allComps.size(); ++i)
  62528. {
  62529. Component* const c = (Component*) allComps[i];
  62530. h = 22;
  62531. const int comboIndex = comboBoxes.indexOf (c);
  62532. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62533. y += labelHeight;
  62534. const int tbIndex = textBoxes.indexOf (c);
  62535. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62536. y += labelHeight;
  62537. if (customComps.contains (c))
  62538. {
  62539. if (c->getName().isNotEmpty())
  62540. y += labelHeight;
  62541. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62542. h = c->getHeight();
  62543. }
  62544. else if (textBlocks.contains (c))
  62545. {
  62546. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62547. h = c->getHeight();
  62548. }
  62549. else
  62550. {
  62551. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62552. }
  62553. y += h + 10;
  62554. }
  62555. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62556. }
  62557. bool AlertWindow::containsAnyExtraComponents() const
  62558. {
  62559. return textBoxes.size()
  62560. + comboBoxes.size()
  62561. + progressBars.size()
  62562. + customComps.size() > 0;
  62563. }
  62564. void AlertWindow::mouseDown (const MouseEvent&)
  62565. {
  62566. dragger.startDraggingComponent (this, &constrainer);
  62567. }
  62568. void AlertWindow::mouseDrag (const MouseEvent& e)
  62569. {
  62570. dragger.dragComponent (this, e);
  62571. }
  62572. bool AlertWindow::keyPressed (const KeyPress& key)
  62573. {
  62574. for (int i = buttons.size(); --i >= 0;)
  62575. {
  62576. TextButton* const b = (TextButton*) buttons[i];
  62577. if (b->isRegisteredForShortcut (key))
  62578. {
  62579. b->triggerClick();
  62580. return true;
  62581. }
  62582. }
  62583. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62584. {
  62585. exitModalState (0);
  62586. return true;
  62587. }
  62588. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62589. {
  62590. ((TextButton*) buttons.getFirst())->triggerClick();
  62591. return true;
  62592. }
  62593. return false;
  62594. }
  62595. void AlertWindow::lookAndFeelChanged()
  62596. {
  62597. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62598. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62599. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62600. }
  62601. int AlertWindow::getDesktopWindowStyleFlags() const
  62602. {
  62603. return getLookAndFeel().getAlertBoxWindowFlags();
  62604. }
  62605. struct AlertWindowInfo
  62606. {
  62607. String title, message, button1, button2, button3;
  62608. AlertWindow::AlertIconType iconType;
  62609. int numButtons;
  62610. Component::SafePointer<Component> associatedComponent;
  62611. int run() const
  62612. {
  62613. return (int) (pointer_sized_int)
  62614. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62615. }
  62616. private:
  62617. int show() const
  62618. {
  62619. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62620. : LookAndFeel::getDefaultLookAndFeel();
  62621. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62622. iconType, numButtons, associatedComponent));
  62623. jassert (alertBox != 0); // you have to return one of these!
  62624. return alertBox->runModalLoop();
  62625. }
  62626. static void* showCallback (void* userData)
  62627. {
  62628. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62629. }
  62630. };
  62631. void AlertWindow::showMessageBox (AlertIconType iconType,
  62632. const String& title,
  62633. const String& message,
  62634. const String& buttonText,
  62635. Component* associatedComponent)
  62636. {
  62637. AlertWindowInfo info;
  62638. info.title = title;
  62639. info.message = message;
  62640. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62641. info.iconType = iconType;
  62642. info.numButtons = 1;
  62643. info.associatedComponent = associatedComponent;
  62644. info.run();
  62645. }
  62646. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62647. const String& title,
  62648. const String& message,
  62649. const String& button1Text,
  62650. const String& button2Text,
  62651. Component* associatedComponent)
  62652. {
  62653. AlertWindowInfo info;
  62654. info.title = title;
  62655. info.message = message;
  62656. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62657. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62658. info.iconType = iconType;
  62659. info.numButtons = 2;
  62660. info.associatedComponent = associatedComponent;
  62661. return info.run() != 0;
  62662. }
  62663. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62664. const String& title,
  62665. const String& message,
  62666. const String& button1Text,
  62667. const String& button2Text,
  62668. const String& button3Text,
  62669. Component* associatedComponent)
  62670. {
  62671. AlertWindowInfo info;
  62672. info.title = title;
  62673. info.message = message;
  62674. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62675. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62676. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62677. info.iconType = iconType;
  62678. info.numButtons = 3;
  62679. info.associatedComponent = associatedComponent;
  62680. return info.run();
  62681. }
  62682. END_JUCE_NAMESPACE
  62683. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62684. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62685. BEGIN_JUCE_NAMESPACE
  62686. CallOutBox::CallOutBox (Component& contentComponent,
  62687. Component& componentToPointTo,
  62688. Component* const parentComponent)
  62689. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62690. {
  62691. addAndMakeVisible (&content);
  62692. if (parentComponent != 0)
  62693. {
  62694. updatePosition (parentComponent->getLocalBounds(),
  62695. componentToPointTo.getLocalBounds()
  62696. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  62697. parentComponent->addAndMakeVisible (this);
  62698. }
  62699. else
  62700. {
  62701. if (! JUCEApplication::isStandaloneApp())
  62702. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62703. updatePosition (componentToPointTo.getScreenBounds(),
  62704. componentToPointTo.getParentMonitorArea());
  62705. addToDesktop (ComponentPeer::windowIsTemporary);
  62706. }
  62707. }
  62708. CallOutBox::~CallOutBox()
  62709. {
  62710. }
  62711. void CallOutBox::setArrowSize (const float newSize)
  62712. {
  62713. arrowSize = newSize;
  62714. borderSpace = jmax (20, (int) arrowSize);
  62715. refreshPath();
  62716. }
  62717. void CallOutBox::paint (Graphics& g)
  62718. {
  62719. if (background.isNull())
  62720. {
  62721. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62722. Graphics g (background);
  62723. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62724. }
  62725. g.setColour (Colours::black);
  62726. g.drawImageAt (background, 0, 0);
  62727. }
  62728. void CallOutBox::resized()
  62729. {
  62730. content.setTopLeftPosition (borderSpace, borderSpace);
  62731. refreshPath();
  62732. }
  62733. void CallOutBox::moved()
  62734. {
  62735. refreshPath();
  62736. }
  62737. void CallOutBox::childBoundsChanged (Component*)
  62738. {
  62739. updatePosition (targetArea, availableArea);
  62740. }
  62741. bool CallOutBox::hitTest (int x, int y)
  62742. {
  62743. return outline.contains ((float) x, (float) y);
  62744. }
  62745. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62746. void CallOutBox::inputAttemptWhenModal()
  62747. {
  62748. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62749. if (targetArea.contains (mousePos))
  62750. {
  62751. // if you click on the area that originally popped-up the callout, you expect it
  62752. // to get rid of the box, but deleting the box here allows the click to pass through and
  62753. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62754. postCommandMessage (callOutBoxDismissCommandId);
  62755. }
  62756. else
  62757. {
  62758. exitModalState (0);
  62759. setVisible (false);
  62760. }
  62761. }
  62762. void CallOutBox::handleCommandMessage (int commandId)
  62763. {
  62764. Component::handleCommandMessage (commandId);
  62765. if (commandId == callOutBoxDismissCommandId)
  62766. {
  62767. exitModalState (0);
  62768. setVisible (false);
  62769. }
  62770. }
  62771. bool CallOutBox::keyPressed (const KeyPress& key)
  62772. {
  62773. if (key.isKeyCode (KeyPress::escapeKey))
  62774. {
  62775. inputAttemptWhenModal();
  62776. return true;
  62777. }
  62778. return false;
  62779. }
  62780. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62781. {
  62782. targetArea = newAreaToPointTo;
  62783. availableArea = newAreaToFitIn;
  62784. Rectangle<int> bounds (0, 0,
  62785. content.getWidth() + borderSpace * 2,
  62786. content.getHeight() + borderSpace * 2);
  62787. const int hw = bounds.getWidth() / 2;
  62788. const int hh = bounds.getHeight() / 2;
  62789. const float hwReduced = (float) (hw - borderSpace * 3);
  62790. const float hhReduced = (float) (hh - borderSpace * 3);
  62791. const float arrowIndent = borderSpace - arrowSize;
  62792. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62793. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62794. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62795. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62796. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62797. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62798. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62799. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62800. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62801. float nearest = 1.0e9f;
  62802. for (int i = 0; i < 4; ++i)
  62803. {
  62804. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62805. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62806. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62807. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62808. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62809. distanceFromCentre *= 2.0f;
  62810. if (distanceFromCentre < nearest)
  62811. {
  62812. nearest = distanceFromCentre;
  62813. targetPoint = targets[i];
  62814. bounds.setPosition ((int) (centre.getX() - hw),
  62815. (int) (centre.getY() - hh));
  62816. }
  62817. }
  62818. setBounds (bounds);
  62819. }
  62820. void CallOutBox::refreshPath()
  62821. {
  62822. repaint();
  62823. background = Image::null;
  62824. outline.clear();
  62825. const float gap = 4.5f;
  62826. const float cornerSize = 9.0f;
  62827. const float cornerSize2 = 2.0f * cornerSize;
  62828. const float arrowBaseWidth = arrowSize * 0.7f;
  62829. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62830. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62831. outline.startNewSubPath (left + cornerSize, top);
  62832. if (targetY <= top)
  62833. {
  62834. outline.lineTo (targetX - arrowBaseWidth, top);
  62835. outline.lineTo (targetX, targetY);
  62836. outline.lineTo (targetX + arrowBaseWidth, top);
  62837. }
  62838. outline.lineTo (right - cornerSize, top);
  62839. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62840. if (targetX >= right)
  62841. {
  62842. outline.lineTo (right, targetY - arrowBaseWidth);
  62843. outline.lineTo (targetX, targetY);
  62844. outline.lineTo (right, targetY + arrowBaseWidth);
  62845. }
  62846. outline.lineTo (right, bottom - cornerSize);
  62847. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62848. if (targetY >= bottom)
  62849. {
  62850. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62851. outline.lineTo (targetX, targetY);
  62852. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62853. }
  62854. outline.lineTo (left + cornerSize, bottom);
  62855. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62856. if (targetX <= left)
  62857. {
  62858. outline.lineTo (left, targetY + arrowBaseWidth);
  62859. outline.lineTo (targetX, targetY);
  62860. outline.lineTo (left, targetY - arrowBaseWidth);
  62861. }
  62862. outline.lineTo (left, top + cornerSize);
  62863. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62864. outline.closeSubPath();
  62865. }
  62866. END_JUCE_NAMESPACE
  62867. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62868. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62869. BEGIN_JUCE_NAMESPACE
  62870. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62871. static Array <ComponentPeer*> heavyweightPeers;
  62872. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62873. : component (component_),
  62874. styleFlags (styleFlags_),
  62875. lastPaintTime (0),
  62876. constrainer (0),
  62877. lastDragAndDropCompUnderMouse (0),
  62878. fakeMouseMessageSent (false),
  62879. isWindowMinimised (false)
  62880. {
  62881. heavyweightPeers.add (this);
  62882. }
  62883. ComponentPeer::~ComponentPeer()
  62884. {
  62885. heavyweightPeers.removeValue (this);
  62886. Desktop::getInstance().triggerFocusCallback();
  62887. }
  62888. int ComponentPeer::getNumPeers() throw()
  62889. {
  62890. return heavyweightPeers.size();
  62891. }
  62892. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62893. {
  62894. return heavyweightPeers [index];
  62895. }
  62896. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62897. {
  62898. for (int i = heavyweightPeers.size(); --i >= 0;)
  62899. {
  62900. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62901. if (peer->getComponent() == component)
  62902. return peer;
  62903. }
  62904. return 0;
  62905. }
  62906. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62907. {
  62908. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62909. }
  62910. void ComponentPeer::updateCurrentModifiers() throw()
  62911. {
  62912. ModifierKeys::updateCurrentModifiers();
  62913. }
  62914. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62915. {
  62916. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62917. jassert (mouse != 0); // not enough sources!
  62918. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62919. }
  62920. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62921. {
  62922. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62923. jassert (mouse != 0); // not enough sources!
  62924. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62925. }
  62926. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62927. {
  62928. Graphics g (&contextToPaintTo);
  62929. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62930. g.saveState();
  62931. #endif
  62932. JUCE_TRY
  62933. {
  62934. component->paintEntireComponent (g);
  62935. }
  62936. JUCE_CATCH_EXCEPTION
  62937. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62938. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62939. // clearly when things are being repainted.
  62940. {
  62941. g.restoreState();
  62942. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62943. (uint8) Random::getSystemRandom().nextInt (255),
  62944. (uint8) Random::getSystemRandom().nextInt (255),
  62945. (uint8) 0x50));
  62946. }
  62947. #endif
  62948. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62949. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62950. mess up a lot of the calculations that the library needs to do.
  62951. */
  62952. jassert (roundToInt (10.1f) == 10);
  62953. }
  62954. bool ComponentPeer::handleKeyPress (const int keyCode,
  62955. const juce_wchar textCharacter)
  62956. {
  62957. updateCurrentModifiers();
  62958. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62959. ? Component::getCurrentlyFocusedComponent()
  62960. : component;
  62961. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62962. {
  62963. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62964. if (currentModalComp != 0)
  62965. target = currentModalComp;
  62966. }
  62967. const KeyPress keyInfo (keyCode,
  62968. ModifierKeys::getCurrentModifiers().getRawFlags()
  62969. & ModifierKeys::allKeyboardModifiers,
  62970. textCharacter);
  62971. bool keyWasUsed = false;
  62972. while (target != 0)
  62973. {
  62974. const Component::SafePointer<Component> deletionChecker (target);
  62975. if (target->keyListeners_ != 0)
  62976. {
  62977. for (int i = target->keyListeners_->size(); --i >= 0;)
  62978. {
  62979. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62980. if (keyWasUsed || deletionChecker == 0)
  62981. return keyWasUsed;
  62982. i = jmin (i, target->keyListeners_->size());
  62983. }
  62984. }
  62985. keyWasUsed = target->keyPressed (keyInfo);
  62986. if (keyWasUsed || deletionChecker == 0)
  62987. break;
  62988. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62989. {
  62990. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62991. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62992. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62993. break;
  62994. }
  62995. target = target->parentComponent_;
  62996. }
  62997. return keyWasUsed;
  62998. }
  62999. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  63000. {
  63001. updateCurrentModifiers();
  63002. Component* target = Component::getCurrentlyFocusedComponent() != 0
  63003. ? Component::getCurrentlyFocusedComponent()
  63004. : component;
  63005. if (target->isCurrentlyBlockedByAnotherModalComponent())
  63006. {
  63007. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  63008. if (currentModalComp != 0)
  63009. target = currentModalComp;
  63010. }
  63011. bool keyWasUsed = false;
  63012. while (target != 0)
  63013. {
  63014. const Component::SafePointer<Component> deletionChecker (target);
  63015. keyWasUsed = target->keyStateChanged (isKeyDown);
  63016. if (keyWasUsed || deletionChecker == 0)
  63017. break;
  63018. if (target->keyListeners_ != 0)
  63019. {
  63020. for (int i = target->keyListeners_->size(); --i >= 0;)
  63021. {
  63022. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  63023. if (keyWasUsed || deletionChecker == 0)
  63024. return keyWasUsed;
  63025. i = jmin (i, target->keyListeners_->size());
  63026. }
  63027. }
  63028. target = target->parentComponent_;
  63029. }
  63030. return keyWasUsed;
  63031. }
  63032. void ComponentPeer::handleModifierKeysChange()
  63033. {
  63034. updateCurrentModifiers();
  63035. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63036. if (target == 0)
  63037. target = Component::getCurrentlyFocusedComponent();
  63038. if (target == 0)
  63039. target = component;
  63040. if (target != 0)
  63041. target->internalModifierKeysChanged();
  63042. }
  63043. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  63044. {
  63045. Component* const c = Component::getCurrentlyFocusedComponent();
  63046. if (component->isParentOf (c))
  63047. {
  63048. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  63049. if (ti != 0 && ti->isTextInputActive())
  63050. return ti;
  63051. }
  63052. return 0;
  63053. }
  63054. void ComponentPeer::handleBroughtToFront()
  63055. {
  63056. updateCurrentModifiers();
  63057. if (component != 0)
  63058. component->internalBroughtToFront();
  63059. }
  63060. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  63061. {
  63062. constrainer = newConstrainer;
  63063. }
  63064. void ComponentPeer::handleMovedOrResized()
  63065. {
  63066. jassert (component->isValidComponent());
  63067. updateCurrentModifiers();
  63068. const bool nowMinimised = isMinimised();
  63069. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  63070. {
  63071. const Component::SafePointer<Component> deletionChecker (component);
  63072. const Rectangle<int> newBounds (getBounds());
  63073. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  63074. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  63075. if (wasMoved || wasResized)
  63076. {
  63077. component->bounds_ = newBounds;
  63078. if (wasResized)
  63079. component->repaint();
  63080. component->sendMovedResizedMessages (wasMoved, wasResized);
  63081. if (deletionChecker == 0)
  63082. return;
  63083. }
  63084. }
  63085. if (isWindowMinimised != nowMinimised)
  63086. {
  63087. isWindowMinimised = nowMinimised;
  63088. component->minimisationStateChanged (nowMinimised);
  63089. component->sendVisibilityChangeMessage();
  63090. }
  63091. if (! isFullScreen())
  63092. lastNonFullscreenBounds = component->getBounds();
  63093. }
  63094. void ComponentPeer::handleFocusGain()
  63095. {
  63096. updateCurrentModifiers();
  63097. if (component->isParentOf (lastFocusedComponent))
  63098. {
  63099. Component::currentlyFocusedComponent = lastFocusedComponent;
  63100. Desktop::getInstance().triggerFocusCallback();
  63101. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  63102. }
  63103. else
  63104. {
  63105. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  63106. component->grabKeyboardFocus();
  63107. else
  63108. Component::bringModalComponentToFront();
  63109. }
  63110. }
  63111. void ComponentPeer::handleFocusLoss()
  63112. {
  63113. updateCurrentModifiers();
  63114. if (component->hasKeyboardFocus (true))
  63115. {
  63116. lastFocusedComponent = Component::currentlyFocusedComponent;
  63117. if (lastFocusedComponent != 0)
  63118. {
  63119. Component::currentlyFocusedComponent = 0;
  63120. Desktop::getInstance().triggerFocusCallback();
  63121. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  63122. }
  63123. }
  63124. }
  63125. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  63126. {
  63127. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  63128. ? static_cast <Component*> (lastFocusedComponent)
  63129. : component;
  63130. }
  63131. void ComponentPeer::handleScreenSizeChange()
  63132. {
  63133. updateCurrentModifiers();
  63134. component->parentSizeChanged();
  63135. handleMovedOrResized();
  63136. }
  63137. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  63138. {
  63139. lastNonFullscreenBounds = newBounds;
  63140. }
  63141. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  63142. {
  63143. return lastNonFullscreenBounds;
  63144. }
  63145. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  63146. const StringArray& files,
  63147. FileDragAndDropTarget* const lastOne)
  63148. {
  63149. while (c != 0)
  63150. {
  63151. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  63152. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  63153. return t;
  63154. c = c->getParentComponent();
  63155. }
  63156. return 0;
  63157. }
  63158. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  63159. {
  63160. updateCurrentModifiers();
  63161. FileDragAndDropTarget* lastTarget
  63162. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63163. FileDragAndDropTarget* newTarget = 0;
  63164. Component* const compUnderMouse = component->getComponentAt (position);
  63165. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  63166. {
  63167. lastDragAndDropCompUnderMouse = compUnderMouse;
  63168. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  63169. if (newTarget != lastTarget)
  63170. {
  63171. if (lastTarget != 0)
  63172. lastTarget->fileDragExit (files);
  63173. dragAndDropTargetComponent = 0;
  63174. if (newTarget != 0)
  63175. {
  63176. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  63177. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  63178. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  63179. }
  63180. }
  63181. }
  63182. else
  63183. {
  63184. newTarget = lastTarget;
  63185. }
  63186. if (newTarget != 0)
  63187. {
  63188. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  63189. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63190. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  63191. }
  63192. }
  63193. void ComponentPeer::handleFileDragExit (const StringArray& files)
  63194. {
  63195. handleFileDragMove (files, Point<int> (-1, -1));
  63196. jassert (dragAndDropTargetComponent == 0);
  63197. lastDragAndDropCompUnderMouse = 0;
  63198. }
  63199. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  63200. {
  63201. handleFileDragMove (files, position);
  63202. if (dragAndDropTargetComponent != 0)
  63203. {
  63204. FileDragAndDropTarget* const target
  63205. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63206. dragAndDropTargetComponent = 0;
  63207. lastDragAndDropCompUnderMouse = 0;
  63208. if (target != 0)
  63209. {
  63210. Component* const targetComp = dynamic_cast <Component*> (target);
  63211. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63212. {
  63213. targetComp->internalModalInputAttempt();
  63214. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63215. return;
  63216. }
  63217. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63218. target->filesDropped (files, pos.getX(), pos.getY());
  63219. }
  63220. }
  63221. }
  63222. void ComponentPeer::handleUserClosingWindow()
  63223. {
  63224. updateCurrentModifiers();
  63225. component->userTriedToCloseWindow();
  63226. }
  63227. void ComponentPeer::bringModalComponentToFront()
  63228. {
  63229. Component::bringModalComponentToFront();
  63230. }
  63231. void ComponentPeer::clearMaskedRegion()
  63232. {
  63233. maskedRegion.clear();
  63234. }
  63235. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  63236. {
  63237. maskedRegion.add (x, y, w, h);
  63238. }
  63239. const StringArray ComponentPeer::getAvailableRenderingEngines()
  63240. {
  63241. StringArray s;
  63242. s.add ("Software Renderer");
  63243. return s;
  63244. }
  63245. int ComponentPeer::getCurrentRenderingEngine() throw()
  63246. {
  63247. return 0;
  63248. }
  63249. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  63250. {
  63251. }
  63252. END_JUCE_NAMESPACE
  63253. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  63254. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  63255. BEGIN_JUCE_NAMESPACE
  63256. DialogWindow::DialogWindow (const String& name,
  63257. const Colour& backgroundColour_,
  63258. const bool escapeKeyTriggersCloseButton_,
  63259. const bool addToDesktop_)
  63260. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  63261. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  63262. {
  63263. }
  63264. DialogWindow::~DialogWindow()
  63265. {
  63266. }
  63267. void DialogWindow::resized()
  63268. {
  63269. DocumentWindow::resized();
  63270. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  63271. if (escapeKeyTriggersCloseButton
  63272. && getCloseButton() != 0
  63273. && ! getCloseButton()->isRegisteredForShortcut (esc))
  63274. {
  63275. getCloseButton()->addShortcut (esc);
  63276. }
  63277. }
  63278. class TempDialogWindow : public DialogWindow
  63279. {
  63280. public:
  63281. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63282. : DialogWindow (title, colour, escapeCloses, true)
  63283. {
  63284. if (! JUCEApplication::isStandaloneApp())
  63285. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63286. }
  63287. ~TempDialogWindow()
  63288. {
  63289. }
  63290. void closeButtonPressed()
  63291. {
  63292. setVisible (false);
  63293. }
  63294. private:
  63295. TempDialogWindow (const TempDialogWindow&);
  63296. TempDialogWindow& operator= (const TempDialogWindow&);
  63297. };
  63298. int DialogWindow::showModalDialog (const String& dialogTitle,
  63299. Component* contentComponent,
  63300. Component* componentToCentreAround,
  63301. const Colour& colour,
  63302. const bool escapeKeyTriggersCloseButton,
  63303. const bool shouldBeResizable,
  63304. const bool useBottomRightCornerResizer)
  63305. {
  63306. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63307. dw.setContentComponent (contentComponent, true, true);
  63308. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63309. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63310. const int result = dw.runModalLoop();
  63311. dw.setContentComponent (0, false);
  63312. return result;
  63313. }
  63314. END_JUCE_NAMESPACE
  63315. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63316. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63317. BEGIN_JUCE_NAMESPACE
  63318. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63319. {
  63320. public:
  63321. ButtonListenerProxy (DocumentWindow& owner_)
  63322. : owner (owner_)
  63323. {
  63324. }
  63325. void buttonClicked (Button* button)
  63326. {
  63327. if (button == owner.getMinimiseButton())
  63328. owner.minimiseButtonPressed();
  63329. else if (button == owner.getMaximiseButton())
  63330. owner.maximiseButtonPressed();
  63331. else if (button == owner.getCloseButton())
  63332. owner.closeButtonPressed();
  63333. }
  63334. juce_UseDebuggingNewOperator
  63335. private:
  63336. DocumentWindow& owner;
  63337. ButtonListenerProxy (const ButtonListenerProxy&);
  63338. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63339. };
  63340. DocumentWindow::DocumentWindow (const String& title,
  63341. const Colour& backgroundColour,
  63342. const int requiredButtons_,
  63343. const bool addToDesktop_)
  63344. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63345. titleBarHeight (26),
  63346. menuBarHeight (24),
  63347. requiredButtons (requiredButtons_),
  63348. #if JUCE_MAC
  63349. positionTitleBarButtonsOnLeft (true),
  63350. #else
  63351. positionTitleBarButtonsOnLeft (false),
  63352. #endif
  63353. drawTitleTextCentred (true),
  63354. menuBarModel (0)
  63355. {
  63356. setResizeLimits (128, 128, 32768, 32768);
  63357. lookAndFeelChanged();
  63358. }
  63359. DocumentWindow::~DocumentWindow()
  63360. {
  63361. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63362. titleBarButtons[i] = 0;
  63363. menuBar = 0;
  63364. }
  63365. void DocumentWindow::repaintTitleBar()
  63366. {
  63367. repaint (getTitleBarArea());
  63368. }
  63369. void DocumentWindow::setName (const String& newName)
  63370. {
  63371. if (newName != getName())
  63372. {
  63373. Component::setName (newName);
  63374. repaintTitleBar();
  63375. }
  63376. }
  63377. void DocumentWindow::setIcon (const Image& imageToUse)
  63378. {
  63379. titleBarIcon = imageToUse;
  63380. repaintTitleBar();
  63381. }
  63382. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63383. {
  63384. titleBarHeight = newHeight;
  63385. resized();
  63386. repaintTitleBar();
  63387. }
  63388. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63389. const bool positionTitleBarButtonsOnLeft_)
  63390. {
  63391. requiredButtons = requiredButtons_;
  63392. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63393. lookAndFeelChanged();
  63394. }
  63395. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63396. {
  63397. drawTitleTextCentred = textShouldBeCentred;
  63398. repaintTitleBar();
  63399. }
  63400. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63401. const int menuBarHeight_)
  63402. {
  63403. if (menuBarModel != menuBarModel_)
  63404. {
  63405. menuBar = 0;
  63406. menuBarModel = menuBarModel_;
  63407. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63408. : getLookAndFeel().getDefaultMenuBarHeight();
  63409. if (menuBarModel != 0)
  63410. {
  63411. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63412. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63413. menuBar->setEnabled (isActiveWindow());
  63414. }
  63415. resized();
  63416. }
  63417. }
  63418. void DocumentWindow::closeButtonPressed()
  63419. {
  63420. /* If you've got a close button, you have to override this method to get
  63421. rid of your window!
  63422. If the window is just a pop-up, you should override this method and make
  63423. it delete the window in whatever way is appropriate for your app. E.g. you
  63424. might just want to call "delete this".
  63425. If your app is centred around this window such that the whole app should quit when
  63426. the window is closed, then you will probably want to use this method as an opportunity
  63427. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63428. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63429. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63430. or closing it via the taskbar icon on Windows).
  63431. */
  63432. jassertfalse;
  63433. }
  63434. void DocumentWindow::minimiseButtonPressed()
  63435. {
  63436. setMinimised (true);
  63437. }
  63438. void DocumentWindow::maximiseButtonPressed()
  63439. {
  63440. setFullScreen (! isFullScreen());
  63441. }
  63442. void DocumentWindow::paint (Graphics& g)
  63443. {
  63444. ResizableWindow::paint (g);
  63445. if (resizableBorder == 0)
  63446. {
  63447. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63448. const BorderSize border (getBorderThickness());
  63449. g.fillRect (0, 0, getWidth(), border.getTop());
  63450. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63451. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63452. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63453. }
  63454. const Rectangle<int> titleBarArea (getTitleBarArea());
  63455. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63456. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  63457. int titleSpaceX1 = 6;
  63458. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63459. for (int i = 0; i < 3; ++i)
  63460. {
  63461. if (titleBarButtons[i] != 0)
  63462. {
  63463. if (positionTitleBarButtonsOnLeft)
  63464. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63465. else
  63466. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63467. }
  63468. }
  63469. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63470. titleBarArea.getWidth(),
  63471. titleBarArea.getHeight(),
  63472. titleSpaceX1,
  63473. jmax (1, titleSpaceX2 - titleSpaceX1),
  63474. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63475. ! drawTitleTextCentred);
  63476. }
  63477. void DocumentWindow::resized()
  63478. {
  63479. ResizableWindow::resized();
  63480. if (titleBarButtons[1] != 0)
  63481. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63482. const Rectangle<int> titleBarArea (getTitleBarArea());
  63483. getLookAndFeel()
  63484. .positionDocumentWindowButtons (*this,
  63485. titleBarArea.getX(), titleBarArea.getY(),
  63486. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63487. titleBarButtons[0],
  63488. titleBarButtons[1],
  63489. titleBarButtons[2],
  63490. positionTitleBarButtonsOnLeft);
  63491. if (menuBar != 0)
  63492. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63493. titleBarArea.getWidth(), menuBarHeight);
  63494. }
  63495. const BorderSize DocumentWindow::getBorderThickness()
  63496. {
  63497. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63498. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63499. }
  63500. const BorderSize DocumentWindow::getContentComponentBorder()
  63501. {
  63502. BorderSize border (getBorderThickness());
  63503. border.setTop (border.getTop()
  63504. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63505. + (menuBar != 0 ? menuBarHeight : 0));
  63506. return border;
  63507. }
  63508. int DocumentWindow::getTitleBarHeight() const
  63509. {
  63510. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63511. }
  63512. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63513. {
  63514. const BorderSize border (getBorderThickness());
  63515. return Rectangle<int> (border.getLeft(), border.getTop(),
  63516. getWidth() - border.getLeftAndRight(),
  63517. getTitleBarHeight());
  63518. }
  63519. Button* DocumentWindow::getCloseButton() const throw()
  63520. {
  63521. return titleBarButtons[2];
  63522. }
  63523. Button* DocumentWindow::getMinimiseButton() const throw()
  63524. {
  63525. return titleBarButtons[0];
  63526. }
  63527. Button* DocumentWindow::getMaximiseButton() const throw()
  63528. {
  63529. return titleBarButtons[1];
  63530. }
  63531. int DocumentWindow::getDesktopWindowStyleFlags() const
  63532. {
  63533. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63534. if ((requiredButtons & minimiseButton) != 0)
  63535. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63536. if ((requiredButtons & maximiseButton) != 0)
  63537. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63538. if ((requiredButtons & closeButton) != 0)
  63539. styleFlags |= ComponentPeer::windowHasCloseButton;
  63540. return styleFlags;
  63541. }
  63542. void DocumentWindow::lookAndFeelChanged()
  63543. {
  63544. int i;
  63545. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63546. titleBarButtons[i] = 0;
  63547. if (! isUsingNativeTitleBar())
  63548. {
  63549. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63550. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63551. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63552. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63553. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63554. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63555. for (i = 0; i < 3; ++i)
  63556. {
  63557. if (titleBarButtons[i] != 0)
  63558. {
  63559. if (buttonListener == 0)
  63560. buttonListener = new ButtonListenerProxy (*this);
  63561. titleBarButtons[i]->addButtonListener (buttonListener);
  63562. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63563. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63564. Component::addAndMakeVisible (titleBarButtons[i]);
  63565. }
  63566. }
  63567. if (getCloseButton() != 0)
  63568. {
  63569. #if JUCE_MAC
  63570. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63571. #else
  63572. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63573. #endif
  63574. }
  63575. }
  63576. activeWindowStatusChanged();
  63577. ResizableWindow::lookAndFeelChanged();
  63578. }
  63579. void DocumentWindow::parentHierarchyChanged()
  63580. {
  63581. lookAndFeelChanged();
  63582. }
  63583. void DocumentWindow::activeWindowStatusChanged()
  63584. {
  63585. ResizableWindow::activeWindowStatusChanged();
  63586. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63587. if (titleBarButtons[i] != 0)
  63588. titleBarButtons[i]->setEnabled (isActiveWindow());
  63589. if (menuBar != 0)
  63590. menuBar->setEnabled (isActiveWindow());
  63591. }
  63592. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63593. {
  63594. if (getTitleBarArea().contains (e.x, e.y)
  63595. && getMaximiseButton() != 0)
  63596. {
  63597. getMaximiseButton()->triggerClick();
  63598. }
  63599. }
  63600. void DocumentWindow::userTriedToCloseWindow()
  63601. {
  63602. closeButtonPressed();
  63603. }
  63604. END_JUCE_NAMESPACE
  63605. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63606. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63607. BEGIN_JUCE_NAMESPACE
  63608. ResizableWindow::ResizableWindow (const String& name,
  63609. const bool addToDesktop_)
  63610. : TopLevelWindow (name, addToDesktop_),
  63611. resizeToFitContent (false),
  63612. fullscreen (false),
  63613. lastNonFullScreenPos (50, 50, 256, 256),
  63614. constrainer (0)
  63615. #if JUCE_DEBUG
  63616. , hasBeenResized (false)
  63617. #endif
  63618. {
  63619. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63620. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63621. if (addToDesktop_)
  63622. Component::addToDesktop (getDesktopWindowStyleFlags());
  63623. }
  63624. ResizableWindow::ResizableWindow (const String& name,
  63625. const Colour& backgroundColour_,
  63626. const bool addToDesktop_)
  63627. : TopLevelWindow (name, addToDesktop_),
  63628. resizeToFitContent (false),
  63629. fullscreen (false),
  63630. lastNonFullScreenPos (50, 50, 256, 256),
  63631. constrainer (0)
  63632. #if JUCE_DEBUG
  63633. , hasBeenResized (false)
  63634. #endif
  63635. {
  63636. setBackgroundColour (backgroundColour_);
  63637. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63638. if (addToDesktop_)
  63639. Component::addToDesktop (getDesktopWindowStyleFlags());
  63640. }
  63641. ResizableWindow::~ResizableWindow()
  63642. {
  63643. resizableCorner = 0;
  63644. resizableBorder = 0;
  63645. contentComponent.deleteAndZero();
  63646. // have you been adding your own components directly to this window..? tut tut tut.
  63647. // Read the instructions for using a ResizableWindow!
  63648. jassert (getNumChildComponents() == 0);
  63649. }
  63650. int ResizableWindow::getDesktopWindowStyleFlags() const
  63651. {
  63652. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63653. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63654. styleFlags |= ComponentPeer::windowIsResizable;
  63655. return styleFlags;
  63656. }
  63657. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63658. const bool deleteOldOne,
  63659. const bool resizeToFit)
  63660. {
  63661. resizeToFitContent = resizeToFit;
  63662. if (newContentComponent != static_cast <Component*> (contentComponent))
  63663. {
  63664. if (deleteOldOne)
  63665. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63666. // external deletion of the content comp)
  63667. else
  63668. removeChildComponent (contentComponent);
  63669. contentComponent = newContentComponent;
  63670. Component::addAndMakeVisible (contentComponent);
  63671. }
  63672. if (resizeToFit)
  63673. childBoundsChanged (contentComponent);
  63674. resized(); // must always be called to position the new content comp
  63675. }
  63676. void ResizableWindow::setContentComponentSize (int width, int height)
  63677. {
  63678. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63679. const BorderSize border (getContentComponentBorder());
  63680. setSize (width + border.getLeftAndRight(),
  63681. height + border.getTopAndBottom());
  63682. }
  63683. const BorderSize ResizableWindow::getBorderThickness()
  63684. {
  63685. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63686. }
  63687. const BorderSize ResizableWindow::getContentComponentBorder()
  63688. {
  63689. return getBorderThickness();
  63690. }
  63691. void ResizableWindow::moved()
  63692. {
  63693. updateLastPos();
  63694. }
  63695. void ResizableWindow::visibilityChanged()
  63696. {
  63697. TopLevelWindow::visibilityChanged();
  63698. updateLastPos();
  63699. }
  63700. void ResizableWindow::resized()
  63701. {
  63702. if (resizableBorder != 0)
  63703. {
  63704. resizableBorder->setVisible (! isFullScreen());
  63705. resizableBorder->setBorderThickness (getBorderThickness());
  63706. resizableBorder->setSize (getWidth(), getHeight());
  63707. resizableBorder->toBack();
  63708. }
  63709. if (resizableCorner != 0)
  63710. {
  63711. resizableCorner->setVisible (! isFullScreen());
  63712. const int resizerSize = 18;
  63713. resizableCorner->setBounds (getWidth() - resizerSize,
  63714. getHeight() - resizerSize,
  63715. resizerSize, resizerSize);
  63716. }
  63717. if (contentComponent != 0)
  63718. contentComponent->setBoundsInset (getContentComponentBorder());
  63719. updateLastPos();
  63720. #if JUCE_DEBUG
  63721. hasBeenResized = true;
  63722. #endif
  63723. }
  63724. void ResizableWindow::childBoundsChanged (Component* child)
  63725. {
  63726. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63727. {
  63728. // not going to look very good if this component has a zero size..
  63729. jassert (child->getWidth() > 0);
  63730. jassert (child->getHeight() > 0);
  63731. const BorderSize borders (getContentComponentBorder());
  63732. setSize (child->getWidth() + borders.getLeftAndRight(),
  63733. child->getHeight() + borders.getTopAndBottom());
  63734. }
  63735. }
  63736. void ResizableWindow::activeWindowStatusChanged()
  63737. {
  63738. const BorderSize border (getContentComponentBorder());
  63739. Rectangle<int> area (getLocalBounds());
  63740. repaint (area.removeFromTop (border.getTop()));
  63741. repaint (area.removeFromLeft (border.getLeft()));
  63742. repaint (area.removeFromRight (border.getRight()));
  63743. repaint (area.removeFromBottom (border.getBottom()));
  63744. }
  63745. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63746. const bool useBottomRightCornerResizer)
  63747. {
  63748. if (shouldBeResizable)
  63749. {
  63750. if (useBottomRightCornerResizer)
  63751. {
  63752. resizableBorder = 0;
  63753. if (resizableCorner == 0)
  63754. {
  63755. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63756. resizableCorner->setAlwaysOnTop (true);
  63757. }
  63758. }
  63759. else
  63760. {
  63761. resizableCorner = 0;
  63762. if (resizableBorder == 0)
  63763. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63764. }
  63765. }
  63766. else
  63767. {
  63768. resizableCorner = 0;
  63769. resizableBorder = 0;
  63770. }
  63771. if (isUsingNativeTitleBar())
  63772. recreateDesktopWindow();
  63773. childBoundsChanged (contentComponent);
  63774. resized();
  63775. }
  63776. bool ResizableWindow::isResizable() const throw()
  63777. {
  63778. return resizableCorner != 0
  63779. || resizableBorder != 0;
  63780. }
  63781. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63782. const int newMinimumHeight,
  63783. const int newMaximumWidth,
  63784. const int newMaximumHeight) throw()
  63785. {
  63786. // if you've set up a custom constrainer then these settings won't have any effect..
  63787. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63788. if (constrainer == 0)
  63789. setConstrainer (&defaultConstrainer);
  63790. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63791. newMaximumWidth, newMaximumHeight);
  63792. setBoundsConstrained (getBounds());
  63793. }
  63794. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63795. {
  63796. if (constrainer != newConstrainer)
  63797. {
  63798. constrainer = newConstrainer;
  63799. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63800. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63801. resizableCorner = 0;
  63802. resizableBorder = 0;
  63803. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63804. ComponentPeer* const peer = getPeer();
  63805. if (peer != 0)
  63806. peer->setConstrainer (newConstrainer);
  63807. }
  63808. }
  63809. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63810. {
  63811. if (constrainer != 0)
  63812. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63813. else
  63814. setBounds (bounds);
  63815. }
  63816. void ResizableWindow::paint (Graphics& g)
  63817. {
  63818. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63819. getBorderThickness(), *this);
  63820. if (! isFullScreen())
  63821. {
  63822. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63823. getBorderThickness(), *this);
  63824. }
  63825. #if JUCE_DEBUG
  63826. /* If this fails, then you've probably written a subclass with a resized()
  63827. callback but forgotten to make it call its parent class's resized() method.
  63828. It's important when you override methods like resized(), moved(),
  63829. etc., that you make sure the base class methods also get called.
  63830. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63831. because your content should all be inside the content component - and it's the
  63832. content component's resized() method that you should be using to do your
  63833. layout.
  63834. */
  63835. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63836. #endif
  63837. }
  63838. void ResizableWindow::lookAndFeelChanged()
  63839. {
  63840. resized();
  63841. if (isOnDesktop())
  63842. {
  63843. Component::addToDesktop (getDesktopWindowStyleFlags());
  63844. ComponentPeer* const peer = getPeer();
  63845. if (peer != 0)
  63846. peer->setConstrainer (constrainer);
  63847. }
  63848. }
  63849. const Colour ResizableWindow::getBackgroundColour() const throw()
  63850. {
  63851. return findColour (backgroundColourId, false);
  63852. }
  63853. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63854. {
  63855. Colour backgroundColour (newColour);
  63856. if (! Desktop::canUseSemiTransparentWindows())
  63857. backgroundColour = newColour.withAlpha (1.0f);
  63858. setColour (backgroundColourId, backgroundColour);
  63859. setOpaque (backgroundColour.isOpaque());
  63860. repaint();
  63861. }
  63862. bool ResizableWindow::isFullScreen() const
  63863. {
  63864. if (isOnDesktop())
  63865. {
  63866. ComponentPeer* const peer = getPeer();
  63867. return peer != 0 && peer->isFullScreen();
  63868. }
  63869. return fullscreen;
  63870. }
  63871. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63872. {
  63873. if (shouldBeFullScreen != isFullScreen())
  63874. {
  63875. updateLastPos();
  63876. fullscreen = shouldBeFullScreen;
  63877. if (isOnDesktop())
  63878. {
  63879. ComponentPeer* const peer = getPeer();
  63880. if (peer != 0)
  63881. {
  63882. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63883. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63884. peer->setFullScreen (shouldBeFullScreen);
  63885. if (! shouldBeFullScreen)
  63886. setBounds (lastPos);
  63887. }
  63888. else
  63889. {
  63890. jassertfalse;
  63891. }
  63892. }
  63893. else
  63894. {
  63895. if (shouldBeFullScreen)
  63896. setBounds (0, 0, getParentWidth(), getParentHeight());
  63897. else
  63898. setBounds (lastNonFullScreenPos);
  63899. }
  63900. resized();
  63901. }
  63902. }
  63903. bool ResizableWindow::isMinimised() const
  63904. {
  63905. ComponentPeer* const peer = getPeer();
  63906. return (peer != 0) && peer->isMinimised();
  63907. }
  63908. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63909. {
  63910. if (shouldMinimise != isMinimised())
  63911. {
  63912. ComponentPeer* const peer = getPeer();
  63913. if (peer != 0)
  63914. {
  63915. updateLastPos();
  63916. peer->setMinimised (shouldMinimise);
  63917. }
  63918. else
  63919. {
  63920. jassertfalse;
  63921. }
  63922. }
  63923. }
  63924. void ResizableWindow::updateLastPos()
  63925. {
  63926. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63927. {
  63928. lastNonFullScreenPos = getBounds();
  63929. }
  63930. }
  63931. void ResizableWindow::parentSizeChanged()
  63932. {
  63933. if (isFullScreen() && getParentComponent() != 0)
  63934. {
  63935. setBounds (0, 0, getParentWidth(), getParentHeight());
  63936. }
  63937. }
  63938. const String ResizableWindow::getWindowStateAsString()
  63939. {
  63940. updateLastPos();
  63941. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63942. }
  63943. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63944. {
  63945. StringArray tokens;
  63946. tokens.addTokens (s, false);
  63947. tokens.removeEmptyStrings();
  63948. tokens.trim();
  63949. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63950. const int firstCoord = fs ? 1 : 0;
  63951. if (tokens.size() != firstCoord + 4)
  63952. return false;
  63953. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63954. tokens[firstCoord + 1].getIntValue(),
  63955. tokens[firstCoord + 2].getIntValue(),
  63956. tokens[firstCoord + 3].getIntValue());
  63957. if (newPos.isEmpty())
  63958. return false;
  63959. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63960. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63961. if (peer != 0)
  63962. peer->getFrameSize().addTo (newPos);
  63963. if (! screen.contains (newPos))
  63964. {
  63965. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63966. jmin (newPos.getHeight(), screen.getHeight()));
  63967. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63968. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63969. }
  63970. if (peer != 0)
  63971. {
  63972. peer->getFrameSize().subtractFrom (newPos);
  63973. peer->setNonFullScreenBounds (newPos);
  63974. }
  63975. lastNonFullScreenPos = newPos;
  63976. setFullScreen (fs);
  63977. if (! fs)
  63978. setBoundsConstrained (newPos);
  63979. return true;
  63980. }
  63981. void ResizableWindow::mouseDown (const MouseEvent&)
  63982. {
  63983. if (! isFullScreen())
  63984. dragger.startDraggingComponent (this, constrainer);
  63985. }
  63986. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63987. {
  63988. if (! isFullScreen())
  63989. dragger.dragComponent (this, e);
  63990. }
  63991. #if JUCE_DEBUG
  63992. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63993. {
  63994. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63995. manages its child components automatically, and if you add your own it'll cause
  63996. trouble. Instead, use setContentComponent() to give it a component which
  63997. will be automatically resized and kept in the right place - then you can add
  63998. subcomponents to the content comp. See the notes for the ResizableWindow class
  63999. for more info.
  64000. If you really know what you're doing and want to avoid this assertion, just call
  64001. Component::addChildComponent directly.
  64002. */
  64003. jassertfalse;
  64004. Component::addChildComponent (child, zOrder);
  64005. }
  64006. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  64007. {
  64008. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  64009. manages its child components automatically, and if you add your own it'll cause
  64010. trouble. Instead, use setContentComponent() to give it a component which
  64011. will be automatically resized and kept in the right place - then you can add
  64012. subcomponents to the content comp. See the notes for the ResizableWindow class
  64013. for more info.
  64014. If you really know what you're doing and want to avoid this assertion, just call
  64015. Component::addAndMakeVisible directly.
  64016. */
  64017. jassertfalse;
  64018. Component::addAndMakeVisible (child, zOrder);
  64019. }
  64020. #endif
  64021. END_JUCE_NAMESPACE
  64022. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  64023. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  64024. BEGIN_JUCE_NAMESPACE
  64025. SplashScreen::SplashScreen()
  64026. {
  64027. setOpaque (true);
  64028. }
  64029. SplashScreen::~SplashScreen()
  64030. {
  64031. }
  64032. void SplashScreen::show (const String& title,
  64033. const Image& backgroundImage_,
  64034. const int minimumTimeToDisplayFor,
  64035. const bool useDropShadow,
  64036. const bool removeOnMouseClick)
  64037. {
  64038. backgroundImage = backgroundImage_;
  64039. jassert (backgroundImage_.isValid());
  64040. if (backgroundImage_.isValid())
  64041. {
  64042. setOpaque (! backgroundImage_.hasAlphaChannel());
  64043. show (title,
  64044. backgroundImage_.getWidth(),
  64045. backgroundImage_.getHeight(),
  64046. minimumTimeToDisplayFor,
  64047. useDropShadow,
  64048. removeOnMouseClick);
  64049. }
  64050. }
  64051. void SplashScreen::show (const String& title,
  64052. const int width,
  64053. const int height,
  64054. const int minimumTimeToDisplayFor,
  64055. const bool useDropShadow,
  64056. const bool removeOnMouseClick)
  64057. {
  64058. setName (title);
  64059. setAlwaysOnTop (true);
  64060. setVisible (true);
  64061. centreWithSize (width, height);
  64062. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  64063. toFront (false);
  64064. MessageManager::getInstance()->runDispatchLoopUntil (300);
  64065. repaint();
  64066. originalClickCounter = removeOnMouseClick
  64067. ? Desktop::getMouseButtonClickCounter()
  64068. : std::numeric_limits<int>::max();
  64069. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  64070. startTimer (50);
  64071. }
  64072. void SplashScreen::paint (Graphics& g)
  64073. {
  64074. g.setOpacity (1.0f);
  64075. g.drawImage (backgroundImage,
  64076. 0, 0, getWidth(), getHeight(),
  64077. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  64078. }
  64079. void SplashScreen::timerCallback()
  64080. {
  64081. if (Time::getCurrentTime() > earliestTimeToDelete
  64082. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  64083. {
  64084. delete this;
  64085. }
  64086. }
  64087. END_JUCE_NAMESPACE
  64088. /*** End of inlined file: juce_SplashScreen.cpp ***/
  64089. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  64090. BEGIN_JUCE_NAMESPACE
  64091. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  64092. const bool hasProgressBar,
  64093. const bool hasCancelButton,
  64094. const int timeOutMsWhenCancelling_,
  64095. const String& cancelButtonText)
  64096. : Thread ("Juce Progress Window"),
  64097. progress (0.0),
  64098. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  64099. {
  64100. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  64101. .createAlertWindow (title, String::empty, cancelButtonText,
  64102. String::empty, String::empty,
  64103. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  64104. if (hasProgressBar)
  64105. alertWindow->addProgressBarComponent (progress);
  64106. }
  64107. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  64108. {
  64109. stopThread (timeOutMsWhenCancelling);
  64110. }
  64111. bool ThreadWithProgressWindow::runThread (const int priority)
  64112. {
  64113. startThread (priority);
  64114. startTimer (100);
  64115. {
  64116. const ScopedLock sl (messageLock);
  64117. alertWindow->setMessage (message);
  64118. }
  64119. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  64120. stopThread (timeOutMsWhenCancelling);
  64121. alertWindow->setVisible (false);
  64122. return finishedNaturally;
  64123. }
  64124. void ThreadWithProgressWindow::setProgress (const double newProgress)
  64125. {
  64126. progress = newProgress;
  64127. }
  64128. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  64129. {
  64130. const ScopedLock sl (messageLock);
  64131. message = newStatusMessage;
  64132. }
  64133. void ThreadWithProgressWindow::timerCallback()
  64134. {
  64135. if (! isThreadRunning())
  64136. {
  64137. // thread has finished normally..
  64138. alertWindow->exitModalState (1);
  64139. alertWindow->setVisible (false);
  64140. }
  64141. else
  64142. {
  64143. const ScopedLock sl (messageLock);
  64144. alertWindow->setMessage (message);
  64145. }
  64146. }
  64147. END_JUCE_NAMESPACE
  64148. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  64149. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  64150. BEGIN_JUCE_NAMESPACE
  64151. TooltipWindow::TooltipWindow (Component* const parentComponent,
  64152. const int millisecondsBeforeTipAppears_)
  64153. : Component ("tooltip"),
  64154. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  64155. mouseClicks (0),
  64156. lastHideTime (0),
  64157. lastComponentUnderMouse (0),
  64158. changedCompsSinceShown (true)
  64159. {
  64160. if (Desktop::getInstance().getMainMouseSource().canHover())
  64161. startTimer (123);
  64162. setAlwaysOnTop (true);
  64163. setOpaque (true);
  64164. if (parentComponent != 0)
  64165. parentComponent->addChildComponent (this);
  64166. }
  64167. TooltipWindow::~TooltipWindow()
  64168. {
  64169. hide();
  64170. }
  64171. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  64172. {
  64173. millisecondsBeforeTipAppears = newTimeMs;
  64174. }
  64175. void TooltipWindow::paint (Graphics& g)
  64176. {
  64177. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  64178. }
  64179. void TooltipWindow::mouseEnter (const MouseEvent&)
  64180. {
  64181. hide();
  64182. }
  64183. void TooltipWindow::showFor (const String& tip)
  64184. {
  64185. jassert (tip.isNotEmpty());
  64186. if (tipShowing != tip)
  64187. repaint();
  64188. tipShowing = tip;
  64189. Point<int> mousePos (Desktop::getMousePosition());
  64190. if (getParentComponent() != 0)
  64191. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  64192. int x, y, w, h;
  64193. getLookAndFeel().getTooltipSize (tip, w, h);
  64194. if (mousePos.getX() > getParentWidth() / 2)
  64195. x = mousePos.getX() - (w + 12);
  64196. else
  64197. x = mousePos.getX() + 24;
  64198. if (mousePos.getY() > getParentHeight() / 2)
  64199. y = mousePos.getY() - (h + 6);
  64200. else
  64201. y = mousePos.getY() + 6;
  64202. setBounds (x, y, w, h);
  64203. setVisible (true);
  64204. if (getParentComponent() == 0)
  64205. {
  64206. addToDesktop (ComponentPeer::windowHasDropShadow
  64207. | ComponentPeer::windowIsTemporary
  64208. | ComponentPeer::windowIgnoresKeyPresses);
  64209. }
  64210. toFront (false);
  64211. }
  64212. const String TooltipWindow::getTipFor (Component* const c)
  64213. {
  64214. if (c != 0
  64215. && Process::isForegroundProcess()
  64216. && ! Component::isMouseButtonDownAnywhere())
  64217. {
  64218. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  64219. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  64220. return ttc->getTooltip();
  64221. }
  64222. return String::empty;
  64223. }
  64224. void TooltipWindow::hide()
  64225. {
  64226. tipShowing = String::empty;
  64227. removeFromDesktop();
  64228. setVisible (false);
  64229. }
  64230. void TooltipWindow::timerCallback()
  64231. {
  64232. const unsigned int now = Time::getApproximateMillisecondCounter();
  64233. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  64234. const String newTip (getTipFor (newComp));
  64235. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  64236. lastComponentUnderMouse = newComp;
  64237. lastTipUnderMouse = newTip;
  64238. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  64239. const bool mouseWasClicked = clickCount > mouseClicks;
  64240. mouseClicks = clickCount;
  64241. const Point<int> mousePos (Desktop::getMousePosition());
  64242. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  64243. lastMousePos = mousePos;
  64244. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  64245. lastCompChangeTime = now;
  64246. if (isVisible() || now < lastHideTime + 500)
  64247. {
  64248. // if a tip is currently visible (or has just disappeared), update to a new one
  64249. // immediately if needed..
  64250. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  64251. {
  64252. if (isVisible())
  64253. {
  64254. lastHideTime = now;
  64255. hide();
  64256. }
  64257. }
  64258. else if (tipChanged)
  64259. {
  64260. showFor (newTip);
  64261. }
  64262. }
  64263. else
  64264. {
  64265. // if there isn't currently a tip, but one is needed, only let it
  64266. // appear after a timeout..
  64267. if (newTip.isNotEmpty()
  64268. && newTip != tipShowing
  64269. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  64270. {
  64271. showFor (newTip);
  64272. }
  64273. }
  64274. }
  64275. END_JUCE_NAMESPACE
  64276. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  64277. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  64278. BEGIN_JUCE_NAMESPACE
  64279. /** Keeps track of the active top level window.
  64280. */
  64281. class TopLevelWindowManager : public Timer,
  64282. public DeletedAtShutdown
  64283. {
  64284. public:
  64285. TopLevelWindowManager()
  64286. : currentActive (0)
  64287. {
  64288. }
  64289. ~TopLevelWindowManager()
  64290. {
  64291. clearSingletonInstance();
  64292. }
  64293. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64294. void timerCallback()
  64295. {
  64296. startTimer (jmin (1731, getTimerInterval() * 2));
  64297. TopLevelWindow* active = 0;
  64298. if (Process::isForegroundProcess())
  64299. {
  64300. active = currentActive;
  64301. Component* const c = Component::getCurrentlyFocusedComponent();
  64302. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64303. if (tlw == 0 && c != 0)
  64304. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64305. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64306. if (tlw != 0)
  64307. active = tlw;
  64308. }
  64309. if (active != currentActive)
  64310. {
  64311. currentActive = active;
  64312. for (int i = windows.size(); --i >= 0;)
  64313. {
  64314. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64315. tlw->setWindowActive (isWindowActive (tlw));
  64316. i = jmin (i, windows.size() - 1);
  64317. }
  64318. Desktop::getInstance().triggerFocusCallback();
  64319. }
  64320. }
  64321. bool addWindow (TopLevelWindow* const w)
  64322. {
  64323. windows.add (w);
  64324. startTimer (10);
  64325. return isWindowActive (w);
  64326. }
  64327. void removeWindow (TopLevelWindow* const w)
  64328. {
  64329. startTimer (10);
  64330. if (currentActive == w)
  64331. currentActive = 0;
  64332. windows.removeValue (w);
  64333. if (windows.size() == 0)
  64334. deleteInstance();
  64335. }
  64336. Array <TopLevelWindow*> windows;
  64337. private:
  64338. TopLevelWindow* currentActive;
  64339. bool isWindowActive (TopLevelWindow* const tlw) const
  64340. {
  64341. return (tlw == currentActive
  64342. || tlw->isParentOf (currentActive)
  64343. || tlw->hasKeyboardFocus (true))
  64344. && tlw->isShowing();
  64345. }
  64346. TopLevelWindowManager (const TopLevelWindowManager&);
  64347. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64348. };
  64349. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64350. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64351. {
  64352. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64353. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64354. }
  64355. TopLevelWindow::TopLevelWindow (const String& name,
  64356. const bool addToDesktop_)
  64357. : Component (name),
  64358. useDropShadow (true),
  64359. useNativeTitleBar (false),
  64360. windowIsActive_ (false)
  64361. {
  64362. setOpaque (true);
  64363. if (addToDesktop_)
  64364. Component::addToDesktop (getDesktopWindowStyleFlags());
  64365. else
  64366. setDropShadowEnabled (true);
  64367. setWantsKeyboardFocus (true);
  64368. setBroughtToFrontOnMouseClick (true);
  64369. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64370. }
  64371. TopLevelWindow::~TopLevelWindow()
  64372. {
  64373. shadower = 0;
  64374. TopLevelWindowManager::getInstance()->removeWindow (this);
  64375. }
  64376. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64377. {
  64378. if (hasKeyboardFocus (true))
  64379. TopLevelWindowManager::getInstance()->timerCallback();
  64380. else
  64381. TopLevelWindowManager::getInstance()->startTimer (10);
  64382. }
  64383. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64384. {
  64385. if (windowIsActive_ != isNowActive)
  64386. {
  64387. windowIsActive_ = isNowActive;
  64388. activeWindowStatusChanged();
  64389. }
  64390. }
  64391. void TopLevelWindow::activeWindowStatusChanged()
  64392. {
  64393. }
  64394. void TopLevelWindow::parentHierarchyChanged()
  64395. {
  64396. setDropShadowEnabled (useDropShadow);
  64397. }
  64398. void TopLevelWindow::visibilityChanged()
  64399. {
  64400. if (isShowing())
  64401. toFront (true);
  64402. }
  64403. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64404. {
  64405. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64406. if (useDropShadow)
  64407. styleFlags |= ComponentPeer::windowHasDropShadow;
  64408. if (useNativeTitleBar)
  64409. styleFlags |= ComponentPeer::windowHasTitleBar;
  64410. return styleFlags;
  64411. }
  64412. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64413. {
  64414. useDropShadow = useShadow;
  64415. if (isOnDesktop())
  64416. {
  64417. shadower = 0;
  64418. Component::addToDesktop (getDesktopWindowStyleFlags());
  64419. }
  64420. else
  64421. {
  64422. if (useShadow && isOpaque())
  64423. {
  64424. if (shadower == 0)
  64425. {
  64426. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64427. if (shadower != 0)
  64428. shadower->setOwner (this);
  64429. }
  64430. }
  64431. else
  64432. {
  64433. shadower = 0;
  64434. }
  64435. }
  64436. }
  64437. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64438. {
  64439. if (useNativeTitleBar != useNativeTitleBar_)
  64440. {
  64441. useNativeTitleBar = useNativeTitleBar_;
  64442. recreateDesktopWindow();
  64443. sendLookAndFeelChange();
  64444. }
  64445. }
  64446. void TopLevelWindow::recreateDesktopWindow()
  64447. {
  64448. if (isOnDesktop())
  64449. {
  64450. Component::addToDesktop (getDesktopWindowStyleFlags());
  64451. toFront (true);
  64452. }
  64453. }
  64454. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64455. {
  64456. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64457. because this class needs to make sure its layout corresponds with settings like whether
  64458. it's got a native title bar or not.
  64459. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64460. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64461. method, then add or remove whatever flags are necessary from this value before returning it.
  64462. */
  64463. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64464. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64465. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64466. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64467. sendLookAndFeelChange();
  64468. }
  64469. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64470. {
  64471. if (c == 0)
  64472. c = TopLevelWindow::getActiveTopLevelWindow();
  64473. if (c == 0)
  64474. {
  64475. centreWithSize (width, height);
  64476. }
  64477. else
  64478. {
  64479. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64480. (c->getHeight() - height) / 2)));
  64481. Rectangle<int> parentArea (c->getParentMonitorArea());
  64482. if (getParentComponent() != 0)
  64483. {
  64484. p = getParentComponent()->globalPositionToRelative (p);
  64485. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64486. }
  64487. parentArea.reduce (12, 12);
  64488. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64489. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64490. width, height);
  64491. }
  64492. }
  64493. int TopLevelWindow::getNumTopLevelWindows() throw()
  64494. {
  64495. return TopLevelWindowManager::getInstance()->windows.size();
  64496. }
  64497. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64498. {
  64499. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64500. }
  64501. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64502. {
  64503. TopLevelWindow* best = 0;
  64504. int bestNumTWLParents = -1;
  64505. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64506. {
  64507. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64508. if (tlw->isActiveWindow())
  64509. {
  64510. int numTWLParents = 0;
  64511. const Component* c = tlw->getParentComponent();
  64512. while (c != 0)
  64513. {
  64514. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64515. ++numTWLParents;
  64516. c = c->getParentComponent();
  64517. }
  64518. if (bestNumTWLParents < numTWLParents)
  64519. {
  64520. best = tlw;
  64521. bestNumTWLParents = numTWLParents;
  64522. }
  64523. }
  64524. }
  64525. return best;
  64526. }
  64527. END_JUCE_NAMESPACE
  64528. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64529. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64530. BEGIN_JUCE_NAMESPACE
  64531. namespace RelativeCoordinateHelpers
  64532. {
  64533. static void skipComma (const juce_wchar* const s, int& i)
  64534. {
  64535. while (CharacterFunctions::isWhitespace (s[i]))
  64536. ++i;
  64537. if (s[i] == ',')
  64538. ++i;
  64539. }
  64540. }
  64541. const String RelativeCoordinate::Strings::parent ("parent");
  64542. const String RelativeCoordinate::Strings::left ("left");
  64543. const String RelativeCoordinate::Strings::right ("right");
  64544. const String RelativeCoordinate::Strings::top ("top");
  64545. const String RelativeCoordinate::Strings::bottom ("bottom");
  64546. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64547. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64548. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64549. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64550. RelativeCoordinate::RelativeCoordinate()
  64551. {
  64552. }
  64553. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64554. : term (term_)
  64555. {
  64556. }
  64557. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64558. : term (other.term)
  64559. {
  64560. }
  64561. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64562. {
  64563. term = other.term;
  64564. return *this;
  64565. }
  64566. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64567. : term (absoluteDistanceFromOrigin)
  64568. {
  64569. }
  64570. RelativeCoordinate::RelativeCoordinate (const String& s)
  64571. {
  64572. try
  64573. {
  64574. term = Expression (s);
  64575. }
  64576. catch (...)
  64577. {}
  64578. }
  64579. RelativeCoordinate::~RelativeCoordinate()
  64580. {
  64581. }
  64582. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64583. {
  64584. return term.toString() == other.term.toString();
  64585. }
  64586. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64587. {
  64588. return ! operator== (other);
  64589. }
  64590. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64591. {
  64592. try
  64593. {
  64594. if (context != 0)
  64595. return term.evaluate (*context);
  64596. else
  64597. return term.evaluate();
  64598. }
  64599. catch (...)
  64600. {}
  64601. return 0.0;
  64602. }
  64603. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64604. {
  64605. try
  64606. {
  64607. if (context != 0)
  64608. term.evaluate (*context);
  64609. else
  64610. term.evaluate();
  64611. }
  64612. catch (...)
  64613. {
  64614. return true;
  64615. }
  64616. return false;
  64617. }
  64618. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64619. {
  64620. try
  64621. {
  64622. if (context != 0)
  64623. {
  64624. term = term.adjustedToGiveNewResult (newPos, *context);
  64625. }
  64626. else
  64627. {
  64628. Expression::EvaluationContext defaultContext;
  64629. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64630. }
  64631. }
  64632. catch (...)
  64633. {}
  64634. }
  64635. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64636. {
  64637. try
  64638. {
  64639. if (context != 0)
  64640. return term.referencesSymbol (coordName, *context);
  64641. Expression::EvaluationContext defaultContext;
  64642. return term.referencesSymbol (coordName, defaultContext);
  64643. }
  64644. catch (...)
  64645. {}
  64646. return false;
  64647. }
  64648. bool RelativeCoordinate::isDynamic() const
  64649. {
  64650. return term.usesAnySymbols();
  64651. }
  64652. const String RelativeCoordinate::toString() const
  64653. {
  64654. return term.toString();
  64655. }
  64656. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName,
  64657. const Expression::EvaluationContext* context)
  64658. {
  64659. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64660. if (term.referencesSymbol (oldName, *context))
  64661. {
  64662. const double oldValue = resolve (context);
  64663. term = term.withRenamedSymbol (oldName, newName);
  64664. moveToAbsolute (oldValue, context);
  64665. }
  64666. }
  64667. RelativePoint::RelativePoint()
  64668. {
  64669. }
  64670. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64671. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64672. {
  64673. }
  64674. RelativePoint::RelativePoint (const float x_, const float y_)
  64675. : x (x_), y (y_)
  64676. {
  64677. }
  64678. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64679. : x (x_), y (y_)
  64680. {
  64681. }
  64682. RelativePoint::RelativePoint (const String& s)
  64683. {
  64684. int i = 0;
  64685. x = RelativeCoordinate (Expression::parse (s, i));
  64686. RelativeCoordinateHelpers::skipComma (s, i);
  64687. y = RelativeCoordinate (Expression::parse (s, i));
  64688. }
  64689. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64690. {
  64691. return x == other.x && y == other.y;
  64692. }
  64693. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64694. {
  64695. return ! operator== (other);
  64696. }
  64697. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64698. {
  64699. return Point<float> ((float) x.resolve (context),
  64700. (float) y.resolve (context));
  64701. }
  64702. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64703. {
  64704. x.moveToAbsolute (newPos.getX(), context);
  64705. y.moveToAbsolute (newPos.getY(), context);
  64706. }
  64707. const String RelativePoint::toString() const
  64708. {
  64709. return x.toString() + ", " + y.toString();
  64710. }
  64711. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName, const Expression::EvaluationContext* context)
  64712. {
  64713. x.renameSymbolIfUsed (oldName, newName, context);
  64714. y.renameSymbolIfUsed (oldName, newName, context);
  64715. }
  64716. bool RelativePoint::isDynamic() const
  64717. {
  64718. return x.isDynamic() || y.isDynamic();
  64719. }
  64720. RelativeRectangle::RelativeRectangle()
  64721. {
  64722. }
  64723. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64724. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64725. : left (left_), right (right_), top (top_), bottom (bottom_)
  64726. {
  64727. }
  64728. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64729. : left (rect.getX()),
  64730. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64731. top (rect.getY()),
  64732. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64733. {
  64734. }
  64735. RelativeRectangle::RelativeRectangle (const String& s)
  64736. {
  64737. int i = 0;
  64738. left = RelativeCoordinate (Expression::parse (s, i));
  64739. RelativeCoordinateHelpers::skipComma (s, i);
  64740. top = RelativeCoordinate (Expression::parse (s, i));
  64741. RelativeCoordinateHelpers::skipComma (s, i);
  64742. right = RelativeCoordinate (Expression::parse (s, i));
  64743. RelativeCoordinateHelpers::skipComma (s, i);
  64744. bottom = RelativeCoordinate (Expression::parse (s, i));
  64745. }
  64746. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64747. {
  64748. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64749. }
  64750. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64751. {
  64752. return ! operator== (other);
  64753. }
  64754. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64755. {
  64756. const double l = left.resolve (context);
  64757. const double r = right.resolve (context);
  64758. const double t = top.resolve (context);
  64759. const double b = bottom.resolve (context);
  64760. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64761. }
  64762. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64763. {
  64764. left.moveToAbsolute (newPos.getX(), context);
  64765. right.moveToAbsolute (newPos.getRight(), context);
  64766. top.moveToAbsolute (newPos.getY(), context);
  64767. bottom.moveToAbsolute (newPos.getBottom(), context);
  64768. }
  64769. const String RelativeRectangle::toString() const
  64770. {
  64771. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64772. }
  64773. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName,
  64774. const Expression::EvaluationContext* context)
  64775. {
  64776. left.renameSymbolIfUsed (oldName, newName, context);
  64777. right.renameSymbolIfUsed (oldName, newName, context);
  64778. top.renameSymbolIfUsed (oldName, newName, context);
  64779. bottom.renameSymbolIfUsed (oldName, newName, context);
  64780. }
  64781. RelativePointPath::RelativePointPath()
  64782. : usesNonZeroWinding (true),
  64783. containsDynamicPoints (false)
  64784. {
  64785. }
  64786. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64787. : usesNonZeroWinding (true),
  64788. containsDynamicPoints (false)
  64789. {
  64790. ValueTree state (DrawablePath::valueTreeType);
  64791. other.writeTo (state, 0);
  64792. parse (state);
  64793. }
  64794. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64795. : usesNonZeroWinding (true),
  64796. containsDynamicPoints (false)
  64797. {
  64798. parse (drawable);
  64799. }
  64800. RelativePointPath::RelativePointPath (const Path& path)
  64801. {
  64802. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64803. Path::Iterator i (path);
  64804. while (i.next())
  64805. {
  64806. switch (i.elementType)
  64807. {
  64808. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64809. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64810. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64811. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64812. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64813. default: jassertfalse; break;
  64814. }
  64815. }
  64816. }
  64817. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64818. {
  64819. DrawablePath::ValueTreeWrapper wrapper (state);
  64820. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64821. ValueTree pathTree (wrapper.getPathState());
  64822. pathTree.removeAllChildren (undoManager);
  64823. for (int i = 0; i < elements.size(); ++i)
  64824. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64825. }
  64826. void RelativePointPath::parse (const ValueTree& state)
  64827. {
  64828. DrawablePath::ValueTreeWrapper wrapper (state);
  64829. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64830. RelativePoint points[3];
  64831. const ValueTree pathTree (wrapper.getPathState());
  64832. const int num = pathTree.getNumChildren();
  64833. for (int i = 0; i < num; ++i)
  64834. {
  64835. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64836. const int numCps = e.getNumControlPoints();
  64837. for (int j = 0; j < numCps; ++j)
  64838. {
  64839. points[j] = e.getControlPoint (j);
  64840. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64841. }
  64842. const Identifier type (e.getType());
  64843. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64844. elements.add (new StartSubPath (points[0]));
  64845. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64846. elements.add (new CloseSubPath());
  64847. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64848. elements.add (new LineTo (points[0]));
  64849. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64850. elements.add (new QuadraticTo (points[0], points[1]));
  64851. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64852. elements.add (new CubicTo (points[0], points[1], points[2]));
  64853. else
  64854. jassertfalse;
  64855. }
  64856. }
  64857. RelativePointPath::~RelativePointPath()
  64858. {
  64859. }
  64860. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64861. {
  64862. elements.swapWithArray (other.elements);
  64863. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64864. }
  64865. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64866. {
  64867. for (int i = 0; i < elements.size(); ++i)
  64868. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64869. }
  64870. bool RelativePointPath::containsAnyDynamicPoints() const
  64871. {
  64872. return containsDynamicPoints;
  64873. }
  64874. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64875. {
  64876. }
  64877. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64878. : ElementBase (startSubPathElement), startPos (pos)
  64879. {
  64880. }
  64881. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64882. {
  64883. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64884. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64885. return v;
  64886. }
  64887. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64888. {
  64889. path.startNewSubPath (startPos.resolve (coordFinder));
  64890. }
  64891. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64892. {
  64893. numPoints = 1;
  64894. return &startPos;
  64895. }
  64896. RelativePointPath::CloseSubPath::CloseSubPath()
  64897. : ElementBase (closeSubPathElement)
  64898. {
  64899. }
  64900. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64901. {
  64902. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64903. }
  64904. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64905. {
  64906. path.closeSubPath();
  64907. }
  64908. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64909. {
  64910. numPoints = 0;
  64911. return 0;
  64912. }
  64913. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64914. : ElementBase (lineToElement), endPoint (endPoint_)
  64915. {
  64916. }
  64917. const ValueTree RelativePointPath::LineTo::createTree() const
  64918. {
  64919. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64920. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64921. return v;
  64922. }
  64923. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64924. {
  64925. path.lineTo (endPoint.resolve (coordFinder));
  64926. }
  64927. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64928. {
  64929. numPoints = 1;
  64930. return &endPoint;
  64931. }
  64932. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64933. : ElementBase (quadraticToElement)
  64934. {
  64935. controlPoints[0] = controlPoint;
  64936. controlPoints[1] = endPoint;
  64937. }
  64938. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64939. {
  64940. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64941. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64942. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64943. return v;
  64944. }
  64945. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64946. {
  64947. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64948. controlPoints[1].resolve (coordFinder));
  64949. }
  64950. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64951. {
  64952. numPoints = 2;
  64953. return controlPoints;
  64954. }
  64955. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64956. : ElementBase (cubicToElement)
  64957. {
  64958. controlPoints[0] = controlPoint1;
  64959. controlPoints[1] = controlPoint2;
  64960. controlPoints[2] = endPoint;
  64961. }
  64962. const ValueTree RelativePointPath::CubicTo::createTree() const
  64963. {
  64964. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64965. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64966. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64967. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64968. return v;
  64969. }
  64970. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64971. {
  64972. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64973. controlPoints[1].resolve (coordFinder),
  64974. controlPoints[2].resolve (coordFinder));
  64975. }
  64976. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64977. {
  64978. numPoints = 3;
  64979. return controlPoints;
  64980. }
  64981. RelativeParallelogram::RelativeParallelogram()
  64982. {
  64983. }
  64984. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64985. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64986. {
  64987. }
  64988. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64989. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64990. {
  64991. }
  64992. RelativeParallelogram::~RelativeParallelogram()
  64993. {
  64994. }
  64995. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64996. {
  64997. points[0] = topLeft.resolve (coordFinder);
  64998. points[1] = topRight.resolve (coordFinder);
  64999. points[2] = bottomLeft.resolve (coordFinder);
  65000. }
  65001. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  65002. {
  65003. resolveThreePoints (points, coordFinder);
  65004. points[3] = points[1] + (points[2] - points[0]);
  65005. }
  65006. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  65007. {
  65008. Point<float> points[4];
  65009. resolveFourCorners (points, coordFinder);
  65010. return Rectangle<float>::findAreaContainingPoints (points, 4);
  65011. }
  65012. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  65013. {
  65014. Point<float> points[4];
  65015. resolveFourCorners (points, coordFinder);
  65016. path.startNewSubPath (points[0]);
  65017. path.lineTo (points[1]);
  65018. path.lineTo (points[3]);
  65019. path.lineTo (points[2]);
  65020. path.closeSubPath();
  65021. }
  65022. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  65023. {
  65024. Point<float> corners[3];
  65025. resolveThreePoints (corners, coordFinder);
  65026. const Line<float> top (corners[0], corners[1]);
  65027. const Line<float> left (corners[0], corners[2]);
  65028. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  65029. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  65030. topRight.moveToAbsolute (newTopRight, coordFinder);
  65031. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  65032. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  65033. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  65034. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  65035. }
  65036. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  65037. {
  65038. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  65039. }
  65040. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  65041. {
  65042. return ! operator== (other);
  65043. }
  65044. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  65045. {
  65046. const Point<float> tr (corners[1] - corners[0]);
  65047. const Point<float> bl (corners[2] - corners[0]);
  65048. target -= corners[0];
  65049. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  65050. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  65051. }
  65052. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  65053. {
  65054. return corners[0]
  65055. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  65056. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  65057. }
  65058. END_JUCE_NAMESPACE
  65059. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  65060. #endif
  65061. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  65062. /*** Start of inlined file: juce_Colour.cpp ***/
  65063. BEGIN_JUCE_NAMESPACE
  65064. namespace ColourHelpers
  65065. {
  65066. static uint8 floatAlphaToInt (const float alpha) throw()
  65067. {
  65068. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  65069. }
  65070. static void convertHSBtoRGB (float h, float s, float v,
  65071. uint8& r, uint8& g, uint8& b) throw()
  65072. {
  65073. v = jlimit (0.0f, 1.0f, v);
  65074. v *= 255.0f;
  65075. const uint8 intV = (uint8) roundToInt (v);
  65076. if (s <= 0)
  65077. {
  65078. r = intV;
  65079. g = intV;
  65080. b = intV;
  65081. }
  65082. else
  65083. {
  65084. s = jmin (1.0f, s);
  65085. h = jlimit (0.0f, 1.0f, h);
  65086. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  65087. const float f = h - std::floor (h);
  65088. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  65089. const float y = v * (1.0f - s * f);
  65090. const float z = v * (1.0f - (s * (1.0f - f)));
  65091. if (h < 1.0f)
  65092. {
  65093. r = intV;
  65094. g = (uint8) roundToInt (z);
  65095. b = x;
  65096. }
  65097. else if (h < 2.0f)
  65098. {
  65099. r = (uint8) roundToInt (y);
  65100. g = intV;
  65101. b = x;
  65102. }
  65103. else if (h < 3.0f)
  65104. {
  65105. r = x;
  65106. g = intV;
  65107. b = (uint8) roundToInt (z);
  65108. }
  65109. else if (h < 4.0f)
  65110. {
  65111. r = x;
  65112. g = (uint8) roundToInt (y);
  65113. b = intV;
  65114. }
  65115. else if (h < 5.0f)
  65116. {
  65117. r = (uint8) roundToInt (z);
  65118. g = x;
  65119. b = intV;
  65120. }
  65121. else if (h < 6.0f)
  65122. {
  65123. r = intV;
  65124. g = x;
  65125. b = (uint8) roundToInt (y);
  65126. }
  65127. else
  65128. {
  65129. r = 0;
  65130. g = 0;
  65131. b = 0;
  65132. }
  65133. }
  65134. }
  65135. }
  65136. Colour::Colour() throw()
  65137. : argb (0)
  65138. {
  65139. }
  65140. Colour::Colour (const Colour& other) throw()
  65141. : argb (other.argb)
  65142. {
  65143. }
  65144. Colour& Colour::operator= (const Colour& other) throw()
  65145. {
  65146. argb = other.argb;
  65147. return *this;
  65148. }
  65149. bool Colour::operator== (const Colour& other) const throw()
  65150. {
  65151. return argb.getARGB() == other.argb.getARGB();
  65152. }
  65153. bool Colour::operator!= (const Colour& other) const throw()
  65154. {
  65155. return argb.getARGB() != other.argb.getARGB();
  65156. }
  65157. Colour::Colour (const uint32 argb_) throw()
  65158. : argb (argb_)
  65159. {
  65160. }
  65161. Colour::Colour (const uint8 red,
  65162. const uint8 green,
  65163. const uint8 blue) throw()
  65164. {
  65165. argb.setARGB (0xff, red, green, blue);
  65166. }
  65167. const Colour Colour::fromRGB (const uint8 red,
  65168. const uint8 green,
  65169. const uint8 blue) throw()
  65170. {
  65171. return Colour (red, green, blue);
  65172. }
  65173. Colour::Colour (const uint8 red,
  65174. const uint8 green,
  65175. const uint8 blue,
  65176. const uint8 alpha) throw()
  65177. {
  65178. argb.setARGB (alpha, red, green, blue);
  65179. }
  65180. const Colour Colour::fromRGBA (const uint8 red,
  65181. const uint8 green,
  65182. const uint8 blue,
  65183. const uint8 alpha) throw()
  65184. {
  65185. return Colour (red, green, blue, alpha);
  65186. }
  65187. Colour::Colour (const uint8 red,
  65188. const uint8 green,
  65189. const uint8 blue,
  65190. const float alpha) throw()
  65191. {
  65192. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  65193. }
  65194. const Colour Colour::fromRGBAFloat (const uint8 red,
  65195. const uint8 green,
  65196. const uint8 blue,
  65197. const float alpha) throw()
  65198. {
  65199. return Colour (red, green, blue, alpha);
  65200. }
  65201. Colour::Colour (const float hue,
  65202. const float saturation,
  65203. const float brightness,
  65204. const float alpha) throw()
  65205. {
  65206. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65207. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65208. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65209. }
  65210. const Colour Colour::fromHSV (const float hue,
  65211. const float saturation,
  65212. const float brightness,
  65213. const float alpha) throw()
  65214. {
  65215. return Colour (hue, saturation, brightness, alpha);
  65216. }
  65217. Colour::Colour (const float hue,
  65218. const float saturation,
  65219. const float brightness,
  65220. const uint8 alpha) throw()
  65221. {
  65222. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65223. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65224. argb.setARGB (alpha, r, g, b);
  65225. }
  65226. Colour::~Colour() throw()
  65227. {
  65228. }
  65229. const PixelARGB Colour::getPixelARGB() const throw()
  65230. {
  65231. PixelARGB p (argb);
  65232. p.premultiply();
  65233. return p;
  65234. }
  65235. uint32 Colour::getARGB() const throw()
  65236. {
  65237. return argb.getARGB();
  65238. }
  65239. bool Colour::isTransparent() const throw()
  65240. {
  65241. return getAlpha() == 0;
  65242. }
  65243. bool Colour::isOpaque() const throw()
  65244. {
  65245. return getAlpha() == 0xff;
  65246. }
  65247. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65248. {
  65249. PixelARGB newCol (argb);
  65250. newCol.setAlpha (newAlpha);
  65251. return Colour (newCol.getARGB());
  65252. }
  65253. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65254. {
  65255. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65256. PixelARGB newCol (argb);
  65257. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65258. return Colour (newCol.getARGB());
  65259. }
  65260. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65261. {
  65262. jassert (alphaMultiplier >= 0);
  65263. PixelARGB newCol (argb);
  65264. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65265. return Colour (newCol.getARGB());
  65266. }
  65267. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65268. {
  65269. const int destAlpha = getAlpha();
  65270. if (destAlpha > 0)
  65271. {
  65272. const int invA = 0xff - (int) src.getAlpha();
  65273. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65274. if (resA > 0)
  65275. {
  65276. const int da = (invA * destAlpha) / resA;
  65277. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65278. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65279. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65280. (uint8) resA);
  65281. }
  65282. return *this;
  65283. }
  65284. else
  65285. {
  65286. return src;
  65287. }
  65288. }
  65289. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65290. {
  65291. if (proportionOfOther <= 0)
  65292. return *this;
  65293. if (proportionOfOther >= 1.0f)
  65294. return other;
  65295. PixelARGB c1 (getPixelARGB());
  65296. const PixelARGB c2 (other.getPixelARGB());
  65297. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65298. c1.unpremultiply();
  65299. return Colour (c1.getARGB());
  65300. }
  65301. float Colour::getFloatRed() const throw()
  65302. {
  65303. return getRed() / 255.0f;
  65304. }
  65305. float Colour::getFloatGreen() const throw()
  65306. {
  65307. return getGreen() / 255.0f;
  65308. }
  65309. float Colour::getFloatBlue() const throw()
  65310. {
  65311. return getBlue() / 255.0f;
  65312. }
  65313. float Colour::getFloatAlpha() const throw()
  65314. {
  65315. return getAlpha() / 255.0f;
  65316. }
  65317. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65318. {
  65319. const int r = getRed();
  65320. const int g = getGreen();
  65321. const int b = getBlue();
  65322. const int hi = jmax (r, g, b);
  65323. const int lo = jmin (r, g, b);
  65324. if (hi != 0)
  65325. {
  65326. s = (hi - lo) / (float) hi;
  65327. if (s != 0)
  65328. {
  65329. const float invDiff = 1.0f / (hi - lo);
  65330. const float red = (hi - r) * invDiff;
  65331. const float green = (hi - g) * invDiff;
  65332. const float blue = (hi - b) * invDiff;
  65333. if (r == hi)
  65334. h = blue - green;
  65335. else if (g == hi)
  65336. h = 2.0f + red - blue;
  65337. else
  65338. h = 4.0f + green - red;
  65339. h *= 1.0f / 6.0f;
  65340. if (h < 0)
  65341. ++h;
  65342. }
  65343. else
  65344. {
  65345. h = 0;
  65346. }
  65347. }
  65348. else
  65349. {
  65350. s = 0;
  65351. h = 0;
  65352. }
  65353. v = hi / 255.0f;
  65354. }
  65355. float Colour::getHue() const throw()
  65356. {
  65357. float h, s, b;
  65358. getHSB (h, s, b);
  65359. return h;
  65360. }
  65361. const Colour Colour::withHue (const float hue) const throw()
  65362. {
  65363. float h, s, b;
  65364. getHSB (h, s, b);
  65365. return Colour (hue, s, b, getAlpha());
  65366. }
  65367. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65368. {
  65369. float h, s, b;
  65370. getHSB (h, s, b);
  65371. h += amountToRotate;
  65372. h -= std::floor (h);
  65373. return Colour (h, s, b, getAlpha());
  65374. }
  65375. float Colour::getSaturation() const throw()
  65376. {
  65377. float h, s, b;
  65378. getHSB (h, s, b);
  65379. return s;
  65380. }
  65381. const Colour Colour::withSaturation (const float saturation) const throw()
  65382. {
  65383. float h, s, b;
  65384. getHSB (h, s, b);
  65385. return Colour (h, saturation, b, getAlpha());
  65386. }
  65387. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65388. {
  65389. float h, s, b;
  65390. getHSB (h, s, b);
  65391. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65392. }
  65393. float Colour::getBrightness() const throw()
  65394. {
  65395. float h, s, b;
  65396. getHSB (h, s, b);
  65397. return b;
  65398. }
  65399. const Colour Colour::withBrightness (const float brightness) const throw()
  65400. {
  65401. float h, s, b;
  65402. getHSB (h, s, b);
  65403. return Colour (h, s, brightness, getAlpha());
  65404. }
  65405. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65406. {
  65407. float h, s, b;
  65408. getHSB (h, s, b);
  65409. b *= amount;
  65410. if (b > 1.0f)
  65411. b = 1.0f;
  65412. return Colour (h, s, b, getAlpha());
  65413. }
  65414. const Colour Colour::brighter (float amount) const throw()
  65415. {
  65416. amount = 1.0f / (1.0f + amount);
  65417. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65418. (uint8) (255 - (amount * (255 - getGreen()))),
  65419. (uint8) (255 - (amount * (255 - getBlue()))),
  65420. getAlpha());
  65421. }
  65422. const Colour Colour::darker (float amount) const throw()
  65423. {
  65424. amount = 1.0f / (1.0f + amount);
  65425. return Colour ((uint8) (amount * getRed()),
  65426. (uint8) (amount * getGreen()),
  65427. (uint8) (amount * getBlue()),
  65428. getAlpha());
  65429. }
  65430. const Colour Colour::greyLevel (const float brightness) throw()
  65431. {
  65432. const uint8 level
  65433. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65434. return Colour (level, level, level);
  65435. }
  65436. const Colour Colour::contrasting (const float amount) const throw()
  65437. {
  65438. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65439. ? Colours::black
  65440. : Colours::white).withAlpha (amount));
  65441. }
  65442. const Colour Colour::contrasting (const Colour& colour1,
  65443. const Colour& colour2) throw()
  65444. {
  65445. const float b1 = colour1.getBrightness();
  65446. const float b2 = colour2.getBrightness();
  65447. float best = 0.0f;
  65448. float bestDist = 0.0f;
  65449. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65450. {
  65451. const float d1 = std::abs (i - b1);
  65452. const float d2 = std::abs (i - b2);
  65453. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65454. if (dist > bestDist)
  65455. {
  65456. best = i;
  65457. bestDist = dist;
  65458. }
  65459. }
  65460. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65461. .withBrightness (best);
  65462. }
  65463. const String Colour::toString() const
  65464. {
  65465. return String::toHexString ((int) argb.getARGB());
  65466. }
  65467. const Colour Colour::fromString (const String& encodedColourString)
  65468. {
  65469. return Colour ((uint32) encodedColourString.getHexValue32());
  65470. }
  65471. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65472. {
  65473. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65474. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65475. .toUpperCase();
  65476. }
  65477. END_JUCE_NAMESPACE
  65478. /*** End of inlined file: juce_Colour.cpp ***/
  65479. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65480. BEGIN_JUCE_NAMESPACE
  65481. ColourGradient::ColourGradient() throw()
  65482. {
  65483. #if JUCE_DEBUG
  65484. point1.setX (987654.0f);
  65485. #endif
  65486. }
  65487. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65488. const Colour& colour2, const float x2_, const float y2_,
  65489. const bool isRadial_)
  65490. : point1 (x1_, y1_),
  65491. point2 (x2_, y2_),
  65492. isRadial (isRadial_)
  65493. {
  65494. colours.add (ColourPoint (0.0, colour1));
  65495. colours.add (ColourPoint (1.0, colour2));
  65496. }
  65497. ColourGradient::~ColourGradient()
  65498. {
  65499. }
  65500. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65501. {
  65502. return point1 == other.point1 && point2 == other.point2
  65503. && isRadial == other.isRadial
  65504. && colours == other.colours;
  65505. }
  65506. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65507. {
  65508. return ! operator== (other);
  65509. }
  65510. void ColourGradient::clearColours()
  65511. {
  65512. colours.clear();
  65513. }
  65514. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65515. {
  65516. // must be within the two end-points
  65517. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65518. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65519. int i;
  65520. for (i = 0; i < colours.size(); ++i)
  65521. if (colours.getReference(i).position > pos)
  65522. break;
  65523. colours.insert (i, ColourPoint (pos, colour));
  65524. return i;
  65525. }
  65526. void ColourGradient::removeColour (int index)
  65527. {
  65528. jassert (index > 0 && index < colours.size() - 1);
  65529. colours.remove (index);
  65530. }
  65531. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65532. {
  65533. for (int i = 0; i < colours.size(); ++i)
  65534. {
  65535. Colour& c = colours.getReference(i).colour;
  65536. c = c.withMultipliedAlpha (multiplier);
  65537. }
  65538. }
  65539. int ColourGradient::getNumColours() const throw()
  65540. {
  65541. return colours.size();
  65542. }
  65543. double ColourGradient::getColourPosition (const int index) const throw()
  65544. {
  65545. if (((unsigned int) index) < (unsigned int) colours.size())
  65546. return colours.getReference (index).position;
  65547. return 0;
  65548. }
  65549. const Colour ColourGradient::getColour (const int index) const throw()
  65550. {
  65551. if (((unsigned int) index) < (unsigned int) colours.size())
  65552. return colours.getReference (index).colour;
  65553. return Colour();
  65554. }
  65555. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65556. {
  65557. if (((unsigned int) index) < (unsigned int) colours.size())
  65558. colours.getReference (index).colour = newColour;
  65559. }
  65560. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65561. {
  65562. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65563. if (position <= 0 || colours.size() <= 1)
  65564. return colours.getReference(0).colour;
  65565. int i = colours.size() - 1;
  65566. while (position < colours.getReference(i).position)
  65567. --i;
  65568. const ColourPoint& p1 = colours.getReference (i);
  65569. if (i >= colours.size() - 1)
  65570. return p1.colour;
  65571. const ColourPoint& p2 = colours.getReference (i + 1);
  65572. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65573. }
  65574. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65575. {
  65576. #if JUCE_DEBUG
  65577. // trying to use the object without setting its co-ordinates? Have a careful read of
  65578. // the comments for the constructors.
  65579. jassert (point1.getX() != 987654.0f);
  65580. #endif
  65581. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65582. 3 * (int) point1.transformedBy (transform)
  65583. .getDistanceFrom (point2.transformedBy (transform)));
  65584. lookupTable.malloc (numEntries);
  65585. if (colours.size() >= 2)
  65586. {
  65587. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65588. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65589. int index = 0;
  65590. for (int j = 1; j < colours.size(); ++j)
  65591. {
  65592. const ColourPoint& p = colours.getReference (j);
  65593. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65594. const PixelARGB pix2 (p.colour.getPixelARGB());
  65595. for (int i = 0; i < numToDo; ++i)
  65596. {
  65597. jassert (index >= 0 && index < numEntries);
  65598. lookupTable[index] = pix1;
  65599. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65600. ++index;
  65601. }
  65602. pix1 = pix2;
  65603. }
  65604. while (index < numEntries)
  65605. lookupTable [index++] = pix1;
  65606. }
  65607. else
  65608. {
  65609. jassertfalse; // no colours specified!
  65610. }
  65611. return numEntries;
  65612. }
  65613. bool ColourGradient::isOpaque() const throw()
  65614. {
  65615. for (int i = 0; i < colours.size(); ++i)
  65616. if (! colours.getReference(i).colour.isOpaque())
  65617. return false;
  65618. return true;
  65619. }
  65620. bool ColourGradient::isInvisible() const throw()
  65621. {
  65622. for (int i = 0; i < colours.size(); ++i)
  65623. if (! colours.getReference(i).colour.isTransparent())
  65624. return false;
  65625. return true;
  65626. }
  65627. END_JUCE_NAMESPACE
  65628. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65629. /*** Start of inlined file: juce_Colours.cpp ***/
  65630. BEGIN_JUCE_NAMESPACE
  65631. const Colour Colours::transparentBlack (0);
  65632. const Colour Colours::transparentWhite (0x00ffffff);
  65633. const Colour Colours::aliceblue (0xfff0f8ff);
  65634. const Colour Colours::antiquewhite (0xfffaebd7);
  65635. const Colour Colours::aqua (0xff00ffff);
  65636. const Colour Colours::aquamarine (0xff7fffd4);
  65637. const Colour Colours::azure (0xfff0ffff);
  65638. const Colour Colours::beige (0xfff5f5dc);
  65639. const Colour Colours::bisque (0xffffe4c4);
  65640. const Colour Colours::black (0xff000000);
  65641. const Colour Colours::blanchedalmond (0xffffebcd);
  65642. const Colour Colours::blue (0xff0000ff);
  65643. const Colour Colours::blueviolet (0xff8a2be2);
  65644. const Colour Colours::brown (0xffa52a2a);
  65645. const Colour Colours::burlywood (0xffdeb887);
  65646. const Colour Colours::cadetblue (0xff5f9ea0);
  65647. const Colour Colours::chartreuse (0xff7fff00);
  65648. const Colour Colours::chocolate (0xffd2691e);
  65649. const Colour Colours::coral (0xffff7f50);
  65650. const Colour Colours::cornflowerblue (0xff6495ed);
  65651. const Colour Colours::cornsilk (0xfffff8dc);
  65652. const Colour Colours::crimson (0xffdc143c);
  65653. const Colour Colours::cyan (0xff00ffff);
  65654. const Colour Colours::darkblue (0xff00008b);
  65655. const Colour Colours::darkcyan (0xff008b8b);
  65656. const Colour Colours::darkgoldenrod (0xffb8860b);
  65657. const Colour Colours::darkgrey (0xff555555);
  65658. const Colour Colours::darkgreen (0xff006400);
  65659. const Colour Colours::darkkhaki (0xffbdb76b);
  65660. const Colour Colours::darkmagenta (0xff8b008b);
  65661. const Colour Colours::darkolivegreen (0xff556b2f);
  65662. const Colour Colours::darkorange (0xffff8c00);
  65663. const Colour Colours::darkorchid (0xff9932cc);
  65664. const Colour Colours::darkred (0xff8b0000);
  65665. const Colour Colours::darksalmon (0xffe9967a);
  65666. const Colour Colours::darkseagreen (0xff8fbc8f);
  65667. const Colour Colours::darkslateblue (0xff483d8b);
  65668. const Colour Colours::darkslategrey (0xff2f4f4f);
  65669. const Colour Colours::darkturquoise (0xff00ced1);
  65670. const Colour Colours::darkviolet (0xff9400d3);
  65671. const Colour Colours::deeppink (0xffff1493);
  65672. const Colour Colours::deepskyblue (0xff00bfff);
  65673. const Colour Colours::dimgrey (0xff696969);
  65674. const Colour Colours::dodgerblue (0xff1e90ff);
  65675. const Colour Colours::firebrick (0xffb22222);
  65676. const Colour Colours::floralwhite (0xfffffaf0);
  65677. const Colour Colours::forestgreen (0xff228b22);
  65678. const Colour Colours::fuchsia (0xffff00ff);
  65679. const Colour Colours::gainsboro (0xffdcdcdc);
  65680. const Colour Colours::gold (0xffffd700);
  65681. const Colour Colours::goldenrod (0xffdaa520);
  65682. const Colour Colours::grey (0xff808080);
  65683. const Colour Colours::green (0xff008000);
  65684. const Colour Colours::greenyellow (0xffadff2f);
  65685. const Colour Colours::honeydew (0xfff0fff0);
  65686. const Colour Colours::hotpink (0xffff69b4);
  65687. const Colour Colours::indianred (0xffcd5c5c);
  65688. const Colour Colours::indigo (0xff4b0082);
  65689. const Colour Colours::ivory (0xfffffff0);
  65690. const Colour Colours::khaki (0xfff0e68c);
  65691. const Colour Colours::lavender (0xffe6e6fa);
  65692. const Colour Colours::lavenderblush (0xfffff0f5);
  65693. const Colour Colours::lemonchiffon (0xfffffacd);
  65694. const Colour Colours::lightblue (0xffadd8e6);
  65695. const Colour Colours::lightcoral (0xfff08080);
  65696. const Colour Colours::lightcyan (0xffe0ffff);
  65697. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65698. const Colour Colours::lightgreen (0xff90ee90);
  65699. const Colour Colours::lightgrey (0xffd3d3d3);
  65700. const Colour Colours::lightpink (0xffffb6c1);
  65701. const Colour Colours::lightsalmon (0xffffa07a);
  65702. const Colour Colours::lightseagreen (0xff20b2aa);
  65703. const Colour Colours::lightskyblue (0xff87cefa);
  65704. const Colour Colours::lightslategrey (0xff778899);
  65705. const Colour Colours::lightsteelblue (0xffb0c4de);
  65706. const Colour Colours::lightyellow (0xffffffe0);
  65707. const Colour Colours::lime (0xff00ff00);
  65708. const Colour Colours::limegreen (0xff32cd32);
  65709. const Colour Colours::linen (0xfffaf0e6);
  65710. const Colour Colours::magenta (0xffff00ff);
  65711. const Colour Colours::maroon (0xff800000);
  65712. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65713. const Colour Colours::mediumblue (0xff0000cd);
  65714. const Colour Colours::mediumorchid (0xffba55d3);
  65715. const Colour Colours::mediumpurple (0xff9370db);
  65716. const Colour Colours::mediumseagreen (0xff3cb371);
  65717. const Colour Colours::mediumslateblue (0xff7b68ee);
  65718. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65719. const Colour Colours::mediumturquoise (0xff48d1cc);
  65720. const Colour Colours::mediumvioletred (0xffc71585);
  65721. const Colour Colours::midnightblue (0xff191970);
  65722. const Colour Colours::mintcream (0xfff5fffa);
  65723. const Colour Colours::mistyrose (0xffffe4e1);
  65724. const Colour Colours::navajowhite (0xffffdead);
  65725. const Colour Colours::navy (0xff000080);
  65726. const Colour Colours::oldlace (0xfffdf5e6);
  65727. const Colour Colours::olive (0xff808000);
  65728. const Colour Colours::olivedrab (0xff6b8e23);
  65729. const Colour Colours::orange (0xffffa500);
  65730. const Colour Colours::orangered (0xffff4500);
  65731. const Colour Colours::orchid (0xffda70d6);
  65732. const Colour Colours::palegoldenrod (0xffeee8aa);
  65733. const Colour Colours::palegreen (0xff98fb98);
  65734. const Colour Colours::paleturquoise (0xffafeeee);
  65735. const Colour Colours::palevioletred (0xffdb7093);
  65736. const Colour Colours::papayawhip (0xffffefd5);
  65737. const Colour Colours::peachpuff (0xffffdab9);
  65738. const Colour Colours::peru (0xffcd853f);
  65739. const Colour Colours::pink (0xffffc0cb);
  65740. const Colour Colours::plum (0xffdda0dd);
  65741. const Colour Colours::powderblue (0xffb0e0e6);
  65742. const Colour Colours::purple (0xff800080);
  65743. const Colour Colours::red (0xffff0000);
  65744. const Colour Colours::rosybrown (0xffbc8f8f);
  65745. const Colour Colours::royalblue (0xff4169e1);
  65746. const Colour Colours::saddlebrown (0xff8b4513);
  65747. const Colour Colours::salmon (0xfffa8072);
  65748. const Colour Colours::sandybrown (0xfff4a460);
  65749. const Colour Colours::seagreen (0xff2e8b57);
  65750. const Colour Colours::seashell (0xfffff5ee);
  65751. const Colour Colours::sienna (0xffa0522d);
  65752. const Colour Colours::silver (0xffc0c0c0);
  65753. const Colour Colours::skyblue (0xff87ceeb);
  65754. const Colour Colours::slateblue (0xff6a5acd);
  65755. const Colour Colours::slategrey (0xff708090);
  65756. const Colour Colours::snow (0xfffffafa);
  65757. const Colour Colours::springgreen (0xff00ff7f);
  65758. const Colour Colours::steelblue (0xff4682b4);
  65759. const Colour Colours::tan (0xffd2b48c);
  65760. const Colour Colours::teal (0xff008080);
  65761. const Colour Colours::thistle (0xffd8bfd8);
  65762. const Colour Colours::tomato (0xffff6347);
  65763. const Colour Colours::turquoise (0xff40e0d0);
  65764. const Colour Colours::violet (0xffee82ee);
  65765. const Colour Colours::wheat (0xfff5deb3);
  65766. const Colour Colours::white (0xffffffff);
  65767. const Colour Colours::whitesmoke (0xfff5f5f5);
  65768. const Colour Colours::yellow (0xffffff00);
  65769. const Colour Colours::yellowgreen (0xff9acd32);
  65770. const Colour Colours::findColourForName (const String& colourName,
  65771. const Colour& defaultColour)
  65772. {
  65773. static const int presets[] =
  65774. {
  65775. // (first value is the string's hashcode, second is ARGB)
  65776. 0x05978fff, 0xff000000, /* black */
  65777. 0x06bdcc29, 0xffffffff, /* white */
  65778. 0x002e305a, 0xff0000ff, /* blue */
  65779. 0x00308adf, 0xff808080, /* grey */
  65780. 0x05e0cf03, 0xff008000, /* green */
  65781. 0x0001b891, 0xffff0000, /* red */
  65782. 0xd43c6474, 0xffffff00, /* yellow */
  65783. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65784. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65785. 0x002dcebc, 0xff00ffff, /* aqua */
  65786. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65787. 0x0590228f, 0xfff0ffff, /* azure */
  65788. 0x05947fe4, 0xfff5f5dc, /* beige */
  65789. 0xad388e35, 0xffffe4c4, /* bisque */
  65790. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65791. 0x39129959, 0xff8a2be2, /* blueviolet */
  65792. 0x059a8136, 0xffa52a2a, /* brown */
  65793. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65794. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65795. 0x6b748956, 0xff7fff00, /* chartreuse */
  65796. 0x2903623c, 0xffd2691e, /* chocolate */
  65797. 0x05a74431, 0xffff7f50, /* coral */
  65798. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65799. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65800. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65801. 0x002ed323, 0xff00ffff, /* cyan */
  65802. 0x67cc74d0, 0xff00008b, /* darkblue */
  65803. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65804. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65805. 0x67cecf55, 0xff555555, /* darkgrey */
  65806. 0x920b194d, 0xff006400, /* darkgreen */
  65807. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65808. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65809. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65810. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65811. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65812. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65813. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65814. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65815. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65816. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65817. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65818. 0xc8769375, 0xff9400d3, /* darkviolet */
  65819. 0x25832862, 0xffff1493, /* deeppink */
  65820. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65821. 0x634c8b67, 0xff696969, /* dimgrey */
  65822. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65823. 0xef19e3cb, 0xffb22222, /* firebrick */
  65824. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65825. 0xd086fd06, 0xff228b22, /* forestgreen */
  65826. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65827. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65828. 0x00308060, 0xffffd700, /* gold */
  65829. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65830. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65831. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65832. 0x41892743, 0xffff69b4, /* hotpink */
  65833. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65834. 0xb969fed2, 0xff4b0082, /* indigo */
  65835. 0x05fef6a9, 0xfffffff0, /* ivory */
  65836. 0x06149302, 0xfff0e68c, /* khaki */
  65837. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65838. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65839. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65840. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65841. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65842. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65843. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65844. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65845. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65846. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65847. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65848. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65849. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65850. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65851. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65852. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65853. 0x0032afd5, 0xff00ff00, /* lime */
  65854. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65855. 0x06234efa, 0xfffaf0e6, /* linen */
  65856. 0x316858a9, 0xffff00ff, /* magenta */
  65857. 0xbf8ca470, 0xff800000, /* maroon */
  65858. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65859. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65860. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65861. 0x07556b71, 0xff9370db, /* mediumpurple */
  65862. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65863. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65864. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65865. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65866. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65867. 0x168eb32a, 0xff191970, /* midnightblue */
  65868. 0x4306b960, 0xfff5fffa, /* mintcream */
  65869. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65870. 0xe97218a6, 0xffffdead, /* navajowhite */
  65871. 0x00337bb6, 0xff000080, /* navy */
  65872. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65873. 0x064ee1db, 0xff808000, /* olive */
  65874. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65875. 0xc3de262e, 0xffffa500, /* orange */
  65876. 0x58bebba3, 0xffff4500, /* orangered */
  65877. 0xc3def8a3, 0xffda70d6, /* orchid */
  65878. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65879. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65880. 0x74022737, 0xffafeeee, /* paleturquoise */
  65881. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65882. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65883. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65884. 0x003472f8, 0xffcd853f, /* peru */
  65885. 0x00348176, 0xffffc0cb, /* pink */
  65886. 0x00348d94, 0xffdda0dd, /* plum */
  65887. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65888. 0xc5c507bc, 0xff800080, /* purple */
  65889. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65890. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65891. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65892. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65893. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65894. 0x34636c14, 0xff2e8b57, /* seagreen */
  65895. 0x3507fb41, 0xfffff5ee, /* seashell */
  65896. 0xca348772, 0xffa0522d, /* sienna */
  65897. 0xca37d30d, 0xffc0c0c0, /* silver */
  65898. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65899. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65900. 0x44ab37f8, 0xff708090, /* slategrey */
  65901. 0x0035f183, 0xfffffafa, /* snow */
  65902. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65903. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65904. 0x0001bfa1, 0xffd2b48c, /* tan */
  65905. 0x0036425c, 0xff008080, /* teal */
  65906. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65907. 0xcc41600a, 0xffff6347, /* tomato */
  65908. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65909. 0xcf57947f, 0xffee82ee, /* violet */
  65910. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65911. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65912. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65913. };
  65914. const int hash = colourName.trim().toLowerCase().hashCode();
  65915. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65916. if (presets [i] == hash)
  65917. return Colour (presets [i + 1]);
  65918. return defaultColour;
  65919. }
  65920. END_JUCE_NAMESPACE
  65921. /*** End of inlined file: juce_Colours.cpp ***/
  65922. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65923. BEGIN_JUCE_NAMESPACE
  65924. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65925. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65926. const Path& path, const AffineTransform& transform)
  65927. : bounds (bounds_),
  65928. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65929. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65930. needToCheckEmptinesss (true)
  65931. {
  65932. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65933. int* t = table;
  65934. for (int i = bounds.getHeight(); --i >= 0;)
  65935. {
  65936. *t = 0;
  65937. t += lineStrideElements;
  65938. }
  65939. const int topLimit = bounds.getY() << 8;
  65940. const int heightLimit = bounds.getHeight() << 8;
  65941. const int leftLimit = bounds.getX() << 8;
  65942. const int rightLimit = bounds.getRight() << 8;
  65943. PathFlatteningIterator iter (path, transform);
  65944. while (iter.next())
  65945. {
  65946. int y1 = roundToInt (iter.y1 * 256.0f);
  65947. int y2 = roundToInt (iter.y2 * 256.0f);
  65948. if (y1 != y2)
  65949. {
  65950. y1 -= topLimit;
  65951. y2 -= topLimit;
  65952. const int startY = y1;
  65953. int direction = -1;
  65954. if (y1 > y2)
  65955. {
  65956. swapVariables (y1, y2);
  65957. direction = 1;
  65958. }
  65959. if (y1 < 0)
  65960. y1 = 0;
  65961. if (y2 > heightLimit)
  65962. y2 = heightLimit;
  65963. if (y1 < y2)
  65964. {
  65965. const double startX = 256.0f * iter.x1;
  65966. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65967. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65968. do
  65969. {
  65970. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65971. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65972. if (x < leftLimit)
  65973. x = leftLimit;
  65974. else if (x >= rightLimit)
  65975. x = rightLimit - 1;
  65976. addEdgePoint (x, y1 >> 8, direction * step);
  65977. y1 += step;
  65978. }
  65979. while (y1 < y2);
  65980. }
  65981. }
  65982. }
  65983. sanitiseLevels (path.isUsingNonZeroWinding());
  65984. }
  65985. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65986. : bounds (rectangleToAdd),
  65987. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65988. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65989. needToCheckEmptinesss (true)
  65990. {
  65991. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65992. table[0] = 0;
  65993. const int x1 = rectangleToAdd.getX() << 8;
  65994. const int x2 = rectangleToAdd.getRight() << 8;
  65995. int* t = table;
  65996. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65997. {
  65998. t[0] = 2;
  65999. t[1] = x1;
  66000. t[2] = 255;
  66001. t[3] = x2;
  66002. t[4] = 0;
  66003. t += lineStrideElements;
  66004. }
  66005. }
  66006. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  66007. : bounds (rectanglesToAdd.getBounds()),
  66008. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66009. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66010. needToCheckEmptinesss (true)
  66011. {
  66012. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66013. int* t = table;
  66014. for (int i = bounds.getHeight(); --i >= 0;)
  66015. {
  66016. *t = 0;
  66017. t += lineStrideElements;
  66018. }
  66019. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  66020. {
  66021. const Rectangle<int>* const r = iter.getRectangle();
  66022. const int x1 = r->getX() << 8;
  66023. const int x2 = r->getRight() << 8;
  66024. int y = r->getY() - bounds.getY();
  66025. for (int j = r->getHeight(); --j >= 0;)
  66026. {
  66027. addEdgePoint (x1, y, 255);
  66028. addEdgePoint (x2, y, -255);
  66029. ++y;
  66030. }
  66031. }
  66032. sanitiseLevels (true);
  66033. }
  66034. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  66035. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  66036. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  66037. 2 + (int) rectangleToAdd.getWidth(),
  66038. 2 + (int) rectangleToAdd.getHeight())),
  66039. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66040. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66041. needToCheckEmptinesss (true)
  66042. {
  66043. jassert (! rectangleToAdd.isEmpty());
  66044. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66045. table[0] = 0;
  66046. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  66047. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  66048. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  66049. jassert (y1 < 256);
  66050. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  66051. if (x2 <= x1 || y2 <= y1)
  66052. {
  66053. bounds.setHeight (0);
  66054. return;
  66055. }
  66056. int lineY = 0;
  66057. int* t = table;
  66058. if ((y1 >> 8) == (y2 >> 8))
  66059. {
  66060. t[0] = 2;
  66061. t[1] = x1;
  66062. t[2] = y2 - y1;
  66063. t[3] = x2;
  66064. t[4] = 0;
  66065. ++lineY;
  66066. t += lineStrideElements;
  66067. }
  66068. else
  66069. {
  66070. t[0] = 2;
  66071. t[1] = x1;
  66072. t[2] = 255 - (y1 & 255);
  66073. t[3] = x2;
  66074. t[4] = 0;
  66075. ++lineY;
  66076. t += lineStrideElements;
  66077. while (lineY < (y2 >> 8))
  66078. {
  66079. t[0] = 2;
  66080. t[1] = x1;
  66081. t[2] = 255;
  66082. t[3] = x2;
  66083. t[4] = 0;
  66084. ++lineY;
  66085. t += lineStrideElements;
  66086. }
  66087. jassert (lineY < bounds.getHeight());
  66088. t[0] = 2;
  66089. t[1] = x1;
  66090. t[2] = y2 & 255;
  66091. t[3] = x2;
  66092. t[4] = 0;
  66093. ++lineY;
  66094. t += lineStrideElements;
  66095. }
  66096. while (lineY < bounds.getHeight())
  66097. {
  66098. t[0] = 0;
  66099. t += lineStrideElements;
  66100. ++lineY;
  66101. }
  66102. }
  66103. EdgeTable::EdgeTable (const EdgeTable& other)
  66104. {
  66105. operator= (other);
  66106. }
  66107. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  66108. {
  66109. bounds = other.bounds;
  66110. maxEdgesPerLine = other.maxEdgesPerLine;
  66111. lineStrideElements = other.lineStrideElements;
  66112. needToCheckEmptinesss = other.needToCheckEmptinesss;
  66113. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66114. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  66115. return *this;
  66116. }
  66117. EdgeTable::~EdgeTable()
  66118. {
  66119. }
  66120. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  66121. {
  66122. while (--numLines >= 0)
  66123. {
  66124. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  66125. src += srcLineStride;
  66126. dest += destLineStride;
  66127. }
  66128. }
  66129. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  66130. {
  66131. // Convert the table from relative windings to absolute levels..
  66132. int* lineStart = table;
  66133. for (int i = bounds.getHeight(); --i >= 0;)
  66134. {
  66135. int* line = lineStart;
  66136. lineStart += lineStrideElements;
  66137. int num = *line;
  66138. if (num == 0)
  66139. continue;
  66140. int level = 0;
  66141. if (useNonZeroWinding)
  66142. {
  66143. while (--num > 0)
  66144. {
  66145. line += 2;
  66146. level += *line;
  66147. int corrected = abs (level);
  66148. if (corrected >> 8)
  66149. corrected = 255;
  66150. *line = corrected;
  66151. }
  66152. }
  66153. else
  66154. {
  66155. while (--num > 0)
  66156. {
  66157. line += 2;
  66158. level += *line;
  66159. int corrected = abs (level);
  66160. if (corrected >> 8)
  66161. {
  66162. corrected &= 511;
  66163. if (corrected >> 8)
  66164. corrected = 511 - corrected;
  66165. }
  66166. *line = corrected;
  66167. }
  66168. }
  66169. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  66170. }
  66171. }
  66172. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  66173. {
  66174. if (newNumEdgesPerLine != maxEdgesPerLine)
  66175. {
  66176. maxEdgesPerLine = newNumEdgesPerLine;
  66177. jassert (bounds.getHeight() > 0);
  66178. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  66179. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  66180. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  66181. table.swapWith (newTable);
  66182. lineStrideElements = newLineStrideElements;
  66183. }
  66184. }
  66185. void EdgeTable::optimiseTable() throw()
  66186. {
  66187. int maxLineElements = 0;
  66188. for (int i = bounds.getHeight(); --i >= 0;)
  66189. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  66190. remapTableForNumEdges (maxLineElements);
  66191. }
  66192. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  66193. {
  66194. jassert (y >= 0 && y < bounds.getHeight());
  66195. int* line = table + lineStrideElements * y;
  66196. const int numPoints = line[0];
  66197. int n = numPoints << 1;
  66198. if (n > 0)
  66199. {
  66200. while (n > 0)
  66201. {
  66202. const int cx = line [n - 1];
  66203. if (cx <= x)
  66204. {
  66205. if (cx == x)
  66206. {
  66207. line [n] += winding;
  66208. return;
  66209. }
  66210. break;
  66211. }
  66212. n -= 2;
  66213. }
  66214. if (numPoints >= maxEdgesPerLine)
  66215. {
  66216. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66217. jassert (numPoints < maxEdgesPerLine);
  66218. line = table + lineStrideElements * y;
  66219. }
  66220. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66221. }
  66222. line [n + 1] = x;
  66223. line [n + 2] = winding;
  66224. line[0]++;
  66225. }
  66226. void EdgeTable::translate (float dx, const int dy) throw()
  66227. {
  66228. bounds.translate ((int) std::floor (dx), dy);
  66229. int* lineStart = table;
  66230. const int intDx = (int) (dx * 256.0f);
  66231. for (int i = bounds.getHeight(); --i >= 0;)
  66232. {
  66233. int* line = lineStart;
  66234. lineStart += lineStrideElements;
  66235. int num = *line++;
  66236. while (--num >= 0)
  66237. {
  66238. *line += intDx;
  66239. line += 2;
  66240. }
  66241. }
  66242. }
  66243. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  66244. {
  66245. jassert (y >= 0 && y < bounds.getHeight());
  66246. int* dest = table + lineStrideElements * y;
  66247. if (dest[0] == 0)
  66248. return;
  66249. int otherNumPoints = *otherLine;
  66250. if (otherNumPoints == 0)
  66251. {
  66252. *dest = 0;
  66253. return;
  66254. }
  66255. const int right = bounds.getRight() << 8;
  66256. // optimise for the common case where our line lies entirely within a
  66257. // single pair of points, as happens when clipping to a simple rect.
  66258. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66259. {
  66260. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66261. return;
  66262. }
  66263. ++otherLine;
  66264. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66265. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66266. memcpy (temp, dest, lineSizeBytes);
  66267. const int* src1 = temp;
  66268. int srcNum1 = *src1++;
  66269. int x1 = *src1++;
  66270. const int* src2 = otherLine;
  66271. int srcNum2 = otherNumPoints;
  66272. int x2 = *src2++;
  66273. int destIndex = 0, destTotal = 0;
  66274. int level1 = 0, level2 = 0;
  66275. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66276. while (srcNum1 > 0 && srcNum2 > 0)
  66277. {
  66278. int nextX;
  66279. if (x1 < x2)
  66280. {
  66281. nextX = x1;
  66282. level1 = *src1++;
  66283. x1 = *src1++;
  66284. --srcNum1;
  66285. }
  66286. else if (x1 == x2)
  66287. {
  66288. nextX = x1;
  66289. level1 = *src1++;
  66290. level2 = *src2++;
  66291. x1 = *src1++;
  66292. x2 = *src2++;
  66293. --srcNum1;
  66294. --srcNum2;
  66295. }
  66296. else
  66297. {
  66298. nextX = x2;
  66299. level2 = *src2++;
  66300. x2 = *src2++;
  66301. --srcNum2;
  66302. }
  66303. if (nextX > lastX)
  66304. {
  66305. if (nextX >= right)
  66306. break;
  66307. lastX = nextX;
  66308. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66309. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66310. if (nextLevel != lastLevel)
  66311. {
  66312. if (destTotal >= maxEdgesPerLine)
  66313. {
  66314. dest[0] = destTotal;
  66315. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66316. dest = table + lineStrideElements * y;
  66317. }
  66318. ++destTotal;
  66319. lastLevel = nextLevel;
  66320. dest[++destIndex] = nextX;
  66321. dest[++destIndex] = nextLevel;
  66322. }
  66323. }
  66324. }
  66325. if (lastLevel > 0)
  66326. {
  66327. if (destTotal >= maxEdgesPerLine)
  66328. {
  66329. dest[0] = destTotal;
  66330. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66331. dest = table + lineStrideElements * y;
  66332. }
  66333. ++destTotal;
  66334. dest[++destIndex] = right;
  66335. dest[++destIndex] = 0;
  66336. }
  66337. dest[0] = destTotal;
  66338. #if JUCE_DEBUG
  66339. int last = std::numeric_limits<int>::min();
  66340. for (int i = 0; i < dest[0]; ++i)
  66341. {
  66342. jassert (dest[i * 2 + 1] > last);
  66343. last = dest[i * 2 + 1];
  66344. }
  66345. jassert (dest [dest[0] * 2] == 0);
  66346. #endif
  66347. }
  66348. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66349. {
  66350. int* lastItem = dest + (dest[0] * 2 - 1);
  66351. if (x2 < lastItem[0])
  66352. {
  66353. if (x2 <= dest[1])
  66354. {
  66355. dest[0] = 0;
  66356. return;
  66357. }
  66358. while (x2 < lastItem[-2])
  66359. {
  66360. --(dest[0]);
  66361. lastItem -= 2;
  66362. }
  66363. lastItem[0] = x2;
  66364. lastItem[1] = 0;
  66365. }
  66366. if (x1 > dest[1])
  66367. {
  66368. while (lastItem[0] > x1)
  66369. lastItem -= 2;
  66370. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66371. if (itemsRemoved > 0)
  66372. {
  66373. dest[0] -= itemsRemoved;
  66374. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66375. }
  66376. dest[1] = x1;
  66377. }
  66378. }
  66379. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66380. {
  66381. const Rectangle<int> clipped (r.getIntersection (bounds));
  66382. if (clipped.isEmpty())
  66383. {
  66384. needToCheckEmptinesss = false;
  66385. bounds.setHeight (0);
  66386. }
  66387. else
  66388. {
  66389. const int top = clipped.getY() - bounds.getY();
  66390. const int bottom = clipped.getBottom() - bounds.getY();
  66391. if (bottom < bounds.getHeight())
  66392. bounds.setHeight (bottom);
  66393. if (clipped.getRight() < bounds.getRight())
  66394. bounds.setRight (clipped.getRight());
  66395. for (int i = top; --i >= 0;)
  66396. table [lineStrideElements * i] = 0;
  66397. if (clipped.getX() > bounds.getX())
  66398. {
  66399. const int x1 = clipped.getX() << 8;
  66400. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66401. int* line = table + lineStrideElements * top;
  66402. for (int i = bottom - top; --i >= 0;)
  66403. {
  66404. if (line[0] != 0)
  66405. clipEdgeTableLineToRange (line, x1, x2);
  66406. line += lineStrideElements;
  66407. }
  66408. }
  66409. needToCheckEmptinesss = true;
  66410. }
  66411. }
  66412. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66413. {
  66414. const Rectangle<int> clipped (r.getIntersection (bounds));
  66415. if (! clipped.isEmpty())
  66416. {
  66417. const int top = clipped.getY() - bounds.getY();
  66418. const int bottom = clipped.getBottom() - bounds.getY();
  66419. //XXX optimise here by shortening the table if it fills top or bottom
  66420. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66421. clipped.getX() << 8, 0,
  66422. clipped.getRight() << 8, 255,
  66423. std::numeric_limits<int>::max(), 0 };
  66424. for (int i = top; i < bottom; ++i)
  66425. intersectWithEdgeTableLine (i, rectLine);
  66426. needToCheckEmptinesss = true;
  66427. }
  66428. }
  66429. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66430. {
  66431. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66432. if (clipped.isEmpty())
  66433. {
  66434. needToCheckEmptinesss = false;
  66435. bounds.setHeight (0);
  66436. }
  66437. else
  66438. {
  66439. const int top = clipped.getY() - bounds.getY();
  66440. const int bottom = clipped.getBottom() - bounds.getY();
  66441. if (bottom < bounds.getHeight())
  66442. bounds.setHeight (bottom);
  66443. if (clipped.getRight() < bounds.getRight())
  66444. bounds.setRight (clipped.getRight());
  66445. int i = 0;
  66446. for (i = top; --i >= 0;)
  66447. table [lineStrideElements * i] = 0;
  66448. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66449. for (i = top; i < bottom; ++i)
  66450. {
  66451. intersectWithEdgeTableLine (i, otherLine);
  66452. otherLine += other.lineStrideElements;
  66453. }
  66454. needToCheckEmptinesss = true;
  66455. }
  66456. }
  66457. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66458. {
  66459. y -= bounds.getY();
  66460. if (y < 0 || y >= bounds.getHeight())
  66461. return;
  66462. needToCheckEmptinesss = true;
  66463. if (numPixels <= 0)
  66464. {
  66465. table [lineStrideElements * y] = 0;
  66466. return;
  66467. }
  66468. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66469. int destIndex = 0, lastLevel = 0;
  66470. while (--numPixels >= 0)
  66471. {
  66472. const int alpha = *mask;
  66473. mask += maskStride;
  66474. if (alpha != lastLevel)
  66475. {
  66476. tempLine[++destIndex] = (x << 8);
  66477. tempLine[++destIndex] = alpha;
  66478. lastLevel = alpha;
  66479. }
  66480. ++x;
  66481. }
  66482. if (lastLevel > 0)
  66483. {
  66484. tempLine[++destIndex] = (x << 8);
  66485. tempLine[++destIndex] = 0;
  66486. }
  66487. tempLine[0] = destIndex >> 1;
  66488. intersectWithEdgeTableLine (y, tempLine);
  66489. }
  66490. bool EdgeTable::isEmpty() throw()
  66491. {
  66492. if (needToCheckEmptinesss)
  66493. {
  66494. needToCheckEmptinesss = false;
  66495. int* t = table;
  66496. for (int i = bounds.getHeight(); --i >= 0;)
  66497. {
  66498. if (t[0] > 1)
  66499. return false;
  66500. t += lineStrideElements;
  66501. }
  66502. bounds.setHeight (0);
  66503. }
  66504. return bounds.getHeight() == 0;
  66505. }
  66506. END_JUCE_NAMESPACE
  66507. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66508. /*** Start of inlined file: juce_FillType.cpp ***/
  66509. BEGIN_JUCE_NAMESPACE
  66510. FillType::FillType() throw()
  66511. : colour (0xff000000), image (0)
  66512. {
  66513. }
  66514. FillType::FillType (const Colour& colour_) throw()
  66515. : colour (colour_), image (0)
  66516. {
  66517. }
  66518. FillType::FillType (const ColourGradient& gradient_)
  66519. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66520. {
  66521. }
  66522. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66523. : colour (0xff000000), image (image_), transform (transform_)
  66524. {
  66525. }
  66526. FillType::FillType (const FillType& other)
  66527. : colour (other.colour),
  66528. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66529. image (other.image), transform (other.transform)
  66530. {
  66531. }
  66532. FillType& FillType::operator= (const FillType& other)
  66533. {
  66534. if (this != &other)
  66535. {
  66536. colour = other.colour;
  66537. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66538. image = other.image;
  66539. transform = other.transform;
  66540. }
  66541. return *this;
  66542. }
  66543. FillType::~FillType() throw()
  66544. {
  66545. }
  66546. bool FillType::operator== (const FillType& other) const
  66547. {
  66548. return colour == other.colour && image == other.image
  66549. && transform == other.transform
  66550. && (gradient == other.gradient
  66551. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66552. }
  66553. bool FillType::operator!= (const FillType& other) const
  66554. {
  66555. return ! operator== (other);
  66556. }
  66557. void FillType::setColour (const Colour& newColour) throw()
  66558. {
  66559. gradient = 0;
  66560. image = Image::null;
  66561. colour = newColour;
  66562. }
  66563. void FillType::setGradient (const ColourGradient& newGradient)
  66564. {
  66565. if (gradient != 0)
  66566. {
  66567. *gradient = newGradient;
  66568. }
  66569. else
  66570. {
  66571. image = Image::null;
  66572. gradient = new ColourGradient (newGradient);
  66573. colour = Colours::black;
  66574. }
  66575. }
  66576. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66577. {
  66578. gradient = 0;
  66579. image = image_;
  66580. transform = transform_;
  66581. colour = Colours::black;
  66582. }
  66583. void FillType::setOpacity (const float newOpacity) throw()
  66584. {
  66585. colour = colour.withAlpha (newOpacity);
  66586. }
  66587. bool FillType::isInvisible() const throw()
  66588. {
  66589. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66590. }
  66591. END_JUCE_NAMESPACE
  66592. /*** End of inlined file: juce_FillType.cpp ***/
  66593. /*** Start of inlined file: juce_Graphics.cpp ***/
  66594. BEGIN_JUCE_NAMESPACE
  66595. template <typename Type>
  66596. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66597. {
  66598. const int maxVal = 0x3fffffff;
  66599. return (int) x >= -maxVal && (int) x <= maxVal
  66600. && (int) y >= -maxVal && (int) y <= maxVal
  66601. && (int) w >= -maxVal && (int) w <= maxVal
  66602. && (int) h >= -maxVal && (int) h <= maxVal;
  66603. }
  66604. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66605. {
  66606. }
  66607. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66608. {
  66609. }
  66610. Graphics::Graphics (const Image& imageToDrawOnto)
  66611. : context (imageToDrawOnto.createLowLevelContext()),
  66612. contextToDelete (context),
  66613. saveStatePending (false)
  66614. {
  66615. }
  66616. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66617. : context (internalContext),
  66618. saveStatePending (false)
  66619. {
  66620. }
  66621. Graphics::~Graphics()
  66622. {
  66623. }
  66624. void Graphics::resetToDefaultState()
  66625. {
  66626. saveStateIfPending();
  66627. context->setFill (FillType());
  66628. context->setFont (Font());
  66629. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66630. }
  66631. bool Graphics::isVectorDevice() const
  66632. {
  66633. return context->isVectorDevice();
  66634. }
  66635. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66636. {
  66637. saveStateIfPending();
  66638. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  66639. }
  66640. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66641. {
  66642. saveStateIfPending();
  66643. return context->clipToRectangleList (clipRegion);
  66644. }
  66645. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66646. {
  66647. saveStateIfPending();
  66648. context->clipToPath (path, transform);
  66649. return ! context->isClipEmpty();
  66650. }
  66651. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66652. {
  66653. saveStateIfPending();
  66654. context->clipToImageAlpha (image, transform);
  66655. return ! context->isClipEmpty();
  66656. }
  66657. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66658. {
  66659. saveStateIfPending();
  66660. context->excludeClipRectangle (rectangleToExclude);
  66661. }
  66662. bool Graphics::isClipEmpty() const
  66663. {
  66664. return context->isClipEmpty();
  66665. }
  66666. const Rectangle<int> Graphics::getClipBounds() const
  66667. {
  66668. return context->getClipBounds();
  66669. }
  66670. void Graphics::saveState()
  66671. {
  66672. saveStateIfPending();
  66673. saveStatePending = true;
  66674. }
  66675. void Graphics::restoreState()
  66676. {
  66677. if (saveStatePending)
  66678. saveStatePending = false;
  66679. else
  66680. context->restoreState();
  66681. }
  66682. void Graphics::saveStateIfPending()
  66683. {
  66684. if (saveStatePending)
  66685. {
  66686. saveStatePending = false;
  66687. context->saveState();
  66688. }
  66689. }
  66690. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66691. {
  66692. saveStateIfPending();
  66693. context->setOrigin (newOriginX, newOriginY);
  66694. }
  66695. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66696. {
  66697. return context->clipRegionIntersects (area);
  66698. }
  66699. void Graphics::setColour (const Colour& newColour)
  66700. {
  66701. saveStateIfPending();
  66702. context->setFill (newColour);
  66703. }
  66704. void Graphics::setOpacity (const float newOpacity)
  66705. {
  66706. saveStateIfPending();
  66707. context->setOpacity (newOpacity);
  66708. }
  66709. void Graphics::setGradientFill (const ColourGradient& gradient)
  66710. {
  66711. setFillType (gradient);
  66712. }
  66713. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66714. {
  66715. saveStateIfPending();
  66716. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66717. context->setOpacity (opacity);
  66718. }
  66719. void Graphics::setFillType (const FillType& newFill)
  66720. {
  66721. saveStateIfPending();
  66722. context->setFill (newFill);
  66723. }
  66724. void Graphics::setFont (const Font& newFont)
  66725. {
  66726. saveStateIfPending();
  66727. context->setFont (newFont);
  66728. }
  66729. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66730. {
  66731. saveStateIfPending();
  66732. Font f (context->getFont());
  66733. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66734. context->setFont (f);
  66735. }
  66736. const Font Graphics::getCurrentFont() const
  66737. {
  66738. return context->getFont();
  66739. }
  66740. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66741. {
  66742. if (text.isNotEmpty()
  66743. && startX < context->getClipBounds().getRight())
  66744. {
  66745. GlyphArrangement arr;
  66746. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66747. arr.draw (*this);
  66748. }
  66749. }
  66750. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66751. {
  66752. if (text.isNotEmpty())
  66753. {
  66754. GlyphArrangement arr;
  66755. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66756. arr.draw (*this, transform);
  66757. }
  66758. }
  66759. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66760. {
  66761. if (text.isNotEmpty()
  66762. && startX < context->getClipBounds().getRight())
  66763. {
  66764. GlyphArrangement arr;
  66765. arr.addJustifiedText (context->getFont(), text,
  66766. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66767. Justification::left);
  66768. arr.draw (*this);
  66769. }
  66770. }
  66771. void Graphics::drawText (const String& text,
  66772. const int x, const int y, const int width, const int height,
  66773. const Justification& justificationType,
  66774. const bool useEllipsesIfTooBig) const
  66775. {
  66776. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66777. {
  66778. GlyphArrangement arr;
  66779. arr.addCurtailedLineOfText (context->getFont(), text,
  66780. 0.0f, 0.0f, (float) width,
  66781. useEllipsesIfTooBig);
  66782. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66783. (float) x, (float) y, (float) width, (float) height,
  66784. justificationType);
  66785. arr.draw (*this);
  66786. }
  66787. }
  66788. void Graphics::drawFittedText (const String& text,
  66789. const int x, const int y, const int width, const int height,
  66790. const Justification& justification,
  66791. const int maximumNumberOfLines,
  66792. const float minimumHorizontalScale) const
  66793. {
  66794. if (text.isNotEmpty()
  66795. && width > 0 && height > 0
  66796. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66797. {
  66798. GlyphArrangement arr;
  66799. arr.addFittedText (context->getFont(), text,
  66800. (float) x, (float) y, (float) width, (float) height,
  66801. justification,
  66802. maximumNumberOfLines,
  66803. minimumHorizontalScale);
  66804. arr.draw (*this);
  66805. }
  66806. }
  66807. void Graphics::fillRect (int x, int y, int width, int height) const
  66808. {
  66809. // passing in a silly number can cause maths problems in rendering!
  66810. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66811. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66812. }
  66813. void Graphics::fillRect (const Rectangle<int>& r) const
  66814. {
  66815. context->fillRect (r, false);
  66816. }
  66817. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66818. {
  66819. // passing in a silly number can cause maths problems in rendering!
  66820. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66821. Path p;
  66822. p.addRectangle (x, y, width, height);
  66823. fillPath (p);
  66824. }
  66825. void Graphics::setPixel (int x, int y) const
  66826. {
  66827. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66828. }
  66829. void Graphics::fillAll() const
  66830. {
  66831. fillRect (context->getClipBounds());
  66832. }
  66833. void Graphics::fillAll (const Colour& colourToUse) const
  66834. {
  66835. if (! colourToUse.isTransparent())
  66836. {
  66837. const Rectangle<int> clip (context->getClipBounds());
  66838. context->saveState();
  66839. context->setFill (colourToUse);
  66840. context->fillRect (clip, false);
  66841. context->restoreState();
  66842. }
  66843. }
  66844. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66845. {
  66846. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66847. context->fillPath (path, transform);
  66848. }
  66849. void Graphics::strokePath (const Path& path,
  66850. const PathStrokeType& strokeType,
  66851. const AffineTransform& transform) const
  66852. {
  66853. Path stroke;
  66854. strokeType.createStrokedPath (stroke, path, transform);
  66855. fillPath (stroke);
  66856. }
  66857. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66858. const int lineThickness) const
  66859. {
  66860. // passing in a silly number can cause maths problems in rendering!
  66861. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66862. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66863. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66864. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66865. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66866. }
  66867. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66868. {
  66869. // passing in a silly number can cause maths problems in rendering!
  66870. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66871. Path p;
  66872. p.addRectangle (x, y, width, lineThickness);
  66873. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66874. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66875. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66876. fillPath (p);
  66877. }
  66878. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66879. {
  66880. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66881. }
  66882. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66883. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66884. const bool useGradient, const bool sharpEdgeOnOutside) const
  66885. {
  66886. // passing in a silly number can cause maths problems in rendering!
  66887. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66888. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66889. {
  66890. context->saveState();
  66891. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66892. const float ramp = oldOpacity / bevelThickness;
  66893. for (int i = bevelThickness; --i >= 0;)
  66894. {
  66895. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66896. : oldOpacity;
  66897. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66898. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66899. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66900. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66901. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66902. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66903. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66904. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66905. }
  66906. context->restoreState();
  66907. }
  66908. }
  66909. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66910. {
  66911. // passing in a silly number can cause maths problems in rendering!
  66912. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66913. Path p;
  66914. p.addEllipse (x, y, width, height);
  66915. fillPath (p);
  66916. }
  66917. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66918. const float lineThickness) const
  66919. {
  66920. // passing in a silly number can cause maths problems in rendering!
  66921. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66922. Path p;
  66923. p.addEllipse (x, y, width, height);
  66924. strokePath (p, PathStrokeType (lineThickness));
  66925. }
  66926. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66927. {
  66928. // passing in a silly number can cause maths problems in rendering!
  66929. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66930. Path p;
  66931. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66932. fillPath (p);
  66933. }
  66934. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66935. {
  66936. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66937. }
  66938. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66939. const float cornerSize, const float lineThickness) const
  66940. {
  66941. // passing in a silly number can cause maths problems in rendering!
  66942. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66943. Path p;
  66944. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66945. strokePath (p, PathStrokeType (lineThickness));
  66946. }
  66947. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66948. {
  66949. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66950. }
  66951. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66952. {
  66953. Path p;
  66954. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66955. fillPath (p);
  66956. }
  66957. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66958. const int checkWidth, const int checkHeight,
  66959. const Colour& colour1, const Colour& colour2) const
  66960. {
  66961. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66962. if (checkWidth > 0 && checkHeight > 0)
  66963. {
  66964. context->saveState();
  66965. if (colour1 == colour2)
  66966. {
  66967. context->setFill (colour1);
  66968. context->fillRect (area, false);
  66969. }
  66970. else
  66971. {
  66972. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66973. if (! clipped.isEmpty())
  66974. {
  66975. context->clipToRectangle (clipped);
  66976. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66977. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66978. const int startX = area.getX() + checkNumX * checkWidth;
  66979. const int startY = area.getY() + checkNumY * checkHeight;
  66980. const int right = clipped.getRight();
  66981. const int bottom = clipped.getBottom();
  66982. for (int i = 0; i < 2; ++i)
  66983. {
  66984. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66985. int cy = i;
  66986. for (int y = startY; y < bottom; y += checkHeight)
  66987. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66988. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66989. }
  66990. }
  66991. }
  66992. context->restoreState();
  66993. }
  66994. }
  66995. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66996. {
  66997. context->drawVerticalLine (x, top, bottom);
  66998. }
  66999. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  67000. {
  67001. context->drawHorizontalLine (y, left, right);
  67002. }
  67003. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  67004. {
  67005. context->drawLine (Line<float> (x1, y1, x2, y2));
  67006. }
  67007. void Graphics::drawLine (const float startX, const float startY,
  67008. const float endX, const float endY,
  67009. const float lineThickness) const
  67010. {
  67011. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  67012. }
  67013. void Graphics::drawLine (const Line<float>& line) const
  67014. {
  67015. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  67016. }
  67017. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  67018. {
  67019. Path p;
  67020. p.addLineSegment (line, lineThickness);
  67021. fillPath (p);
  67022. }
  67023. void Graphics::drawDashedLine (const float startX, const float startY,
  67024. const float endX, const float endY,
  67025. const float* const dashLengths,
  67026. const int numDashLengths,
  67027. const float lineThickness) const
  67028. {
  67029. const double dx = endX - startX;
  67030. const double dy = endY - startY;
  67031. const double totalLen = juce_hypot (dx, dy);
  67032. if (totalLen >= 0.5)
  67033. {
  67034. const double onePixAlpha = 1.0 / totalLen;
  67035. double alpha = 0.0;
  67036. float x = startX;
  67037. float y = startY;
  67038. int n = 0;
  67039. while (alpha < 1.0f)
  67040. {
  67041. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  67042. n = n % numDashLengths;
  67043. const float oldX = x;
  67044. const float oldY = y;
  67045. x = (float) (startX + dx * alpha);
  67046. y = (float) (startY + dy * alpha);
  67047. if ((n & 1) != 0)
  67048. {
  67049. if (lineThickness != 1.0f)
  67050. drawLine (oldX, oldY, x, y, lineThickness);
  67051. else
  67052. drawLine (oldX, oldY, x, y);
  67053. }
  67054. }
  67055. }
  67056. }
  67057. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  67058. {
  67059. saveStateIfPending();
  67060. context->setInterpolationQuality (newQuality);
  67061. }
  67062. void Graphics::drawImageAt (const Image& imageToDraw,
  67063. const int topLeftX, const int topLeftY,
  67064. const bool fillAlphaChannelWithCurrentBrush) const
  67065. {
  67066. const int imageW = imageToDraw.getWidth();
  67067. const int imageH = imageToDraw.getHeight();
  67068. drawImage (imageToDraw,
  67069. topLeftX, topLeftY, imageW, imageH,
  67070. 0, 0, imageW, imageH,
  67071. fillAlphaChannelWithCurrentBrush);
  67072. }
  67073. void Graphics::drawImageWithin (const Image& imageToDraw,
  67074. const int destX, const int destY,
  67075. const int destW, const int destH,
  67076. const RectanglePlacement& placementWithinTarget,
  67077. const bool fillAlphaChannelWithCurrentBrush) const
  67078. {
  67079. // passing in a silly number can cause maths problems in rendering!
  67080. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  67081. if (imageToDraw.isValid())
  67082. {
  67083. const int imageW = imageToDraw.getWidth();
  67084. const int imageH = imageToDraw.getHeight();
  67085. if (imageW > 0 && imageH > 0)
  67086. {
  67087. double newX = 0.0, newY = 0.0;
  67088. double newW = imageW;
  67089. double newH = imageH;
  67090. placementWithinTarget.applyTo (newX, newY, newW, newH,
  67091. destX, destY, destW, destH);
  67092. if (newW > 0 && newH > 0)
  67093. {
  67094. drawImage (imageToDraw,
  67095. roundToInt (newX), roundToInt (newY),
  67096. roundToInt (newW), roundToInt (newH),
  67097. 0, 0, imageW, imageH,
  67098. fillAlphaChannelWithCurrentBrush);
  67099. }
  67100. }
  67101. }
  67102. }
  67103. void Graphics::drawImage (const Image& imageToDraw,
  67104. int dx, int dy, int dw, int dh,
  67105. int sx, int sy, int sw, int sh,
  67106. const bool fillAlphaChannelWithCurrentBrush) const
  67107. {
  67108. // passing in a silly number can cause maths problems in rendering!
  67109. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  67110. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  67111. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  67112. {
  67113. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  67114. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  67115. .translated ((float) dx, (float) dy),
  67116. fillAlphaChannelWithCurrentBrush);
  67117. }
  67118. }
  67119. void Graphics::drawImageTransformed (const Image& imageToDraw,
  67120. const AffineTransform& transform,
  67121. const bool fillAlphaChannelWithCurrentBrush) const
  67122. {
  67123. if (imageToDraw.isValid() && ! context->isClipEmpty())
  67124. {
  67125. if (fillAlphaChannelWithCurrentBrush)
  67126. {
  67127. context->saveState();
  67128. context->clipToImageAlpha (imageToDraw, transform);
  67129. fillAll();
  67130. context->restoreState();
  67131. }
  67132. else
  67133. {
  67134. context->drawImage (imageToDraw, transform, false);
  67135. }
  67136. }
  67137. }
  67138. END_JUCE_NAMESPACE
  67139. /*** End of inlined file: juce_Graphics.cpp ***/
  67140. /*** Start of inlined file: juce_Justification.cpp ***/
  67141. BEGIN_JUCE_NAMESPACE
  67142. Justification::Justification (const Justification& other) throw()
  67143. : flags (other.flags)
  67144. {
  67145. }
  67146. Justification& Justification::operator= (const Justification& other) throw()
  67147. {
  67148. flags = other.flags;
  67149. return *this;
  67150. }
  67151. int Justification::getOnlyVerticalFlags() const throw()
  67152. {
  67153. return flags & (top | bottom | verticallyCentred);
  67154. }
  67155. int Justification::getOnlyHorizontalFlags() const throw()
  67156. {
  67157. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  67158. }
  67159. void Justification::applyToRectangle (int& x, int& y,
  67160. const int w, const int h,
  67161. const int spaceX, const int spaceY,
  67162. const int spaceW, const int spaceH) const throw()
  67163. {
  67164. if ((flags & horizontallyCentred) != 0)
  67165. x = spaceX + ((spaceW - w) >> 1);
  67166. else if ((flags & right) != 0)
  67167. x = spaceX + spaceW - w;
  67168. else
  67169. x = spaceX;
  67170. if ((flags & verticallyCentred) != 0)
  67171. y = spaceY + ((spaceH - h) >> 1);
  67172. else if ((flags & bottom) != 0)
  67173. y = spaceY + spaceH - h;
  67174. else
  67175. y = spaceY;
  67176. }
  67177. END_JUCE_NAMESPACE
  67178. /*** End of inlined file: juce_Justification.cpp ***/
  67179. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67180. BEGIN_JUCE_NAMESPACE
  67181. // this will throw an assertion if you try to draw something that's not
  67182. // possible in postscript
  67183. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  67184. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  67185. #define notPossibleInPostscriptAssert jassertfalse
  67186. #else
  67187. #define notPossibleInPostscriptAssert
  67188. #endif
  67189. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  67190. const String& documentTitle,
  67191. const int totalWidth_,
  67192. const int totalHeight_)
  67193. : out (resultingPostScript),
  67194. totalWidth (totalWidth_),
  67195. totalHeight (totalHeight_),
  67196. needToClip (true)
  67197. {
  67198. stateStack.add (new SavedState());
  67199. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67200. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67201. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67202. "\n%%BoundingBox: 0 0 600 824"
  67203. "\n%%Pages: 0"
  67204. "\n%%Creator: Raw Material Software JUCE"
  67205. "\n%%Title: " << documentTitle <<
  67206. "\n%%CreationDate: none"
  67207. "\n%%LanguageLevel: 2"
  67208. "\n%%EndComments"
  67209. "\n%%BeginProlog"
  67210. "\n%%BeginResource: JRes"
  67211. "\n/bd {bind def} bind def"
  67212. "\n/c {setrgbcolor} bd"
  67213. "\n/m {moveto} bd"
  67214. "\n/l {lineto} bd"
  67215. "\n/rl {rlineto} bd"
  67216. "\n/ct {curveto} bd"
  67217. "\n/cp {closepath} bd"
  67218. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67219. "\n/doclip {initclip newpath} bd"
  67220. "\n/endclip {clip newpath} bd"
  67221. "\n%%EndResource"
  67222. "\n%%EndProlog"
  67223. "\n%%BeginSetup"
  67224. "\n%%EndSetup"
  67225. "\n%%Page: 1 1"
  67226. "\n%%BeginPageSetup"
  67227. "\n%%EndPageSetup\n\n"
  67228. << "40 800 translate\n"
  67229. << scale << ' ' << scale << " scale\n\n";
  67230. }
  67231. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67232. {
  67233. }
  67234. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67235. {
  67236. return true;
  67237. }
  67238. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67239. {
  67240. if (x != 0 || y != 0)
  67241. {
  67242. stateStack.getLast()->xOffset += x;
  67243. stateStack.getLast()->yOffset += y;
  67244. needToClip = true;
  67245. }
  67246. }
  67247. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67248. {
  67249. needToClip = true;
  67250. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67251. }
  67252. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67253. {
  67254. needToClip = true;
  67255. return stateStack.getLast()->clip.clipTo (clipRegion);
  67256. }
  67257. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67258. {
  67259. needToClip = true;
  67260. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67261. }
  67262. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67263. {
  67264. writeClip();
  67265. Path p (path);
  67266. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67267. writePath (p);
  67268. out << "clip\n";
  67269. }
  67270. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67271. {
  67272. needToClip = true;
  67273. jassertfalse; // xxx
  67274. }
  67275. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67276. {
  67277. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67278. }
  67279. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67280. {
  67281. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67282. -stateStack.getLast()->yOffset);
  67283. }
  67284. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67285. {
  67286. return stateStack.getLast()->clip.isEmpty();
  67287. }
  67288. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67289. : xOffset (0),
  67290. yOffset (0)
  67291. {
  67292. }
  67293. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67294. {
  67295. }
  67296. void LowLevelGraphicsPostScriptRenderer::saveState()
  67297. {
  67298. stateStack.add (new SavedState (*stateStack.getLast()));
  67299. }
  67300. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67301. {
  67302. jassert (stateStack.size() > 0);
  67303. if (stateStack.size() > 0)
  67304. stateStack.removeLast();
  67305. }
  67306. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67307. {
  67308. if (needToClip)
  67309. {
  67310. needToClip = false;
  67311. out << "doclip ";
  67312. int itemsOnLine = 0;
  67313. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67314. {
  67315. if (++itemsOnLine == 6)
  67316. {
  67317. itemsOnLine = 0;
  67318. out << '\n';
  67319. }
  67320. const Rectangle<int>& r = *i.getRectangle();
  67321. out << r.getX() << ' ' << -r.getY() << ' '
  67322. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67323. }
  67324. out << "endclip\n";
  67325. }
  67326. }
  67327. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67328. {
  67329. Colour c (Colours::white.overlaidWith (colour));
  67330. if (lastColour != c)
  67331. {
  67332. lastColour = c;
  67333. out << String (c.getFloatRed(), 3) << ' '
  67334. << String (c.getFloatGreen(), 3) << ' '
  67335. << String (c.getFloatBlue(), 3) << " c\n";
  67336. }
  67337. }
  67338. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67339. {
  67340. out << String (x, 2) << ' '
  67341. << String (-y, 2) << ' ';
  67342. }
  67343. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67344. {
  67345. out << "newpath ";
  67346. float lastX = 0.0f;
  67347. float lastY = 0.0f;
  67348. int itemsOnLine = 0;
  67349. Path::Iterator i (path);
  67350. while (i.next())
  67351. {
  67352. if (++itemsOnLine == 4)
  67353. {
  67354. itemsOnLine = 0;
  67355. out << '\n';
  67356. }
  67357. switch (i.elementType)
  67358. {
  67359. case Path::Iterator::startNewSubPath:
  67360. writeXY (i.x1, i.y1);
  67361. lastX = i.x1;
  67362. lastY = i.y1;
  67363. out << "m ";
  67364. break;
  67365. case Path::Iterator::lineTo:
  67366. writeXY (i.x1, i.y1);
  67367. lastX = i.x1;
  67368. lastY = i.y1;
  67369. out << "l ";
  67370. break;
  67371. case Path::Iterator::quadraticTo:
  67372. {
  67373. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67374. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67375. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67376. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67377. writeXY (cp1x, cp1y);
  67378. writeXY (cp2x, cp2y);
  67379. writeXY (i.x2, i.y2);
  67380. out << "ct ";
  67381. lastX = i.x2;
  67382. lastY = i.y2;
  67383. }
  67384. break;
  67385. case Path::Iterator::cubicTo:
  67386. writeXY (i.x1, i.y1);
  67387. writeXY (i.x2, i.y2);
  67388. writeXY (i.x3, i.y3);
  67389. out << "ct ";
  67390. lastX = i.x3;
  67391. lastY = i.y3;
  67392. break;
  67393. case Path::Iterator::closePath:
  67394. out << "cp ";
  67395. break;
  67396. default:
  67397. jassertfalse;
  67398. break;
  67399. }
  67400. }
  67401. out << '\n';
  67402. }
  67403. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67404. {
  67405. out << "[ "
  67406. << trans.mat00 << ' '
  67407. << trans.mat10 << ' '
  67408. << trans.mat01 << ' '
  67409. << trans.mat11 << ' '
  67410. << trans.mat02 << ' '
  67411. << trans.mat12 << " ] concat ";
  67412. }
  67413. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67414. {
  67415. stateStack.getLast()->fillType = fillType;
  67416. }
  67417. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67418. {
  67419. }
  67420. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67421. {
  67422. }
  67423. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67424. {
  67425. if (stateStack.getLast()->fillType.isColour())
  67426. {
  67427. writeClip();
  67428. writeColour (stateStack.getLast()->fillType.colour);
  67429. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67430. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67431. }
  67432. else
  67433. {
  67434. Path p;
  67435. p.addRectangle (r);
  67436. fillPath (p, AffineTransform::identity);
  67437. }
  67438. }
  67439. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67440. {
  67441. if (stateStack.getLast()->fillType.isColour())
  67442. {
  67443. writeClip();
  67444. Path p (path);
  67445. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67446. (float) stateStack.getLast()->yOffset));
  67447. writePath (p);
  67448. writeColour (stateStack.getLast()->fillType.colour);
  67449. out << "fill\n";
  67450. }
  67451. else if (stateStack.getLast()->fillType.isGradient())
  67452. {
  67453. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67454. // postscript can't do semi-transparent ones.
  67455. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67456. writeClip();
  67457. out << "gsave ";
  67458. {
  67459. Path p (path);
  67460. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67461. writePath (p);
  67462. out << "clip\n";
  67463. }
  67464. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67465. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67466. // time-being, this just fills it with the average colour..
  67467. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67468. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67469. out << "grestore\n";
  67470. }
  67471. }
  67472. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67473. const int sx, const int sy,
  67474. const int maxW, const int maxH) const
  67475. {
  67476. out << "{<\n";
  67477. const int w = jmin (maxW, im.getWidth());
  67478. const int h = jmin (maxH, im.getHeight());
  67479. int charsOnLine = 0;
  67480. const Image::BitmapData srcData (im, 0, 0, w, h);
  67481. Colour pixel;
  67482. for (int y = h; --y >= 0;)
  67483. {
  67484. for (int x = 0; x < w; ++x)
  67485. {
  67486. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67487. if (x >= sx && y >= sy)
  67488. {
  67489. if (im.isARGB())
  67490. {
  67491. PixelARGB p (*(const PixelARGB*) pixelData);
  67492. p.unpremultiply();
  67493. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67494. }
  67495. else if (im.isRGB())
  67496. {
  67497. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67498. }
  67499. else
  67500. {
  67501. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67502. }
  67503. }
  67504. else
  67505. {
  67506. pixel = Colours::transparentWhite;
  67507. }
  67508. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67509. out << String::toHexString (pixelValues, 3, 0);
  67510. charsOnLine += 3;
  67511. if (charsOnLine > 100)
  67512. {
  67513. out << '\n';
  67514. charsOnLine = 0;
  67515. }
  67516. }
  67517. }
  67518. out << "\n>}\n";
  67519. }
  67520. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67521. {
  67522. const int w = sourceImage.getWidth();
  67523. const int h = sourceImage.getHeight();
  67524. writeClip();
  67525. out << "gsave ";
  67526. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67527. .scaled (1.0f, -1.0f));
  67528. RectangleList imageClip;
  67529. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67530. out << "newpath ";
  67531. int itemsOnLine = 0;
  67532. for (RectangleList::Iterator i (imageClip); i.next();)
  67533. {
  67534. if (++itemsOnLine == 6)
  67535. {
  67536. out << '\n';
  67537. itemsOnLine = 0;
  67538. }
  67539. const Rectangle<int>& r = *i.getRectangle();
  67540. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67541. }
  67542. out << " clip newpath\n";
  67543. out << w << ' ' << h << " scale\n";
  67544. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67545. writeImage (sourceImage, 0, 0, w, h);
  67546. out << "false 3 colorimage grestore\n";
  67547. needToClip = true;
  67548. }
  67549. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67550. {
  67551. Path p;
  67552. p.addLineSegment (line, 1.0f);
  67553. fillPath (p, AffineTransform::identity);
  67554. }
  67555. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67556. {
  67557. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67558. }
  67559. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67560. {
  67561. drawLine (Line<float> (left, (float) y, right, (float) y));
  67562. }
  67563. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67564. {
  67565. stateStack.getLast()->font = newFont;
  67566. }
  67567. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67568. {
  67569. return stateStack.getLast()->font;
  67570. }
  67571. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67572. {
  67573. Path p;
  67574. Font& font = stateStack.getLast()->font;
  67575. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67576. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67577. }
  67578. END_JUCE_NAMESPACE
  67579. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67580. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67581. BEGIN_JUCE_NAMESPACE
  67582. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67583. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67584. #endif
  67585. #if JUCE_MSVC
  67586. #pragma warning (push)
  67587. #pragma warning (disable: 4127) // "expression is constant" warning
  67588. #if JUCE_DEBUG
  67589. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67590. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67591. #endif
  67592. #endif
  67593. namespace SoftwareRendererClasses
  67594. {
  67595. template <class PixelType, bool replaceExisting = false>
  67596. class SolidColourEdgeTableRenderer
  67597. {
  67598. public:
  67599. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67600. : data (data_),
  67601. sourceColour (colour)
  67602. {
  67603. if (sizeof (PixelType) == 3)
  67604. {
  67605. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67606. && sourceColour.getGreen() == sourceColour.getBlue();
  67607. filler[0].set (sourceColour);
  67608. filler[1].set (sourceColour);
  67609. filler[2].set (sourceColour);
  67610. filler[3].set (sourceColour);
  67611. }
  67612. }
  67613. forcedinline void setEdgeTableYPos (const int y) throw()
  67614. {
  67615. linePixels = (PixelType*) data.getLinePointer (y);
  67616. }
  67617. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67618. {
  67619. if (replaceExisting)
  67620. linePixels[x].set (sourceColour);
  67621. else
  67622. linePixels[x].blend (sourceColour, alphaLevel);
  67623. }
  67624. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67625. {
  67626. if (replaceExisting)
  67627. linePixels[x].set (sourceColour);
  67628. else
  67629. linePixels[x].blend (sourceColour);
  67630. }
  67631. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67632. {
  67633. PixelARGB p (sourceColour);
  67634. p.multiplyAlpha (alphaLevel);
  67635. PixelType* dest = linePixels + x;
  67636. if (replaceExisting || p.getAlpha() >= 0xff)
  67637. replaceLine (dest, p, width);
  67638. else
  67639. blendLine (dest, p, width);
  67640. }
  67641. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67642. {
  67643. PixelType* dest = linePixels + x;
  67644. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67645. replaceLine (dest, sourceColour, width);
  67646. else
  67647. blendLine (dest, sourceColour, width);
  67648. }
  67649. private:
  67650. const Image::BitmapData& data;
  67651. PixelType* linePixels;
  67652. PixelARGB sourceColour;
  67653. PixelRGB filler [4];
  67654. bool areRGBComponentsEqual;
  67655. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67656. {
  67657. do
  67658. {
  67659. dest->blend (colour);
  67660. ++dest;
  67661. } while (--width > 0);
  67662. }
  67663. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67664. {
  67665. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67666. {
  67667. memset (dest, colour.getRed(), width * 3);
  67668. }
  67669. else
  67670. {
  67671. if (width >> 5)
  67672. {
  67673. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67674. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67675. {
  67676. dest->set (colour);
  67677. ++dest;
  67678. --width;
  67679. }
  67680. while (width > 4)
  67681. {
  67682. int* d = reinterpret_cast<int*> (dest);
  67683. *d++ = intFiller[0];
  67684. *d++ = intFiller[1];
  67685. *d++ = intFiller[2];
  67686. dest = reinterpret_cast<PixelRGB*> (d);
  67687. width -= 4;
  67688. }
  67689. }
  67690. while (--width >= 0)
  67691. {
  67692. dest->set (colour);
  67693. ++dest;
  67694. }
  67695. }
  67696. }
  67697. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67698. {
  67699. memset (dest, colour.getAlpha(), width);
  67700. }
  67701. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67702. {
  67703. do
  67704. {
  67705. dest->set (colour);
  67706. ++dest;
  67707. } while (--width > 0);
  67708. }
  67709. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67710. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67711. };
  67712. class LinearGradientPixelGenerator
  67713. {
  67714. public:
  67715. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67716. : lookupTable (lookupTable_), numEntries (numEntries_)
  67717. {
  67718. jassert (numEntries_ >= 0);
  67719. Point<float> p1 (gradient.point1);
  67720. Point<float> p2 (gradient.point2);
  67721. if (! transform.isIdentity())
  67722. {
  67723. const Line<float> l (p2, p1);
  67724. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67725. p1.applyTransform (transform);
  67726. p2.applyTransform (transform);
  67727. p3.applyTransform (transform);
  67728. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67729. }
  67730. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67731. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67732. if (vertical)
  67733. {
  67734. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67735. start = roundToInt (p1.getY() * scale);
  67736. }
  67737. else if (horizontal)
  67738. {
  67739. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67740. start = roundToInt (p1.getX() * scale);
  67741. }
  67742. else
  67743. {
  67744. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67745. yTerm = p1.getY() - p1.getX() / grad;
  67746. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67747. grad *= scale;
  67748. }
  67749. }
  67750. forcedinline void setY (const int y) throw()
  67751. {
  67752. if (vertical)
  67753. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67754. else if (! horizontal)
  67755. start = roundToInt ((y - yTerm) * grad);
  67756. }
  67757. inline const PixelARGB getPixel (const int x) const throw()
  67758. {
  67759. return vertical ? linePix
  67760. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67761. }
  67762. private:
  67763. const PixelARGB* const lookupTable;
  67764. const int numEntries;
  67765. PixelARGB linePix;
  67766. int start, scale;
  67767. double grad, yTerm;
  67768. bool vertical, horizontal;
  67769. enum { numScaleBits = 12 };
  67770. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67771. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67772. };
  67773. class RadialGradientPixelGenerator
  67774. {
  67775. public:
  67776. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67777. const PixelARGB* const lookupTable_, const int numEntries_)
  67778. : lookupTable (lookupTable_),
  67779. numEntries (numEntries_),
  67780. gx1 (gradient.point1.getX()),
  67781. gy1 (gradient.point1.getY())
  67782. {
  67783. jassert (numEntries_ >= 0);
  67784. const Point<float> diff (gradient.point1 - gradient.point2);
  67785. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67786. invScale = numEntries / std::sqrt (maxDist);
  67787. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67788. }
  67789. forcedinline void setY (const int y) throw()
  67790. {
  67791. dy = y - gy1;
  67792. dy *= dy;
  67793. }
  67794. inline const PixelARGB getPixel (const int px) const throw()
  67795. {
  67796. double x = px - gx1;
  67797. x *= x;
  67798. x += dy;
  67799. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67800. }
  67801. protected:
  67802. const PixelARGB* const lookupTable;
  67803. const int numEntries;
  67804. const double gx1, gy1;
  67805. double maxDist, invScale, dy;
  67806. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67807. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67808. };
  67809. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67810. {
  67811. public:
  67812. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67813. const PixelARGB* const lookupTable_, const int numEntries_)
  67814. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67815. inverseTransform (transform.inverted())
  67816. {
  67817. tM10 = inverseTransform.mat10;
  67818. tM00 = inverseTransform.mat00;
  67819. }
  67820. forcedinline void setY (const int y) throw()
  67821. {
  67822. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67823. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67824. }
  67825. inline const PixelARGB getPixel (const int px) const throw()
  67826. {
  67827. double x = px;
  67828. const double y = tM10 * x + lineYM11;
  67829. x = tM00 * x + lineYM01;
  67830. x *= x;
  67831. x += y * y;
  67832. if (x >= maxDist)
  67833. return lookupTable [numEntries];
  67834. else
  67835. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67836. }
  67837. private:
  67838. double tM10, tM00, lineYM01, lineYM11;
  67839. const AffineTransform inverseTransform;
  67840. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67841. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67842. };
  67843. template <class PixelType, class GradientType>
  67844. class GradientEdgeTableRenderer : public GradientType
  67845. {
  67846. public:
  67847. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67848. const PixelARGB* const lookupTable_, const int numEntries_)
  67849. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67850. destData (destData_)
  67851. {
  67852. }
  67853. forcedinline void setEdgeTableYPos (const int y) throw()
  67854. {
  67855. linePixels = (PixelType*) destData.getLinePointer (y);
  67856. GradientType::setY (y);
  67857. }
  67858. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67859. {
  67860. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67861. }
  67862. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67863. {
  67864. linePixels[x].blend (GradientType::getPixel (x));
  67865. }
  67866. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67867. {
  67868. PixelType* dest = linePixels + x;
  67869. if (alphaLevel < 0xff)
  67870. {
  67871. do
  67872. {
  67873. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67874. } while (--width > 0);
  67875. }
  67876. else
  67877. {
  67878. do
  67879. {
  67880. (dest++)->blend (GradientType::getPixel (x++));
  67881. } while (--width > 0);
  67882. }
  67883. }
  67884. void handleEdgeTableLineFull (int x, int width) const throw()
  67885. {
  67886. PixelType* dest = linePixels + x;
  67887. do
  67888. {
  67889. (dest++)->blend (GradientType::getPixel (x++));
  67890. } while (--width > 0);
  67891. }
  67892. private:
  67893. const Image::BitmapData& destData;
  67894. PixelType* linePixels;
  67895. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67896. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67897. };
  67898. static forcedinline int safeModulo (int n, const int divisor) throw()
  67899. {
  67900. jassert (divisor > 0);
  67901. n %= divisor;
  67902. return (n < 0) ? (n + divisor) : n;
  67903. }
  67904. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67905. class ImageFillEdgeTableRenderer
  67906. {
  67907. public:
  67908. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67909. const Image::BitmapData& srcData_,
  67910. const int extraAlpha_,
  67911. const int x, const int y)
  67912. : destData (destData_),
  67913. srcData (srcData_),
  67914. extraAlpha (extraAlpha_ + 1),
  67915. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67916. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67917. {
  67918. }
  67919. forcedinline void setEdgeTableYPos (int y) throw()
  67920. {
  67921. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67922. y -= yOffset;
  67923. if (repeatPattern)
  67924. {
  67925. jassert (y >= 0);
  67926. y %= srcData.height;
  67927. }
  67928. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67929. }
  67930. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67931. {
  67932. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67933. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67934. }
  67935. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67936. {
  67937. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67938. }
  67939. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67940. {
  67941. DestPixelType* dest = linePixels + x;
  67942. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67943. x -= xOffset;
  67944. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67945. if (alphaLevel < 0xfe)
  67946. {
  67947. do
  67948. {
  67949. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67950. } while (--width > 0);
  67951. }
  67952. else
  67953. {
  67954. if (repeatPattern)
  67955. {
  67956. do
  67957. {
  67958. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67959. } while (--width > 0);
  67960. }
  67961. else
  67962. {
  67963. copyRow (dest, sourceLineStart + x, width);
  67964. }
  67965. }
  67966. }
  67967. void handleEdgeTableLineFull (int x, int width) const throw()
  67968. {
  67969. DestPixelType* dest = linePixels + x;
  67970. x -= xOffset;
  67971. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67972. if (extraAlpha < 0xfe)
  67973. {
  67974. do
  67975. {
  67976. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67977. } while (--width > 0);
  67978. }
  67979. else
  67980. {
  67981. if (repeatPattern)
  67982. {
  67983. do
  67984. {
  67985. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67986. } while (--width > 0);
  67987. }
  67988. else
  67989. {
  67990. copyRow (dest, sourceLineStart + x, width);
  67991. }
  67992. }
  67993. }
  67994. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67995. {
  67996. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67997. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67998. uint8* mask = (uint8*) (s + x - xOffset);
  67999. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  68000. mask += PixelARGB::indexA;
  68001. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  68002. }
  68003. private:
  68004. const Image::BitmapData& destData;
  68005. const Image::BitmapData& srcData;
  68006. const int extraAlpha, xOffset, yOffset;
  68007. DestPixelType* linePixels;
  68008. SrcPixelType* sourceLineStart;
  68009. template <class PixelType1, class PixelType2>
  68010. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  68011. {
  68012. do
  68013. {
  68014. dest++ ->blend (*src++);
  68015. } while (--width > 0);
  68016. }
  68017. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  68018. {
  68019. memcpy (dest, src, width * sizeof (PixelRGB));
  68020. }
  68021. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  68022. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  68023. };
  68024. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  68025. class TransformedImageFillEdgeTableRenderer
  68026. {
  68027. public:
  68028. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  68029. const Image::BitmapData& srcData_,
  68030. const AffineTransform& transform,
  68031. const int extraAlpha_,
  68032. const bool betterQuality_)
  68033. : interpolator (transform),
  68034. destData (destData_),
  68035. srcData (srcData_),
  68036. extraAlpha (extraAlpha_ + 1),
  68037. betterQuality (betterQuality_),
  68038. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  68039. pixelOffsetInt (betterQuality_ ? -128 : 0),
  68040. maxX (srcData_.width - 1),
  68041. maxY (srcData_.height - 1),
  68042. scratchSize (2048)
  68043. {
  68044. scratchBuffer.malloc (scratchSize);
  68045. }
  68046. ~TransformedImageFillEdgeTableRenderer()
  68047. {
  68048. }
  68049. forcedinline void setEdgeTableYPos (const int newY) throw()
  68050. {
  68051. y = newY;
  68052. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  68053. }
  68054. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  68055. {
  68056. alphaLevel *= extraAlpha;
  68057. alphaLevel >>= 8;
  68058. SrcPixelType p;
  68059. generate (&p, x, 1);
  68060. linePixels[x].blend (p, alphaLevel);
  68061. }
  68062. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  68063. {
  68064. SrcPixelType p;
  68065. generate (&p, x, 1);
  68066. linePixels[x].blend (p, extraAlpha);
  68067. }
  68068. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  68069. {
  68070. if (width > scratchSize)
  68071. {
  68072. scratchSize = width;
  68073. scratchBuffer.malloc (scratchSize);
  68074. }
  68075. SrcPixelType* span = scratchBuffer;
  68076. generate (span, x, width);
  68077. DestPixelType* dest = linePixels + x;
  68078. alphaLevel *= extraAlpha;
  68079. alphaLevel >>= 8;
  68080. if (alphaLevel < 0xfe)
  68081. {
  68082. do
  68083. {
  68084. dest++ ->blend (*span++, alphaLevel);
  68085. } while (--width > 0);
  68086. }
  68087. else
  68088. {
  68089. do
  68090. {
  68091. dest++ ->blend (*span++);
  68092. } while (--width > 0);
  68093. }
  68094. }
  68095. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  68096. {
  68097. handleEdgeTableLine (x, width, 255);
  68098. }
  68099. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  68100. {
  68101. if (width > scratchSize)
  68102. {
  68103. scratchSize = width;
  68104. scratchBuffer.malloc (scratchSize);
  68105. }
  68106. y = y_;
  68107. generate (scratchBuffer, x, width);
  68108. et.clipLineToMask (x, y_,
  68109. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  68110. sizeof (SrcPixelType), width);
  68111. }
  68112. private:
  68113. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  68114. {
  68115. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68116. do
  68117. {
  68118. int hiResX, hiResY;
  68119. this->interpolator.next (hiResX, hiResY);
  68120. hiResX += pixelOffsetInt;
  68121. hiResY += pixelOffsetInt;
  68122. int loResX = hiResX >> 8;
  68123. int loResY = hiResY >> 8;
  68124. if (repeatPattern)
  68125. {
  68126. loResX = safeModulo (loResX, srcData.width);
  68127. loResY = safeModulo (loResY, srcData.height);
  68128. }
  68129. if (betterQuality
  68130. && ((unsigned int) loResX) < (unsigned int) maxX
  68131. && ((unsigned int) loResY) < (unsigned int) maxY)
  68132. {
  68133. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  68134. hiResX &= 255;
  68135. hiResY &= 255;
  68136. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68137. uint32 weight = (256 - hiResX) * (256 - hiResY);
  68138. c[0] += weight * src[0];
  68139. c[1] += weight * src[1];
  68140. c[2] += weight * src[2];
  68141. c[3] += weight * src[3];
  68142. weight = hiResX * (256 - hiResY);
  68143. c[0] += weight * src[4];
  68144. c[1] += weight * src[5];
  68145. c[2] += weight * src[6];
  68146. c[3] += weight * src[7];
  68147. src += this->srcData.lineStride;
  68148. weight = (256 - hiResX) * hiResY;
  68149. c[0] += weight * src[0];
  68150. c[1] += weight * src[1];
  68151. c[2] += weight * src[2];
  68152. c[3] += weight * src[3];
  68153. weight = hiResX * hiResY;
  68154. c[0] += weight * src[4];
  68155. c[1] += weight * src[5];
  68156. c[2] += weight * src[6];
  68157. c[3] += weight * src[7];
  68158. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  68159. (uint8) (c[PixelARGB::indexR] >> 16),
  68160. (uint8) (c[PixelARGB::indexG] >> 16),
  68161. (uint8) (c[PixelARGB::indexB] >> 16));
  68162. }
  68163. else
  68164. {
  68165. if (! repeatPattern)
  68166. {
  68167. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68168. if (loResX < 0) loResX = 0;
  68169. if (loResY < 0) loResY = 0;
  68170. if (loResX > maxX) loResX = maxX;
  68171. if (loResY > maxY) loResY = maxY;
  68172. }
  68173. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  68174. }
  68175. ++dest;
  68176. } while (--numPixels > 0);
  68177. }
  68178. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  68179. {
  68180. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68181. do
  68182. {
  68183. int hiResX, hiResY;
  68184. this->interpolator.next (hiResX, hiResY);
  68185. hiResX += pixelOffsetInt;
  68186. hiResY += pixelOffsetInt;
  68187. int loResX = hiResX >> 8;
  68188. int loResY = hiResY >> 8;
  68189. if (repeatPattern)
  68190. {
  68191. loResX = safeModulo (loResX, srcData.width);
  68192. loResY = safeModulo (loResY, srcData.height);
  68193. }
  68194. if (betterQuality
  68195. && ((unsigned int) loResX) < (unsigned int) maxX
  68196. && ((unsigned int) loResY) < (unsigned int) maxY)
  68197. {
  68198. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68199. hiResX &= 255;
  68200. hiResY &= 255;
  68201. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68202. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  68203. c[0] += weight * src[0];
  68204. c[1] += weight * src[1];
  68205. c[2] += weight * src[2];
  68206. weight = hiResX * (256 - hiResY);
  68207. c[0] += weight * src[3];
  68208. c[1] += weight * src[4];
  68209. c[2] += weight * src[5];
  68210. src += this->srcData.lineStride;
  68211. weight = (256 - hiResX) * hiResY;
  68212. c[0] += weight * src[0];
  68213. c[1] += weight * src[1];
  68214. c[2] += weight * src[2];
  68215. weight = hiResX * hiResY;
  68216. c[0] += weight * src[3];
  68217. c[1] += weight * src[4];
  68218. c[2] += weight * src[5];
  68219. dest->setARGB ((uint8) 255,
  68220. (uint8) (c[PixelRGB::indexR] >> 16),
  68221. (uint8) (c[PixelRGB::indexG] >> 16),
  68222. (uint8) (c[PixelRGB::indexB] >> 16));
  68223. }
  68224. else
  68225. {
  68226. if (! repeatPattern)
  68227. {
  68228. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68229. if (loResX < 0) loResX = 0;
  68230. if (loResY < 0) loResY = 0;
  68231. if (loResX > maxX) loResX = maxX;
  68232. if (loResY > maxY) loResY = maxY;
  68233. }
  68234. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  68235. }
  68236. ++dest;
  68237. } while (--numPixels > 0);
  68238. }
  68239. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  68240. {
  68241. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68242. do
  68243. {
  68244. int hiResX, hiResY;
  68245. this->interpolator.next (hiResX, hiResY);
  68246. hiResX += pixelOffsetInt;
  68247. hiResY += pixelOffsetInt;
  68248. int loResX = hiResX >> 8;
  68249. int loResY = hiResY >> 8;
  68250. if (repeatPattern)
  68251. {
  68252. loResX = safeModulo (loResX, srcData.width);
  68253. loResY = safeModulo (loResY, srcData.height);
  68254. }
  68255. if (betterQuality
  68256. && ((unsigned int) loResX) < (unsigned int) maxX
  68257. && ((unsigned int) loResY) < (unsigned int) maxY)
  68258. {
  68259. hiResX &= 255;
  68260. hiResY &= 255;
  68261. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68262. uint32 c = 256 * 128;
  68263. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  68264. c += src[1] * (hiResX * (256 - hiResY));
  68265. src += this->srcData.lineStride;
  68266. c += src[0] * ((256 - hiResX) * hiResY);
  68267. c += src[1] * (hiResX * hiResY);
  68268. *((uint8*) dest) = (uint8) c;
  68269. }
  68270. else
  68271. {
  68272. if (! repeatPattern)
  68273. {
  68274. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68275. if (loResX < 0) loResX = 0;
  68276. if (loResY < 0) loResY = 0;
  68277. if (loResX > maxX) loResX = maxX;
  68278. if (loResY > maxY) loResY = maxY;
  68279. }
  68280. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  68281. }
  68282. ++dest;
  68283. } while (--numPixels > 0);
  68284. }
  68285. class TransformedImageSpanInterpolator
  68286. {
  68287. public:
  68288. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68289. : inverseTransform (transform.inverted())
  68290. {}
  68291. void setStartOfLine (float x, float y, const int numPixels) throw()
  68292. {
  68293. float x1 = x, y1 = y;
  68294. x += numPixels;
  68295. inverseTransform.transformPoints (x1, y1, x, y);
  68296. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68297. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68298. }
  68299. void next (int& x, int& y) throw()
  68300. {
  68301. x = xBresenham.n;
  68302. xBresenham.stepToNext();
  68303. y = yBresenham.n;
  68304. yBresenham.stepToNext();
  68305. }
  68306. private:
  68307. class BresenhamInterpolator
  68308. {
  68309. public:
  68310. BresenhamInterpolator() throw() {}
  68311. void set (const int n1, const int n2, const int numSteps_) throw()
  68312. {
  68313. numSteps = jmax (1, numSteps_);
  68314. step = (n2 - n1) / numSteps;
  68315. remainder = modulo = (n2 - n1) % numSteps;
  68316. n = n1;
  68317. if (modulo <= 0)
  68318. {
  68319. modulo += numSteps;
  68320. remainder += numSteps;
  68321. --step;
  68322. }
  68323. modulo -= numSteps;
  68324. }
  68325. forcedinline void stepToNext() throw()
  68326. {
  68327. modulo += remainder;
  68328. n += step;
  68329. if (modulo > 0)
  68330. {
  68331. modulo -= numSteps;
  68332. ++n;
  68333. }
  68334. }
  68335. int n;
  68336. private:
  68337. int numSteps, step, modulo, remainder;
  68338. };
  68339. const AffineTransform inverseTransform;
  68340. BresenhamInterpolator xBresenham, yBresenham;
  68341. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68342. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68343. };
  68344. TransformedImageSpanInterpolator interpolator;
  68345. const Image::BitmapData& destData;
  68346. const Image::BitmapData& srcData;
  68347. const int extraAlpha;
  68348. const bool betterQuality;
  68349. const float pixelOffset;
  68350. const int pixelOffsetInt, maxX, maxY;
  68351. int y;
  68352. DestPixelType* linePixels;
  68353. HeapBlock <SrcPixelType> scratchBuffer;
  68354. int scratchSize;
  68355. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68356. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68357. };
  68358. class ClipRegionBase : public ReferenceCountedObject
  68359. {
  68360. public:
  68361. ClipRegionBase() {}
  68362. virtual ~ClipRegionBase() {}
  68363. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68364. virtual const Ptr clone() const = 0;
  68365. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68366. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68367. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68368. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68369. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68370. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68371. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68372. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68373. virtual const Rectangle<int> getClipBounds() const = 0;
  68374. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68375. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68376. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68377. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68378. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68379. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68380. protected:
  68381. template <class Iterator>
  68382. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68383. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68384. {
  68385. switch (destData.pixelFormat)
  68386. {
  68387. case Image::ARGB:
  68388. switch (srcData.pixelFormat)
  68389. {
  68390. case Image::ARGB:
  68391. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68392. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68393. break;
  68394. case Image::RGB:
  68395. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68396. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68397. break;
  68398. default:
  68399. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68400. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68401. break;
  68402. }
  68403. break;
  68404. case Image::RGB:
  68405. switch (srcData.pixelFormat)
  68406. {
  68407. case Image::ARGB:
  68408. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68409. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68410. break;
  68411. case Image::RGB:
  68412. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68413. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68414. break;
  68415. default:
  68416. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68417. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68418. break;
  68419. }
  68420. break;
  68421. default:
  68422. switch (srcData.pixelFormat)
  68423. {
  68424. case Image::ARGB:
  68425. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68426. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68427. break;
  68428. case Image::RGB:
  68429. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68430. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68431. break;
  68432. default:
  68433. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68434. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68435. break;
  68436. }
  68437. break;
  68438. }
  68439. }
  68440. template <class Iterator>
  68441. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68442. {
  68443. switch (destData.pixelFormat)
  68444. {
  68445. case Image::ARGB:
  68446. switch (srcData.pixelFormat)
  68447. {
  68448. case Image::ARGB:
  68449. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68450. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68451. break;
  68452. case Image::RGB:
  68453. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68454. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68455. break;
  68456. default:
  68457. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68458. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68459. break;
  68460. }
  68461. break;
  68462. case Image::RGB:
  68463. switch (srcData.pixelFormat)
  68464. {
  68465. case Image::ARGB:
  68466. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68467. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68468. break;
  68469. case Image::RGB:
  68470. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68471. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68472. break;
  68473. default:
  68474. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68475. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68476. break;
  68477. }
  68478. break;
  68479. default:
  68480. switch (srcData.pixelFormat)
  68481. {
  68482. case Image::ARGB:
  68483. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68484. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68485. break;
  68486. case Image::RGB:
  68487. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68488. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68489. break;
  68490. default:
  68491. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68492. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68493. break;
  68494. }
  68495. break;
  68496. }
  68497. }
  68498. template <class Iterator, class DestPixelType>
  68499. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68500. {
  68501. jassert (destData.pixelStride == sizeof (DestPixelType));
  68502. if (replaceContents)
  68503. {
  68504. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68505. iter.iterate (r);
  68506. }
  68507. else
  68508. {
  68509. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68510. iter.iterate (r);
  68511. }
  68512. }
  68513. template <class Iterator, class DestPixelType>
  68514. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68515. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68516. {
  68517. jassert (destData.pixelStride == sizeof (DestPixelType));
  68518. if (g.isRadial)
  68519. {
  68520. if (isIdentity)
  68521. {
  68522. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68523. iter.iterate (renderer);
  68524. }
  68525. else
  68526. {
  68527. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68528. iter.iterate (renderer);
  68529. }
  68530. }
  68531. else
  68532. {
  68533. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68534. iter.iterate (renderer);
  68535. }
  68536. }
  68537. };
  68538. class ClipRegion_EdgeTable : public ClipRegionBase
  68539. {
  68540. public:
  68541. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68542. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68543. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68544. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68545. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68546. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68547. ~ClipRegion_EdgeTable() {}
  68548. const Ptr clone() const
  68549. {
  68550. return new ClipRegion_EdgeTable (*this);
  68551. }
  68552. const Ptr applyClipTo (const Ptr& target) const
  68553. {
  68554. return target->clipToEdgeTable (edgeTable);
  68555. }
  68556. const Ptr clipToRectangle (const Rectangle<int>& r)
  68557. {
  68558. edgeTable.clipToRectangle (r);
  68559. return edgeTable.isEmpty() ? 0 : this;
  68560. }
  68561. const Ptr clipToRectangleList (const RectangleList& r)
  68562. {
  68563. RectangleList inverse (edgeTable.getMaximumBounds());
  68564. if (inverse.subtract (r))
  68565. for (RectangleList::Iterator iter (inverse); iter.next();)
  68566. edgeTable.excludeRectangle (*iter.getRectangle());
  68567. return edgeTable.isEmpty() ? 0 : this;
  68568. }
  68569. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68570. {
  68571. edgeTable.excludeRectangle (r);
  68572. return edgeTable.isEmpty() ? 0 : this;
  68573. }
  68574. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68575. {
  68576. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68577. edgeTable.clipToEdgeTable (et);
  68578. return edgeTable.isEmpty() ? 0 : this;
  68579. }
  68580. const Ptr clipToEdgeTable (const EdgeTable& et)
  68581. {
  68582. edgeTable.clipToEdgeTable (et);
  68583. return edgeTable.isEmpty() ? 0 : this;
  68584. }
  68585. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68586. {
  68587. const Image::BitmapData srcData (image, false);
  68588. if (transform.isOnlyTranslation())
  68589. {
  68590. // If our translation doesn't involve any distortion, just use a simple blit..
  68591. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68592. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68593. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68594. {
  68595. const int imageX = ((tx + 128) >> 8);
  68596. const int imageY = ((ty + 128) >> 8);
  68597. if (image.getFormat() == Image::ARGB)
  68598. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68599. else
  68600. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68601. return edgeTable.isEmpty() ? 0 : this;
  68602. }
  68603. }
  68604. if (transform.isSingularity())
  68605. return 0;
  68606. {
  68607. Path p;
  68608. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68609. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68610. edgeTable.clipToEdgeTable (et2);
  68611. }
  68612. if (! edgeTable.isEmpty())
  68613. {
  68614. if (image.getFormat() == Image::ARGB)
  68615. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68616. else
  68617. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68618. }
  68619. return edgeTable.isEmpty() ? 0 : this;
  68620. }
  68621. bool clipRegionIntersects (const Rectangle<int>& r) const
  68622. {
  68623. return edgeTable.getMaximumBounds().intersects (r);
  68624. }
  68625. const Rectangle<int> getClipBounds() const
  68626. {
  68627. return edgeTable.getMaximumBounds();
  68628. }
  68629. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68630. {
  68631. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68632. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68633. if (! clipped.isEmpty())
  68634. {
  68635. ClipRegion_EdgeTable et (clipped);
  68636. et.edgeTable.clipToEdgeTable (edgeTable);
  68637. et.fillAllWithColour (destData, colour, replaceContents);
  68638. }
  68639. }
  68640. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68641. {
  68642. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68643. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68644. if (! clipped.isEmpty())
  68645. {
  68646. ClipRegion_EdgeTable et (clipped);
  68647. et.edgeTable.clipToEdgeTable (edgeTable);
  68648. et.fillAllWithColour (destData, colour, false);
  68649. }
  68650. }
  68651. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68652. {
  68653. switch (destData.pixelFormat)
  68654. {
  68655. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68656. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68657. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68658. }
  68659. }
  68660. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68661. {
  68662. HeapBlock <PixelARGB> lookupTable;
  68663. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68664. jassert (numLookupEntries > 0);
  68665. switch (destData.pixelFormat)
  68666. {
  68667. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68668. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68669. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68670. }
  68671. }
  68672. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68673. {
  68674. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68675. }
  68676. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68677. {
  68678. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68679. }
  68680. EdgeTable edgeTable;
  68681. private:
  68682. template <class SrcPixelType>
  68683. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68684. {
  68685. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68686. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68687. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68688. edgeTable.getMaximumBounds().getWidth());
  68689. }
  68690. template <class SrcPixelType>
  68691. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68692. {
  68693. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68694. edgeTable.clipToRectangle (r);
  68695. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68696. for (int y = 0; y < r.getHeight(); ++y)
  68697. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68698. }
  68699. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68700. };
  68701. class ClipRegion_RectangleList : public ClipRegionBase
  68702. {
  68703. public:
  68704. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68705. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68706. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68707. ~ClipRegion_RectangleList() {}
  68708. const Ptr clone() const
  68709. {
  68710. return new ClipRegion_RectangleList (*this);
  68711. }
  68712. const Ptr applyClipTo (const Ptr& target) const
  68713. {
  68714. return target->clipToRectangleList (clip);
  68715. }
  68716. const Ptr clipToRectangle (const Rectangle<int>& r)
  68717. {
  68718. clip.clipTo (r);
  68719. return clip.isEmpty() ? 0 : this;
  68720. }
  68721. const Ptr clipToRectangleList (const RectangleList& r)
  68722. {
  68723. clip.clipTo (r);
  68724. return clip.isEmpty() ? 0 : this;
  68725. }
  68726. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68727. {
  68728. clip.subtract (r);
  68729. return clip.isEmpty() ? 0 : this;
  68730. }
  68731. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68732. {
  68733. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68734. }
  68735. const Ptr clipToEdgeTable (const EdgeTable& et)
  68736. {
  68737. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68738. }
  68739. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68740. {
  68741. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68742. }
  68743. bool clipRegionIntersects (const Rectangle<int>& r) const
  68744. {
  68745. return clip.intersects (r);
  68746. }
  68747. const Rectangle<int> getClipBounds() const
  68748. {
  68749. return clip.getBounds();
  68750. }
  68751. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68752. {
  68753. SubRectangleIterator iter (clip, area);
  68754. switch (destData.pixelFormat)
  68755. {
  68756. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68757. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68758. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68759. }
  68760. }
  68761. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68762. {
  68763. SubRectangleIteratorFloat iter (clip, area);
  68764. switch (destData.pixelFormat)
  68765. {
  68766. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68767. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68768. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68769. }
  68770. }
  68771. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68772. {
  68773. switch (destData.pixelFormat)
  68774. {
  68775. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68776. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68777. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68778. }
  68779. }
  68780. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68781. {
  68782. HeapBlock <PixelARGB> lookupTable;
  68783. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68784. jassert (numLookupEntries > 0);
  68785. switch (destData.pixelFormat)
  68786. {
  68787. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68788. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68789. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68790. }
  68791. }
  68792. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68793. {
  68794. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68795. }
  68796. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68797. {
  68798. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68799. }
  68800. RectangleList clip;
  68801. template <class Renderer>
  68802. void iterate (Renderer& r) const throw()
  68803. {
  68804. RectangleList::Iterator iter (clip);
  68805. while (iter.next())
  68806. {
  68807. const Rectangle<int> rect (*iter.getRectangle());
  68808. const int x = rect.getX();
  68809. const int w = rect.getWidth();
  68810. jassert (w > 0);
  68811. const int bottom = rect.getBottom();
  68812. for (int y = rect.getY(); y < bottom; ++y)
  68813. {
  68814. r.setEdgeTableYPos (y);
  68815. r.handleEdgeTableLineFull (x, w);
  68816. }
  68817. }
  68818. }
  68819. private:
  68820. class SubRectangleIterator
  68821. {
  68822. public:
  68823. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68824. : clip (clip_), area (area_)
  68825. {
  68826. }
  68827. template <class Renderer>
  68828. void iterate (Renderer& r) const throw()
  68829. {
  68830. RectangleList::Iterator iter (clip);
  68831. while (iter.next())
  68832. {
  68833. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68834. if (! rect.isEmpty())
  68835. {
  68836. const int x = rect.getX();
  68837. const int w = rect.getWidth();
  68838. const int bottom = rect.getBottom();
  68839. for (int y = rect.getY(); y < bottom; ++y)
  68840. {
  68841. r.setEdgeTableYPos (y);
  68842. r.handleEdgeTableLineFull (x, w);
  68843. }
  68844. }
  68845. }
  68846. }
  68847. private:
  68848. const RectangleList& clip;
  68849. const Rectangle<int> area;
  68850. SubRectangleIterator (const SubRectangleIterator&);
  68851. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68852. };
  68853. class SubRectangleIteratorFloat
  68854. {
  68855. public:
  68856. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68857. : clip (clip_), area (area_)
  68858. {
  68859. }
  68860. template <class Renderer>
  68861. void iterate (Renderer& r) const throw()
  68862. {
  68863. int left = roundToInt (area.getX() * 256.0f);
  68864. int top = roundToInt (area.getY() * 256.0f);
  68865. int right = roundToInt (area.getRight() * 256.0f);
  68866. int bottom = roundToInt (area.getBottom() * 256.0f);
  68867. int totalTop, totalLeft, totalBottom, totalRight;
  68868. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68869. if ((top >> 8) == (bottom >> 8))
  68870. {
  68871. topAlpha = bottom - top;
  68872. bottomAlpha = 0;
  68873. totalTop = top >> 8;
  68874. totalBottom = bottom = top = totalTop + 1;
  68875. }
  68876. else
  68877. {
  68878. if ((top & 255) == 0)
  68879. {
  68880. topAlpha = 0;
  68881. top = totalTop = (top >> 8);
  68882. }
  68883. else
  68884. {
  68885. topAlpha = 255 - (top & 255);
  68886. totalTop = (top >> 8);
  68887. top = totalTop + 1;
  68888. }
  68889. bottomAlpha = bottom & 255;
  68890. bottom >>= 8;
  68891. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68892. }
  68893. if ((left >> 8) == (right >> 8))
  68894. {
  68895. leftAlpha = right - left;
  68896. rightAlpha = 0;
  68897. totalLeft = (left >> 8);
  68898. totalRight = right = left = totalLeft + 1;
  68899. }
  68900. else
  68901. {
  68902. if ((left & 255) == 0)
  68903. {
  68904. leftAlpha = 0;
  68905. left = totalLeft = (left >> 8);
  68906. }
  68907. else
  68908. {
  68909. leftAlpha = 255 - (left & 255);
  68910. totalLeft = (left >> 8);
  68911. left = totalLeft + 1;
  68912. }
  68913. rightAlpha = right & 255;
  68914. right >>= 8;
  68915. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68916. }
  68917. RectangleList::Iterator iter (clip);
  68918. while (iter.next())
  68919. {
  68920. const int clipLeft = iter.getRectangle()->getX();
  68921. const int clipRight = iter.getRectangle()->getRight();
  68922. const int clipTop = iter.getRectangle()->getY();
  68923. const int clipBottom = iter.getRectangle()->getBottom();
  68924. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68925. {
  68926. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68927. {
  68928. if (topAlpha != 0 && totalTop >= clipTop)
  68929. {
  68930. r.setEdgeTableYPos (totalTop);
  68931. r.handleEdgeTablePixel (left, topAlpha);
  68932. }
  68933. const int endY = jmin (bottom, clipBottom);
  68934. for (int y = jmax (clipTop, top); y < endY; ++y)
  68935. {
  68936. r.setEdgeTableYPos (y);
  68937. r.handleEdgeTablePixelFull (left);
  68938. }
  68939. if (bottomAlpha != 0 && bottom < clipBottom)
  68940. {
  68941. r.setEdgeTableYPos (bottom);
  68942. r.handleEdgeTablePixel (left, bottomAlpha);
  68943. }
  68944. }
  68945. else
  68946. {
  68947. const int clippedLeft = jmax (left, clipLeft);
  68948. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68949. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68950. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68951. if (topAlpha != 0 && totalTop >= clipTop)
  68952. {
  68953. r.setEdgeTableYPos (totalTop);
  68954. if (doLeftAlpha)
  68955. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68956. if (clippedWidth > 0)
  68957. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68958. if (doRightAlpha)
  68959. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68960. }
  68961. const int endY = jmin (bottom, clipBottom);
  68962. for (int y = jmax (clipTop, top); y < endY; ++y)
  68963. {
  68964. r.setEdgeTableYPos (y);
  68965. if (doLeftAlpha)
  68966. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68967. if (clippedWidth > 0)
  68968. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68969. if (doRightAlpha)
  68970. r.handleEdgeTablePixel (right, rightAlpha);
  68971. }
  68972. if (bottomAlpha != 0 && bottom < clipBottom)
  68973. {
  68974. r.setEdgeTableYPos (bottom);
  68975. if (doLeftAlpha)
  68976. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68977. if (clippedWidth > 0)
  68978. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68979. if (doRightAlpha)
  68980. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68981. }
  68982. }
  68983. }
  68984. }
  68985. }
  68986. private:
  68987. const RectangleList& clip;
  68988. const Rectangle<float>& area;
  68989. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68990. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68991. };
  68992. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68993. };
  68994. }
  68995. class LowLevelGraphicsSoftwareRenderer::SavedState
  68996. {
  68997. public:
  68998. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68999. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  69000. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  69001. {
  69002. }
  69003. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  69004. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  69005. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  69006. {
  69007. }
  69008. SavedState (const SavedState& other)
  69009. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  69010. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  69011. {
  69012. }
  69013. ~SavedState()
  69014. {
  69015. }
  69016. void setOrigin (const int x, const int y) throw()
  69017. {
  69018. xOffset += x;
  69019. yOffset += y;
  69020. }
  69021. bool clipToRectangle (const Rectangle<int>& r)
  69022. {
  69023. if (clip != 0)
  69024. {
  69025. cloneClipIfMultiplyReferenced();
  69026. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  69027. }
  69028. return clip != 0;
  69029. }
  69030. bool clipToRectangleList (const RectangleList& r)
  69031. {
  69032. if (clip != 0)
  69033. {
  69034. cloneClipIfMultiplyReferenced();
  69035. RectangleList offsetList (r);
  69036. offsetList.offsetAll (xOffset, yOffset);
  69037. clip = clip->clipToRectangleList (offsetList);
  69038. }
  69039. return clip != 0;
  69040. }
  69041. bool excludeClipRectangle (const Rectangle<int>& r)
  69042. {
  69043. if (clip != 0)
  69044. {
  69045. cloneClipIfMultiplyReferenced();
  69046. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  69047. }
  69048. return clip != 0;
  69049. }
  69050. void clipToPath (const Path& p, const AffineTransform& transform)
  69051. {
  69052. if (clip != 0)
  69053. {
  69054. cloneClipIfMultiplyReferenced();
  69055. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  69056. }
  69057. }
  69058. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  69059. {
  69060. if (clip != 0)
  69061. {
  69062. if (image.hasAlphaChannel())
  69063. {
  69064. cloneClipIfMultiplyReferenced();
  69065. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  69066. interpolationQuality != Graphics::lowResamplingQuality);
  69067. }
  69068. else
  69069. {
  69070. Path p;
  69071. p.addRectangle (image.getBounds());
  69072. clipToPath (p, t);
  69073. }
  69074. }
  69075. }
  69076. bool clipRegionIntersects (const Rectangle<int>& r) const
  69077. {
  69078. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  69079. }
  69080. const Rectangle<int> getClipBounds() const
  69081. {
  69082. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  69083. }
  69084. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  69085. {
  69086. if (clip != 0)
  69087. {
  69088. if (fillType.isColour())
  69089. {
  69090. Image::BitmapData destData (image, true);
  69091. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  69092. }
  69093. else
  69094. {
  69095. const Rectangle<int> totalClip (clip->getClipBounds());
  69096. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  69097. if (! clipped.isEmpty())
  69098. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  69099. }
  69100. }
  69101. }
  69102. void fillRect (Image& image, const Rectangle<float>& r)
  69103. {
  69104. if (clip != 0)
  69105. {
  69106. if (fillType.isColour())
  69107. {
  69108. Image::BitmapData destData (image, true);
  69109. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  69110. }
  69111. else
  69112. {
  69113. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  69114. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  69115. if (! clipped.isEmpty())
  69116. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  69117. }
  69118. }
  69119. }
  69120. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  69121. {
  69122. if (clip != 0)
  69123. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  69124. }
  69125. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  69126. {
  69127. if (clip != 0)
  69128. {
  69129. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69130. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69131. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69132. fillShape (image, shapeToFill, false);
  69133. }
  69134. }
  69135. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69136. {
  69137. jassert (clip != 0);
  69138. shapeToFill = clip->applyClipTo (shapeToFill);
  69139. if (shapeToFill != 0)
  69140. {
  69141. Image::BitmapData destData (image, true);
  69142. if (fillType.isGradient())
  69143. {
  69144. jassert (! replaceContents); // that option is just for solid colours
  69145. ColourGradient g2 (*(fillType.gradient));
  69146. g2.multiplyOpacity (fillType.getOpacity());
  69147. g2.point1.addXY (-0.5f, -0.5f);
  69148. g2.point2.addXY (-0.5f, -0.5f);
  69149. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  69150. const bool isIdentity = transform.isOnlyTranslation();
  69151. if (isIdentity)
  69152. {
  69153. // If our translation doesn't involve any distortion, we can speed it up..
  69154. g2.point1.applyTransform (transform);
  69155. g2.point2.applyTransform (transform);
  69156. transform = AffineTransform::identity;
  69157. }
  69158. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69159. }
  69160. else if (fillType.isTiledImage())
  69161. {
  69162. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  69163. }
  69164. else
  69165. {
  69166. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69167. }
  69168. }
  69169. }
  69170. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69171. {
  69172. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  69173. const Image::BitmapData destData (destImage, true);
  69174. const Image::BitmapData srcData (sourceImage, false);
  69175. const int alpha = fillType.colour.getAlpha();
  69176. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69177. if (transform.isOnlyTranslation())
  69178. {
  69179. // If our translation doesn't involve any distortion, just use a simple blit..
  69180. int tx = (int) (transform.getTranslationX() * 256.0f);
  69181. int ty = (int) (transform.getTranslationY() * 256.0f);
  69182. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69183. {
  69184. tx = ((tx + 128) >> 8);
  69185. ty = ((ty + 128) >> 8);
  69186. if (tiledFillClipRegion != 0)
  69187. {
  69188. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69189. }
  69190. else
  69191. {
  69192. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  69193. c = clip->applyClipTo (c);
  69194. if (c != 0)
  69195. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69196. }
  69197. return;
  69198. }
  69199. }
  69200. if (transform.isSingularity())
  69201. return;
  69202. if (tiledFillClipRegion != 0)
  69203. {
  69204. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69205. }
  69206. else
  69207. {
  69208. Path p;
  69209. p.addRectangle (sourceImage.getBounds());
  69210. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69211. c = c->clipToPath (p, transform);
  69212. if (c != 0)
  69213. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69214. }
  69215. }
  69216. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69217. int xOffset, yOffset;
  69218. Font font;
  69219. FillType fillType;
  69220. Graphics::ResamplingQuality interpolationQuality;
  69221. private:
  69222. void cloneClipIfMultiplyReferenced()
  69223. {
  69224. if (clip->getReferenceCount() > 1)
  69225. clip = clip->clone();
  69226. }
  69227. SavedState& operator= (const SavedState&);
  69228. };
  69229. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69230. : image (image_)
  69231. {
  69232. currentState = new SavedState (image_.getBounds(), 0, 0);
  69233. }
  69234. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69235. const RectangleList& initialClip)
  69236. : image (image_)
  69237. {
  69238. currentState = new SavedState (initialClip, xOffset, yOffset);
  69239. }
  69240. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69241. {
  69242. }
  69243. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69244. {
  69245. return false;
  69246. }
  69247. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69248. {
  69249. currentState->setOrigin (x, y);
  69250. }
  69251. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69252. {
  69253. return currentState->clipToRectangle (r);
  69254. }
  69255. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69256. {
  69257. return currentState->clipToRectangleList (clipRegion);
  69258. }
  69259. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69260. {
  69261. currentState->excludeClipRectangle (r);
  69262. }
  69263. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69264. {
  69265. currentState->clipToPath (path, transform);
  69266. }
  69267. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69268. {
  69269. currentState->clipToImageAlpha (sourceImage, transform);
  69270. }
  69271. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69272. {
  69273. return currentState->clipRegionIntersects (r);
  69274. }
  69275. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69276. {
  69277. return currentState->getClipBounds();
  69278. }
  69279. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69280. {
  69281. return currentState->clip == 0;
  69282. }
  69283. void LowLevelGraphicsSoftwareRenderer::saveState()
  69284. {
  69285. stateStack.add (new SavedState (*currentState));
  69286. }
  69287. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69288. {
  69289. SavedState* const top = stateStack.getLast();
  69290. if (top != 0)
  69291. {
  69292. currentState = top;
  69293. stateStack.removeLast (1, false);
  69294. }
  69295. else
  69296. {
  69297. jassertfalse; // trying to pop with an empty stack!
  69298. }
  69299. }
  69300. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69301. {
  69302. currentState->fillType = fillType;
  69303. }
  69304. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69305. {
  69306. currentState->fillType.setOpacity (newOpacity);
  69307. }
  69308. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69309. {
  69310. currentState->interpolationQuality = quality;
  69311. }
  69312. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69313. {
  69314. currentState->fillRect (image, r, replaceExistingContents);
  69315. }
  69316. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69317. {
  69318. currentState->fillPath (image, path, transform);
  69319. }
  69320. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69321. {
  69322. currentState->renderImage (image, sourceImage, transform,
  69323. fillEntireClipAsTiles ? currentState->clip : 0);
  69324. }
  69325. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69326. {
  69327. Path p;
  69328. p.addLineSegment (line, 1.0f);
  69329. fillPath (p, AffineTransform::identity);
  69330. }
  69331. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69332. {
  69333. if (bottom > top)
  69334. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69335. }
  69336. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69337. {
  69338. if (right > left)
  69339. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69340. }
  69341. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69342. {
  69343. public:
  69344. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69345. ~CachedGlyph() {}
  69346. void draw (SavedState& state, Image& image, const float x, const float y) const
  69347. {
  69348. if (edgeTable != 0)
  69349. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69350. }
  69351. void generate (const Font& newFont, const int glyphNumber)
  69352. {
  69353. font = newFont;
  69354. glyph = glyphNumber;
  69355. edgeTable = 0;
  69356. Path glyphPath;
  69357. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69358. if (! glyphPath.isEmpty())
  69359. {
  69360. const float fontHeight = font.getHeight();
  69361. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69362. #if JUCE_MAC || JUCE_IOS
  69363. .translated (0.0f, -0.5f)
  69364. #endif
  69365. );
  69366. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69367. glyphPath, transform);
  69368. }
  69369. }
  69370. int glyph, lastAccessCount;
  69371. Font font;
  69372. juce_UseDebuggingNewOperator
  69373. private:
  69374. ScopedPointer <EdgeTable> edgeTable;
  69375. CachedGlyph (const CachedGlyph&);
  69376. CachedGlyph& operator= (const CachedGlyph&);
  69377. };
  69378. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69379. {
  69380. public:
  69381. GlyphCache()
  69382. : accessCounter (0), hits (0), misses (0)
  69383. {
  69384. for (int i = 120; --i >= 0;)
  69385. glyphs.add (new CachedGlyph());
  69386. }
  69387. ~GlyphCache()
  69388. {
  69389. clearSingletonInstance();
  69390. }
  69391. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69392. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69393. {
  69394. ++accessCounter;
  69395. int oldestCounter = std::numeric_limits<int>::max();
  69396. CachedGlyph* oldest = 0;
  69397. for (int i = glyphs.size(); --i >= 0;)
  69398. {
  69399. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69400. if (glyph->glyph == glyphNumber && glyph->font == font)
  69401. {
  69402. ++hits;
  69403. glyph->lastAccessCount = accessCounter;
  69404. glyph->draw (state, image, x, y);
  69405. return;
  69406. }
  69407. if (glyph->lastAccessCount <= oldestCounter)
  69408. {
  69409. oldestCounter = glyph->lastAccessCount;
  69410. oldest = glyph;
  69411. }
  69412. }
  69413. if (hits + ++misses > (glyphs.size() << 4))
  69414. {
  69415. if (misses * 2 > hits)
  69416. {
  69417. for (int i = 32; --i >= 0;)
  69418. glyphs.add (new CachedGlyph());
  69419. }
  69420. hits = misses = 0;
  69421. oldest = glyphs.getLast();
  69422. }
  69423. jassert (oldest != 0);
  69424. oldest->lastAccessCount = accessCounter;
  69425. oldest->generate (font, glyphNumber);
  69426. oldest->draw (state, image, x, y);
  69427. }
  69428. juce_UseDebuggingNewOperator
  69429. private:
  69430. friend class OwnedArray <CachedGlyph>;
  69431. OwnedArray <CachedGlyph> glyphs;
  69432. int accessCounter, hits, misses;
  69433. GlyphCache (const GlyphCache&);
  69434. GlyphCache& operator= (const GlyphCache&);
  69435. };
  69436. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69437. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69438. {
  69439. currentState->font = newFont;
  69440. }
  69441. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69442. {
  69443. return currentState->font;
  69444. }
  69445. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69446. {
  69447. Font& f = currentState->font;
  69448. if (transform.isOnlyTranslation())
  69449. {
  69450. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69451. transform.getTranslationX(),
  69452. transform.getTranslationY());
  69453. }
  69454. else
  69455. {
  69456. Path p;
  69457. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69458. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69459. }
  69460. }
  69461. #if JUCE_MSVC
  69462. #pragma warning (pop)
  69463. #if JUCE_DEBUG
  69464. #pragma optimize ("", on) // resets optimisations to the project defaults
  69465. #endif
  69466. #endif
  69467. END_JUCE_NAMESPACE
  69468. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69469. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69470. BEGIN_JUCE_NAMESPACE
  69471. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69472. : flags (other.flags)
  69473. {
  69474. }
  69475. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69476. {
  69477. flags = other.flags;
  69478. return *this;
  69479. }
  69480. void RectanglePlacement::applyTo (double& x, double& y,
  69481. double& w, double& h,
  69482. const double dx, const double dy,
  69483. const double dw, const double dh) const throw()
  69484. {
  69485. if (w == 0 || h == 0)
  69486. return;
  69487. if ((flags & stretchToFit) != 0)
  69488. {
  69489. x = dx;
  69490. y = dy;
  69491. w = dw;
  69492. h = dh;
  69493. }
  69494. else
  69495. {
  69496. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69497. : jmin (dw / w, dh / h);
  69498. if ((flags & onlyReduceInSize) != 0)
  69499. scale = jmin (scale, 1.0);
  69500. if ((flags & onlyIncreaseInSize) != 0)
  69501. scale = jmax (scale, 1.0);
  69502. w *= scale;
  69503. h *= scale;
  69504. if ((flags & xLeft) != 0)
  69505. x = dx;
  69506. else if ((flags & xRight) != 0)
  69507. x = dx + dw - w;
  69508. else
  69509. x = dx + (dw - w) * 0.5;
  69510. if ((flags & yTop) != 0)
  69511. y = dy;
  69512. else if ((flags & yBottom) != 0)
  69513. y = dy + dh - h;
  69514. else
  69515. y = dy + (dh - h) * 0.5;
  69516. }
  69517. }
  69518. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  69519. float w, float h,
  69520. const float dx, const float dy,
  69521. const float dw, const float dh) const throw()
  69522. {
  69523. if (w == 0 || h == 0)
  69524. return AffineTransform::identity;
  69525. const float scaleX = dw / w;
  69526. const float scaleY = dh / h;
  69527. if ((flags & stretchToFit) != 0)
  69528. return AffineTransform::translation (-x, -y)
  69529. .scaled (scaleX, scaleY)
  69530. .translated (dx, dy);
  69531. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69532. : jmin (scaleX, scaleY);
  69533. if ((flags & onlyReduceInSize) != 0)
  69534. scale = jmin (scale, 1.0f);
  69535. if ((flags & onlyIncreaseInSize) != 0)
  69536. scale = jmax (scale, 1.0f);
  69537. w *= scale;
  69538. h *= scale;
  69539. float newX = dx;
  69540. if ((flags & xRight) != 0)
  69541. newX += dw - w; // right
  69542. else if ((flags & xLeft) == 0)
  69543. newX += (dw - w) / 2.0f; // centre
  69544. float newY = dy;
  69545. if ((flags & yBottom) != 0)
  69546. newY += dh - h; // bottom
  69547. else if ((flags & yTop) == 0)
  69548. newY += (dh - h) / 2.0f; // centre
  69549. return AffineTransform::translation (-x, -y)
  69550. .scaled (scale, scale)
  69551. .translated (newX, newY);
  69552. }
  69553. END_JUCE_NAMESPACE
  69554. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69555. /*** Start of inlined file: juce_Drawable.cpp ***/
  69556. BEGIN_JUCE_NAMESPACE
  69557. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69558. const AffineTransform& transform_,
  69559. const float opacity_) throw()
  69560. : g (g_),
  69561. transform (transform_),
  69562. opacity (opacity_)
  69563. {
  69564. }
  69565. Drawable::Drawable()
  69566. : parent (0)
  69567. {
  69568. }
  69569. Drawable::~Drawable()
  69570. {
  69571. }
  69572. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69573. {
  69574. render (RenderingContext (g, transform, opacity));
  69575. }
  69576. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69577. {
  69578. draw (g, opacity, AffineTransform::translation (x, y));
  69579. }
  69580. void Drawable::drawWithin (Graphics& g,
  69581. const int destX,
  69582. const int destY,
  69583. const int destW,
  69584. const int destH,
  69585. const RectanglePlacement& placement,
  69586. const float opacity) const
  69587. {
  69588. if (destW > 0 && destH > 0)
  69589. {
  69590. Rectangle<float> bounds (getBounds());
  69591. draw (g, opacity,
  69592. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  69593. (float) destX, (float) destY,
  69594. (float) destW, (float) destH));
  69595. }
  69596. }
  69597. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69598. {
  69599. Drawable* result = 0;
  69600. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69601. if (image.isValid())
  69602. {
  69603. DrawableImage* const di = new DrawableImage();
  69604. di->setImage (image);
  69605. result = di;
  69606. }
  69607. else
  69608. {
  69609. const String asString (String::createStringFromData (data, (int) numBytes));
  69610. XmlDocument doc (asString);
  69611. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69612. if (outer != 0 && outer->hasTagName ("svg"))
  69613. {
  69614. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69615. if (svg != 0)
  69616. result = Drawable::createFromSVG (*svg);
  69617. }
  69618. }
  69619. return result;
  69620. }
  69621. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69622. {
  69623. MemoryOutputStream mo;
  69624. mo.writeFromInputStream (dataSource, -1);
  69625. return createFromImageData (mo.getData(), mo.getDataSize());
  69626. }
  69627. Drawable* Drawable::createFromImageFile (const File& file)
  69628. {
  69629. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69630. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69631. }
  69632. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69633. {
  69634. return createChildFromValueTree (0, tree, imageProvider);
  69635. }
  69636. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69637. {
  69638. const Identifier type (tree.getType());
  69639. Drawable* d = 0;
  69640. if (type == DrawablePath::valueTreeType)
  69641. d = new DrawablePath();
  69642. else if (type == DrawableComposite::valueTreeType)
  69643. d = new DrawableComposite();
  69644. else if (type == DrawableImage::valueTreeType)
  69645. d = new DrawableImage();
  69646. else if (type == DrawableText::valueTreeType)
  69647. d = new DrawableText();
  69648. if (d != 0)
  69649. {
  69650. d->parent = parent;
  69651. d->refreshFromValueTree (tree, imageProvider);
  69652. }
  69653. return d;
  69654. }
  69655. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69656. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  69657. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  69658. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  69659. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  69660. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  69661. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  69662. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  69663. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  69664. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  69665. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69666. : state (state_)
  69667. {
  69668. }
  69669. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69670. {
  69671. }
  69672. const String Drawable::ValueTreeWrapperBase::getID() const
  69673. {
  69674. return state [idProperty];
  69675. }
  69676. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69677. {
  69678. if (newID.isEmpty())
  69679. state.removeProperty (idProperty, undoManager);
  69680. else
  69681. state.setProperty (idProperty, newID, undoManager);
  69682. }
  69683. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69684. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69685. {
  69686. const String newType (v[type].toString());
  69687. if (newType == "solid")
  69688. {
  69689. const String colourString (v [colour].toString());
  69690. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69691. : (uint32) colourString.getHexValue32()));
  69692. }
  69693. else if (newType == "gradient")
  69694. {
  69695. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69696. ColourGradient g;
  69697. if (gp1 != 0) *gp1 = p1;
  69698. if (gp2 != 0) *gp2 = p2;
  69699. if (gp3 != 0) *gp3 = p3;
  69700. g.point1 = p1.resolve (nameFinder);
  69701. g.point2 = p2.resolve (nameFinder);
  69702. g.isRadial = v[radial];
  69703. StringArray colourSteps;
  69704. colourSteps.addTokens (v[colours].toString(), false);
  69705. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69706. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69707. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69708. FillType fillType (g);
  69709. if (g.isRadial)
  69710. {
  69711. const Point<float> point3 (p3.resolve (nameFinder));
  69712. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69713. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69714. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69715. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69716. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69717. }
  69718. return fillType;
  69719. }
  69720. else if (newType == "image")
  69721. {
  69722. Image im;
  69723. if (imageProvider != 0)
  69724. im = imageProvider->getImageForIdentifier (v[imageId]);
  69725. FillType f (im, AffineTransform::identity);
  69726. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69727. return f;
  69728. }
  69729. jassertfalse;
  69730. return FillType();
  69731. }
  69732. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69733. {
  69734. const ColourGradient& g = *fillType.gradient;
  69735. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69736. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69737. return point3Source.transformedBy (fillType.transform);
  69738. }
  69739. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  69740. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69741. ImageProvider* imageProvider, UndoManager* const undoManager)
  69742. {
  69743. if (fillType.isColour())
  69744. {
  69745. v.setProperty (type, "solid", undoManager);
  69746. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69747. }
  69748. else if (fillType.isGradient())
  69749. {
  69750. v.setProperty (type, "gradient", undoManager);
  69751. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69752. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69753. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  69754. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69755. String s;
  69756. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69757. s << ' ' << fillType.gradient->getColourPosition (i)
  69758. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69759. v.setProperty (colours, s.trimStart(), undoManager);
  69760. }
  69761. else if (fillType.isTiledImage())
  69762. {
  69763. v.setProperty (type, "image", undoManager);
  69764. if (imageProvider != 0)
  69765. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69766. if (fillType.getOpacity() < 1.0f)
  69767. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69768. else
  69769. v.removeProperty (imageOpacity, undoManager);
  69770. }
  69771. else
  69772. {
  69773. jassertfalse;
  69774. }
  69775. }
  69776. END_JUCE_NAMESPACE
  69777. /*** End of inlined file: juce_Drawable.cpp ***/
  69778. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69779. BEGIN_JUCE_NAMESPACE
  69780. DrawableComposite::DrawableComposite()
  69781. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69782. {
  69783. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69784. RelativeCoordinate (100.0),
  69785. RelativeCoordinate (0.0),
  69786. RelativeCoordinate (100.0)));
  69787. }
  69788. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69789. {
  69790. bounds = other.bounds;
  69791. for (int i = 0; i < other.drawables.size(); ++i)
  69792. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69793. markersX.addCopiesOf (other.markersX);
  69794. markersY.addCopiesOf (other.markersY);
  69795. }
  69796. DrawableComposite::~DrawableComposite()
  69797. {
  69798. }
  69799. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69800. {
  69801. if (drawable != 0)
  69802. {
  69803. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69804. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69805. drawables.insert (index, drawable);
  69806. drawable->parent = this;
  69807. }
  69808. }
  69809. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69810. {
  69811. insertDrawable (drawable.createCopy(), index);
  69812. }
  69813. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69814. {
  69815. drawables.remove (index, deleteDrawable);
  69816. }
  69817. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69818. {
  69819. for (int i = drawables.size(); --i >= 0;)
  69820. if (drawables.getUnchecked(i)->getName() == name)
  69821. return drawables.getUnchecked(i);
  69822. return 0;
  69823. }
  69824. void DrawableComposite::bringToFront (const int index)
  69825. {
  69826. if (index >= 0 && index < drawables.size() - 1)
  69827. drawables.move (index, -1);
  69828. }
  69829. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69830. {
  69831. bounds = newBoundingBox;
  69832. }
  69833. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69834. : name (other.name), position (other.position)
  69835. {
  69836. }
  69837. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69838. : name (name_), position (position_)
  69839. {
  69840. }
  69841. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69842. {
  69843. return name != other.name || position != other.position;
  69844. }
  69845. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69846. const char* const DrawableComposite::contentRightMarkerName ("right");
  69847. const char* const DrawableComposite::contentTopMarkerName ("top");
  69848. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69849. const RelativeRectangle DrawableComposite::getContentArea() const
  69850. {
  69851. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69852. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69853. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69854. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69855. }
  69856. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69857. {
  69858. setMarker (contentLeftMarkerName, true, newArea.left);
  69859. setMarker (contentRightMarkerName, true, newArea.right);
  69860. setMarker (contentTopMarkerName, false, newArea.top);
  69861. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69862. }
  69863. void DrawableComposite::resetBoundingBoxToContentArea()
  69864. {
  69865. const RelativeRectangle content (getContentArea());
  69866. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69867. RelativePoint (content.right, content.top),
  69868. RelativePoint (content.left, content.bottom)));
  69869. }
  69870. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69871. {
  69872. const Rectangle<float> bounds (getUntransformedBounds (false));
  69873. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69874. RelativeCoordinate (bounds.getRight()),
  69875. RelativeCoordinate (bounds.getY()),
  69876. RelativeCoordinate (bounds.getBottom())));
  69877. resetBoundingBoxToContentArea();
  69878. }
  69879. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69880. {
  69881. return (xAxis ? markersX : markersY).size();
  69882. }
  69883. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69884. {
  69885. return (xAxis ? markersX : markersY) [index];
  69886. }
  69887. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69888. {
  69889. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69890. for (int i = 0; i < markers.size(); ++i)
  69891. {
  69892. Marker* const m = markers.getUnchecked(i);
  69893. if (m->name == name)
  69894. {
  69895. if (m->position != position)
  69896. {
  69897. m->position = position;
  69898. invalidatePoints();
  69899. }
  69900. return;
  69901. }
  69902. }
  69903. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69904. invalidatePoints();
  69905. }
  69906. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69907. {
  69908. jassert (index >= 2);
  69909. if (index >= 2)
  69910. (xAxis ? markersX : markersY).remove (index);
  69911. }
  69912. const AffineTransform DrawableComposite::calculateTransform() const
  69913. {
  69914. Point<float> resolved[3];
  69915. bounds.resolveThreePoints (resolved, parent);
  69916. const Rectangle<float> content (getContentArea().resolve (parent));
  69917. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69918. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69919. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69920. }
  69921. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69922. {
  69923. if (drawables.size() > 0 && context.opacity > 0)
  69924. {
  69925. if (context.opacity >= 1.0f || drawables.size() == 1)
  69926. {
  69927. Drawable::RenderingContext contextCopy (context);
  69928. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69929. for (int i = 0; i < drawables.size(); ++i)
  69930. drawables.getUnchecked(i)->render (contextCopy);
  69931. }
  69932. else
  69933. {
  69934. // To correctly render a whole composite layer with an overall transparency,
  69935. // we need to render everything opaquely into a temp buffer, then blend that
  69936. // with the target opacity...
  69937. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69938. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69939. {
  69940. Graphics tempG (tempImage);
  69941. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69942. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69943. render (tempContext);
  69944. }
  69945. context.g.setOpacity (context.opacity);
  69946. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69947. }
  69948. }
  69949. }
  69950. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69951. {
  69952. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69953. int i;
  69954. for (i = 0; i < markersX.size(); ++i)
  69955. {
  69956. Marker* const m = markersX.getUnchecked(i);
  69957. if (m->name == symbol)
  69958. return m->position.getExpression();
  69959. }
  69960. for (i = 0; i < markersY.size(); ++i)
  69961. {
  69962. Marker* const m = markersY.getUnchecked(i);
  69963. if (m->name == symbol)
  69964. return m->position.getExpression();
  69965. }
  69966. return Expression::EvaluationContext::getSymbolValue (symbol, member);
  69967. }
  69968. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69969. {
  69970. Rectangle<float> bounds;
  69971. int i;
  69972. for (i = 0; i < drawables.size(); ++i)
  69973. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69974. if (includeMarkers)
  69975. {
  69976. if (markersX.size() > 0)
  69977. {
  69978. float minX = std::numeric_limits<float>::max();
  69979. float maxX = std::numeric_limits<float>::min();
  69980. for (i = markersX.size(); --i >= 0;)
  69981. {
  69982. const Marker* m = markersX.getUnchecked(i);
  69983. const float pos = (float) m->position.resolve (this);
  69984. minX = jmin (minX, pos);
  69985. maxX = jmax (maxX, pos);
  69986. }
  69987. if (minX <= maxX)
  69988. {
  69989. if (bounds.getHeight() > 0)
  69990. {
  69991. minX = jmin (minX, bounds.getX());
  69992. maxX = jmax (maxX, bounds.getRight());
  69993. }
  69994. bounds.setLeft (minX);
  69995. bounds.setWidth (maxX - minX);
  69996. }
  69997. }
  69998. if (markersY.size() > 0)
  69999. {
  70000. float minY = std::numeric_limits<float>::max();
  70001. float maxY = std::numeric_limits<float>::min();
  70002. for (i = markersY.size(); --i >= 0;)
  70003. {
  70004. const Marker* m = markersY.getUnchecked(i);
  70005. const float pos = (float) m->position.resolve (this);
  70006. minY = jmin (minY, pos);
  70007. maxY = jmax (maxY, pos);
  70008. }
  70009. if (minY <= maxY)
  70010. {
  70011. if (bounds.getHeight() > 0)
  70012. {
  70013. minY = jmin (minY, bounds.getY());
  70014. maxY = jmax (maxY, bounds.getBottom());
  70015. }
  70016. bounds.setTop (minY);
  70017. bounds.setHeight (maxY - minY);
  70018. }
  70019. }
  70020. }
  70021. return bounds;
  70022. }
  70023. const Rectangle<float> DrawableComposite::getBounds() const
  70024. {
  70025. return getUntransformedBounds (true).transformed (calculateTransform());
  70026. }
  70027. bool DrawableComposite::hitTest (float x, float y) const
  70028. {
  70029. calculateTransform().inverted().transformPoint (x, y);
  70030. for (int i = 0; i < drawables.size(); ++i)
  70031. if (drawables.getUnchecked(i)->hitTest (x, y))
  70032. return true;
  70033. return false;
  70034. }
  70035. Drawable* DrawableComposite::createCopy() const
  70036. {
  70037. return new DrawableComposite (*this);
  70038. }
  70039. void DrawableComposite::invalidatePoints()
  70040. {
  70041. for (int i = 0; i < drawables.size(); ++i)
  70042. drawables.getUnchecked(i)->invalidatePoints();
  70043. }
  70044. const Identifier DrawableComposite::valueTreeType ("Group");
  70045. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70046. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70047. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70048. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70049. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70050. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70051. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  70052. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  70053. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  70054. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70055. : ValueTreeWrapperBase (state_)
  70056. {
  70057. jassert (state.hasType (valueTreeType));
  70058. }
  70059. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70060. {
  70061. return state.getChildWithName (childGroupTag);
  70062. }
  70063. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70064. {
  70065. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70066. }
  70067. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  70068. {
  70069. return getChildList().getNumChildren();
  70070. }
  70071. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  70072. {
  70073. return getChildList().getChild (index);
  70074. }
  70075. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  70076. {
  70077. if (getID() == objectId)
  70078. return state;
  70079. if (! recursive)
  70080. {
  70081. return getChildList().getChildWithProperty (idProperty, objectId);
  70082. }
  70083. else
  70084. {
  70085. const ValueTree childList (getChildList());
  70086. for (int i = getNumDrawables(); --i >= 0;)
  70087. {
  70088. const ValueTree& child = childList.getChild (i);
  70089. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  70090. return child;
  70091. if (child.hasType (DrawableComposite::valueTreeType))
  70092. {
  70093. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  70094. if (v.isValid())
  70095. return v;
  70096. }
  70097. }
  70098. return ValueTree::invalid;
  70099. }
  70100. }
  70101. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  70102. {
  70103. return getChildList().indexOf (item);
  70104. }
  70105. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  70106. {
  70107. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  70108. }
  70109. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  70110. {
  70111. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  70112. }
  70113. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  70114. {
  70115. getChildList().removeChild (child, undoManager);
  70116. }
  70117. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70118. {
  70119. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70120. state.getProperty (topRight, "100, 0"),
  70121. state.getProperty (bottomLeft, "0, 100"));
  70122. }
  70123. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70124. {
  70125. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70126. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70127. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70128. }
  70129. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70130. {
  70131. const RelativeRectangle content (getContentArea());
  70132. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70133. RelativePoint (content.right, content.top),
  70134. RelativePoint (content.left, content.bottom)), undoManager);
  70135. }
  70136. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70137. {
  70138. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  70139. getMarker (true, getMarkerState (true, 1)).position,
  70140. getMarker (false, getMarkerState (false, 0)).position,
  70141. getMarker (false, getMarkerState (false, 1)).position);
  70142. }
  70143. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70144. {
  70145. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  70146. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  70147. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  70148. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70149. }
  70150. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70151. {
  70152. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70153. }
  70154. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70155. {
  70156. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70157. }
  70158. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  70159. {
  70160. return getMarkerList (xAxis).getNumChildren();
  70161. }
  70162. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  70163. {
  70164. return getMarkerList (xAxis).getChild (index);
  70165. }
  70166. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  70167. {
  70168. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  70169. }
  70170. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  70171. {
  70172. return state.isAChildOf (getMarkerList (xAxis));
  70173. }
  70174. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70175. {
  70176. jassert (containsMarker (xAxis, state));
  70177. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70178. }
  70179. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70180. {
  70181. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70182. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70183. if (marker.isValid())
  70184. {
  70185. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70186. }
  70187. else
  70188. {
  70189. marker = ValueTree (markerTag);
  70190. marker.setProperty (nameProperty, m.name, 0);
  70191. marker.setProperty (posProperty, m.position.toString(), 0);
  70192. markerList.addChild (marker, -1, undoManager);
  70193. }
  70194. }
  70195. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70196. {
  70197. if (state [nameProperty].toString() != contentLeftMarkerName
  70198. && state [nameProperty].toString() != contentRightMarkerName
  70199. && state [nameProperty].toString() != contentTopMarkerName
  70200. && state [nameProperty].toString() != contentBottomMarkerName)
  70201. return getMarkerList (xAxis).removeChild (state, undoManager);
  70202. }
  70203. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70204. {
  70205. const ValueTreeWrapper wrapper (tree);
  70206. setName (wrapper.getID());
  70207. Rectangle<float> damage;
  70208. bool redrawAll = false;
  70209. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70210. if (bounds != newBounds)
  70211. {
  70212. redrawAll = true;
  70213. damage = getBounds();
  70214. bounds = newBounds;
  70215. }
  70216. const int numMarkersX = wrapper.getNumMarkers (true);
  70217. const int numMarkersY = wrapper.getNumMarkers (false);
  70218. // Remove deleted markers...
  70219. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70220. {
  70221. if (! redrawAll)
  70222. {
  70223. redrawAll = true;
  70224. damage = getBounds();
  70225. }
  70226. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70227. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70228. }
  70229. // Update markers and add new ones..
  70230. int i;
  70231. for (i = 0; i < numMarkersX; ++i)
  70232. {
  70233. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70234. Marker* m = markersX[i];
  70235. if (m == 0 || newMarker != *m)
  70236. {
  70237. if (! redrawAll)
  70238. {
  70239. redrawAll = true;
  70240. damage = getBounds();
  70241. }
  70242. if (m == 0)
  70243. markersX.add (new Marker (newMarker));
  70244. else
  70245. *m = newMarker;
  70246. }
  70247. }
  70248. for (i = 0; i < numMarkersY; ++i)
  70249. {
  70250. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70251. Marker* m = markersY[i];
  70252. if (m == 0 || newMarker != *m)
  70253. {
  70254. if (! redrawAll)
  70255. {
  70256. redrawAll = true;
  70257. damage = getBounds();
  70258. }
  70259. if (m == 0)
  70260. markersY.add (new Marker (newMarker));
  70261. else
  70262. *m = newMarker;
  70263. }
  70264. }
  70265. // Remove deleted drawables..
  70266. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70267. {
  70268. Drawable* const d = drawables.getUnchecked(i);
  70269. if (! redrawAll)
  70270. damage = damage.getUnion (d->getBounds());
  70271. d->parent = 0;
  70272. drawables.remove (i);
  70273. }
  70274. // Update drawables and add new ones..
  70275. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70276. {
  70277. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70278. Drawable* d = drawables[i];
  70279. if (d != 0)
  70280. {
  70281. if (newDrawable.hasType (d->getValueTreeType()))
  70282. {
  70283. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70284. if (! redrawAll)
  70285. damage = damage.getUnion (area);
  70286. }
  70287. else
  70288. {
  70289. if (! redrawAll)
  70290. damage = damage.getUnion (d->getBounds());
  70291. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70292. drawables.set (i, d);
  70293. if (! redrawAll)
  70294. damage = damage.getUnion (d->getBounds());
  70295. }
  70296. }
  70297. else
  70298. {
  70299. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70300. drawables.set (i, d);
  70301. if (! redrawAll)
  70302. damage = damage.getUnion (d->getBounds());
  70303. }
  70304. }
  70305. if (redrawAll)
  70306. damage = damage.getUnion (getBounds());
  70307. else if (! damage.isEmpty())
  70308. damage = damage.transformed (calculateTransform());
  70309. return damage;
  70310. }
  70311. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70312. {
  70313. ValueTree tree (valueTreeType);
  70314. ValueTreeWrapper v (tree);
  70315. v.setID (getName(), 0);
  70316. v.setBoundingBox (bounds, 0);
  70317. int i;
  70318. for (i = 0; i < drawables.size(); ++i)
  70319. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70320. for (i = 0; i < markersX.size(); ++i)
  70321. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70322. for (i = 0; i < markersY.size(); ++i)
  70323. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70324. return tree;
  70325. }
  70326. END_JUCE_NAMESPACE
  70327. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70328. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70329. BEGIN_JUCE_NAMESPACE
  70330. DrawableImage::DrawableImage()
  70331. : image (0),
  70332. opacity (1.0f),
  70333. overlayColour (0x00000000)
  70334. {
  70335. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70336. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70337. }
  70338. DrawableImage::DrawableImage (const DrawableImage& other)
  70339. : image (other.image),
  70340. opacity (other.opacity),
  70341. overlayColour (other.overlayColour),
  70342. bounds (other.bounds)
  70343. {
  70344. }
  70345. DrawableImage::~DrawableImage()
  70346. {
  70347. }
  70348. void DrawableImage::setImage (const Image& imageToUse)
  70349. {
  70350. image = imageToUse;
  70351. if (image.isValid())
  70352. {
  70353. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70354. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70355. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70356. }
  70357. }
  70358. void DrawableImage::setOpacity (const float newOpacity)
  70359. {
  70360. opacity = newOpacity;
  70361. }
  70362. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70363. {
  70364. overlayColour = newOverlayColour;
  70365. }
  70366. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70367. {
  70368. bounds = newBounds;
  70369. }
  70370. const AffineTransform DrawableImage::calculateTransform() const
  70371. {
  70372. if (image.isNull())
  70373. return AffineTransform::identity;
  70374. Point<float> resolved[3];
  70375. bounds.resolveThreePoints (resolved, parent);
  70376. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70377. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70378. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70379. tr.getX(), tr.getY(),
  70380. bl.getX(), bl.getY());
  70381. }
  70382. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70383. {
  70384. if (image.isValid())
  70385. {
  70386. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70387. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70388. {
  70389. context.g.setOpacity (context.opacity * opacity);
  70390. context.g.drawImageTransformed (image, t, false);
  70391. }
  70392. if (! overlayColour.isTransparent())
  70393. {
  70394. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70395. context.g.drawImageTransformed (image, t, true);
  70396. }
  70397. }
  70398. }
  70399. const Rectangle<float> DrawableImage::getBounds() const
  70400. {
  70401. if (image.isNull())
  70402. return Rectangle<float>();
  70403. return bounds.getBounds (parent);
  70404. }
  70405. bool DrawableImage::hitTest (float x, float y) const
  70406. {
  70407. if (image.isNull())
  70408. return false;
  70409. calculateTransform().inverted().transformPoint (x, y);
  70410. const int ix = roundToInt (x);
  70411. const int iy = roundToInt (y);
  70412. return ix >= 0
  70413. && iy >= 0
  70414. && ix < image.getWidth()
  70415. && iy < image.getHeight()
  70416. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70417. }
  70418. Drawable* DrawableImage::createCopy() const
  70419. {
  70420. return new DrawableImage (*this);
  70421. }
  70422. void DrawableImage::invalidatePoints()
  70423. {
  70424. }
  70425. const Identifier DrawableImage::valueTreeType ("Image");
  70426. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70427. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70428. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70429. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70430. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70431. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70432. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70433. : ValueTreeWrapperBase (state_)
  70434. {
  70435. jassert (state.hasType (valueTreeType));
  70436. }
  70437. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70438. {
  70439. return state [image];
  70440. }
  70441. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70442. {
  70443. return state.getPropertyAsValue (image, undoManager);
  70444. }
  70445. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70446. {
  70447. state.setProperty (image, newIdentifier, undoManager);
  70448. }
  70449. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70450. {
  70451. return (float) state.getProperty (opacity, 1.0);
  70452. }
  70453. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70454. {
  70455. if (! state.hasProperty (opacity))
  70456. state.setProperty (opacity, 1.0, undoManager);
  70457. return state.getPropertyAsValue (opacity, undoManager);
  70458. }
  70459. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70460. {
  70461. state.setProperty (opacity, newOpacity, undoManager);
  70462. }
  70463. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70464. {
  70465. return Colour (state [overlay].toString().getHexValue32());
  70466. }
  70467. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70468. {
  70469. if (newColour.isTransparent())
  70470. state.removeProperty (overlay, undoManager);
  70471. else
  70472. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70473. }
  70474. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70475. {
  70476. return state.getPropertyAsValue (overlay, undoManager);
  70477. }
  70478. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70479. {
  70480. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70481. state.getProperty (topRight, "100, 0"),
  70482. state.getProperty (bottomLeft, "0, 100"));
  70483. }
  70484. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70485. {
  70486. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70487. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70488. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70489. }
  70490. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70491. {
  70492. const ValueTreeWrapper controller (tree);
  70493. setName (controller.getID());
  70494. const float newOpacity = controller.getOpacity();
  70495. const Colour newOverlayColour (controller.getOverlayColour());
  70496. Image newImage;
  70497. const var imageIdentifier (controller.getImageIdentifier());
  70498. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70499. if (imageProvider != 0)
  70500. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70501. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70502. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70503. {
  70504. const Rectangle<float> damage (getBounds());
  70505. opacity = newOpacity;
  70506. overlayColour = newOverlayColour;
  70507. bounds = newBounds;
  70508. image = newImage;
  70509. return damage.getUnion (getBounds());
  70510. }
  70511. return Rectangle<float>();
  70512. }
  70513. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70514. {
  70515. ValueTree tree (valueTreeType);
  70516. ValueTreeWrapper v (tree);
  70517. v.setID (getName(), 0);
  70518. v.setOpacity (opacity, 0);
  70519. v.setOverlayColour (overlayColour, 0);
  70520. v.setBoundingBox (bounds, 0);
  70521. if (image.isValid())
  70522. {
  70523. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70524. if (imageProvider != 0)
  70525. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70526. }
  70527. return tree;
  70528. }
  70529. END_JUCE_NAMESPACE
  70530. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70531. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70532. BEGIN_JUCE_NAMESPACE
  70533. DrawablePath::DrawablePath()
  70534. : mainFill (Colours::black),
  70535. strokeFill (Colours::black),
  70536. strokeType (0.0f),
  70537. pathNeedsUpdating (true),
  70538. strokeNeedsUpdating (true)
  70539. {
  70540. }
  70541. DrawablePath::DrawablePath (const DrawablePath& other)
  70542. : mainFill (other.mainFill),
  70543. strokeFill (other.strokeFill),
  70544. strokeType (other.strokeType),
  70545. pathNeedsUpdating (true),
  70546. strokeNeedsUpdating (true)
  70547. {
  70548. if (other.relativePath != 0)
  70549. relativePath = new RelativePointPath (*other.relativePath);
  70550. else
  70551. path = other.path;
  70552. }
  70553. DrawablePath::~DrawablePath()
  70554. {
  70555. }
  70556. void DrawablePath::setPath (const Path& newPath)
  70557. {
  70558. path = newPath;
  70559. strokeNeedsUpdating = true;
  70560. }
  70561. void DrawablePath::setFill (const FillType& newFill)
  70562. {
  70563. mainFill = newFill;
  70564. }
  70565. void DrawablePath::setStrokeFill (const FillType& newFill)
  70566. {
  70567. strokeFill = newFill;
  70568. }
  70569. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  70570. {
  70571. strokeType = newStrokeType;
  70572. strokeNeedsUpdating = true;
  70573. }
  70574. void DrawablePath::setStrokeThickness (const float newThickness)
  70575. {
  70576. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70577. }
  70578. void DrawablePath::updatePath() const
  70579. {
  70580. if (pathNeedsUpdating)
  70581. {
  70582. pathNeedsUpdating = false;
  70583. if (relativePath != 0)
  70584. {
  70585. path.clear();
  70586. relativePath->createPath (path, parent);
  70587. strokeNeedsUpdating = true;
  70588. }
  70589. }
  70590. }
  70591. void DrawablePath::updateStroke() const
  70592. {
  70593. if (strokeNeedsUpdating)
  70594. {
  70595. strokeNeedsUpdating = false;
  70596. updatePath();
  70597. stroke.clear();
  70598. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  70599. }
  70600. }
  70601. const Path& DrawablePath::getPath() const
  70602. {
  70603. updatePath();
  70604. return path;
  70605. }
  70606. const Path& DrawablePath::getStrokePath() const
  70607. {
  70608. updateStroke();
  70609. return stroke;
  70610. }
  70611. bool DrawablePath::isStrokeVisible() const throw()
  70612. {
  70613. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  70614. }
  70615. void DrawablePath::invalidatePoints()
  70616. {
  70617. pathNeedsUpdating = true;
  70618. strokeNeedsUpdating = true;
  70619. }
  70620. void DrawablePath::render (const Drawable::RenderingContext& context) const
  70621. {
  70622. {
  70623. FillType f (mainFill);
  70624. if (f.isGradient())
  70625. f.gradient->multiplyOpacity (context.opacity);
  70626. else
  70627. f.setOpacity (f.getOpacity() * context.opacity);
  70628. f.transform = f.transform.followedBy (context.transform);
  70629. context.g.setFillType (f);
  70630. context.g.fillPath (getPath(), context.transform);
  70631. }
  70632. if (isStrokeVisible())
  70633. {
  70634. FillType f (strokeFill);
  70635. if (f.isGradient())
  70636. f.gradient->multiplyOpacity (context.opacity);
  70637. else
  70638. f.setOpacity (f.getOpacity() * context.opacity);
  70639. f.transform = f.transform.followedBy (context.transform);
  70640. context.g.setFillType (f);
  70641. context.g.fillPath (getStrokePath(), context.transform);
  70642. }
  70643. }
  70644. const Rectangle<float> DrawablePath::getBounds() const
  70645. {
  70646. if (isStrokeVisible())
  70647. return getStrokePath().getBounds();
  70648. else
  70649. return getPath().getBounds();
  70650. }
  70651. bool DrawablePath::hitTest (float x, float y) const
  70652. {
  70653. return getPath().contains (x, y)
  70654. || (isStrokeVisible() && getStrokePath().contains (x, y));
  70655. }
  70656. Drawable* DrawablePath::createCopy() const
  70657. {
  70658. return new DrawablePath (*this);
  70659. }
  70660. const Identifier DrawablePath::valueTreeType ("Path");
  70661. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  70662. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  70663. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  70664. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  70665. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  70666. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  70667. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70668. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70669. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70670. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70671. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70672. : ValueTreeWrapperBase (state_)
  70673. {
  70674. jassert (state.hasType (valueTreeType));
  70675. }
  70676. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70677. {
  70678. return state.getOrCreateChildWithName (path, 0);
  70679. }
  70680. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  70681. {
  70682. ValueTree v (state.getChildWithName (fill));
  70683. if (v.isValid())
  70684. return v;
  70685. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  70686. return getMainFillState();
  70687. }
  70688. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  70689. {
  70690. ValueTree v (state.getChildWithName (stroke));
  70691. if (v.isValid())
  70692. return v;
  70693. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  70694. return getStrokeFillState();
  70695. }
  70696. const FillType DrawablePath::ValueTreeWrapper::getMainFill (Expression::EvaluationContext* nameFinder,
  70697. ImageProvider* imageProvider) const
  70698. {
  70699. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  70700. }
  70701. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  70702. const RelativePoint* gp2, const RelativePoint* gp3,
  70703. ImageProvider* imageProvider, UndoManager* undoManager)
  70704. {
  70705. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  70706. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70707. }
  70708. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (Expression::EvaluationContext* nameFinder,
  70709. ImageProvider* imageProvider) const
  70710. {
  70711. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  70712. }
  70713. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  70714. const RelativePoint* gp2, const RelativePoint* gp3,
  70715. ImageProvider* imageProvider, UndoManager* undoManager)
  70716. {
  70717. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  70718. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70719. }
  70720. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  70721. {
  70722. const String jointStyleString (state [jointStyle].toString());
  70723. const String capStyleString (state [capStyle].toString());
  70724. return PathStrokeType (state [strokeWidth],
  70725. jointStyleString == "curved" ? PathStrokeType::curved
  70726. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70727. : PathStrokeType::mitered),
  70728. capStyleString == "square" ? PathStrokeType::square
  70729. : (capStyleString == "round" ? PathStrokeType::rounded
  70730. : PathStrokeType::butt));
  70731. }
  70732. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70733. {
  70734. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70735. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70736. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70737. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70738. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70739. }
  70740. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70741. {
  70742. return state [nonZeroWinding];
  70743. }
  70744. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70745. {
  70746. state.setProperty (nonZeroWinding, b, undoManager);
  70747. }
  70748. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70749. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70750. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70751. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70752. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70753. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70754. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70755. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70756. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70757. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70758. : state (state_)
  70759. {
  70760. }
  70761. DrawablePath::ValueTreeWrapper::Element::~Element()
  70762. {
  70763. }
  70764. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70765. {
  70766. return ValueTreeWrapper (state.getParent().getParent());
  70767. }
  70768. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70769. {
  70770. return Element (state.getSibling (-1));
  70771. }
  70772. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70773. {
  70774. const Identifier i (state.getType());
  70775. if (i == startSubPathElement || i == lineToElement) return 1;
  70776. if (i == quadraticToElement) return 2;
  70777. if (i == cubicToElement) return 3;
  70778. return 0;
  70779. }
  70780. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70781. {
  70782. jassert (index >= 0 && index < getNumControlPoints());
  70783. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70784. }
  70785. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70786. {
  70787. jassert (index >= 0 && index < getNumControlPoints());
  70788. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70789. }
  70790. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70791. {
  70792. jassert (index >= 0 && index < getNumControlPoints());
  70793. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70794. }
  70795. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70796. {
  70797. const Identifier i (state.getType());
  70798. if (i == startSubPathElement)
  70799. return getControlPoint (0);
  70800. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70801. return getPreviousElement().getEndPoint();
  70802. }
  70803. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70804. {
  70805. const Identifier i (state.getType());
  70806. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70807. if (i == quadraticToElement) return getControlPoint (1);
  70808. if (i == cubicToElement) return getControlPoint (2);
  70809. jassert (i == closeSubPathElement);
  70810. return RelativePoint();
  70811. }
  70812. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70813. {
  70814. const Identifier i (state.getType());
  70815. if (i == lineToElement || i == closeSubPathElement)
  70816. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70817. if (i == cubicToElement)
  70818. {
  70819. Path p;
  70820. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70821. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70822. return p.getLength();
  70823. }
  70824. if (i == quadraticToElement)
  70825. {
  70826. Path p;
  70827. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70828. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70829. return p.getLength();
  70830. }
  70831. jassert (i == startSubPathElement);
  70832. return 0;
  70833. }
  70834. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70835. {
  70836. return state [mode].toString();
  70837. }
  70838. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70839. {
  70840. if (state.hasType (cubicToElement))
  70841. state.setProperty (mode, newMode, undoManager);
  70842. }
  70843. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70844. {
  70845. const Identifier i (state.getType());
  70846. if (i == quadraticToElement || i == cubicToElement)
  70847. {
  70848. ValueTree newState (lineToElement);
  70849. Element e (newState);
  70850. e.setControlPoint (0, getEndPoint(), undoManager);
  70851. state = newState;
  70852. }
  70853. }
  70854. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70855. {
  70856. const Identifier i (state.getType());
  70857. if (i == lineToElement || i == quadraticToElement)
  70858. {
  70859. ValueTree newState (cubicToElement);
  70860. Element e (newState);
  70861. const RelativePoint start (getStartPoint());
  70862. const RelativePoint end (getEndPoint());
  70863. const Point<float> startResolved (start.resolve (nameFinder));
  70864. const Point<float> endResolved (end.resolve (nameFinder));
  70865. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70866. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70867. e.setControlPoint (2, end, undoManager);
  70868. state = newState;
  70869. }
  70870. }
  70871. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70872. {
  70873. const Identifier i (state.getType());
  70874. if (i != startSubPathElement)
  70875. {
  70876. ValueTree newState (startSubPathElement);
  70877. Element e (newState);
  70878. e.setControlPoint (0, getEndPoint(), undoManager);
  70879. state = newState;
  70880. }
  70881. }
  70882. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70883. {
  70884. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70885. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70886. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70887. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70888. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70889. return newCp1 + (newCp2 - newCp1) * proportion;
  70890. }
  70891. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70892. {
  70893. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70894. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70895. return mid1 + (mid2 - mid1) * proportion;
  70896. }
  70897. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70898. {
  70899. const Identifier i (state.getType());
  70900. float bestProp = 0;
  70901. if (i == cubicToElement)
  70902. {
  70903. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70904. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70905. float bestDistance = std::numeric_limits<float>::max();
  70906. for (int i = 110; --i >= 0;)
  70907. {
  70908. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70909. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70910. const float distance = centre.getDistanceFrom (targetPoint);
  70911. if (distance < bestDistance)
  70912. {
  70913. bestProp = prop;
  70914. bestDistance = distance;
  70915. }
  70916. }
  70917. }
  70918. else if (i == quadraticToElement)
  70919. {
  70920. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70921. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70922. float bestDistance = std::numeric_limits<float>::max();
  70923. for (int i = 110; --i >= 0;)
  70924. {
  70925. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70926. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70927. const float distance = centre.getDistanceFrom (targetPoint);
  70928. if (distance < bestDistance)
  70929. {
  70930. bestProp = prop;
  70931. bestDistance = distance;
  70932. }
  70933. }
  70934. }
  70935. else if (i == lineToElement)
  70936. {
  70937. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70938. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70939. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70940. }
  70941. return bestProp;
  70942. }
  70943. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70944. {
  70945. ValueTree newTree;
  70946. const Identifier i (state.getType());
  70947. if (i == cubicToElement)
  70948. {
  70949. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70950. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70951. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70952. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70953. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70954. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70955. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70956. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70957. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70958. setControlPoint (0, mid1, undoManager);
  70959. setControlPoint (1, newCp1, undoManager);
  70960. setControlPoint (2, newCentre, undoManager);
  70961. setModeOfEndPoint (roundedMode, undoManager);
  70962. Element newElement (newTree = ValueTree (cubicToElement));
  70963. newElement.setControlPoint (0, newCp2, 0);
  70964. newElement.setControlPoint (1, mid3, 0);
  70965. newElement.setControlPoint (2, rp4, 0);
  70966. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70967. }
  70968. else if (i == quadraticToElement)
  70969. {
  70970. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70971. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70972. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70973. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70974. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70975. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70976. setControlPoint (0, mid1, undoManager);
  70977. setControlPoint (1, newCentre, undoManager);
  70978. setModeOfEndPoint (roundedMode, undoManager);
  70979. Element newElement (newTree = ValueTree (quadraticToElement));
  70980. newElement.setControlPoint (0, mid2, 0);
  70981. newElement.setControlPoint (1, rp3, 0);
  70982. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70983. }
  70984. else if (i == lineToElement)
  70985. {
  70986. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70987. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70988. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70989. setControlPoint (0, newPoint, undoManager);
  70990. Element newElement (newTree = ValueTree (lineToElement));
  70991. newElement.setControlPoint (0, rp2, 0);
  70992. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70993. }
  70994. else if (i == closeSubPathElement)
  70995. {
  70996. }
  70997. return newTree;
  70998. }
  70999. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  71000. {
  71001. state.getParent().removeChild (state, undoManager);
  71002. }
  71003. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  71004. {
  71005. Rectangle<float> damageRect;
  71006. ValueTreeWrapper v (tree);
  71007. setName (v.getID());
  71008. bool needsRedraw = false;
  71009. const FillType newFill (v.getMainFill (parent, imageProvider));
  71010. if (mainFill != newFill)
  71011. {
  71012. needsRedraw = true;
  71013. mainFill = newFill;
  71014. }
  71015. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  71016. if (strokeFill != newStrokeFill)
  71017. {
  71018. needsRedraw = true;
  71019. strokeFill = newStrokeFill;
  71020. }
  71021. const PathStrokeType newStroke (v.getStrokeType());
  71022. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  71023. Path newPath;
  71024. newRelativePath->createPath (newPath, parent);
  71025. if (! newRelativePath->containsAnyDynamicPoints())
  71026. newRelativePath = 0;
  71027. if (strokeType != newStroke || path != newPath)
  71028. {
  71029. damageRect = getBounds();
  71030. path.swapWithPath (newPath);
  71031. strokeNeedsUpdating = true;
  71032. strokeType = newStroke;
  71033. needsRedraw = true;
  71034. }
  71035. relativePath = newRelativePath;
  71036. if (needsRedraw)
  71037. damageRect = damageRect.getUnion (getBounds());
  71038. return damageRect;
  71039. }
  71040. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  71041. {
  71042. ValueTree tree (valueTreeType);
  71043. ValueTreeWrapper v (tree);
  71044. v.setID (getName(), 0);
  71045. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  71046. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  71047. v.setStrokeType (strokeType, 0);
  71048. if (relativePath != 0)
  71049. {
  71050. relativePath->writeTo (tree, 0);
  71051. }
  71052. else
  71053. {
  71054. RelativePointPath rp (path);
  71055. rp.writeTo (tree, 0);
  71056. }
  71057. return tree;
  71058. }
  71059. END_JUCE_NAMESPACE
  71060. /*** End of inlined file: juce_DrawablePath.cpp ***/
  71061. /*** Start of inlined file: juce_DrawableText.cpp ***/
  71062. BEGIN_JUCE_NAMESPACE
  71063. DrawableText::DrawableText()
  71064. : colour (Colours::black),
  71065. justification (Justification::centredLeft)
  71066. {
  71067. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  71068. RelativePoint (50.0f, 0.0f),
  71069. RelativePoint (0.0f, 20.0f)));
  71070. setFont (Font (15.0f), true);
  71071. }
  71072. DrawableText::DrawableText (const DrawableText& other)
  71073. : text (other.text),
  71074. font (other.font),
  71075. colour (other.colour),
  71076. justification (other.justification),
  71077. bounds (other.bounds),
  71078. fontSizeControlPoint (other.fontSizeControlPoint)
  71079. {
  71080. }
  71081. DrawableText::~DrawableText()
  71082. {
  71083. }
  71084. void DrawableText::setText (const String& newText)
  71085. {
  71086. text = newText;
  71087. }
  71088. void DrawableText::setColour (const Colour& newColour)
  71089. {
  71090. colour = newColour;
  71091. }
  71092. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71093. {
  71094. font = newFont;
  71095. if (applySizeAndScale)
  71096. {
  71097. Point<float> corners[3];
  71098. bounds.resolveThreePoints (corners, parent);
  71099. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  71100. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71101. }
  71102. }
  71103. void DrawableText::setJustification (const Justification& newJustification)
  71104. {
  71105. justification = newJustification;
  71106. }
  71107. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71108. {
  71109. bounds = newBounds;
  71110. }
  71111. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71112. {
  71113. fontSizeControlPoint = newPoint;
  71114. }
  71115. void DrawableText::render (const Drawable::RenderingContext& context) const
  71116. {
  71117. Point<float> points[3];
  71118. bounds.resolveThreePoints (points, parent);
  71119. const float w = Line<float> (points[0], points[1]).getLength();
  71120. const float h = Line<float> (points[0], points[2]).getLength();
  71121. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  71122. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  71123. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  71124. Font f (font);
  71125. f.setHeight (fontHeight);
  71126. f.setHorizontalScale (fontWidth / fontHeight);
  71127. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  71128. GlyphArrangement ga;
  71129. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  71130. ga.draw (context.g,
  71131. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71132. w, 0, points[1].getX(), points[1].getY(),
  71133. 0, h, points[2].getX(), points[2].getY())
  71134. .followedBy (context.transform));
  71135. }
  71136. const Rectangle<float> DrawableText::getBounds() const
  71137. {
  71138. return bounds.getBounds (parent);
  71139. }
  71140. bool DrawableText::hitTest (float x, float y) const
  71141. {
  71142. Path p;
  71143. bounds.getPath (p, parent);
  71144. return p.contains (x, y);
  71145. }
  71146. Drawable* DrawableText::createCopy() const
  71147. {
  71148. return new DrawableText (*this);
  71149. }
  71150. void DrawableText::invalidatePoints()
  71151. {
  71152. }
  71153. const Identifier DrawableText::valueTreeType ("Text");
  71154. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71155. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71156. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71157. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71158. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71159. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71160. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71161. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71162. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71163. : ValueTreeWrapperBase (state_)
  71164. {
  71165. jassert (state.hasType (valueTreeType));
  71166. }
  71167. const String DrawableText::ValueTreeWrapper::getText() const
  71168. {
  71169. return state [text].toString();
  71170. }
  71171. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71172. {
  71173. state.setProperty (text, newText, undoManager);
  71174. }
  71175. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71176. {
  71177. return state.getPropertyAsValue (text, undoManager);
  71178. }
  71179. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71180. {
  71181. return Colour::fromString (state [colour].toString());
  71182. }
  71183. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71184. {
  71185. state.setProperty (colour, newColour.toString(), undoManager);
  71186. }
  71187. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71188. {
  71189. return Justification ((int) state [justification]);
  71190. }
  71191. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71192. {
  71193. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71194. }
  71195. const Font DrawableText::ValueTreeWrapper::getFont() const
  71196. {
  71197. return Font::fromString (state [font]);
  71198. }
  71199. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71200. {
  71201. state.setProperty (font, newFont.toString(), undoManager);
  71202. }
  71203. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71204. {
  71205. return state.getPropertyAsValue (font, undoManager);
  71206. }
  71207. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71208. {
  71209. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71210. }
  71211. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71212. {
  71213. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71214. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71215. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71216. }
  71217. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71218. {
  71219. return state [fontSizeAnchor].toString();
  71220. }
  71221. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71222. {
  71223. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71224. }
  71225. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71226. {
  71227. ValueTreeWrapper v (tree);
  71228. setName (v.getID());
  71229. const RelativeParallelogram newBounds (v.getBoundingBox());
  71230. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71231. const Colour newColour (v.getColour());
  71232. const Justification newJustification (v.getJustification());
  71233. const String newText (v.getText());
  71234. const Font newFont (v.getFont());
  71235. if (text != newText || font != newFont || justification != newJustification
  71236. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71237. {
  71238. const Rectangle<float> damage (getBounds());
  71239. setBoundingBox (newBounds);
  71240. setFontSizeControlPoint (newFontPoint);
  71241. setColour (newColour);
  71242. setFont (newFont, false);
  71243. setJustification (newJustification);
  71244. setText (newText);
  71245. return damage.getUnion (getBounds());
  71246. }
  71247. return Rectangle<float>();
  71248. }
  71249. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71250. {
  71251. ValueTree tree (valueTreeType);
  71252. ValueTreeWrapper v (tree);
  71253. v.setID (getName(), 0);
  71254. v.setText (text, 0);
  71255. v.setFont (font, 0);
  71256. v.setJustification (justification, 0);
  71257. v.setColour (colour, 0);
  71258. v.setBoundingBox (bounds, 0);
  71259. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71260. return tree;
  71261. }
  71262. END_JUCE_NAMESPACE
  71263. /*** End of inlined file: juce_DrawableText.cpp ***/
  71264. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71265. BEGIN_JUCE_NAMESPACE
  71266. class SVGState
  71267. {
  71268. public:
  71269. SVGState (const XmlElement* const topLevel)
  71270. : topLevelXml (topLevel),
  71271. elementX (0), elementY (0),
  71272. width (512), height (512),
  71273. viewBoxW (0), viewBoxH (0)
  71274. {
  71275. }
  71276. ~SVGState()
  71277. {
  71278. }
  71279. Drawable* parseSVGElement (const XmlElement& xml)
  71280. {
  71281. if (! xml.hasTagName ("svg"))
  71282. return 0;
  71283. DrawableComposite* const drawable = new DrawableComposite();
  71284. drawable->setName (xml.getStringAttribute ("id"));
  71285. SVGState newState (*this);
  71286. if (xml.hasAttribute ("transform"))
  71287. newState.addTransform (xml);
  71288. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71289. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71290. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71291. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71292. if (xml.hasAttribute ("viewBox"))
  71293. {
  71294. const String viewParams (xml.getStringAttribute ("viewBox"));
  71295. int i = 0;
  71296. float vx, vy, vw, vh;
  71297. if (parseCoords (viewParams, vx, vy, i, true)
  71298. && parseCoords (viewParams, vw, vh, i, true)
  71299. && vw > 0
  71300. && vh > 0)
  71301. {
  71302. newState.viewBoxW = vw;
  71303. newState.viewBoxH = vh;
  71304. int placementFlags = 0;
  71305. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71306. if (aspect.containsIgnoreCase ("none"))
  71307. {
  71308. placementFlags = RectanglePlacement::stretchToFit;
  71309. }
  71310. else
  71311. {
  71312. if (aspect.containsIgnoreCase ("slice"))
  71313. placementFlags |= RectanglePlacement::fillDestination;
  71314. if (aspect.containsIgnoreCase ("xMin"))
  71315. placementFlags |= RectanglePlacement::xLeft;
  71316. else if (aspect.containsIgnoreCase ("xMax"))
  71317. placementFlags |= RectanglePlacement::xRight;
  71318. else
  71319. placementFlags |= RectanglePlacement::xMid;
  71320. if (aspect.containsIgnoreCase ("yMin"))
  71321. placementFlags |= RectanglePlacement::yTop;
  71322. else if (aspect.containsIgnoreCase ("yMax"))
  71323. placementFlags |= RectanglePlacement::yBottom;
  71324. else
  71325. placementFlags |= RectanglePlacement::yMid;
  71326. }
  71327. const RectanglePlacement placement (placementFlags);
  71328. newState.transform
  71329. = placement.getTransformToFit (vx, vy, vw, vh,
  71330. 0.0f, 0.0f, newState.width, newState.height)
  71331. .followedBy (newState.transform);
  71332. }
  71333. }
  71334. else
  71335. {
  71336. if (viewBoxW == 0)
  71337. newState.viewBoxW = newState.width;
  71338. if (viewBoxH == 0)
  71339. newState.viewBoxH = newState.height;
  71340. }
  71341. newState.parseSubElements (xml, drawable);
  71342. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71343. return drawable;
  71344. }
  71345. private:
  71346. const XmlElement* const topLevelXml;
  71347. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71348. AffineTransform transform;
  71349. String cssStyleText;
  71350. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71351. {
  71352. forEachXmlChildElement (xml, e)
  71353. {
  71354. Drawable* d = 0;
  71355. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71356. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71357. else if (e->hasTagName ("path")) d = parsePath (*e);
  71358. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71359. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71360. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71361. else if (e->hasTagName ("line")) d = parseLine (*e);
  71362. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71363. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71364. else if (e->hasTagName ("text")) d = parseText (*e);
  71365. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71366. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71367. parentDrawable->insertDrawable (d);
  71368. }
  71369. }
  71370. DrawableComposite* parseSwitch (const XmlElement& xml)
  71371. {
  71372. const XmlElement* const group = xml.getChildByName ("g");
  71373. if (group != 0)
  71374. return parseGroupElement (*group);
  71375. return 0;
  71376. }
  71377. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71378. {
  71379. DrawableComposite* const drawable = new DrawableComposite();
  71380. drawable->setName (xml.getStringAttribute ("id"));
  71381. if (xml.hasAttribute ("transform"))
  71382. {
  71383. SVGState newState (*this);
  71384. newState.addTransform (xml);
  71385. newState.parseSubElements (xml, drawable);
  71386. }
  71387. else
  71388. {
  71389. parseSubElements (xml, drawable);
  71390. }
  71391. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71392. return drawable;
  71393. }
  71394. Drawable* parsePath (const XmlElement& xml) const
  71395. {
  71396. const String d (xml.getStringAttribute ("d").trimStart());
  71397. Path path;
  71398. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71399. path.setUsingNonZeroWinding (false);
  71400. int index = 0;
  71401. float lastX = 0, lastY = 0;
  71402. float lastX2 = 0, lastY2 = 0;
  71403. juce_wchar lastCommandChar = 0;
  71404. bool isRelative = true;
  71405. bool carryOn = true;
  71406. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71407. while (d[index] != 0)
  71408. {
  71409. float x, y, x2, y2, x3, y3;
  71410. if (validCommandChars.containsChar (d[index]))
  71411. {
  71412. lastCommandChar = d [index++];
  71413. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71414. }
  71415. switch (lastCommandChar)
  71416. {
  71417. case 'M':
  71418. case 'm':
  71419. case 'L':
  71420. case 'l':
  71421. if (parseCoords (d, x, y, index, false))
  71422. {
  71423. if (isRelative)
  71424. {
  71425. x += lastX;
  71426. y += lastY;
  71427. }
  71428. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71429. {
  71430. path.startNewSubPath (x, y);
  71431. lastCommandChar = 'l';
  71432. }
  71433. else
  71434. path.lineTo (x, y);
  71435. lastX2 = lastX;
  71436. lastY2 = lastY;
  71437. lastX = x;
  71438. lastY = y;
  71439. }
  71440. else
  71441. {
  71442. ++index;
  71443. }
  71444. break;
  71445. case 'H':
  71446. case 'h':
  71447. if (parseCoord (d, x, index, false, true))
  71448. {
  71449. if (isRelative)
  71450. x += lastX;
  71451. path.lineTo (x, lastY);
  71452. lastX2 = lastX;
  71453. lastX = x;
  71454. }
  71455. else
  71456. {
  71457. ++index;
  71458. }
  71459. break;
  71460. case 'V':
  71461. case 'v':
  71462. if (parseCoord (d, y, index, false, false))
  71463. {
  71464. if (isRelative)
  71465. y += lastY;
  71466. path.lineTo (lastX, y);
  71467. lastY2 = lastY;
  71468. lastY = y;
  71469. }
  71470. else
  71471. {
  71472. ++index;
  71473. }
  71474. break;
  71475. case 'C':
  71476. case 'c':
  71477. if (parseCoords (d, x, y, index, false)
  71478. && parseCoords (d, x2, y2, index, false)
  71479. && parseCoords (d, x3, y3, index, false))
  71480. {
  71481. if (isRelative)
  71482. {
  71483. x += lastX;
  71484. y += lastY;
  71485. x2 += lastX;
  71486. y2 += lastY;
  71487. x3 += lastX;
  71488. y3 += lastY;
  71489. }
  71490. path.cubicTo (x, y, x2, y2, x3, y3);
  71491. lastX2 = x2;
  71492. lastY2 = y2;
  71493. lastX = x3;
  71494. lastY = y3;
  71495. }
  71496. else
  71497. {
  71498. ++index;
  71499. }
  71500. break;
  71501. case 'S':
  71502. case 's':
  71503. if (parseCoords (d, x, y, index, false)
  71504. && parseCoords (d, x3, y3, index, false))
  71505. {
  71506. if (isRelative)
  71507. {
  71508. x += lastX;
  71509. y += lastY;
  71510. x3 += lastX;
  71511. y3 += lastY;
  71512. }
  71513. x2 = lastX + (lastX - lastX2);
  71514. y2 = lastY + (lastY - lastY2);
  71515. path.cubicTo (x2, y2, x, y, x3, y3);
  71516. lastX2 = x;
  71517. lastY2 = y;
  71518. lastX = x3;
  71519. lastY = y3;
  71520. }
  71521. else
  71522. {
  71523. ++index;
  71524. }
  71525. break;
  71526. case 'Q':
  71527. case 'q':
  71528. if (parseCoords (d, x, y, index, false)
  71529. && parseCoords (d, x2, y2, index, false))
  71530. {
  71531. if (isRelative)
  71532. {
  71533. x += lastX;
  71534. y += lastY;
  71535. x2 += lastX;
  71536. y2 += lastY;
  71537. }
  71538. path.quadraticTo (x, y, x2, y2);
  71539. lastX2 = x;
  71540. lastY2 = y;
  71541. lastX = x2;
  71542. lastY = y2;
  71543. }
  71544. else
  71545. {
  71546. ++index;
  71547. }
  71548. break;
  71549. case 'T':
  71550. case 't':
  71551. if (parseCoords (d, x, y, index, false))
  71552. {
  71553. if (isRelative)
  71554. {
  71555. x += lastX;
  71556. y += lastY;
  71557. }
  71558. x2 = lastX + (lastX - lastX2);
  71559. y2 = lastY + (lastY - lastY2);
  71560. path.quadraticTo (x2, y2, x, y);
  71561. lastX2 = x2;
  71562. lastY2 = y2;
  71563. lastX = x;
  71564. lastY = y;
  71565. }
  71566. else
  71567. {
  71568. ++index;
  71569. }
  71570. break;
  71571. case 'A':
  71572. case 'a':
  71573. if (parseCoords (d, x, y, index, false))
  71574. {
  71575. String num;
  71576. if (parseNextNumber (d, num, index, false))
  71577. {
  71578. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71579. if (parseNextNumber (d, num, index, false))
  71580. {
  71581. const bool largeArc = num.getIntValue() != 0;
  71582. if (parseNextNumber (d, num, index, false))
  71583. {
  71584. const bool sweep = num.getIntValue() != 0;
  71585. if (parseCoords (d, x2, y2, index, false))
  71586. {
  71587. if (isRelative)
  71588. {
  71589. x2 += lastX;
  71590. y2 += lastY;
  71591. }
  71592. if (lastX != x2 || lastY != y2)
  71593. {
  71594. double centreX, centreY, startAngle, deltaAngle;
  71595. double rx = x, ry = y;
  71596. endpointToCentreParameters (lastX, lastY, x2, y2,
  71597. angle, largeArc, sweep,
  71598. rx, ry, centreX, centreY,
  71599. startAngle, deltaAngle);
  71600. path.addCentredArc ((float) centreX, (float) centreY,
  71601. (float) rx, (float) ry,
  71602. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71603. false);
  71604. path.lineTo (x2, y2);
  71605. }
  71606. lastX2 = lastX;
  71607. lastY2 = lastY;
  71608. lastX = x2;
  71609. lastY = y2;
  71610. }
  71611. }
  71612. }
  71613. }
  71614. }
  71615. else
  71616. {
  71617. ++index;
  71618. }
  71619. break;
  71620. case 'Z':
  71621. case 'z':
  71622. path.closeSubPath();
  71623. while (CharacterFunctions::isWhitespace (d [index]))
  71624. ++index;
  71625. break;
  71626. default:
  71627. carryOn = false;
  71628. break;
  71629. }
  71630. if (! carryOn)
  71631. break;
  71632. }
  71633. return parseShape (xml, path);
  71634. }
  71635. Drawable* parseRect (const XmlElement& xml) const
  71636. {
  71637. Path rect;
  71638. const bool hasRX = xml.hasAttribute ("rx");
  71639. const bool hasRY = xml.hasAttribute ("ry");
  71640. if (hasRX || hasRY)
  71641. {
  71642. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71643. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71644. if (! hasRX)
  71645. rx = ry;
  71646. else if (! hasRY)
  71647. ry = rx;
  71648. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71649. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71650. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71651. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71652. rx, ry);
  71653. }
  71654. else
  71655. {
  71656. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71657. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71658. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71659. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71660. }
  71661. return parseShape (xml, rect);
  71662. }
  71663. Drawable* parseCircle (const XmlElement& xml) const
  71664. {
  71665. Path circle;
  71666. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71667. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71668. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71669. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71670. return parseShape (xml, circle);
  71671. }
  71672. Drawable* parseEllipse (const XmlElement& xml) const
  71673. {
  71674. Path ellipse;
  71675. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71676. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71677. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71678. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71679. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71680. return parseShape (xml, ellipse);
  71681. }
  71682. Drawable* parseLine (const XmlElement& xml) const
  71683. {
  71684. Path line;
  71685. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71686. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71687. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71688. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71689. line.startNewSubPath (x1, y1);
  71690. line.lineTo (x2, y2);
  71691. return parseShape (xml, line);
  71692. }
  71693. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71694. {
  71695. const String points (xml.getStringAttribute ("points"));
  71696. Path path;
  71697. int index = 0;
  71698. float x, y;
  71699. if (parseCoords (points, x, y, index, true))
  71700. {
  71701. float firstX = x;
  71702. float firstY = y;
  71703. float lastX = 0, lastY = 0;
  71704. path.startNewSubPath (x, y);
  71705. while (parseCoords (points, x, y, index, true))
  71706. {
  71707. lastX = x;
  71708. lastY = y;
  71709. path.lineTo (x, y);
  71710. }
  71711. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71712. path.closeSubPath();
  71713. }
  71714. return parseShape (xml, path);
  71715. }
  71716. Drawable* parseShape (const XmlElement& xml, Path& path,
  71717. const bool shouldParseTransform = true) const
  71718. {
  71719. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71720. {
  71721. SVGState newState (*this);
  71722. newState.addTransform (xml);
  71723. return newState.parseShape (xml, path, false);
  71724. }
  71725. DrawablePath* dp = new DrawablePath();
  71726. dp->setName (xml.getStringAttribute ("id"));
  71727. dp->setFill (Colours::transparentBlack);
  71728. path.applyTransform (transform);
  71729. dp->setPath (path);
  71730. Path::Iterator iter (path);
  71731. bool containsClosedSubPath = false;
  71732. while (iter.next())
  71733. {
  71734. if (iter.elementType == Path::Iterator::closePath)
  71735. {
  71736. containsClosedSubPath = true;
  71737. break;
  71738. }
  71739. }
  71740. dp->setFill (getPathFillType (path,
  71741. getStyleAttribute (&xml, "fill"),
  71742. getStyleAttribute (&xml, "fill-opacity"),
  71743. getStyleAttribute (&xml, "opacity"),
  71744. containsClosedSubPath ? Colours::black
  71745. : Colours::transparentBlack));
  71746. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71747. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71748. {
  71749. dp->setStrokeFill (getPathFillType (path, strokeType,
  71750. getStyleAttribute (&xml, "stroke-opacity"),
  71751. getStyleAttribute (&xml, "opacity"),
  71752. Colours::transparentBlack));
  71753. dp->setStrokeType (getStrokeFor (&xml));
  71754. }
  71755. return dp;
  71756. }
  71757. const XmlElement* findLinkedElement (const XmlElement* e) const
  71758. {
  71759. const String id (e->getStringAttribute ("xlink:href"));
  71760. if (! id.startsWithChar ('#'))
  71761. return 0;
  71762. return findElementForId (topLevelXml, id.substring (1));
  71763. }
  71764. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71765. {
  71766. if (fillXml == 0)
  71767. return;
  71768. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71769. {
  71770. int index = 0;
  71771. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71772. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71773. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71774. double offset = e->getDoubleAttribute ("offset");
  71775. if (e->getStringAttribute ("offset").containsChar ('%'))
  71776. offset *= 0.01;
  71777. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71778. }
  71779. }
  71780. const FillType getPathFillType (const Path& path,
  71781. const String& fill,
  71782. const String& fillOpacity,
  71783. const String& overallOpacity,
  71784. const Colour& defaultColour) const
  71785. {
  71786. float opacity = 1.0f;
  71787. if (overallOpacity.isNotEmpty())
  71788. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71789. if (fillOpacity.isNotEmpty())
  71790. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71791. if (fill.startsWithIgnoreCase ("url"))
  71792. {
  71793. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71794. .upToLastOccurrenceOf (")", false, false).trim());
  71795. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71796. if (fillXml != 0
  71797. && (fillXml->hasTagName ("linearGradient")
  71798. || fillXml->hasTagName ("radialGradient")))
  71799. {
  71800. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71801. ColourGradient gradient;
  71802. addGradientStopsIn (gradient, inheritedFrom);
  71803. addGradientStopsIn (gradient, fillXml);
  71804. if (gradient.getNumColours() > 0)
  71805. {
  71806. gradient.addColour (0.0, gradient.getColour (0));
  71807. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71808. }
  71809. else
  71810. {
  71811. gradient.addColour (0.0, Colours::black);
  71812. gradient.addColour (1.0, Colours::black);
  71813. }
  71814. if (overallOpacity.isNotEmpty())
  71815. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71816. jassert (gradient.getNumColours() > 0);
  71817. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71818. float gradientWidth = viewBoxW;
  71819. float gradientHeight = viewBoxH;
  71820. float dx = 0.0f;
  71821. float dy = 0.0f;
  71822. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71823. if (! userSpace)
  71824. {
  71825. const Rectangle<float> bounds (path.getBounds());
  71826. dx = bounds.getX();
  71827. dy = bounds.getY();
  71828. gradientWidth = bounds.getWidth();
  71829. gradientHeight = bounds.getHeight();
  71830. }
  71831. if (gradient.isRadial)
  71832. {
  71833. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71834. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71835. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71836. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71837. //xxx (the fx, fy focal point isn't handled properly here..)
  71838. }
  71839. else
  71840. {
  71841. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71842. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71843. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71844. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71845. if (gradient.point1 == gradient.point2)
  71846. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71847. }
  71848. FillType type (gradient);
  71849. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71850. .followedBy (transform);
  71851. return type;
  71852. }
  71853. }
  71854. if (fill.equalsIgnoreCase ("none"))
  71855. return Colours::transparentBlack;
  71856. int i = 0;
  71857. const Colour colour (parseColour (fill, i, defaultColour));
  71858. return colour.withMultipliedAlpha (opacity);
  71859. }
  71860. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71861. {
  71862. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71863. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71864. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71865. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71866. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71867. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71868. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71869. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71870. if (join.equalsIgnoreCase ("round"))
  71871. joinStyle = PathStrokeType::curved;
  71872. else if (join.equalsIgnoreCase ("bevel"))
  71873. joinStyle = PathStrokeType::beveled;
  71874. if (cap.equalsIgnoreCase ("round"))
  71875. capStyle = PathStrokeType::rounded;
  71876. else if (cap.equalsIgnoreCase ("square"))
  71877. capStyle = PathStrokeType::square;
  71878. float ox = 0.0f, oy = 0.0f;
  71879. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71880. transform.transformPoints (ox, oy, x, y);
  71881. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71882. joinStyle, capStyle);
  71883. }
  71884. Drawable* parseText (const XmlElement& xml)
  71885. {
  71886. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71887. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71888. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71889. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71890. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71891. //xxx not done text yet!
  71892. forEachXmlChildElement (xml, e)
  71893. {
  71894. if (e->isTextElement())
  71895. {
  71896. const String text (e->getText());
  71897. Path path;
  71898. Drawable* s = parseShape (*e, path);
  71899. delete s; // xxx not finished!
  71900. }
  71901. else if (e->hasTagName ("tspan"))
  71902. {
  71903. Drawable* s = parseText (*e);
  71904. delete s; // xxx not finished!
  71905. }
  71906. }
  71907. return 0;
  71908. }
  71909. void addTransform (const XmlElement& xml)
  71910. {
  71911. transform = parseTransform (xml.getStringAttribute ("transform"))
  71912. .followedBy (transform);
  71913. }
  71914. bool parseCoord (const String& s, float& value, int& index,
  71915. const bool allowUnits, const bool isX) const
  71916. {
  71917. String number;
  71918. if (! parseNextNumber (s, number, index, allowUnits))
  71919. {
  71920. value = 0;
  71921. return false;
  71922. }
  71923. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71924. return true;
  71925. }
  71926. bool parseCoords (const String& s, float& x, float& y,
  71927. int& index, const bool allowUnits) const
  71928. {
  71929. return parseCoord (s, x, index, allowUnits, true)
  71930. && parseCoord (s, y, index, allowUnits, false);
  71931. }
  71932. float getCoordLength (const String& s, const float sizeForProportions) const
  71933. {
  71934. float n = s.getFloatValue();
  71935. const int len = s.length();
  71936. if (len > 2)
  71937. {
  71938. const float dpi = 96.0f;
  71939. const juce_wchar n1 = s [len - 2];
  71940. const juce_wchar n2 = s [len - 1];
  71941. if (n1 == 'i' && n2 == 'n')
  71942. n *= dpi;
  71943. else if (n1 == 'm' && n2 == 'm')
  71944. n *= dpi / 25.4f;
  71945. else if (n1 == 'c' && n2 == 'm')
  71946. n *= dpi / 2.54f;
  71947. else if (n1 == 'p' && n2 == 'c')
  71948. n *= 15.0f;
  71949. else if (n2 == '%')
  71950. n *= 0.01f * sizeForProportions;
  71951. }
  71952. return n;
  71953. }
  71954. void getCoordList (Array <float>& coords, const String& list,
  71955. const bool allowUnits, const bool isX) const
  71956. {
  71957. int index = 0;
  71958. float value;
  71959. while (parseCoord (list, value, index, allowUnits, isX))
  71960. coords.add (value);
  71961. }
  71962. void parseCSSStyle (const XmlElement& xml)
  71963. {
  71964. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71965. }
  71966. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71967. const String& defaultValue = String::empty) const
  71968. {
  71969. if (xml->hasAttribute (attributeName))
  71970. return xml->getStringAttribute (attributeName, defaultValue);
  71971. const String styleAtt (xml->getStringAttribute ("style"));
  71972. if (styleAtt.isNotEmpty())
  71973. {
  71974. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71975. if (value.isNotEmpty())
  71976. return value;
  71977. }
  71978. else if (xml->hasAttribute ("class"))
  71979. {
  71980. const String className ("." + xml->getStringAttribute ("class"));
  71981. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71982. if (index < 0)
  71983. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71984. if (index >= 0)
  71985. {
  71986. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71987. if (openBracket > index)
  71988. {
  71989. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71990. if (closeBracket > openBracket)
  71991. {
  71992. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71993. if (value.isNotEmpty())
  71994. return value;
  71995. }
  71996. }
  71997. }
  71998. }
  71999. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72000. if (xml != 0)
  72001. return getStyleAttribute (xml, attributeName, defaultValue);
  72002. return defaultValue;
  72003. }
  72004. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  72005. {
  72006. if (xml->hasAttribute (attributeName))
  72007. return xml->getStringAttribute (attributeName);
  72008. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72009. if (xml != 0)
  72010. return getInheritedAttribute (xml, attributeName);
  72011. return String::empty;
  72012. }
  72013. static bool isIdentifierChar (const juce_wchar c)
  72014. {
  72015. return CharacterFunctions::isLetter (c) || c == '-';
  72016. }
  72017. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  72018. {
  72019. int i = 0;
  72020. for (;;)
  72021. {
  72022. i = list.indexOf (i, attributeName);
  72023. if (i < 0)
  72024. break;
  72025. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  72026. && ! isIdentifierChar (list [i + attributeName.length()]))
  72027. {
  72028. i = list.indexOfChar (i, ':');
  72029. if (i < 0)
  72030. break;
  72031. int end = list.indexOfChar (i, ';');
  72032. if (end < 0)
  72033. end = 0x7ffff;
  72034. return list.substring (i + 1, end).trim();
  72035. }
  72036. ++i;
  72037. }
  72038. return defaultValue;
  72039. }
  72040. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  72041. {
  72042. const juce_wchar* const s = source;
  72043. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72044. ++index;
  72045. int start = index;
  72046. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  72047. ++index;
  72048. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  72049. ++index;
  72050. if ((s[index] == 'e' || s[index] == 'E')
  72051. && (CharacterFunctions::isDigit (s[index + 1])
  72052. || s[index + 1] == '-'
  72053. || s[index + 1] == '+'))
  72054. {
  72055. index += 2;
  72056. while (CharacterFunctions::isDigit (s[index]))
  72057. ++index;
  72058. }
  72059. if (allowUnits)
  72060. {
  72061. while (CharacterFunctions::isLetter (s[index]))
  72062. ++index;
  72063. }
  72064. if (index == start)
  72065. return false;
  72066. value = String (s + start, index - start);
  72067. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72068. ++index;
  72069. return true;
  72070. }
  72071. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  72072. {
  72073. if (s [index] == '#')
  72074. {
  72075. uint32 hex [6];
  72076. zeromem (hex, sizeof (hex));
  72077. int numChars = 0;
  72078. for (int i = 6; --i >= 0;)
  72079. {
  72080. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72081. if (hexValue >= 0)
  72082. hex [numChars++] = hexValue;
  72083. else
  72084. break;
  72085. }
  72086. if (numChars <= 3)
  72087. return Colour ((uint8) (hex [0] * 0x11),
  72088. (uint8) (hex [1] * 0x11),
  72089. (uint8) (hex [2] * 0x11));
  72090. else
  72091. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72092. (uint8) ((hex [2] << 4) + hex [3]),
  72093. (uint8) ((hex [4] << 4) + hex [5]));
  72094. }
  72095. else if (s [index] == 'r'
  72096. && s [index + 1] == 'g'
  72097. && s [index + 2] == 'b')
  72098. {
  72099. const int openBracket = s.indexOfChar (index, '(');
  72100. const int closeBracket = s.indexOfChar (openBracket, ')');
  72101. if (openBracket >= 3 && closeBracket > openBracket)
  72102. {
  72103. index = closeBracket;
  72104. StringArray tokens;
  72105. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72106. tokens.trim();
  72107. tokens.removeEmptyStrings();
  72108. if (tokens[0].containsChar ('%'))
  72109. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72110. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72111. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72112. else
  72113. return Colour ((uint8) tokens[0].getIntValue(),
  72114. (uint8) tokens[1].getIntValue(),
  72115. (uint8) tokens[2].getIntValue());
  72116. }
  72117. }
  72118. return Colours::findColourForName (s, defaultColour);
  72119. }
  72120. static const AffineTransform parseTransform (String t)
  72121. {
  72122. AffineTransform result;
  72123. while (t.isNotEmpty())
  72124. {
  72125. StringArray tokens;
  72126. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72127. .upToFirstOccurrenceOf (")", false, false),
  72128. ", ", String::empty);
  72129. tokens.removeEmptyStrings (true);
  72130. float numbers [6];
  72131. for (int i = 0; i < 6; ++i)
  72132. numbers[i] = tokens[i].getFloatValue();
  72133. AffineTransform trans;
  72134. if (t.startsWithIgnoreCase ("matrix"))
  72135. {
  72136. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72137. numbers[1], numbers[3], numbers[5]);
  72138. }
  72139. else if (t.startsWithIgnoreCase ("translate"))
  72140. {
  72141. jassert (tokens.size() == 2);
  72142. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72143. }
  72144. else if (t.startsWithIgnoreCase ("scale"))
  72145. {
  72146. if (tokens.size() == 1)
  72147. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72148. else
  72149. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72150. }
  72151. else if (t.startsWithIgnoreCase ("rotate"))
  72152. {
  72153. if (tokens.size() != 3)
  72154. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72155. else
  72156. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72157. numbers[1], numbers[2]);
  72158. }
  72159. else if (t.startsWithIgnoreCase ("skewX"))
  72160. {
  72161. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72162. 0.0f, 1.0f, 0.0f);
  72163. }
  72164. else if (t.startsWithIgnoreCase ("skewY"))
  72165. {
  72166. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72167. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72168. }
  72169. result = trans.followedBy (result);
  72170. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72171. }
  72172. return result;
  72173. }
  72174. static void endpointToCentreParameters (const double x1, const double y1,
  72175. const double x2, const double y2,
  72176. const double angle,
  72177. const bool largeArc, const bool sweep,
  72178. double& rx, double& ry,
  72179. double& centreX, double& centreY,
  72180. double& startAngle, double& deltaAngle)
  72181. {
  72182. const double midX = (x1 - x2) * 0.5;
  72183. const double midY = (y1 - y2) * 0.5;
  72184. const double cosAngle = cos (angle);
  72185. const double sinAngle = sin (angle);
  72186. const double xp = cosAngle * midX + sinAngle * midY;
  72187. const double yp = cosAngle * midY - sinAngle * midX;
  72188. const double xp2 = xp * xp;
  72189. const double yp2 = yp * yp;
  72190. double rx2 = rx * rx;
  72191. double ry2 = ry * ry;
  72192. const double s = (xp2 / rx2) + (yp2 / ry2);
  72193. double c;
  72194. if (s <= 1.0)
  72195. {
  72196. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72197. / (( rx2 * yp2) + (ry2 * xp2))));
  72198. if (largeArc == sweep)
  72199. c = -c;
  72200. }
  72201. else
  72202. {
  72203. const double s2 = std::sqrt (s);
  72204. rx *= s2;
  72205. ry *= s2;
  72206. rx2 = rx * rx;
  72207. ry2 = ry * ry;
  72208. c = 0;
  72209. }
  72210. const double cpx = ((rx * yp) / ry) * c;
  72211. const double cpy = ((-ry * xp) / rx) * c;
  72212. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72213. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72214. const double ux = (xp - cpx) / rx;
  72215. const double uy = (yp - cpy) / ry;
  72216. const double vx = (-xp - cpx) / rx;
  72217. const double vy = (-yp - cpy) / ry;
  72218. const double length = juce_hypot (ux, uy);
  72219. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72220. if (uy < 0)
  72221. startAngle = -startAngle;
  72222. startAngle += double_Pi * 0.5;
  72223. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72224. / (length * juce_hypot (vx, vy))));
  72225. if ((ux * vy) - (uy * vx) < 0)
  72226. deltaAngle = -deltaAngle;
  72227. if (sweep)
  72228. {
  72229. if (deltaAngle < 0)
  72230. deltaAngle += double_Pi * 2.0;
  72231. }
  72232. else
  72233. {
  72234. if (deltaAngle > 0)
  72235. deltaAngle -= double_Pi * 2.0;
  72236. }
  72237. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72238. }
  72239. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72240. {
  72241. forEachXmlChildElement (*parent, e)
  72242. {
  72243. if (e->compareAttribute ("id", id))
  72244. return e;
  72245. const XmlElement* const found = findElementForId (e, id);
  72246. if (found != 0)
  72247. return found;
  72248. }
  72249. return 0;
  72250. }
  72251. SVGState& operator= (const SVGState&);
  72252. };
  72253. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72254. {
  72255. SVGState state (&svgDocument);
  72256. return state.parseSVGElement (svgDocument);
  72257. }
  72258. END_JUCE_NAMESPACE
  72259. /*** End of inlined file: juce_SVGParser.cpp ***/
  72260. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72261. BEGIN_JUCE_NAMESPACE
  72262. #if JUCE_MSVC && JUCE_DEBUG
  72263. #pragma optimize ("t", on)
  72264. #endif
  72265. DropShadowEffect::DropShadowEffect()
  72266. : offsetX (0),
  72267. offsetY (0),
  72268. radius (4),
  72269. opacity (0.6f)
  72270. {
  72271. }
  72272. DropShadowEffect::~DropShadowEffect()
  72273. {
  72274. }
  72275. void DropShadowEffect::setShadowProperties (const float newRadius,
  72276. const float newOpacity,
  72277. const int newShadowOffsetX,
  72278. const int newShadowOffsetY)
  72279. {
  72280. radius = jmax (1.1f, newRadius);
  72281. offsetX = newShadowOffsetX;
  72282. offsetY = newShadowOffsetY;
  72283. opacity = newOpacity;
  72284. }
  72285. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  72286. {
  72287. const int w = image.getWidth();
  72288. const int h = image.getHeight();
  72289. Image shadowImage (Image::SingleChannel, w, h, false);
  72290. const Image::BitmapData srcData (image, false);
  72291. const Image::BitmapData destData (shadowImage, true);
  72292. const int filter = roundToInt (63.0f / radius);
  72293. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72294. for (int x = w; --x >= 0;)
  72295. {
  72296. int shadowAlpha = 0;
  72297. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72298. uint8* shadowPix = destData.data + x;
  72299. for (int y = h; --y >= 0;)
  72300. {
  72301. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72302. *shadowPix = (uint8) shadowAlpha;
  72303. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72304. shadowPix += destData.lineStride;
  72305. }
  72306. }
  72307. for (int y = h; --y >= 0;)
  72308. {
  72309. int shadowAlpha = 0;
  72310. uint8* shadowPix = destData.getLinePointer (y);
  72311. for (int x = w; --x >= 0;)
  72312. {
  72313. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72314. *shadowPix++ = (uint8) shadowAlpha;
  72315. }
  72316. }
  72317. g.setColour (Colours::black.withAlpha (opacity));
  72318. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72319. g.setOpacity (1.0f);
  72320. g.drawImageAt (image, 0, 0);
  72321. }
  72322. #if JUCE_MSVC && JUCE_DEBUG
  72323. #pragma optimize ("", on) // resets optimisations to the project defaults
  72324. #endif
  72325. END_JUCE_NAMESPACE
  72326. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72327. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72328. BEGIN_JUCE_NAMESPACE
  72329. GlowEffect::GlowEffect()
  72330. : radius (2.0f),
  72331. colour (Colours::white)
  72332. {
  72333. }
  72334. GlowEffect::~GlowEffect()
  72335. {
  72336. }
  72337. void GlowEffect::setGlowProperties (const float newRadius,
  72338. const Colour& newColour)
  72339. {
  72340. radius = newRadius;
  72341. colour = newColour;
  72342. }
  72343. void GlowEffect::applyEffect (Image& image, Graphics& g)
  72344. {
  72345. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72346. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72347. blurKernel.createGaussianBlur (radius);
  72348. blurKernel.rescaleAllValues (radius);
  72349. blurKernel.applyToImage (temp, image, image.getBounds());
  72350. g.setColour (colour);
  72351. g.drawImageAt (temp, 0, 0, true);
  72352. g.setOpacity (1.0f);
  72353. g.drawImageAt (image, 0, 0, false);
  72354. }
  72355. END_JUCE_NAMESPACE
  72356. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72357. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72358. BEGIN_JUCE_NAMESPACE
  72359. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  72360. : opacity (opacity_)
  72361. {
  72362. }
  72363. ReduceOpacityEffect::~ReduceOpacityEffect()
  72364. {
  72365. }
  72366. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  72367. {
  72368. opacity = jlimit (0.0f, 1.0f, newOpacity);
  72369. }
  72370. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  72371. {
  72372. g.setOpacity (opacity);
  72373. g.drawImageAt (image, 0, 0);
  72374. }
  72375. END_JUCE_NAMESPACE
  72376. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72377. /*** Start of inlined file: juce_Font.cpp ***/
  72378. BEGIN_JUCE_NAMESPACE
  72379. namespace FontValues
  72380. {
  72381. static float limitFontHeight (const float height) throw()
  72382. {
  72383. return jlimit (0.1f, 10000.0f, height);
  72384. }
  72385. static const float defaultFontHeight = 14.0f;
  72386. static String fallbackFont;
  72387. }
  72388. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72389. const float kerning_, const float ascent_, const int styleFlags_,
  72390. Typeface* const typeface_) throw()
  72391. : typefaceName (typefaceName_),
  72392. height (height_),
  72393. horizontalScale (horizontalScale_),
  72394. kerning (kerning_),
  72395. ascent (ascent_),
  72396. styleFlags (styleFlags_),
  72397. typeface (typeface_)
  72398. {
  72399. }
  72400. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72401. : typefaceName (other.typefaceName),
  72402. height (other.height),
  72403. horizontalScale (other.horizontalScale),
  72404. kerning (other.kerning),
  72405. ascent (other.ascent),
  72406. styleFlags (other.styleFlags),
  72407. typeface (other.typeface)
  72408. {
  72409. }
  72410. Font::Font() throw()
  72411. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72412. 1.0f, 0, 0, Font::plain, 0))
  72413. {
  72414. }
  72415. Font::Font (const float fontHeight, const int styleFlags_) throw()
  72416. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72417. 1.0f, 0, 0, styleFlags_, 0))
  72418. {
  72419. }
  72420. Font::Font (const String& typefaceName_,
  72421. const float fontHeight,
  72422. const int styleFlags_) throw()
  72423. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72424. 1.0f, 0, 0, styleFlags_, 0))
  72425. {
  72426. }
  72427. Font::Font (const Font& other) throw()
  72428. : font (other.font)
  72429. {
  72430. }
  72431. Font& Font::operator= (const Font& other) throw()
  72432. {
  72433. font = other.font;
  72434. return *this;
  72435. }
  72436. Font::~Font() throw()
  72437. {
  72438. }
  72439. Font::Font (const Typeface::Ptr& typeface) throw()
  72440. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72441. 1.0f, 0, 0, Font::plain, typeface))
  72442. {
  72443. }
  72444. bool Font::operator== (const Font& other) const throw()
  72445. {
  72446. return font == other.font
  72447. || (font->height == other.font->height
  72448. && font->styleFlags == other.font->styleFlags
  72449. && font->horizontalScale == other.font->horizontalScale
  72450. && font->kerning == other.font->kerning
  72451. && font->typefaceName == other.font->typefaceName);
  72452. }
  72453. bool Font::operator!= (const Font& other) const throw()
  72454. {
  72455. return ! operator== (other);
  72456. }
  72457. void Font::dupeInternalIfShared() throw()
  72458. {
  72459. if (font->getReferenceCount() > 1)
  72460. font = new SharedFontInternal (*font);
  72461. }
  72462. const String Font::getDefaultSansSerifFontName() throw()
  72463. {
  72464. static const String name ("<Sans-Serif>");
  72465. return name;
  72466. }
  72467. const String Font::getDefaultSerifFontName() throw()
  72468. {
  72469. static const String name ("<Serif>");
  72470. return name;
  72471. }
  72472. const String Font::getDefaultMonospacedFontName() throw()
  72473. {
  72474. static const String name ("<Monospaced>");
  72475. return name;
  72476. }
  72477. void Font::setTypefaceName (const String& faceName) throw()
  72478. {
  72479. if (faceName != font->typefaceName)
  72480. {
  72481. dupeInternalIfShared();
  72482. font->typefaceName = faceName;
  72483. font->typeface = 0;
  72484. font->ascent = 0;
  72485. }
  72486. }
  72487. const String Font::getFallbackFontName() throw()
  72488. {
  72489. return FontValues::fallbackFont;
  72490. }
  72491. void Font::setFallbackFontName (const String& name) throw()
  72492. {
  72493. FontValues::fallbackFont = name;
  72494. }
  72495. void Font::setHeight (float newHeight) throw()
  72496. {
  72497. newHeight = FontValues::limitFontHeight (newHeight);
  72498. if (font->height != newHeight)
  72499. {
  72500. dupeInternalIfShared();
  72501. font->height = newHeight;
  72502. }
  72503. }
  72504. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  72505. {
  72506. newHeight = FontValues::limitFontHeight (newHeight);
  72507. if (font->height != newHeight)
  72508. {
  72509. dupeInternalIfShared();
  72510. font->horizontalScale *= (font->height / newHeight);
  72511. font->height = newHeight;
  72512. }
  72513. }
  72514. void Font::setStyleFlags (const int newFlags) throw()
  72515. {
  72516. if (font->styleFlags != newFlags)
  72517. {
  72518. dupeInternalIfShared();
  72519. font->styleFlags = newFlags;
  72520. font->typeface = 0;
  72521. font->ascent = 0;
  72522. }
  72523. }
  72524. void Font::setSizeAndStyle (float newHeight,
  72525. const int newStyleFlags,
  72526. const float newHorizontalScale,
  72527. const float newKerningAmount) throw()
  72528. {
  72529. newHeight = FontValues::limitFontHeight (newHeight);
  72530. if (font->height != newHeight
  72531. || font->horizontalScale != newHorizontalScale
  72532. || font->kerning != newKerningAmount)
  72533. {
  72534. dupeInternalIfShared();
  72535. font->height = newHeight;
  72536. font->horizontalScale = newHorizontalScale;
  72537. font->kerning = newKerningAmount;
  72538. }
  72539. setStyleFlags (newStyleFlags);
  72540. }
  72541. void Font::setHorizontalScale (const float scaleFactor) throw()
  72542. {
  72543. dupeInternalIfShared();
  72544. font->horizontalScale = scaleFactor;
  72545. }
  72546. void Font::setExtraKerningFactor (const float extraKerning) throw()
  72547. {
  72548. dupeInternalIfShared();
  72549. font->kerning = extraKerning;
  72550. }
  72551. void Font::setBold (const bool shouldBeBold) throw()
  72552. {
  72553. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72554. : (font->styleFlags & ~bold));
  72555. }
  72556. bool Font::isBold() const throw()
  72557. {
  72558. return (font->styleFlags & bold) != 0;
  72559. }
  72560. void Font::setItalic (const bool shouldBeItalic) throw()
  72561. {
  72562. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72563. : (font->styleFlags & ~italic));
  72564. }
  72565. bool Font::isItalic() const throw()
  72566. {
  72567. return (font->styleFlags & italic) != 0;
  72568. }
  72569. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  72570. {
  72571. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72572. : (font->styleFlags & ~underlined));
  72573. }
  72574. bool Font::isUnderlined() const throw()
  72575. {
  72576. return (font->styleFlags & underlined) != 0;
  72577. }
  72578. float Font::getAscent() const throw()
  72579. {
  72580. if (font->ascent == 0)
  72581. font->ascent = getTypeface()->getAscent();
  72582. return font->height * font->ascent;
  72583. }
  72584. float Font::getDescent() const throw()
  72585. {
  72586. return font->height - getAscent();
  72587. }
  72588. int Font::getStringWidth (const String& text) const throw()
  72589. {
  72590. return roundToInt (getStringWidthFloat (text));
  72591. }
  72592. float Font::getStringWidthFloat (const String& text) const throw()
  72593. {
  72594. float w = getTypeface()->getStringWidth (text);
  72595. if (font->kerning != 0)
  72596. w += font->kerning * text.length();
  72597. return w * font->height * font->horizontalScale;
  72598. }
  72599. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  72600. {
  72601. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72602. const float scale = font->height * font->horizontalScale;
  72603. const int num = xOffsets.size();
  72604. if (num > 0)
  72605. {
  72606. float* const x = &(xOffsets.getReference(0));
  72607. if (font->kerning != 0)
  72608. {
  72609. for (int i = 0; i < num; ++i)
  72610. x[i] = (x[i] + i * font->kerning) * scale;
  72611. }
  72612. else
  72613. {
  72614. for (int i = 0; i < num; ++i)
  72615. x[i] *= scale;
  72616. }
  72617. }
  72618. }
  72619. void Font::findFonts (Array<Font>& destArray) throw()
  72620. {
  72621. const StringArray names (findAllTypefaceNames());
  72622. for (int i = 0; i < names.size(); ++i)
  72623. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72624. }
  72625. const String Font::toString() const
  72626. {
  72627. String s (getTypefaceName());
  72628. if (s == getDefaultSansSerifFontName())
  72629. s = String::empty;
  72630. else
  72631. s += "; ";
  72632. s += String (getHeight(), 1);
  72633. if (isBold())
  72634. s += " bold";
  72635. if (isItalic())
  72636. s += " italic";
  72637. return s;
  72638. }
  72639. const Font Font::fromString (const String& fontDescription)
  72640. {
  72641. String name;
  72642. const int separator = fontDescription.indexOfChar (';');
  72643. if (separator > 0)
  72644. name = fontDescription.substring (0, separator).trim();
  72645. if (name.isEmpty())
  72646. name = getDefaultSansSerifFontName();
  72647. String sizeAndStyle (fontDescription.substring (separator + 1));
  72648. float height = sizeAndStyle.getFloatValue();
  72649. if (height <= 0)
  72650. height = 10.0f;
  72651. int flags = Font::plain;
  72652. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72653. flags |= Font::bold;
  72654. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72655. flags |= Font::italic;
  72656. return Font (name, height, flags);
  72657. }
  72658. class TypefaceCache : public DeletedAtShutdown
  72659. {
  72660. public:
  72661. TypefaceCache (int numToCache = 10) throw()
  72662. : counter (1)
  72663. {
  72664. while (--numToCache >= 0)
  72665. faces.add (new CachedFace());
  72666. }
  72667. ~TypefaceCache()
  72668. {
  72669. clearSingletonInstance();
  72670. }
  72671. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72672. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  72673. {
  72674. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72675. const String faceName (font.getTypefaceName());
  72676. int i;
  72677. for (i = faces.size(); --i >= 0;)
  72678. {
  72679. CachedFace* const face = faces.getUnchecked(i);
  72680. if (face->flags == flags
  72681. && face->typefaceName == faceName)
  72682. {
  72683. face->lastUsageCount = ++counter;
  72684. return face->typeFace;
  72685. }
  72686. }
  72687. int replaceIndex = 0;
  72688. int bestLastUsageCount = std::numeric_limits<int>::max();
  72689. for (i = faces.size(); --i >= 0;)
  72690. {
  72691. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72692. if (bestLastUsageCount > lu)
  72693. {
  72694. bestLastUsageCount = lu;
  72695. replaceIndex = i;
  72696. }
  72697. }
  72698. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72699. face->typefaceName = faceName;
  72700. face->flags = flags;
  72701. face->lastUsageCount = ++counter;
  72702. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72703. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72704. return face->typeFace;
  72705. }
  72706. juce_UseDebuggingNewOperator
  72707. private:
  72708. struct CachedFace
  72709. {
  72710. CachedFace() throw()
  72711. : lastUsageCount (0), flags (-1)
  72712. {
  72713. }
  72714. String typefaceName;
  72715. int lastUsageCount;
  72716. int flags;
  72717. Typeface::Ptr typeFace;
  72718. };
  72719. int counter;
  72720. OwnedArray <CachedFace> faces;
  72721. TypefaceCache (const TypefaceCache&);
  72722. TypefaceCache& operator= (const TypefaceCache&);
  72723. };
  72724. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72725. Typeface* Font::getTypeface() const throw()
  72726. {
  72727. if (font->typeface == 0)
  72728. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72729. return font->typeface;
  72730. }
  72731. END_JUCE_NAMESPACE
  72732. /*** End of inlined file: juce_Font.cpp ***/
  72733. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72734. BEGIN_JUCE_NAMESPACE
  72735. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72736. const juce_wchar character_, const int glyph_)
  72737. : x (x_),
  72738. y (y_),
  72739. w (w_),
  72740. font (font_),
  72741. character (character_),
  72742. glyph (glyph_)
  72743. {
  72744. }
  72745. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72746. : x (other.x),
  72747. y (other.y),
  72748. w (other.w),
  72749. font (other.font),
  72750. character (other.character),
  72751. glyph (other.glyph)
  72752. {
  72753. }
  72754. void PositionedGlyph::draw (const Graphics& g) const
  72755. {
  72756. if (! isWhitespace())
  72757. {
  72758. g.getInternalContext()->setFont (font);
  72759. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72760. }
  72761. }
  72762. void PositionedGlyph::draw (const Graphics& g,
  72763. const AffineTransform& transform) const
  72764. {
  72765. if (! isWhitespace())
  72766. {
  72767. g.getInternalContext()->setFont (font);
  72768. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72769. .followedBy (transform));
  72770. }
  72771. }
  72772. void PositionedGlyph::createPath (Path& path) const
  72773. {
  72774. if (! isWhitespace())
  72775. {
  72776. Typeface* const t = font.getTypeface();
  72777. if (t != 0)
  72778. {
  72779. Path p;
  72780. t->getOutlineForGlyph (glyph, p);
  72781. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72782. .translated (x, y));
  72783. }
  72784. }
  72785. }
  72786. bool PositionedGlyph::hitTest (float px, float py) const
  72787. {
  72788. if (getBounds().contains (px, py) && ! isWhitespace())
  72789. {
  72790. Typeface* const t = font.getTypeface();
  72791. if (t != 0)
  72792. {
  72793. Path p;
  72794. t->getOutlineForGlyph (glyph, p);
  72795. AffineTransform::translation (-x, -y)
  72796. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72797. .transformPoint (px, py);
  72798. return p.contains (px, py);
  72799. }
  72800. }
  72801. return false;
  72802. }
  72803. void PositionedGlyph::moveBy (const float deltaX,
  72804. const float deltaY)
  72805. {
  72806. x += deltaX;
  72807. y += deltaY;
  72808. }
  72809. GlyphArrangement::GlyphArrangement()
  72810. {
  72811. glyphs.ensureStorageAllocated (128);
  72812. }
  72813. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72814. {
  72815. addGlyphArrangement (other);
  72816. }
  72817. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72818. {
  72819. if (this != &other)
  72820. {
  72821. clear();
  72822. addGlyphArrangement (other);
  72823. }
  72824. return *this;
  72825. }
  72826. GlyphArrangement::~GlyphArrangement()
  72827. {
  72828. }
  72829. void GlyphArrangement::clear()
  72830. {
  72831. glyphs.clear();
  72832. }
  72833. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72834. {
  72835. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72836. return *glyphs [index];
  72837. }
  72838. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72839. {
  72840. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72841. glyphs.addCopiesOf (other.glyphs);
  72842. }
  72843. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72844. {
  72845. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72846. }
  72847. void GlyphArrangement::addLineOfText (const Font& font,
  72848. const String& text,
  72849. const float xOffset,
  72850. const float yOffset)
  72851. {
  72852. addCurtailedLineOfText (font, text,
  72853. xOffset, yOffset,
  72854. 1.0e10f, false);
  72855. }
  72856. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72857. const String& text,
  72858. float xOffset,
  72859. const float yOffset,
  72860. const float maxWidthPixels,
  72861. const bool useEllipsis)
  72862. {
  72863. if (text.isNotEmpty())
  72864. {
  72865. Array <int> newGlyphs;
  72866. Array <float> xOffsets;
  72867. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72868. const int textLen = newGlyphs.size();
  72869. const juce_wchar* const unicodeText = text;
  72870. for (int i = 0; i < textLen; ++i)
  72871. {
  72872. const float thisX = xOffsets.getUnchecked (i);
  72873. const float nextX = xOffsets.getUnchecked (i + 1);
  72874. if (nextX > maxWidthPixels + 1.0f)
  72875. {
  72876. // curtail the string if it's too wide..
  72877. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72878. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72879. break;
  72880. }
  72881. else
  72882. {
  72883. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72884. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72885. }
  72886. }
  72887. }
  72888. }
  72889. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72890. const int startIndex, int endIndex)
  72891. {
  72892. int numDeleted = 0;
  72893. if (glyphs.size() > 0)
  72894. {
  72895. Array<int> dotGlyphs;
  72896. Array<float> dotXs;
  72897. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72898. const float dx = dotXs[1];
  72899. float xOffset = 0.0f, yOffset = 0.0f;
  72900. while (endIndex > startIndex)
  72901. {
  72902. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72903. xOffset = pg->x;
  72904. yOffset = pg->y;
  72905. glyphs.remove (endIndex);
  72906. ++numDeleted;
  72907. if (xOffset + dx * 3 <= maxXPos)
  72908. break;
  72909. }
  72910. for (int i = 3; --i >= 0;)
  72911. {
  72912. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72913. font, '.', dotGlyphs.getFirst()));
  72914. --numDeleted;
  72915. xOffset += dx;
  72916. if (xOffset > maxXPos)
  72917. break;
  72918. }
  72919. }
  72920. return numDeleted;
  72921. }
  72922. void GlyphArrangement::addJustifiedText (const Font& font,
  72923. const String& text,
  72924. float x, float y,
  72925. const float maxLineWidth,
  72926. const Justification& horizontalLayout)
  72927. {
  72928. int lineStartIndex = glyphs.size();
  72929. addLineOfText (font, text, x, y);
  72930. const float originalY = y;
  72931. while (lineStartIndex < glyphs.size())
  72932. {
  72933. int i = lineStartIndex;
  72934. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72935. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72936. ++i;
  72937. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72938. int lastWordBreakIndex = -1;
  72939. while (i < glyphs.size())
  72940. {
  72941. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72942. const juce_wchar c = pg->getCharacter();
  72943. if (c == '\r' || c == '\n')
  72944. {
  72945. ++i;
  72946. if (c == '\r' && i < glyphs.size()
  72947. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72948. ++i;
  72949. break;
  72950. }
  72951. else if (pg->isWhitespace())
  72952. {
  72953. lastWordBreakIndex = i + 1;
  72954. }
  72955. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72956. {
  72957. if (lastWordBreakIndex >= 0)
  72958. i = lastWordBreakIndex;
  72959. break;
  72960. }
  72961. ++i;
  72962. }
  72963. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72964. float currentLineEndX = currentLineStartX;
  72965. for (int j = i; --j >= lineStartIndex;)
  72966. {
  72967. if (! glyphs.getUnchecked (j)->isWhitespace())
  72968. {
  72969. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72970. break;
  72971. }
  72972. }
  72973. float deltaX = 0.0f;
  72974. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72975. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72976. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72977. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72978. else if (horizontalLayout.testFlags (Justification::right))
  72979. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72980. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72981. x + deltaX - currentLineStartX, y - originalY);
  72982. lineStartIndex = i;
  72983. y += font.getHeight();
  72984. }
  72985. }
  72986. void GlyphArrangement::addFittedText (const Font& f,
  72987. const String& text,
  72988. const float x, const float y,
  72989. const float width, const float height,
  72990. const Justification& layout,
  72991. int maximumLines,
  72992. const float minimumHorizontalScale)
  72993. {
  72994. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72995. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72996. if (text.containsAnyOf ("\r\n"))
  72997. {
  72998. GlyphArrangement ga;
  72999. ga.addJustifiedText (f, text, x, y, width, layout);
  73000. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  73001. float dy = y - bb.getY();
  73002. if (layout.testFlags (Justification::verticallyCentred))
  73003. dy += (height - bb.getHeight()) * 0.5f;
  73004. else if (layout.testFlags (Justification::bottom))
  73005. dy += height - bb.getHeight();
  73006. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  73007. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  73008. for (int i = 0; i < ga.glyphs.size(); ++i)
  73009. glyphs.add (ga.glyphs.getUnchecked (i));
  73010. ga.glyphs.clear (false);
  73011. return;
  73012. }
  73013. int startIndex = glyphs.size();
  73014. addLineOfText (f, text.trim(), x, y);
  73015. if (glyphs.size() > startIndex)
  73016. {
  73017. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73018. - glyphs.getUnchecked (startIndex)->getLeft();
  73019. if (lineWidth <= 0)
  73020. return;
  73021. if (lineWidth * minimumHorizontalScale < width)
  73022. {
  73023. if (lineWidth > width)
  73024. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  73025. width / lineWidth);
  73026. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  73027. x, y, width, height, layout);
  73028. }
  73029. else if (maximumLines <= 1)
  73030. {
  73031. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  73032. x, y, width, height, f, layout, minimumHorizontalScale);
  73033. }
  73034. else
  73035. {
  73036. Font font (f);
  73037. String txt (text.trim());
  73038. const int length = txt.length();
  73039. const int originalStartIndex = startIndex;
  73040. int numLines = 1;
  73041. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  73042. maximumLines = 1;
  73043. maximumLines = jmin (maximumLines, length);
  73044. while (numLines < maximumLines)
  73045. {
  73046. ++numLines;
  73047. const float newFontHeight = height / (float) numLines;
  73048. if (newFontHeight < font.getHeight())
  73049. {
  73050. font.setHeight (jmax (8.0f, newFontHeight));
  73051. removeRangeOfGlyphs (startIndex, -1);
  73052. addLineOfText (font, txt, x, y);
  73053. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73054. - glyphs.getUnchecked (startIndex)->getLeft();
  73055. }
  73056. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  73057. break;
  73058. }
  73059. if (numLines < 1)
  73060. numLines = 1;
  73061. float lineY = y;
  73062. float widthPerLine = lineWidth / numLines;
  73063. int lastLineStartIndex = 0;
  73064. for (int line = 0; line < numLines; ++line)
  73065. {
  73066. int i = startIndex;
  73067. lastLineStartIndex = i;
  73068. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  73069. if (line == numLines - 1)
  73070. {
  73071. widthPerLine = width;
  73072. i = glyphs.size();
  73073. }
  73074. else
  73075. {
  73076. while (i < glyphs.size())
  73077. {
  73078. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73079. if (lineWidth > widthPerLine)
  73080. {
  73081. // got to a point where the line's too long, so skip forward to find a
  73082. // good place to break it..
  73083. const int searchStartIndex = i;
  73084. while (i < glyphs.size())
  73085. {
  73086. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73087. {
  73088. if (glyphs.getUnchecked (i)->isWhitespace()
  73089. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73090. {
  73091. ++i;
  73092. break;
  73093. }
  73094. }
  73095. else
  73096. {
  73097. // can't find a suitable break, so try looking backwards..
  73098. i = searchStartIndex;
  73099. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73100. {
  73101. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73102. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73103. {
  73104. i -= back - 1;
  73105. break;
  73106. }
  73107. }
  73108. break;
  73109. }
  73110. ++i;
  73111. }
  73112. break;
  73113. }
  73114. ++i;
  73115. }
  73116. int wsStart = i;
  73117. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73118. --wsStart;
  73119. int wsEnd = i;
  73120. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73121. ++wsEnd;
  73122. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73123. i = jmax (wsStart, startIndex + 1);
  73124. }
  73125. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73126. x, lineY, width, font.getHeight(), font,
  73127. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73128. minimumHorizontalScale);
  73129. startIndex = i;
  73130. lineY += font.getHeight();
  73131. if (startIndex >= glyphs.size())
  73132. break;
  73133. }
  73134. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73135. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73136. }
  73137. }
  73138. }
  73139. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73140. const float dx, const float dy)
  73141. {
  73142. jassert (startIndex >= 0);
  73143. if (dx != 0.0f || dy != 0.0f)
  73144. {
  73145. if (num < 0 || startIndex + num > glyphs.size())
  73146. num = glyphs.size() - startIndex;
  73147. while (--num >= 0)
  73148. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73149. }
  73150. }
  73151. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73152. const Justification& justification, float minimumHorizontalScale)
  73153. {
  73154. int numDeleted = 0;
  73155. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73156. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73157. if (lineWidth > w)
  73158. {
  73159. if (minimumHorizontalScale < 1.0f)
  73160. {
  73161. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73162. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73163. }
  73164. if (lineWidth > w)
  73165. {
  73166. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73167. numGlyphs -= numDeleted;
  73168. }
  73169. }
  73170. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73171. return numDeleted;
  73172. }
  73173. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73174. const float horizontalScaleFactor)
  73175. {
  73176. jassert (startIndex >= 0);
  73177. if (num < 0 || startIndex + num > glyphs.size())
  73178. num = glyphs.size() - startIndex;
  73179. if (num > 0)
  73180. {
  73181. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73182. while (--num >= 0)
  73183. {
  73184. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73185. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73186. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73187. pg->w *= horizontalScaleFactor;
  73188. }
  73189. }
  73190. }
  73191. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73192. {
  73193. jassert (startIndex >= 0);
  73194. if (num < 0 || startIndex + num > glyphs.size())
  73195. num = glyphs.size() - startIndex;
  73196. Rectangle<float> result;
  73197. while (--num >= 0)
  73198. {
  73199. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73200. if (includeWhitespace || ! pg->isWhitespace())
  73201. result = result.getUnion (pg->getBounds());
  73202. }
  73203. return result;
  73204. }
  73205. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73206. const float x, const float y, const float width, const float height,
  73207. const Justification& justification)
  73208. {
  73209. jassert (num >= 0 && startIndex >= 0);
  73210. if (glyphs.size() > 0 && num > 0)
  73211. {
  73212. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73213. | Justification::horizontallyCentred)));
  73214. float deltaX = 0.0f;
  73215. if (justification.testFlags (Justification::horizontallyJustified))
  73216. deltaX = x - bb.getX();
  73217. else if (justification.testFlags (Justification::horizontallyCentred))
  73218. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73219. else if (justification.testFlags (Justification::right))
  73220. deltaX = (x + width) - bb.getRight();
  73221. else
  73222. deltaX = x - bb.getX();
  73223. float deltaY = 0.0f;
  73224. if (justification.testFlags (Justification::top))
  73225. deltaY = y - bb.getY();
  73226. else if (justification.testFlags (Justification::bottom))
  73227. deltaY = (y + height) - bb.getBottom();
  73228. else
  73229. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73230. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73231. if (justification.testFlags (Justification::horizontallyJustified))
  73232. {
  73233. int lineStart = 0;
  73234. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73235. int i;
  73236. for (i = 0; i < num; ++i)
  73237. {
  73238. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73239. if (glyphY != baseY)
  73240. {
  73241. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73242. lineStart = i;
  73243. baseY = glyphY;
  73244. }
  73245. }
  73246. if (i > lineStart)
  73247. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73248. }
  73249. }
  73250. }
  73251. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73252. {
  73253. if (start + num < glyphs.size()
  73254. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73255. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73256. {
  73257. int numSpaces = 0;
  73258. int spacesAtEnd = 0;
  73259. for (int i = 0; i < num; ++i)
  73260. {
  73261. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73262. {
  73263. ++spacesAtEnd;
  73264. ++numSpaces;
  73265. }
  73266. else
  73267. {
  73268. spacesAtEnd = 0;
  73269. }
  73270. }
  73271. numSpaces -= spacesAtEnd;
  73272. if (numSpaces > 0)
  73273. {
  73274. const float startX = glyphs.getUnchecked (start)->getLeft();
  73275. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73276. const float extraPaddingBetweenWords
  73277. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73278. float deltaX = 0.0f;
  73279. for (int i = 0; i < num; ++i)
  73280. {
  73281. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73282. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73283. deltaX += extraPaddingBetweenWords;
  73284. }
  73285. }
  73286. }
  73287. }
  73288. void GlyphArrangement::draw (const Graphics& g) const
  73289. {
  73290. for (int i = 0; i < glyphs.size(); ++i)
  73291. {
  73292. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73293. if (pg->font.isUnderlined())
  73294. {
  73295. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73296. float nextX = pg->x + pg->w;
  73297. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73298. nextX = glyphs.getUnchecked (i + 1)->x;
  73299. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73300. nextX - pg->x, lineThickness);
  73301. }
  73302. pg->draw (g);
  73303. }
  73304. }
  73305. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73306. {
  73307. for (int i = 0; i < glyphs.size(); ++i)
  73308. {
  73309. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73310. if (pg->font.isUnderlined())
  73311. {
  73312. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73313. float nextX = pg->x + pg->w;
  73314. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73315. nextX = glyphs.getUnchecked (i + 1)->x;
  73316. Path p;
  73317. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73318. nextX, pg->y + lineThickness * 2.0f),
  73319. lineThickness);
  73320. g.fillPath (p, transform);
  73321. }
  73322. pg->draw (g, transform);
  73323. }
  73324. }
  73325. void GlyphArrangement::createPath (Path& path) const
  73326. {
  73327. for (int i = 0; i < glyphs.size(); ++i)
  73328. glyphs.getUnchecked (i)->createPath (path);
  73329. }
  73330. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73331. {
  73332. for (int i = 0; i < glyphs.size(); ++i)
  73333. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73334. return i;
  73335. return -1;
  73336. }
  73337. END_JUCE_NAMESPACE
  73338. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73339. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73340. BEGIN_JUCE_NAMESPACE
  73341. class TextLayout::Token
  73342. {
  73343. public:
  73344. String text;
  73345. Font font;
  73346. int x, y, w, h;
  73347. int line, lineHeight;
  73348. bool isWhitespace, isNewLine;
  73349. Token (const String& t,
  73350. const Font& f,
  73351. const bool isWhitespace_)
  73352. : text (t),
  73353. font (f),
  73354. x(0),
  73355. y(0),
  73356. isWhitespace (isWhitespace_)
  73357. {
  73358. w = font.getStringWidth (t);
  73359. h = roundToInt (f.getHeight());
  73360. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73361. }
  73362. Token (const Token& other)
  73363. : text (other.text),
  73364. font (other.font),
  73365. x (other.x),
  73366. y (other.y),
  73367. w (other.w),
  73368. h (other.h),
  73369. line (other.line),
  73370. lineHeight (other.lineHeight),
  73371. isWhitespace (other.isWhitespace),
  73372. isNewLine (other.isNewLine)
  73373. {
  73374. }
  73375. ~Token()
  73376. {
  73377. }
  73378. void draw (Graphics& g,
  73379. const int xOffset,
  73380. const int yOffset)
  73381. {
  73382. if (! isWhitespace)
  73383. {
  73384. g.setFont (font);
  73385. g.drawSingleLineText (text.trimEnd(),
  73386. xOffset + x,
  73387. yOffset + y + (lineHeight - h)
  73388. + roundToInt (font.getAscent()));
  73389. }
  73390. }
  73391. juce_UseDebuggingNewOperator
  73392. };
  73393. TextLayout::TextLayout()
  73394. : totalLines (0)
  73395. {
  73396. tokens.ensureStorageAllocated (64);
  73397. }
  73398. TextLayout::TextLayout (const String& text, const Font& font)
  73399. : totalLines (0)
  73400. {
  73401. tokens.ensureStorageAllocated (64);
  73402. appendText (text, font);
  73403. }
  73404. TextLayout::TextLayout (const TextLayout& other)
  73405. : totalLines (0)
  73406. {
  73407. *this = other;
  73408. }
  73409. TextLayout& TextLayout::operator= (const TextLayout& other)
  73410. {
  73411. if (this != &other)
  73412. {
  73413. clear();
  73414. totalLines = other.totalLines;
  73415. tokens.addCopiesOf (other.tokens);
  73416. }
  73417. return *this;
  73418. }
  73419. TextLayout::~TextLayout()
  73420. {
  73421. clear();
  73422. }
  73423. void TextLayout::clear()
  73424. {
  73425. tokens.clear();
  73426. totalLines = 0;
  73427. }
  73428. void TextLayout::appendText (const String& text, const Font& font)
  73429. {
  73430. const juce_wchar* t = text;
  73431. String currentString;
  73432. int lastCharType = 0;
  73433. for (;;)
  73434. {
  73435. const juce_wchar c = *t++;
  73436. if (c == 0)
  73437. break;
  73438. int charType;
  73439. if (c == '\r' || c == '\n')
  73440. {
  73441. charType = 0;
  73442. }
  73443. else if (CharacterFunctions::isWhitespace (c))
  73444. {
  73445. charType = 2;
  73446. }
  73447. else
  73448. {
  73449. charType = 1;
  73450. }
  73451. if (charType == 0 || charType != lastCharType)
  73452. {
  73453. if (currentString.isNotEmpty())
  73454. {
  73455. tokens.add (new Token (currentString, font,
  73456. lastCharType == 2 || lastCharType == 0));
  73457. }
  73458. currentString = String::charToString (c);
  73459. if (c == '\r' && *t == '\n')
  73460. currentString += *t++;
  73461. }
  73462. else
  73463. {
  73464. currentString += c;
  73465. }
  73466. lastCharType = charType;
  73467. }
  73468. if (currentString.isNotEmpty())
  73469. tokens.add (new Token (currentString, font, lastCharType == 2));
  73470. }
  73471. void TextLayout::setText (const String& text, const Font& font)
  73472. {
  73473. clear();
  73474. appendText (text, font);
  73475. }
  73476. void TextLayout::layout (int maxWidth,
  73477. const Justification& justification,
  73478. const bool attemptToBalanceLineLengths)
  73479. {
  73480. if (attemptToBalanceLineLengths)
  73481. {
  73482. const int originalW = maxWidth;
  73483. int bestWidth = maxWidth;
  73484. float bestLineProportion = 0.0f;
  73485. while (maxWidth > originalW / 2)
  73486. {
  73487. layout (maxWidth, justification, false);
  73488. if (getNumLines() <= 1)
  73489. return;
  73490. const int lastLineW = getLineWidth (getNumLines() - 1);
  73491. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73492. const float prop = lastLineW / (float) lastButOneLineW;
  73493. if (prop > 0.9f)
  73494. return;
  73495. if (prop > bestLineProportion)
  73496. {
  73497. bestLineProportion = prop;
  73498. bestWidth = maxWidth;
  73499. }
  73500. maxWidth -= 10;
  73501. }
  73502. layout (bestWidth, justification, false);
  73503. }
  73504. else
  73505. {
  73506. int x = 0;
  73507. int y = 0;
  73508. int h = 0;
  73509. totalLines = 0;
  73510. int i;
  73511. for (i = 0; i < tokens.size(); ++i)
  73512. {
  73513. Token* const t = tokens.getUnchecked(i);
  73514. t->x = x;
  73515. t->y = y;
  73516. t->line = totalLines;
  73517. x += t->w;
  73518. h = jmax (h, t->h);
  73519. const Token* nextTok = tokens [i + 1];
  73520. if (nextTok == 0)
  73521. break;
  73522. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73523. {
  73524. // finished a line, so go back and update the heights of the things on it
  73525. for (int j = i; j >= 0; --j)
  73526. {
  73527. Token* const tok = tokens.getUnchecked(j);
  73528. if (tok->line == totalLines)
  73529. tok->lineHeight = h;
  73530. else
  73531. break;
  73532. }
  73533. x = 0;
  73534. y += h;
  73535. h = 0;
  73536. ++totalLines;
  73537. }
  73538. }
  73539. // finished a line, so go back and update the heights of the things on it
  73540. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73541. {
  73542. Token* const t = tokens.getUnchecked(j);
  73543. if (t->line == totalLines)
  73544. t->lineHeight = h;
  73545. else
  73546. break;
  73547. }
  73548. ++totalLines;
  73549. if (! justification.testFlags (Justification::left))
  73550. {
  73551. int totalW = getWidth();
  73552. for (i = totalLines; --i >= 0;)
  73553. {
  73554. const int lineW = getLineWidth (i);
  73555. int dx = 0;
  73556. if (justification.testFlags (Justification::horizontallyCentred))
  73557. dx = (totalW - lineW) / 2;
  73558. else if (justification.testFlags (Justification::right))
  73559. dx = totalW - lineW;
  73560. for (int j = tokens.size(); --j >= 0;)
  73561. {
  73562. Token* const t = tokens.getUnchecked(j);
  73563. if (t->line == i)
  73564. t->x += dx;
  73565. }
  73566. }
  73567. }
  73568. }
  73569. }
  73570. int TextLayout::getLineWidth (const int lineNumber) const
  73571. {
  73572. int maxW = 0;
  73573. for (int i = tokens.size(); --i >= 0;)
  73574. {
  73575. const Token* const t = tokens.getUnchecked(i);
  73576. if (t->line == lineNumber && ! t->isWhitespace)
  73577. maxW = jmax (maxW, t->x + t->w);
  73578. }
  73579. return maxW;
  73580. }
  73581. int TextLayout::getWidth() const
  73582. {
  73583. int maxW = 0;
  73584. for (int i = tokens.size(); --i >= 0;)
  73585. {
  73586. const Token* const t = tokens.getUnchecked(i);
  73587. if (! t->isWhitespace)
  73588. maxW = jmax (maxW, t->x + t->w);
  73589. }
  73590. return maxW;
  73591. }
  73592. int TextLayout::getHeight() const
  73593. {
  73594. int maxH = 0;
  73595. for (int i = tokens.size(); --i >= 0;)
  73596. {
  73597. const Token* const t = tokens.getUnchecked(i);
  73598. if (! t->isWhitespace)
  73599. maxH = jmax (maxH, t->y + t->h);
  73600. }
  73601. return maxH;
  73602. }
  73603. void TextLayout::draw (Graphics& g,
  73604. const int xOffset,
  73605. const int yOffset) const
  73606. {
  73607. for (int i = tokens.size(); --i >= 0;)
  73608. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73609. }
  73610. void TextLayout::drawWithin (Graphics& g,
  73611. int x, int y, int w, int h,
  73612. const Justification& justification) const
  73613. {
  73614. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73615. x, y, w, h);
  73616. draw (g, x, y);
  73617. }
  73618. END_JUCE_NAMESPACE
  73619. /*** End of inlined file: juce_TextLayout.cpp ***/
  73620. /*** Start of inlined file: juce_Typeface.cpp ***/
  73621. BEGIN_JUCE_NAMESPACE
  73622. Typeface::Typeface (const String& name_) throw()
  73623. : name (name_)
  73624. {
  73625. }
  73626. Typeface::~Typeface()
  73627. {
  73628. }
  73629. class CustomTypeface::GlyphInfo
  73630. {
  73631. public:
  73632. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73633. : character (character_), path (path_), width (width_)
  73634. {
  73635. }
  73636. ~GlyphInfo() throw()
  73637. {
  73638. }
  73639. struct KerningPair
  73640. {
  73641. juce_wchar character2;
  73642. float kerningAmount;
  73643. };
  73644. void addKerningPair (const juce_wchar subsequentCharacter,
  73645. const float extraKerningAmount) throw()
  73646. {
  73647. KerningPair kp;
  73648. kp.character2 = subsequentCharacter;
  73649. kp.kerningAmount = extraKerningAmount;
  73650. kerningPairs.add (kp);
  73651. }
  73652. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73653. {
  73654. if (subsequentCharacter != 0)
  73655. {
  73656. for (int i = kerningPairs.size(); --i >= 0;)
  73657. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73658. return width + kerningPairs.getReference(i).kerningAmount;
  73659. }
  73660. return width;
  73661. }
  73662. const juce_wchar character;
  73663. const Path path;
  73664. float width;
  73665. Array <KerningPair> kerningPairs;
  73666. juce_UseDebuggingNewOperator
  73667. private:
  73668. GlyphInfo (const GlyphInfo&);
  73669. GlyphInfo& operator= (const GlyphInfo&);
  73670. };
  73671. CustomTypeface::CustomTypeface()
  73672. : Typeface (String::empty)
  73673. {
  73674. clear();
  73675. }
  73676. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73677. : Typeface (String::empty)
  73678. {
  73679. clear();
  73680. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  73681. BufferedInputStream in (&gzin, 32768, false);
  73682. name = in.readString();
  73683. isBold = in.readBool();
  73684. isItalic = in.readBool();
  73685. ascent = in.readFloat();
  73686. defaultCharacter = (juce_wchar) in.readShort();
  73687. int i, numChars = in.readInt();
  73688. for (i = 0; i < numChars; ++i)
  73689. {
  73690. const juce_wchar c = (juce_wchar) in.readShort();
  73691. const float width = in.readFloat();
  73692. Path p;
  73693. p.loadPathFromStream (in);
  73694. addGlyph (c, p, width);
  73695. }
  73696. const int numKerningPairs = in.readInt();
  73697. for (i = 0; i < numKerningPairs; ++i)
  73698. {
  73699. const juce_wchar char1 = (juce_wchar) in.readShort();
  73700. const juce_wchar char2 = (juce_wchar) in.readShort();
  73701. addKerningPair (char1, char2, in.readFloat());
  73702. }
  73703. }
  73704. CustomTypeface::~CustomTypeface()
  73705. {
  73706. }
  73707. void CustomTypeface::clear()
  73708. {
  73709. defaultCharacter = 0;
  73710. ascent = 1.0f;
  73711. isBold = isItalic = false;
  73712. zeromem (lookupTable, sizeof (lookupTable));
  73713. glyphs.clear();
  73714. }
  73715. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73716. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73717. {
  73718. name = name_;
  73719. defaultCharacter = defaultCharacter_;
  73720. ascent = ascent_;
  73721. isBold = isBold_;
  73722. isItalic = isItalic_;
  73723. }
  73724. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73725. {
  73726. // Check that you're not trying to add the same character twice..
  73727. jassert (findGlyph (character, false) == 0);
  73728. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73729. lookupTable [character] = (short) glyphs.size();
  73730. glyphs.add (new GlyphInfo (character, path, width));
  73731. }
  73732. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73733. {
  73734. if (extraAmount != 0)
  73735. {
  73736. GlyphInfo* const g = findGlyph (char1, true);
  73737. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73738. if (g != 0)
  73739. g->addKerningPair (char2, extraAmount);
  73740. }
  73741. }
  73742. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73743. {
  73744. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73745. return glyphs [(int) lookupTable [(int) character]];
  73746. for (int i = 0; i < glyphs.size(); ++i)
  73747. {
  73748. GlyphInfo* const g = glyphs.getUnchecked(i);
  73749. if (g->character == character)
  73750. return g;
  73751. }
  73752. if (loadIfNeeded && loadGlyphIfPossible (character))
  73753. return findGlyph (character, false);
  73754. return 0;
  73755. }
  73756. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73757. {
  73758. GlyphInfo* glyph = findGlyph (character, true);
  73759. if (glyph == 0)
  73760. {
  73761. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73762. glyph = findGlyph (L' ', true);
  73763. if (glyph == 0)
  73764. {
  73765. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73766. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73767. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73768. {
  73769. //xxx
  73770. }
  73771. if (glyph == 0)
  73772. glyph = findGlyph (defaultCharacter, true);
  73773. }
  73774. }
  73775. return glyph;
  73776. }
  73777. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73778. {
  73779. return false;
  73780. }
  73781. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73782. {
  73783. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73784. for (int i = 0; i < numCharacters; ++i)
  73785. {
  73786. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73787. Array <int> glyphIndexes;
  73788. Array <float> offsets;
  73789. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73790. const int glyphIndex = glyphIndexes.getFirst();
  73791. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73792. {
  73793. const float glyphWidth = offsets[1];
  73794. Path p;
  73795. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73796. addGlyph (c, p, glyphWidth);
  73797. for (int j = glyphs.size() - 1; --j >= 0;)
  73798. {
  73799. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73800. glyphIndexes.clearQuick();
  73801. offsets.clearQuick();
  73802. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73803. if (offsets.size() > 1)
  73804. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73805. }
  73806. }
  73807. }
  73808. }
  73809. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73810. {
  73811. GZIPCompressorOutputStream out (&outputStream);
  73812. out.writeString (name);
  73813. out.writeBool (isBold);
  73814. out.writeBool (isItalic);
  73815. out.writeFloat (ascent);
  73816. out.writeShort ((short) (unsigned short) defaultCharacter);
  73817. out.writeInt (glyphs.size());
  73818. int i, numKerningPairs = 0;
  73819. for (i = 0; i < glyphs.size(); ++i)
  73820. {
  73821. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73822. out.writeShort ((short) (unsigned short) g->character);
  73823. out.writeFloat (g->width);
  73824. g->path.writePathToStream (out);
  73825. numKerningPairs += g->kerningPairs.size();
  73826. }
  73827. out.writeInt (numKerningPairs);
  73828. for (i = 0; i < glyphs.size(); ++i)
  73829. {
  73830. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73831. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73832. {
  73833. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73834. out.writeShort ((short) (unsigned short) g->character);
  73835. out.writeShort ((short) (unsigned short) p.character2);
  73836. out.writeFloat (p.kerningAmount);
  73837. }
  73838. }
  73839. return true;
  73840. }
  73841. float CustomTypeface::getAscent() const
  73842. {
  73843. return ascent;
  73844. }
  73845. float CustomTypeface::getDescent() const
  73846. {
  73847. return 1.0f - ascent;
  73848. }
  73849. float CustomTypeface::getStringWidth (const String& text)
  73850. {
  73851. float x = 0;
  73852. const juce_wchar* t = text;
  73853. while (*t != 0)
  73854. {
  73855. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73856. if (glyph != 0)
  73857. x += glyph->getHorizontalSpacing (*t);
  73858. }
  73859. return x;
  73860. }
  73861. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73862. {
  73863. xOffsets.add (0);
  73864. float x = 0;
  73865. const juce_wchar* t = text;
  73866. while (*t != 0)
  73867. {
  73868. const juce_wchar c = *t++;
  73869. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73870. if (glyph != 0)
  73871. {
  73872. x += glyph->getHorizontalSpacing (*t);
  73873. resultGlyphs.add ((int) glyph->character);
  73874. xOffsets.add (x);
  73875. }
  73876. }
  73877. }
  73878. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73879. {
  73880. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73881. if (glyph != 0)
  73882. {
  73883. path = glyph->path;
  73884. return true;
  73885. }
  73886. return false;
  73887. }
  73888. END_JUCE_NAMESPACE
  73889. /*** End of inlined file: juce_Typeface.cpp ***/
  73890. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73891. BEGIN_JUCE_NAMESPACE
  73892. AffineTransform::AffineTransform() throw()
  73893. : mat00 (1.0f),
  73894. mat01 (0),
  73895. mat02 (0),
  73896. mat10 (0),
  73897. mat11 (1.0f),
  73898. mat12 (0)
  73899. {
  73900. }
  73901. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73902. : mat00 (other.mat00),
  73903. mat01 (other.mat01),
  73904. mat02 (other.mat02),
  73905. mat10 (other.mat10),
  73906. mat11 (other.mat11),
  73907. mat12 (other.mat12)
  73908. {
  73909. }
  73910. AffineTransform::AffineTransform (const float mat00_,
  73911. const float mat01_,
  73912. const float mat02_,
  73913. const float mat10_,
  73914. const float mat11_,
  73915. const float mat12_) throw()
  73916. : mat00 (mat00_),
  73917. mat01 (mat01_),
  73918. mat02 (mat02_),
  73919. mat10 (mat10_),
  73920. mat11 (mat11_),
  73921. mat12 (mat12_)
  73922. {
  73923. }
  73924. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73925. {
  73926. mat00 = other.mat00;
  73927. mat01 = other.mat01;
  73928. mat02 = other.mat02;
  73929. mat10 = other.mat10;
  73930. mat11 = other.mat11;
  73931. mat12 = other.mat12;
  73932. return *this;
  73933. }
  73934. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73935. {
  73936. return mat00 == other.mat00
  73937. && mat01 == other.mat01
  73938. && mat02 == other.mat02
  73939. && mat10 == other.mat10
  73940. && mat11 == other.mat11
  73941. && mat12 == other.mat12;
  73942. }
  73943. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73944. {
  73945. return ! operator== (other);
  73946. }
  73947. bool AffineTransform::isIdentity() const throw()
  73948. {
  73949. return (mat01 == 0)
  73950. && (mat02 == 0)
  73951. && (mat10 == 0)
  73952. && (mat12 == 0)
  73953. && (mat00 == 1.0f)
  73954. && (mat11 == 1.0f);
  73955. }
  73956. const AffineTransform AffineTransform::identity;
  73957. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73958. {
  73959. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73960. other.mat00 * mat01 + other.mat01 * mat11,
  73961. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73962. other.mat10 * mat00 + other.mat11 * mat10,
  73963. other.mat10 * mat01 + other.mat11 * mat11,
  73964. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73965. }
  73966. const AffineTransform AffineTransform::followedBy (const float omat00,
  73967. const float omat01,
  73968. const float omat02,
  73969. const float omat10,
  73970. const float omat11,
  73971. const float omat12) const throw()
  73972. {
  73973. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73974. omat00 * mat01 + omat01 * mat11,
  73975. omat00 * mat02 + omat01 * mat12 + omat02,
  73976. omat10 * mat00 + omat11 * mat10,
  73977. omat10 * mat01 + omat11 * mat11,
  73978. omat10 * mat02 + omat11 * mat12 + omat12);
  73979. }
  73980. const AffineTransform AffineTransform::translated (const float dx,
  73981. const float dy) const throw()
  73982. {
  73983. return AffineTransform (mat00, mat01, mat02 + dx,
  73984. mat10, mat11, mat12 + dy);
  73985. }
  73986. const AffineTransform AffineTransform::translation (const float dx,
  73987. const float dy) throw()
  73988. {
  73989. return AffineTransform (1.0f, 0, dx,
  73990. 0, 1.0f, dy);
  73991. }
  73992. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73993. {
  73994. const float cosRad = std::cos (rad);
  73995. const float sinRad = std::sin (rad);
  73996. return followedBy (cosRad, -sinRad, 0,
  73997. sinRad, cosRad, 0);
  73998. }
  73999. const AffineTransform AffineTransform::rotation (const float rad) throw()
  74000. {
  74001. const float cosRad = std::cos (rad);
  74002. const float sinRad = std::sin (rad);
  74003. return AffineTransform (cosRad, -sinRad, 0,
  74004. sinRad, cosRad, 0);
  74005. }
  74006. const AffineTransform AffineTransform::rotated (const float angle,
  74007. const float pivotX,
  74008. const float pivotY) const throw()
  74009. {
  74010. return translated (-pivotX, -pivotY)
  74011. .rotated (angle)
  74012. .translated (pivotX, pivotY);
  74013. }
  74014. const AffineTransform AffineTransform::rotation (const float angle,
  74015. const float pivotX,
  74016. const float pivotY) throw()
  74017. {
  74018. return translation (-pivotX, -pivotY)
  74019. .rotated (angle)
  74020. .translated (pivotX, pivotY);
  74021. }
  74022. const AffineTransform AffineTransform::scaled (const float factorX,
  74023. const float factorY) const throw()
  74024. {
  74025. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  74026. factorY * mat10, factorY * mat11, factorY * mat12);
  74027. }
  74028. const AffineTransform AffineTransform::scale (const float factorX,
  74029. const float factorY) throw()
  74030. {
  74031. return AffineTransform (factorX, 0, 0,
  74032. 0, factorY, 0);
  74033. }
  74034. const AffineTransform AffineTransform::sheared (const float shearX,
  74035. const float shearY) const throw()
  74036. {
  74037. return followedBy (1.0f, shearX, 0,
  74038. shearY, 1.0f, 0);
  74039. }
  74040. const AffineTransform AffineTransform::inverted() const throw()
  74041. {
  74042. double determinant = (mat00 * mat11 - mat10 * mat01);
  74043. if (determinant != 0.0)
  74044. {
  74045. determinant = 1.0 / determinant;
  74046. const float dst00 = (float) (mat11 * determinant);
  74047. const float dst10 = (float) (-mat10 * determinant);
  74048. const float dst01 = (float) (-mat01 * determinant);
  74049. const float dst11 = (float) (mat00 * determinant);
  74050. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  74051. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  74052. }
  74053. else
  74054. {
  74055. // singularity..
  74056. return *this;
  74057. }
  74058. }
  74059. bool AffineTransform::isSingularity() const throw()
  74060. {
  74061. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  74062. }
  74063. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74064. const float x10, const float y10,
  74065. const float x01, const float y01) throw()
  74066. {
  74067. return AffineTransform (x10 - x00, x01 - x00, x00,
  74068. y10 - y00, y01 - y00, y00);
  74069. }
  74070. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74071. const float sx2, const float sy2, const float tx2, const float ty2,
  74072. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74073. {
  74074. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74075. .inverted()
  74076. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74077. }
  74078. bool AffineTransform::isOnlyTranslation() const throw()
  74079. {
  74080. return (mat01 == 0)
  74081. && (mat10 == 0)
  74082. && (mat00 == 1.0f)
  74083. && (mat11 == 1.0f);
  74084. }
  74085. END_JUCE_NAMESPACE
  74086. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74087. /*** Start of inlined file: juce_BorderSize.cpp ***/
  74088. BEGIN_JUCE_NAMESPACE
  74089. BorderSize::BorderSize() throw()
  74090. : top (0),
  74091. left (0),
  74092. bottom (0),
  74093. right (0)
  74094. {
  74095. }
  74096. BorderSize::BorderSize (const BorderSize& other) throw()
  74097. : top (other.top),
  74098. left (other.left),
  74099. bottom (other.bottom),
  74100. right (other.right)
  74101. {
  74102. }
  74103. BorderSize::BorderSize (const int topGap,
  74104. const int leftGap,
  74105. const int bottomGap,
  74106. const int rightGap) throw()
  74107. : top (topGap),
  74108. left (leftGap),
  74109. bottom (bottomGap),
  74110. right (rightGap)
  74111. {
  74112. }
  74113. BorderSize::BorderSize (const int allGaps) throw()
  74114. : top (allGaps),
  74115. left (allGaps),
  74116. bottom (allGaps),
  74117. right (allGaps)
  74118. {
  74119. }
  74120. BorderSize::~BorderSize() throw()
  74121. {
  74122. }
  74123. void BorderSize::setTop (const int newTopGap) throw()
  74124. {
  74125. top = newTopGap;
  74126. }
  74127. void BorderSize::setLeft (const int newLeftGap) throw()
  74128. {
  74129. left = newLeftGap;
  74130. }
  74131. void BorderSize::setBottom (const int newBottomGap) throw()
  74132. {
  74133. bottom = newBottomGap;
  74134. }
  74135. void BorderSize::setRight (const int newRightGap) throw()
  74136. {
  74137. right = newRightGap;
  74138. }
  74139. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  74140. {
  74141. return Rectangle<int> (r.getX() + left,
  74142. r.getY() + top,
  74143. r.getWidth() - (left + right),
  74144. r.getHeight() - (top + bottom));
  74145. }
  74146. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  74147. {
  74148. r.setBounds (r.getX() + left,
  74149. r.getY() + top,
  74150. r.getWidth() - (left + right),
  74151. r.getHeight() - (top + bottom));
  74152. }
  74153. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  74154. {
  74155. return Rectangle<int> (r.getX() - left,
  74156. r.getY() - top,
  74157. r.getWidth() + (left + right),
  74158. r.getHeight() + (top + bottom));
  74159. }
  74160. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74161. {
  74162. r.setBounds (r.getX() - left,
  74163. r.getY() - top,
  74164. r.getWidth() + (left + right),
  74165. r.getHeight() + (top + bottom));
  74166. }
  74167. bool BorderSize::operator== (const BorderSize& other) const throw()
  74168. {
  74169. return top == other.top
  74170. && left == other.left
  74171. && bottom == other.bottom
  74172. && right == other.right;
  74173. }
  74174. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74175. {
  74176. return ! operator== (other);
  74177. }
  74178. END_JUCE_NAMESPACE
  74179. /*** End of inlined file: juce_BorderSize.cpp ***/
  74180. /*** Start of inlined file: juce_Path.cpp ***/
  74181. BEGIN_JUCE_NAMESPACE
  74182. // tests that some co-ords aren't NaNs
  74183. #define CHECK_COORDS_ARE_VALID(x, y) \
  74184. jassert (x == x && y == y);
  74185. namespace PathHelpers
  74186. {
  74187. static const float ellipseAngularIncrement = 0.05f;
  74188. static const String nextToken (const juce_wchar*& t)
  74189. {
  74190. while (CharacterFunctions::isWhitespace (*t))
  74191. ++t;
  74192. const juce_wchar* const start = t;
  74193. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74194. ++t;
  74195. return String (start, (int) (t - start));
  74196. }
  74197. }
  74198. const float Path::lineMarker = 100001.0f;
  74199. const float Path::moveMarker = 100002.0f;
  74200. const float Path::quadMarker = 100003.0f;
  74201. const float Path::cubicMarker = 100004.0f;
  74202. const float Path::closeSubPathMarker = 100005.0f;
  74203. Path::Path()
  74204. : numElements (0),
  74205. pathXMin (0),
  74206. pathXMax (0),
  74207. pathYMin (0),
  74208. pathYMax (0),
  74209. useNonZeroWinding (true)
  74210. {
  74211. }
  74212. Path::~Path()
  74213. {
  74214. }
  74215. Path::Path (const Path& other)
  74216. : numElements (other.numElements),
  74217. pathXMin (other.pathXMin),
  74218. pathXMax (other.pathXMax),
  74219. pathYMin (other.pathYMin),
  74220. pathYMax (other.pathYMax),
  74221. useNonZeroWinding (other.useNonZeroWinding)
  74222. {
  74223. if (numElements > 0)
  74224. {
  74225. data.setAllocatedSize ((int) numElements);
  74226. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74227. }
  74228. }
  74229. Path& Path::operator= (const Path& other)
  74230. {
  74231. if (this != &other)
  74232. {
  74233. data.ensureAllocatedSize ((int) other.numElements);
  74234. numElements = other.numElements;
  74235. pathXMin = other.pathXMin;
  74236. pathXMax = other.pathXMax;
  74237. pathYMin = other.pathYMin;
  74238. pathYMax = other.pathYMax;
  74239. useNonZeroWinding = other.useNonZeroWinding;
  74240. if (numElements > 0)
  74241. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74242. }
  74243. return *this;
  74244. }
  74245. bool Path::operator== (const Path& other) const throw()
  74246. {
  74247. return ! operator!= (other);
  74248. }
  74249. bool Path::operator!= (const Path& other) const throw()
  74250. {
  74251. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74252. return true;
  74253. for (size_t i = 0; i < numElements; ++i)
  74254. if (data.elements[i] != other.data.elements[i])
  74255. return true;
  74256. return false;
  74257. }
  74258. void Path::clear() throw()
  74259. {
  74260. numElements = 0;
  74261. pathXMin = 0;
  74262. pathYMin = 0;
  74263. pathYMax = 0;
  74264. pathXMax = 0;
  74265. }
  74266. void Path::swapWithPath (Path& other) throw()
  74267. {
  74268. data.swapWith (other.data);
  74269. swapVariables <size_t> (numElements, other.numElements);
  74270. swapVariables <float> (pathXMin, other.pathXMin);
  74271. swapVariables <float> (pathXMax, other.pathXMax);
  74272. swapVariables <float> (pathYMin, other.pathYMin);
  74273. swapVariables <float> (pathYMax, other.pathYMax);
  74274. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74275. }
  74276. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74277. {
  74278. useNonZeroWinding = isNonZero;
  74279. }
  74280. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74281. const bool preserveProportions) throw()
  74282. {
  74283. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74284. }
  74285. bool Path::isEmpty() const throw()
  74286. {
  74287. size_t i = 0;
  74288. while (i < numElements)
  74289. {
  74290. const float type = data.elements [i++];
  74291. if (type == moveMarker)
  74292. {
  74293. i += 2;
  74294. }
  74295. else if (type == lineMarker
  74296. || type == quadMarker
  74297. || type == cubicMarker)
  74298. {
  74299. return false;
  74300. }
  74301. }
  74302. return true;
  74303. }
  74304. const Rectangle<float> Path::getBounds() const throw()
  74305. {
  74306. return Rectangle<float> (pathXMin, pathYMin,
  74307. pathXMax - pathXMin,
  74308. pathYMax - pathYMin);
  74309. }
  74310. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74311. {
  74312. return getBounds().transformed (transform);
  74313. }
  74314. void Path::startNewSubPath (const float x, const float y)
  74315. {
  74316. CHECK_COORDS_ARE_VALID (x, y);
  74317. if (numElements == 0)
  74318. {
  74319. pathXMin = pathXMax = x;
  74320. pathYMin = pathYMax = y;
  74321. }
  74322. else
  74323. {
  74324. pathXMin = jmin (pathXMin, x);
  74325. pathXMax = jmax (pathXMax, x);
  74326. pathYMin = jmin (pathYMin, y);
  74327. pathYMax = jmax (pathYMax, y);
  74328. }
  74329. data.ensureAllocatedSize ((int) numElements + 3);
  74330. data.elements [numElements++] = moveMarker;
  74331. data.elements [numElements++] = x;
  74332. data.elements [numElements++] = y;
  74333. }
  74334. void Path::startNewSubPath (const Point<float>& start)
  74335. {
  74336. startNewSubPath (start.getX(), start.getY());
  74337. }
  74338. void Path::lineTo (const float x, const float y)
  74339. {
  74340. CHECK_COORDS_ARE_VALID (x, y);
  74341. if (numElements == 0)
  74342. startNewSubPath (0, 0);
  74343. data.ensureAllocatedSize ((int) numElements + 3);
  74344. data.elements [numElements++] = lineMarker;
  74345. data.elements [numElements++] = x;
  74346. data.elements [numElements++] = y;
  74347. pathXMin = jmin (pathXMin, x);
  74348. pathXMax = jmax (pathXMax, x);
  74349. pathYMin = jmin (pathYMin, y);
  74350. pathYMax = jmax (pathYMax, y);
  74351. }
  74352. void Path::lineTo (const Point<float>& end)
  74353. {
  74354. lineTo (end.getX(), end.getY());
  74355. }
  74356. void Path::quadraticTo (const float x1, const float y1,
  74357. const float x2, const float y2)
  74358. {
  74359. CHECK_COORDS_ARE_VALID (x1, y1);
  74360. CHECK_COORDS_ARE_VALID (x2, y2);
  74361. if (numElements == 0)
  74362. startNewSubPath (0, 0);
  74363. data.ensureAllocatedSize ((int) numElements + 5);
  74364. data.elements [numElements++] = quadMarker;
  74365. data.elements [numElements++] = x1;
  74366. data.elements [numElements++] = y1;
  74367. data.elements [numElements++] = x2;
  74368. data.elements [numElements++] = y2;
  74369. pathXMin = jmin (pathXMin, x1, x2);
  74370. pathXMax = jmax (pathXMax, x1, x2);
  74371. pathYMin = jmin (pathYMin, y1, y2);
  74372. pathYMax = jmax (pathYMax, y1, y2);
  74373. }
  74374. void Path::quadraticTo (const Point<float>& controlPoint,
  74375. const Point<float>& endPoint)
  74376. {
  74377. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74378. endPoint.getX(), endPoint.getY());
  74379. }
  74380. void Path::cubicTo (const float x1, const float y1,
  74381. const float x2, const float y2,
  74382. const float x3, const float y3)
  74383. {
  74384. CHECK_COORDS_ARE_VALID (x1, y1);
  74385. CHECK_COORDS_ARE_VALID (x2, y2);
  74386. CHECK_COORDS_ARE_VALID (x3, y3);
  74387. if (numElements == 0)
  74388. startNewSubPath (0, 0);
  74389. data.ensureAllocatedSize ((int) numElements + 7);
  74390. data.elements [numElements++] = cubicMarker;
  74391. data.elements [numElements++] = x1;
  74392. data.elements [numElements++] = y1;
  74393. data.elements [numElements++] = x2;
  74394. data.elements [numElements++] = y2;
  74395. data.elements [numElements++] = x3;
  74396. data.elements [numElements++] = y3;
  74397. pathXMin = jmin (pathXMin, x1, x2, x3);
  74398. pathXMax = jmax (pathXMax, x1, x2, x3);
  74399. pathYMin = jmin (pathYMin, y1, y2, y3);
  74400. pathYMax = jmax (pathYMax, y1, y2, y3);
  74401. }
  74402. void Path::cubicTo (const Point<float>& controlPoint1,
  74403. const Point<float>& controlPoint2,
  74404. const Point<float>& endPoint)
  74405. {
  74406. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74407. controlPoint2.getX(), controlPoint2.getY(),
  74408. endPoint.getX(), endPoint.getY());
  74409. }
  74410. void Path::closeSubPath()
  74411. {
  74412. if (numElements > 0
  74413. && data.elements [numElements - 1] != closeSubPathMarker)
  74414. {
  74415. data.ensureAllocatedSize ((int) numElements + 1);
  74416. data.elements [numElements++] = closeSubPathMarker;
  74417. }
  74418. }
  74419. const Point<float> Path::getCurrentPosition() const
  74420. {
  74421. size_t i = numElements - 1;
  74422. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74423. {
  74424. while (i >= 0)
  74425. {
  74426. if (data.elements[i] == moveMarker)
  74427. {
  74428. i += 2;
  74429. break;
  74430. }
  74431. --i;
  74432. }
  74433. }
  74434. if (i > 0)
  74435. return Point<float> (data.elements [i - 1], data.elements [i]);
  74436. return Point<float>();
  74437. }
  74438. void Path::addRectangle (const float x, const float y,
  74439. const float w, const float h)
  74440. {
  74441. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74442. if (w < 0)
  74443. swapVariables (x1, x2);
  74444. if (h < 0)
  74445. swapVariables (y1, y2);
  74446. data.ensureAllocatedSize ((int) numElements + 13);
  74447. if (numElements == 0)
  74448. {
  74449. pathXMin = x1;
  74450. pathXMax = x2;
  74451. pathYMin = y1;
  74452. pathYMax = y2;
  74453. }
  74454. else
  74455. {
  74456. pathXMin = jmin (pathXMin, x1);
  74457. pathXMax = jmax (pathXMax, x2);
  74458. pathYMin = jmin (pathYMin, y1);
  74459. pathYMax = jmax (pathYMax, y2);
  74460. }
  74461. data.elements [numElements++] = moveMarker;
  74462. data.elements [numElements++] = x1;
  74463. data.elements [numElements++] = y2;
  74464. data.elements [numElements++] = lineMarker;
  74465. data.elements [numElements++] = x1;
  74466. data.elements [numElements++] = y1;
  74467. data.elements [numElements++] = lineMarker;
  74468. data.elements [numElements++] = x2;
  74469. data.elements [numElements++] = y1;
  74470. data.elements [numElements++] = lineMarker;
  74471. data.elements [numElements++] = x2;
  74472. data.elements [numElements++] = y2;
  74473. data.elements [numElements++] = closeSubPathMarker;
  74474. }
  74475. void Path::addRectangle (const Rectangle<int>& rectangle)
  74476. {
  74477. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  74478. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  74479. }
  74480. void Path::addRoundedRectangle (const float x, const float y,
  74481. const float w, const float h,
  74482. float csx,
  74483. float csy)
  74484. {
  74485. csx = jmin (csx, w * 0.5f);
  74486. csy = jmin (csy, h * 0.5f);
  74487. const float cs45x = csx * 0.45f;
  74488. const float cs45y = csy * 0.45f;
  74489. const float x2 = x + w;
  74490. const float y2 = y + h;
  74491. startNewSubPath (x + csx, y);
  74492. lineTo (x2 - csx, y);
  74493. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74494. lineTo (x2, y2 - csy);
  74495. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74496. lineTo (x + csx, y2);
  74497. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74498. lineTo (x, y + csy);
  74499. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74500. closeSubPath();
  74501. }
  74502. void Path::addRoundedRectangle (const float x, const float y,
  74503. const float w, const float h,
  74504. float cs)
  74505. {
  74506. addRoundedRectangle (x, y, w, h, cs, cs);
  74507. }
  74508. void Path::addTriangle (const float x1, const float y1,
  74509. const float x2, const float y2,
  74510. const float x3, const float y3)
  74511. {
  74512. startNewSubPath (x1, y1);
  74513. lineTo (x2, y2);
  74514. lineTo (x3, y3);
  74515. closeSubPath();
  74516. }
  74517. void Path::addQuadrilateral (const float x1, const float y1,
  74518. const float x2, const float y2,
  74519. const float x3, const float y3,
  74520. const float x4, const float y4)
  74521. {
  74522. startNewSubPath (x1, y1);
  74523. lineTo (x2, y2);
  74524. lineTo (x3, y3);
  74525. lineTo (x4, y4);
  74526. closeSubPath();
  74527. }
  74528. void Path::addEllipse (const float x, const float y,
  74529. const float w, const float h)
  74530. {
  74531. const float hw = w * 0.5f;
  74532. const float hw55 = hw * 0.55f;
  74533. const float hh = h * 0.5f;
  74534. const float hh45 = hh * 0.55f;
  74535. const float cx = x + hw;
  74536. const float cy = y + hh;
  74537. startNewSubPath (cx, cy - hh);
  74538. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  74539. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  74540. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  74541. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  74542. closeSubPath();
  74543. }
  74544. void Path::addArc (const float x, const float y,
  74545. const float w, const float h,
  74546. const float fromRadians,
  74547. const float toRadians,
  74548. const bool startAsNewSubPath)
  74549. {
  74550. const float radiusX = w / 2.0f;
  74551. const float radiusY = h / 2.0f;
  74552. addCentredArc (x + radiusX,
  74553. y + radiusY,
  74554. radiusX, radiusY,
  74555. 0.0f,
  74556. fromRadians, toRadians,
  74557. startAsNewSubPath);
  74558. }
  74559. void Path::addCentredArc (const float centreX, const float centreY,
  74560. const float radiusX, const float radiusY,
  74561. const float rotationOfEllipse,
  74562. const float fromRadians,
  74563. const float toRadians,
  74564. const bool startAsNewSubPath)
  74565. {
  74566. if (radiusX > 0.0f && radiusY > 0.0f)
  74567. {
  74568. const Point<float> centre (centreX, centreY);
  74569. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74570. float angle = fromRadians;
  74571. if (startAsNewSubPath)
  74572. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74573. if (fromRadians < toRadians)
  74574. {
  74575. if (startAsNewSubPath)
  74576. angle += PathHelpers::ellipseAngularIncrement;
  74577. while (angle < toRadians)
  74578. {
  74579. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74580. angle += PathHelpers::ellipseAngularIncrement;
  74581. }
  74582. }
  74583. else
  74584. {
  74585. if (startAsNewSubPath)
  74586. angle -= PathHelpers::ellipseAngularIncrement;
  74587. while (angle > toRadians)
  74588. {
  74589. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74590. angle -= PathHelpers::ellipseAngularIncrement;
  74591. }
  74592. }
  74593. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74594. }
  74595. }
  74596. void Path::addPieSegment (const float x, const float y,
  74597. const float width, const float height,
  74598. const float fromRadians,
  74599. const float toRadians,
  74600. const float innerCircleProportionalSize)
  74601. {
  74602. float radiusX = width * 0.5f;
  74603. float radiusY = height * 0.5f;
  74604. const Point<float> centre (x + radiusX, y + radiusY);
  74605. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74606. addArc (x, y, width, height, fromRadians, toRadians);
  74607. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74608. {
  74609. closeSubPath();
  74610. if (innerCircleProportionalSize > 0)
  74611. {
  74612. radiusX *= innerCircleProportionalSize;
  74613. radiusY *= innerCircleProportionalSize;
  74614. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74615. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74616. }
  74617. }
  74618. else
  74619. {
  74620. if (innerCircleProportionalSize > 0)
  74621. {
  74622. radiusX *= innerCircleProportionalSize;
  74623. radiusY *= innerCircleProportionalSize;
  74624. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74625. }
  74626. else
  74627. {
  74628. lineTo (centre);
  74629. }
  74630. }
  74631. closeSubPath();
  74632. }
  74633. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74634. {
  74635. const Line<float> reversed (line.reversed());
  74636. lineThickness *= 0.5f;
  74637. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74638. lineTo (line.getPointAlongLine (0, -lineThickness));
  74639. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74640. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74641. closeSubPath();
  74642. }
  74643. void Path::addArrow (const Line<float>& line, float lineThickness,
  74644. float arrowheadWidth, float arrowheadLength)
  74645. {
  74646. const Line<float> reversed (line.reversed());
  74647. lineThickness *= 0.5f;
  74648. arrowheadWidth *= 0.5f;
  74649. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74650. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74651. lineTo (line.getPointAlongLine (0, -lineThickness));
  74652. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74653. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74654. lineTo (line.getEnd());
  74655. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74656. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74657. closeSubPath();
  74658. }
  74659. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74660. const float radius, const float startAngle)
  74661. {
  74662. jassert (numberOfSides > 1); // this would be silly.
  74663. if (numberOfSides > 1)
  74664. {
  74665. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74666. for (int i = 0; i < numberOfSides; ++i)
  74667. {
  74668. const float angle = startAngle + i * angleBetweenPoints;
  74669. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74670. if (i == 0)
  74671. startNewSubPath (p);
  74672. else
  74673. lineTo (p);
  74674. }
  74675. closeSubPath();
  74676. }
  74677. }
  74678. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74679. const float innerRadius, const float outerRadius, const float startAngle)
  74680. {
  74681. jassert (numberOfPoints > 1); // this would be silly.
  74682. if (numberOfPoints > 1)
  74683. {
  74684. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74685. for (int i = 0; i < numberOfPoints; ++i)
  74686. {
  74687. const float angle = startAngle + i * angleBetweenPoints;
  74688. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74689. if (i == 0)
  74690. startNewSubPath (p);
  74691. else
  74692. lineTo (p);
  74693. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74694. }
  74695. closeSubPath();
  74696. }
  74697. }
  74698. void Path::addBubble (float x, float y,
  74699. float w, float h,
  74700. float cs,
  74701. float tipX,
  74702. float tipY,
  74703. int whichSide,
  74704. float arrowPos,
  74705. float arrowWidth)
  74706. {
  74707. if (w > 1.0f && h > 1.0f)
  74708. {
  74709. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74710. const float cs2 = 2.0f * cs;
  74711. startNewSubPath (x + cs, y);
  74712. if (whichSide == 0)
  74713. {
  74714. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74715. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74716. lineTo (arrowX1, y);
  74717. lineTo (tipX, tipY);
  74718. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74719. }
  74720. lineTo (x + w - cs, y);
  74721. if (cs > 0.0f)
  74722. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74723. if (whichSide == 3)
  74724. {
  74725. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74726. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74727. lineTo (x + w, arrowY1);
  74728. lineTo (tipX, tipY);
  74729. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74730. }
  74731. lineTo (x + w, y + h - cs);
  74732. if (cs > 0.0f)
  74733. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74734. if (whichSide == 2)
  74735. {
  74736. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74737. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74738. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74739. lineTo (tipX, tipY);
  74740. lineTo (arrowX1, y + h);
  74741. }
  74742. lineTo (x + cs, y + h);
  74743. if (cs > 0.0f)
  74744. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74745. if (whichSide == 1)
  74746. {
  74747. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74748. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74749. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74750. lineTo (tipX, tipY);
  74751. lineTo (x, arrowY1);
  74752. }
  74753. lineTo (x, y + cs);
  74754. if (cs > 0.0f)
  74755. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74756. closeSubPath();
  74757. }
  74758. }
  74759. void Path::addPath (const Path& other)
  74760. {
  74761. size_t i = 0;
  74762. while (i < other.numElements)
  74763. {
  74764. const float type = other.data.elements [i++];
  74765. if (type == moveMarker)
  74766. {
  74767. startNewSubPath (other.data.elements [i],
  74768. other.data.elements [i + 1]);
  74769. i += 2;
  74770. }
  74771. else if (type == lineMarker)
  74772. {
  74773. lineTo (other.data.elements [i],
  74774. other.data.elements [i + 1]);
  74775. i += 2;
  74776. }
  74777. else if (type == quadMarker)
  74778. {
  74779. quadraticTo (other.data.elements [i],
  74780. other.data.elements [i + 1],
  74781. other.data.elements [i + 2],
  74782. other.data.elements [i + 3]);
  74783. i += 4;
  74784. }
  74785. else if (type == cubicMarker)
  74786. {
  74787. cubicTo (other.data.elements [i],
  74788. other.data.elements [i + 1],
  74789. other.data.elements [i + 2],
  74790. other.data.elements [i + 3],
  74791. other.data.elements [i + 4],
  74792. other.data.elements [i + 5]);
  74793. i += 6;
  74794. }
  74795. else if (type == closeSubPathMarker)
  74796. {
  74797. closeSubPath();
  74798. }
  74799. else
  74800. {
  74801. // something's gone wrong with the element list!
  74802. jassertfalse;
  74803. }
  74804. }
  74805. }
  74806. void Path::addPath (const Path& other,
  74807. const AffineTransform& transformToApply)
  74808. {
  74809. size_t i = 0;
  74810. while (i < other.numElements)
  74811. {
  74812. const float type = other.data.elements [i++];
  74813. if (type == closeSubPathMarker)
  74814. {
  74815. closeSubPath();
  74816. }
  74817. else
  74818. {
  74819. float x = other.data.elements [i++];
  74820. float y = other.data.elements [i++];
  74821. transformToApply.transformPoint (x, y);
  74822. if (type == moveMarker)
  74823. {
  74824. startNewSubPath (x, y);
  74825. }
  74826. else if (type == lineMarker)
  74827. {
  74828. lineTo (x, y);
  74829. }
  74830. else if (type == quadMarker)
  74831. {
  74832. float x2 = other.data.elements [i++];
  74833. float y2 = other.data.elements [i++];
  74834. transformToApply.transformPoint (x2, y2);
  74835. quadraticTo (x, y, x2, y2);
  74836. }
  74837. else if (type == cubicMarker)
  74838. {
  74839. float x2 = other.data.elements [i++];
  74840. float y2 = other.data.elements [i++];
  74841. float x3 = other.data.elements [i++];
  74842. float y3 = other.data.elements [i++];
  74843. transformToApply.transformPoints (x2, y2, x3, y3);
  74844. cubicTo (x, y, x2, y2, x3, y3);
  74845. }
  74846. else
  74847. {
  74848. // something's gone wrong with the element list!
  74849. jassertfalse;
  74850. }
  74851. }
  74852. }
  74853. }
  74854. void Path::applyTransform (const AffineTransform& transform) throw()
  74855. {
  74856. size_t i = 0;
  74857. pathYMin = pathXMin = 0;
  74858. pathYMax = pathXMax = 0;
  74859. bool setMaxMin = false;
  74860. while (i < numElements)
  74861. {
  74862. const float type = data.elements [i++];
  74863. if (type == moveMarker)
  74864. {
  74865. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74866. if (setMaxMin)
  74867. {
  74868. pathXMin = jmin (pathXMin, data.elements [i]);
  74869. pathXMax = jmax (pathXMax, data.elements [i]);
  74870. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74871. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74872. }
  74873. else
  74874. {
  74875. pathXMin = pathXMax = data.elements [i];
  74876. pathYMin = pathYMax = data.elements [i + 1];
  74877. setMaxMin = true;
  74878. }
  74879. i += 2;
  74880. }
  74881. else if (type == lineMarker)
  74882. {
  74883. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74884. pathXMin = jmin (pathXMin, data.elements [i]);
  74885. pathXMax = jmax (pathXMax, data.elements [i]);
  74886. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74887. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74888. i += 2;
  74889. }
  74890. else if (type == quadMarker)
  74891. {
  74892. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74893. data.elements [i + 2], data.elements [i + 3]);
  74894. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74895. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74896. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74897. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74898. i += 4;
  74899. }
  74900. else if (type == cubicMarker)
  74901. {
  74902. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74903. data.elements [i + 2], data.elements [i + 3],
  74904. data.elements [i + 4], data.elements [i + 5]);
  74905. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74906. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74907. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74908. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74909. i += 6;
  74910. }
  74911. }
  74912. }
  74913. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74914. const float w, const float h,
  74915. const bool preserveProportions,
  74916. const Justification& justification) const
  74917. {
  74918. Rectangle<float> bounds (getBounds());
  74919. if (preserveProportions)
  74920. {
  74921. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74922. return AffineTransform::identity;
  74923. float newW, newH;
  74924. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74925. if (srcRatio > h / w)
  74926. {
  74927. newW = h / srcRatio;
  74928. newH = h;
  74929. }
  74930. else
  74931. {
  74932. newW = w;
  74933. newH = w * srcRatio;
  74934. }
  74935. float newXCentre = x;
  74936. float newYCentre = y;
  74937. if (justification.testFlags (Justification::left))
  74938. newXCentre += newW * 0.5f;
  74939. else if (justification.testFlags (Justification::right))
  74940. newXCentre += w - newW * 0.5f;
  74941. else
  74942. newXCentre += w * 0.5f;
  74943. if (justification.testFlags (Justification::top))
  74944. newYCentre += newH * 0.5f;
  74945. else if (justification.testFlags (Justification::bottom))
  74946. newYCentre += h - newH * 0.5f;
  74947. else
  74948. newYCentre += h * 0.5f;
  74949. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74950. bounds.getHeight() * -0.5f - bounds.getY())
  74951. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74952. .translated (newXCentre, newYCentre);
  74953. }
  74954. else
  74955. {
  74956. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74957. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74958. .translated (x, y);
  74959. }
  74960. }
  74961. bool Path::contains (const float x, const float y, const float tolerence) const
  74962. {
  74963. if (x <= pathXMin || x >= pathXMax
  74964. || y <= pathYMin || y >= pathYMax)
  74965. return false;
  74966. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74967. int positiveCrossings = 0;
  74968. int negativeCrossings = 0;
  74969. while (i.next())
  74970. {
  74971. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74972. {
  74973. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74974. if (intersectX <= x)
  74975. {
  74976. if (i.y1 < i.y2)
  74977. ++positiveCrossings;
  74978. else
  74979. ++negativeCrossings;
  74980. }
  74981. }
  74982. }
  74983. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74984. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74985. }
  74986. bool Path::contains (const Point<float>& point, const float tolerence) const
  74987. {
  74988. return contains (point.getX(), point.getY(), tolerence);
  74989. }
  74990. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74991. {
  74992. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74993. Point<float> intersection;
  74994. while (i.next())
  74995. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74996. return true;
  74997. return false;
  74998. }
  74999. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  75000. {
  75001. Line<float> result (line);
  75002. const bool startInside = contains (line.getStart());
  75003. const bool endInside = contains (line.getEnd());
  75004. if (startInside == endInside)
  75005. {
  75006. if (keepSectionOutsidePath == startInside)
  75007. result = Line<float>();
  75008. }
  75009. else
  75010. {
  75011. PathFlatteningIterator i (*this, AffineTransform::identity);
  75012. Point<float> intersection;
  75013. while (i.next())
  75014. {
  75015. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75016. {
  75017. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  75018. result.setStart (intersection);
  75019. else
  75020. result.setEnd (intersection);
  75021. }
  75022. }
  75023. }
  75024. return result;
  75025. }
  75026. float Path::getLength (const AffineTransform& transform) const
  75027. {
  75028. float length = 0;
  75029. PathFlatteningIterator i (*this, transform);
  75030. while (i.next())
  75031. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  75032. return length;
  75033. }
  75034. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  75035. {
  75036. PathFlatteningIterator i (*this, transform);
  75037. while (i.next())
  75038. {
  75039. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75040. const float lineLength = line.getLength();
  75041. if (distanceFromStart <= lineLength)
  75042. return line.getPointAlongLine (distanceFromStart);
  75043. distanceFromStart -= lineLength;
  75044. }
  75045. return Point<float> (i.x2, i.y2);
  75046. }
  75047. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  75048. const AffineTransform& transform) const
  75049. {
  75050. PathFlatteningIterator i (*this, transform);
  75051. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  75052. float length = 0;
  75053. Point<float> pointOnLine;
  75054. while (i.next())
  75055. {
  75056. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75057. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  75058. if (distance < bestDistance)
  75059. {
  75060. bestDistance = distance;
  75061. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  75062. pointOnPath = pointOnLine;
  75063. }
  75064. length += line.getLength();
  75065. }
  75066. return bestPosition;
  75067. }
  75068. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  75069. {
  75070. if (cornerRadius <= 0.01f)
  75071. return *this;
  75072. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  75073. size_t n = 0;
  75074. bool lastWasLine = false, firstWasLine = false;
  75075. Path p;
  75076. while (n < numElements)
  75077. {
  75078. const float type = data.elements [n++];
  75079. if (type == moveMarker)
  75080. {
  75081. indexOfPathStart = p.numElements;
  75082. indexOfPathStartThis = n - 1;
  75083. const float x = data.elements [n++];
  75084. const float y = data.elements [n++];
  75085. p.startNewSubPath (x, y);
  75086. lastWasLine = false;
  75087. firstWasLine = (data.elements [n] == lineMarker);
  75088. }
  75089. else if (type == lineMarker || type == closeSubPathMarker)
  75090. {
  75091. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75092. if (type == lineMarker)
  75093. {
  75094. endX = data.elements [n++];
  75095. endY = data.elements [n++];
  75096. if (n > 8)
  75097. {
  75098. startX = data.elements [n - 8];
  75099. startY = data.elements [n - 7];
  75100. joinX = data.elements [n - 5];
  75101. joinY = data.elements [n - 4];
  75102. }
  75103. }
  75104. else
  75105. {
  75106. endX = data.elements [indexOfPathStartThis + 1];
  75107. endY = data.elements [indexOfPathStartThis + 2];
  75108. if (n > 6)
  75109. {
  75110. startX = data.elements [n - 6];
  75111. startY = data.elements [n - 5];
  75112. joinX = data.elements [n - 3];
  75113. joinY = data.elements [n - 2];
  75114. }
  75115. }
  75116. if (lastWasLine)
  75117. {
  75118. const double len1 = juce_hypot (startX - joinX,
  75119. startY - joinY);
  75120. if (len1 > 0)
  75121. {
  75122. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75123. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75124. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75125. }
  75126. const double len2 = juce_hypot (endX - joinX,
  75127. endY - joinY);
  75128. if (len2 > 0)
  75129. {
  75130. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75131. p.quadraticTo (joinX, joinY,
  75132. (float) (joinX + (endX - joinX) * propNeeded),
  75133. (float) (joinY + (endY - joinY) * propNeeded));
  75134. }
  75135. p.lineTo (endX, endY);
  75136. }
  75137. else if (type == lineMarker)
  75138. {
  75139. p.lineTo (endX, endY);
  75140. lastWasLine = true;
  75141. }
  75142. if (type == closeSubPathMarker)
  75143. {
  75144. if (firstWasLine)
  75145. {
  75146. startX = data.elements [n - 3];
  75147. startY = data.elements [n - 2];
  75148. joinX = endX;
  75149. joinY = endY;
  75150. endX = data.elements [indexOfPathStartThis + 4];
  75151. endY = data.elements [indexOfPathStartThis + 5];
  75152. const double len1 = juce_hypot (startX - joinX,
  75153. startY - joinY);
  75154. if (len1 > 0)
  75155. {
  75156. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75157. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75158. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75159. }
  75160. const double len2 = juce_hypot (endX - joinX,
  75161. endY - joinY);
  75162. if (len2 > 0)
  75163. {
  75164. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75165. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75166. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75167. p.quadraticTo (joinX, joinY, endX, endY);
  75168. p.data.elements [indexOfPathStart + 1] = endX;
  75169. p.data.elements [indexOfPathStart + 2] = endY;
  75170. }
  75171. }
  75172. p.closeSubPath();
  75173. }
  75174. }
  75175. else if (type == quadMarker)
  75176. {
  75177. lastWasLine = false;
  75178. const float x1 = data.elements [n++];
  75179. const float y1 = data.elements [n++];
  75180. const float x2 = data.elements [n++];
  75181. const float y2 = data.elements [n++];
  75182. p.quadraticTo (x1, y1, x2, y2);
  75183. }
  75184. else if (type == cubicMarker)
  75185. {
  75186. lastWasLine = false;
  75187. const float x1 = data.elements [n++];
  75188. const float y1 = data.elements [n++];
  75189. const float x2 = data.elements [n++];
  75190. const float y2 = data.elements [n++];
  75191. const float x3 = data.elements [n++];
  75192. const float y3 = data.elements [n++];
  75193. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75194. }
  75195. }
  75196. return p;
  75197. }
  75198. void Path::loadPathFromStream (InputStream& source)
  75199. {
  75200. while (! source.isExhausted())
  75201. {
  75202. switch (source.readByte())
  75203. {
  75204. case 'm':
  75205. {
  75206. const float x = source.readFloat();
  75207. const float y = source.readFloat();
  75208. startNewSubPath (x, y);
  75209. break;
  75210. }
  75211. case 'l':
  75212. {
  75213. const float x = source.readFloat();
  75214. const float y = source.readFloat();
  75215. lineTo (x, y);
  75216. break;
  75217. }
  75218. case 'q':
  75219. {
  75220. const float x1 = source.readFloat();
  75221. const float y1 = source.readFloat();
  75222. const float x2 = source.readFloat();
  75223. const float y2 = source.readFloat();
  75224. quadraticTo (x1, y1, x2, y2);
  75225. break;
  75226. }
  75227. case 'b':
  75228. {
  75229. const float x1 = source.readFloat();
  75230. const float y1 = source.readFloat();
  75231. const float x2 = source.readFloat();
  75232. const float y2 = source.readFloat();
  75233. const float x3 = source.readFloat();
  75234. const float y3 = source.readFloat();
  75235. cubicTo (x1, y1, x2, y2, x3, y3);
  75236. break;
  75237. }
  75238. case 'c':
  75239. closeSubPath();
  75240. break;
  75241. case 'n':
  75242. useNonZeroWinding = true;
  75243. break;
  75244. case 'z':
  75245. useNonZeroWinding = false;
  75246. break;
  75247. case 'e':
  75248. return; // end of path marker
  75249. default:
  75250. jassertfalse; // illegal char in the stream
  75251. break;
  75252. }
  75253. }
  75254. }
  75255. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75256. {
  75257. MemoryInputStream in (pathData, numberOfBytes, false);
  75258. loadPathFromStream (in);
  75259. }
  75260. void Path::writePathToStream (OutputStream& dest) const
  75261. {
  75262. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75263. size_t i = 0;
  75264. while (i < numElements)
  75265. {
  75266. const float type = data.elements [i++];
  75267. if (type == moveMarker)
  75268. {
  75269. dest.writeByte ('m');
  75270. dest.writeFloat (data.elements [i++]);
  75271. dest.writeFloat (data.elements [i++]);
  75272. }
  75273. else if (type == lineMarker)
  75274. {
  75275. dest.writeByte ('l');
  75276. dest.writeFloat (data.elements [i++]);
  75277. dest.writeFloat (data.elements [i++]);
  75278. }
  75279. else if (type == quadMarker)
  75280. {
  75281. dest.writeByte ('q');
  75282. dest.writeFloat (data.elements [i++]);
  75283. dest.writeFloat (data.elements [i++]);
  75284. dest.writeFloat (data.elements [i++]);
  75285. dest.writeFloat (data.elements [i++]);
  75286. }
  75287. else if (type == cubicMarker)
  75288. {
  75289. dest.writeByte ('b');
  75290. dest.writeFloat (data.elements [i++]);
  75291. dest.writeFloat (data.elements [i++]);
  75292. dest.writeFloat (data.elements [i++]);
  75293. dest.writeFloat (data.elements [i++]);
  75294. dest.writeFloat (data.elements [i++]);
  75295. dest.writeFloat (data.elements [i++]);
  75296. }
  75297. else if (type == closeSubPathMarker)
  75298. {
  75299. dest.writeByte ('c');
  75300. }
  75301. }
  75302. dest.writeByte ('e'); // marks the end-of-path
  75303. }
  75304. const String Path::toString() const
  75305. {
  75306. MemoryOutputStream s (2048);
  75307. if (! useNonZeroWinding)
  75308. s << 'a';
  75309. size_t i = 0;
  75310. float lastMarker = 0.0f;
  75311. while (i < numElements)
  75312. {
  75313. const float marker = data.elements [i++];
  75314. char markerChar = 0;
  75315. int numCoords = 0;
  75316. if (marker == moveMarker)
  75317. {
  75318. markerChar = 'm';
  75319. numCoords = 2;
  75320. }
  75321. else if (marker == lineMarker)
  75322. {
  75323. markerChar = 'l';
  75324. numCoords = 2;
  75325. }
  75326. else if (marker == quadMarker)
  75327. {
  75328. markerChar = 'q';
  75329. numCoords = 4;
  75330. }
  75331. else if (marker == cubicMarker)
  75332. {
  75333. markerChar = 'c';
  75334. numCoords = 6;
  75335. }
  75336. else
  75337. {
  75338. jassert (marker == closeSubPathMarker);
  75339. markerChar = 'z';
  75340. }
  75341. if (marker != lastMarker)
  75342. {
  75343. if (s.getDataSize() != 0)
  75344. s << ' ';
  75345. s << markerChar;
  75346. lastMarker = marker;
  75347. }
  75348. while (--numCoords >= 0 && i < numElements)
  75349. {
  75350. String coord (data.elements [i++], 3);
  75351. while (coord.endsWithChar ('0') && coord != "0")
  75352. coord = coord.dropLastCharacters (1);
  75353. if (coord.endsWithChar ('.'))
  75354. coord = coord.dropLastCharacters (1);
  75355. if (s.getDataSize() != 0)
  75356. s << ' ';
  75357. s << coord;
  75358. }
  75359. }
  75360. return s.toUTF8();
  75361. }
  75362. void Path::restoreFromString (const String& stringVersion)
  75363. {
  75364. clear();
  75365. setUsingNonZeroWinding (true);
  75366. const juce_wchar* t = stringVersion;
  75367. juce_wchar marker = 'm';
  75368. int numValues = 2;
  75369. float values [6];
  75370. for (;;)
  75371. {
  75372. const String token (PathHelpers::nextToken (t));
  75373. const juce_wchar firstChar = token[0];
  75374. int startNum = 0;
  75375. if (firstChar == 0)
  75376. break;
  75377. if (firstChar == 'm' || firstChar == 'l')
  75378. {
  75379. marker = firstChar;
  75380. numValues = 2;
  75381. }
  75382. else if (firstChar == 'q')
  75383. {
  75384. marker = firstChar;
  75385. numValues = 4;
  75386. }
  75387. else if (firstChar == 'c')
  75388. {
  75389. marker = firstChar;
  75390. numValues = 6;
  75391. }
  75392. else if (firstChar == 'z')
  75393. {
  75394. marker = firstChar;
  75395. numValues = 0;
  75396. }
  75397. else if (firstChar == 'a')
  75398. {
  75399. setUsingNonZeroWinding (false);
  75400. continue;
  75401. }
  75402. else
  75403. {
  75404. ++startNum;
  75405. values [0] = token.getFloatValue();
  75406. }
  75407. for (int i = startNum; i < numValues; ++i)
  75408. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75409. switch (marker)
  75410. {
  75411. case 'm':
  75412. startNewSubPath (values[0], values[1]);
  75413. break;
  75414. case 'l':
  75415. lineTo (values[0], values[1]);
  75416. break;
  75417. case 'q':
  75418. quadraticTo (values[0], values[1],
  75419. values[2], values[3]);
  75420. break;
  75421. case 'c':
  75422. cubicTo (values[0], values[1],
  75423. values[2], values[3],
  75424. values[4], values[5]);
  75425. break;
  75426. case 'z':
  75427. closeSubPath();
  75428. break;
  75429. default:
  75430. jassertfalse; // illegal string format?
  75431. break;
  75432. }
  75433. }
  75434. }
  75435. Path::Iterator::Iterator (const Path& path_)
  75436. : path (path_),
  75437. index (0)
  75438. {
  75439. }
  75440. Path::Iterator::~Iterator()
  75441. {
  75442. }
  75443. bool Path::Iterator::next()
  75444. {
  75445. const float* const elements = path.data.elements;
  75446. if (index < path.numElements)
  75447. {
  75448. const float type = elements [index++];
  75449. if (type == moveMarker)
  75450. {
  75451. elementType = startNewSubPath;
  75452. x1 = elements [index++];
  75453. y1 = elements [index++];
  75454. }
  75455. else if (type == lineMarker)
  75456. {
  75457. elementType = lineTo;
  75458. x1 = elements [index++];
  75459. y1 = elements [index++];
  75460. }
  75461. else if (type == quadMarker)
  75462. {
  75463. elementType = quadraticTo;
  75464. x1 = elements [index++];
  75465. y1 = elements [index++];
  75466. x2 = elements [index++];
  75467. y2 = elements [index++];
  75468. }
  75469. else if (type == cubicMarker)
  75470. {
  75471. elementType = cubicTo;
  75472. x1 = elements [index++];
  75473. y1 = elements [index++];
  75474. x2 = elements [index++];
  75475. y2 = elements [index++];
  75476. x3 = elements [index++];
  75477. y3 = elements [index++];
  75478. }
  75479. else if (type == closeSubPathMarker)
  75480. {
  75481. elementType = closePath;
  75482. }
  75483. return true;
  75484. }
  75485. return false;
  75486. }
  75487. END_JUCE_NAMESPACE
  75488. /*** End of inlined file: juce_Path.cpp ***/
  75489. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75490. BEGIN_JUCE_NAMESPACE
  75491. #if JUCE_MSVC && JUCE_DEBUG
  75492. #pragma optimize ("t", on)
  75493. #endif
  75494. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75495. const AffineTransform& transform_,
  75496. float tolerence_)
  75497. : x2 (0),
  75498. y2 (0),
  75499. closesSubPath (false),
  75500. subPathIndex (-1),
  75501. path (path_),
  75502. transform (transform_),
  75503. points (path_.data.elements),
  75504. tolerence (tolerence_ * tolerence_),
  75505. subPathCloseX (0),
  75506. subPathCloseY (0),
  75507. isIdentityTransform (transform_.isIdentity()),
  75508. stackBase (32),
  75509. index (0),
  75510. stackSize (32)
  75511. {
  75512. stackPos = stackBase;
  75513. }
  75514. PathFlatteningIterator::~PathFlatteningIterator()
  75515. {
  75516. }
  75517. bool PathFlatteningIterator::next()
  75518. {
  75519. x1 = x2;
  75520. y1 = y2;
  75521. float x3 = 0;
  75522. float y3 = 0;
  75523. float x4 = 0;
  75524. float y4 = 0;
  75525. float type;
  75526. for (;;)
  75527. {
  75528. if (stackPos == stackBase)
  75529. {
  75530. if (index >= path.numElements)
  75531. {
  75532. return false;
  75533. }
  75534. else
  75535. {
  75536. type = points [index++];
  75537. if (type != Path::closeSubPathMarker)
  75538. {
  75539. x2 = points [index++];
  75540. y2 = points [index++];
  75541. if (type == Path::quadMarker)
  75542. {
  75543. x3 = points [index++];
  75544. y3 = points [index++];
  75545. if (! isIdentityTransform)
  75546. transform.transformPoints (x2, y2, x3, y3);
  75547. }
  75548. else if (type == Path::cubicMarker)
  75549. {
  75550. x3 = points [index++];
  75551. y3 = points [index++];
  75552. x4 = points [index++];
  75553. y4 = points [index++];
  75554. if (! isIdentityTransform)
  75555. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75556. }
  75557. else
  75558. {
  75559. if (! isIdentityTransform)
  75560. transform.transformPoint (x2, y2);
  75561. }
  75562. }
  75563. }
  75564. }
  75565. else
  75566. {
  75567. type = *--stackPos;
  75568. if (type != Path::closeSubPathMarker)
  75569. {
  75570. x2 = *--stackPos;
  75571. y2 = *--stackPos;
  75572. if (type == Path::quadMarker)
  75573. {
  75574. x3 = *--stackPos;
  75575. y3 = *--stackPos;
  75576. }
  75577. else if (type == Path::cubicMarker)
  75578. {
  75579. x3 = *--stackPos;
  75580. y3 = *--stackPos;
  75581. x4 = *--stackPos;
  75582. y4 = *--stackPos;
  75583. }
  75584. }
  75585. }
  75586. if (type == Path::lineMarker)
  75587. {
  75588. ++subPathIndex;
  75589. closesSubPath = (stackPos == stackBase)
  75590. && (index < path.numElements)
  75591. && (points [index] == Path::closeSubPathMarker)
  75592. && x2 == subPathCloseX
  75593. && y2 == subPathCloseY;
  75594. return true;
  75595. }
  75596. else if (type == Path::quadMarker)
  75597. {
  75598. const size_t offset = (size_t) (stackPos - stackBase);
  75599. if (offset >= stackSize - 10)
  75600. {
  75601. stackSize <<= 1;
  75602. stackBase.realloc (stackSize);
  75603. stackPos = stackBase + offset;
  75604. }
  75605. const float dx1 = x1 - x2;
  75606. const float dy1 = y1 - y2;
  75607. const float dx2 = x2 - x3;
  75608. const float dy2 = y2 - y3;
  75609. const float m1x = (x1 + x2) * 0.5f;
  75610. const float m1y = (y1 + y2) * 0.5f;
  75611. const float m2x = (x2 + x3) * 0.5f;
  75612. const float m2y = (y2 + y3) * 0.5f;
  75613. const float m3x = (m1x + m2x) * 0.5f;
  75614. const float m3y = (m1y + m2y) * 0.5f;
  75615. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75616. {
  75617. *stackPos++ = y3;
  75618. *stackPos++ = x3;
  75619. *stackPos++ = m2y;
  75620. *stackPos++ = m2x;
  75621. *stackPos++ = Path::quadMarker;
  75622. *stackPos++ = m3y;
  75623. *stackPos++ = m3x;
  75624. *stackPos++ = m1y;
  75625. *stackPos++ = m1x;
  75626. *stackPos++ = Path::quadMarker;
  75627. }
  75628. else
  75629. {
  75630. *stackPos++ = y3;
  75631. *stackPos++ = x3;
  75632. *stackPos++ = Path::lineMarker;
  75633. *stackPos++ = m3y;
  75634. *stackPos++ = m3x;
  75635. *stackPos++ = Path::lineMarker;
  75636. }
  75637. jassert (stackPos < stackBase + stackSize);
  75638. }
  75639. else if (type == Path::cubicMarker)
  75640. {
  75641. const size_t offset = (size_t) (stackPos - stackBase);
  75642. if (offset >= stackSize - 16)
  75643. {
  75644. stackSize <<= 1;
  75645. stackBase.realloc (stackSize);
  75646. stackPos = stackBase + offset;
  75647. }
  75648. const float dx1 = x1 - x2;
  75649. const float dy1 = y1 - y2;
  75650. const float dx2 = x2 - x3;
  75651. const float dy2 = y2 - y3;
  75652. const float dx3 = x3 - x4;
  75653. const float dy3 = y3 - y4;
  75654. const float m1x = (x1 + x2) * 0.5f;
  75655. const float m1y = (y1 + y2) * 0.5f;
  75656. const float m2x = (x3 + x2) * 0.5f;
  75657. const float m2y = (y3 + y2) * 0.5f;
  75658. const float m3x = (x3 + x4) * 0.5f;
  75659. const float m3y = (y3 + y4) * 0.5f;
  75660. const float m4x = (m1x + m2x) * 0.5f;
  75661. const float m4y = (m1y + m2y) * 0.5f;
  75662. const float m5x = (m3x + m2x) * 0.5f;
  75663. const float m5y = (m3y + m2y) * 0.5f;
  75664. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75665. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75666. {
  75667. *stackPos++ = y4;
  75668. *stackPos++ = x4;
  75669. *stackPos++ = m3y;
  75670. *stackPos++ = m3x;
  75671. *stackPos++ = m5y;
  75672. *stackPos++ = m5x;
  75673. *stackPos++ = Path::cubicMarker;
  75674. *stackPos++ = (m4y + m5y) * 0.5f;
  75675. *stackPos++ = (m4x + m5x) * 0.5f;
  75676. *stackPos++ = m4y;
  75677. *stackPos++ = m4x;
  75678. *stackPos++ = m1y;
  75679. *stackPos++ = m1x;
  75680. *stackPos++ = Path::cubicMarker;
  75681. }
  75682. else
  75683. {
  75684. *stackPos++ = y4;
  75685. *stackPos++ = x4;
  75686. *stackPos++ = Path::lineMarker;
  75687. *stackPos++ = m5y;
  75688. *stackPos++ = m5x;
  75689. *stackPos++ = Path::lineMarker;
  75690. *stackPos++ = m4y;
  75691. *stackPos++ = m4x;
  75692. *stackPos++ = Path::lineMarker;
  75693. }
  75694. }
  75695. else if (type == Path::closeSubPathMarker)
  75696. {
  75697. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75698. {
  75699. x1 = x2;
  75700. y1 = y2;
  75701. x2 = subPathCloseX;
  75702. y2 = subPathCloseY;
  75703. closesSubPath = true;
  75704. return true;
  75705. }
  75706. }
  75707. else
  75708. {
  75709. jassert (type == Path::moveMarker);
  75710. subPathIndex = -1;
  75711. subPathCloseX = x1 = x2;
  75712. subPathCloseY = y1 = y2;
  75713. }
  75714. }
  75715. }
  75716. #if JUCE_MSVC && JUCE_DEBUG
  75717. #pragma optimize ("", on) // resets optimisations to the project defaults
  75718. #endif
  75719. END_JUCE_NAMESPACE
  75720. /*** End of inlined file: juce_PathIterator.cpp ***/
  75721. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75722. BEGIN_JUCE_NAMESPACE
  75723. PathStrokeType::PathStrokeType (const float strokeThickness,
  75724. const JointStyle jointStyle_,
  75725. const EndCapStyle endStyle_) throw()
  75726. : thickness (strokeThickness),
  75727. jointStyle (jointStyle_),
  75728. endStyle (endStyle_)
  75729. {
  75730. }
  75731. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75732. : thickness (other.thickness),
  75733. jointStyle (other.jointStyle),
  75734. endStyle (other.endStyle)
  75735. {
  75736. }
  75737. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75738. {
  75739. thickness = other.thickness;
  75740. jointStyle = other.jointStyle;
  75741. endStyle = other.endStyle;
  75742. return *this;
  75743. }
  75744. PathStrokeType::~PathStrokeType() throw()
  75745. {
  75746. }
  75747. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75748. {
  75749. return thickness == other.thickness
  75750. && jointStyle == other.jointStyle
  75751. && endStyle == other.endStyle;
  75752. }
  75753. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75754. {
  75755. return ! operator== (other);
  75756. }
  75757. namespace PathStrokeHelpers
  75758. {
  75759. static bool lineIntersection (const float x1, const float y1,
  75760. const float x2, const float y2,
  75761. const float x3, const float y3,
  75762. const float x4, const float y4,
  75763. float& intersectionX,
  75764. float& intersectionY,
  75765. float& distanceBeyondLine1EndSquared) throw()
  75766. {
  75767. if (x2 != x3 || y2 != y3)
  75768. {
  75769. const float dx1 = x2 - x1;
  75770. const float dy1 = y2 - y1;
  75771. const float dx2 = x4 - x3;
  75772. const float dy2 = y4 - y3;
  75773. const float divisor = dx1 * dy2 - dx2 * dy1;
  75774. if (divisor == 0)
  75775. {
  75776. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75777. {
  75778. if (dy1 == 0 && dy2 != 0)
  75779. {
  75780. const float along = (y1 - y3) / dy2;
  75781. intersectionX = x3 + along * dx2;
  75782. intersectionY = y1;
  75783. distanceBeyondLine1EndSquared = intersectionX - x2;
  75784. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75785. if ((x2 > x1) == (intersectionX < x2))
  75786. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75787. return along >= 0 && along <= 1.0f;
  75788. }
  75789. else if (dy2 == 0 && dy1 != 0)
  75790. {
  75791. const float along = (y3 - y1) / dy1;
  75792. intersectionX = x1 + along * dx1;
  75793. intersectionY = y3;
  75794. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75795. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75796. if (along < 1.0f)
  75797. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75798. return along >= 0 && along <= 1.0f;
  75799. }
  75800. else if (dx1 == 0 && dx2 != 0)
  75801. {
  75802. const float along = (x1 - x3) / dx2;
  75803. intersectionX = x1;
  75804. intersectionY = y3 + along * dy2;
  75805. distanceBeyondLine1EndSquared = intersectionY - y2;
  75806. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75807. if ((y2 > y1) == (intersectionY < y2))
  75808. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75809. return along >= 0 && along <= 1.0f;
  75810. }
  75811. else if (dx2 == 0 && dx1 != 0)
  75812. {
  75813. const float along = (x3 - x1) / dx1;
  75814. intersectionX = x3;
  75815. intersectionY = y1 + along * dy1;
  75816. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75817. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75818. if (along < 1.0f)
  75819. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75820. return along >= 0 && along <= 1.0f;
  75821. }
  75822. }
  75823. intersectionX = 0.5f * (x2 + x3);
  75824. intersectionY = 0.5f * (y2 + y3);
  75825. distanceBeyondLine1EndSquared = 0.0f;
  75826. return false;
  75827. }
  75828. else
  75829. {
  75830. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75831. intersectionX = x1 + along1 * dx1;
  75832. intersectionY = y1 + along1 * dy1;
  75833. if (along1 >= 0 && along1 <= 1.0f)
  75834. {
  75835. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75836. if (along2 >= 0 && along2 <= divisor)
  75837. {
  75838. distanceBeyondLine1EndSquared = 0.0f;
  75839. return true;
  75840. }
  75841. }
  75842. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75843. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75844. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75845. if (along1 < 1.0f)
  75846. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75847. return false;
  75848. }
  75849. }
  75850. intersectionX = x2;
  75851. intersectionY = y2;
  75852. distanceBeyondLine1EndSquared = 0.0f;
  75853. return true;
  75854. }
  75855. static void addEdgeAndJoint (Path& destPath,
  75856. const PathStrokeType::JointStyle style,
  75857. const float maxMiterExtensionSquared, const float width,
  75858. const float x1, const float y1,
  75859. const float x2, const float y2,
  75860. const float x3, const float y3,
  75861. const float x4, const float y4,
  75862. const float midX, const float midY)
  75863. {
  75864. if (style == PathStrokeType::beveled
  75865. || (x3 == x4 && y3 == y4)
  75866. || (x1 == x2 && y1 == y2))
  75867. {
  75868. destPath.lineTo (x2, y2);
  75869. destPath.lineTo (x3, y3);
  75870. }
  75871. else
  75872. {
  75873. float jx, jy, distanceBeyondLine1EndSquared;
  75874. // if they intersect, use this point..
  75875. if (lineIntersection (x1, y1, x2, y2,
  75876. x3, y3, x4, y4,
  75877. jx, jy, distanceBeyondLine1EndSquared))
  75878. {
  75879. destPath.lineTo (jx, jy);
  75880. }
  75881. else
  75882. {
  75883. if (style == PathStrokeType::mitered)
  75884. {
  75885. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75886. && distanceBeyondLine1EndSquared > 0.0f)
  75887. {
  75888. destPath.lineTo (jx, jy);
  75889. }
  75890. else
  75891. {
  75892. // the end sticks out too far, so just use a blunt joint
  75893. destPath.lineTo (x2, y2);
  75894. destPath.lineTo (x3, y3);
  75895. }
  75896. }
  75897. else
  75898. {
  75899. // curved joints
  75900. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75901. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75902. const float angleIncrement = 0.1f;
  75903. destPath.lineTo (x2, y2);
  75904. if (std::abs (angle1 - angle2) > angleIncrement)
  75905. {
  75906. if (angle2 > angle1 + float_Pi
  75907. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75908. {
  75909. if (angle2 > angle1)
  75910. angle2 -= float_Pi * 2.0f;
  75911. jassert (angle1 <= angle2 + float_Pi);
  75912. angle1 -= angleIncrement;
  75913. while (angle1 > angle2)
  75914. {
  75915. destPath.lineTo (midX + width * std::sin (angle1),
  75916. midY + width * std::cos (angle1));
  75917. angle1 -= angleIncrement;
  75918. }
  75919. }
  75920. else
  75921. {
  75922. if (angle1 > angle2)
  75923. angle1 -= float_Pi * 2.0f;
  75924. jassert (angle1 >= angle2 - float_Pi);
  75925. angle1 += angleIncrement;
  75926. while (angle1 < angle2)
  75927. {
  75928. destPath.lineTo (midX + width * std::sin (angle1),
  75929. midY + width * std::cos (angle1));
  75930. angle1 += angleIncrement;
  75931. }
  75932. }
  75933. }
  75934. destPath.lineTo (x3, y3);
  75935. }
  75936. }
  75937. }
  75938. }
  75939. static void addLineEnd (Path& destPath,
  75940. const PathStrokeType::EndCapStyle style,
  75941. const float x1, const float y1,
  75942. const float x2, const float y2,
  75943. const float width)
  75944. {
  75945. if (style == PathStrokeType::butt)
  75946. {
  75947. destPath.lineTo (x2, y2);
  75948. }
  75949. else
  75950. {
  75951. float offx1, offy1, offx2, offy2;
  75952. float dx = x2 - x1;
  75953. float dy = y2 - y1;
  75954. const float len = juce_hypotf (dx, dy);
  75955. if (len == 0)
  75956. {
  75957. offx1 = offx2 = x1;
  75958. offy1 = offy2 = y1;
  75959. }
  75960. else
  75961. {
  75962. const float offset = width / len;
  75963. dx *= offset;
  75964. dy *= offset;
  75965. offx1 = x1 + dy;
  75966. offy1 = y1 - dx;
  75967. offx2 = x2 + dy;
  75968. offy2 = y2 - dx;
  75969. }
  75970. if (style == PathStrokeType::square)
  75971. {
  75972. // sqaure ends
  75973. destPath.lineTo (offx1, offy1);
  75974. destPath.lineTo (offx2, offy2);
  75975. destPath.lineTo (x2, y2);
  75976. }
  75977. else
  75978. {
  75979. // rounded ends
  75980. const float midx = (offx1 + offx2) * 0.5f;
  75981. const float midy = (offy1 + offy2) * 0.5f;
  75982. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75983. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75984. midx, midy);
  75985. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75986. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75987. x2, y2);
  75988. }
  75989. }
  75990. }
  75991. struct Arrowhead
  75992. {
  75993. float startWidth, startLength;
  75994. float endWidth, endLength;
  75995. };
  75996. static void addArrowhead (Path& destPath,
  75997. const float x1, const float y1,
  75998. const float x2, const float y2,
  75999. const float tipX, const float tipY,
  76000. const float width,
  76001. const float arrowheadWidth)
  76002. {
  76003. Line<float> line (x1, y1, x2, y2);
  76004. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  76005. destPath.lineTo (tipX, tipY);
  76006. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  76007. destPath.lineTo (x2, y2);
  76008. }
  76009. struct LineSection
  76010. {
  76011. float x1, y1, x2, y2; // original line
  76012. float lx1, ly1, lx2, ly2; // the left-hand stroke
  76013. float rx1, ry1, rx2, ry2; // the right-hand stroke
  76014. };
  76015. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  76016. {
  76017. while (amountAtEnd > 0 && subPath.size() > 0)
  76018. {
  76019. LineSection& l = subPath.getReference (subPath.size() - 1);
  76020. float dx = l.rx2 - l.rx1;
  76021. float dy = l.ry2 - l.ry1;
  76022. const float len = juce_hypotf (dx, dy);
  76023. if (len <= amountAtEnd && subPath.size() > 1)
  76024. {
  76025. LineSection& prev = subPath.getReference (subPath.size() - 2);
  76026. prev.x2 = l.x2;
  76027. prev.y2 = l.y2;
  76028. subPath.removeLast();
  76029. amountAtEnd -= len;
  76030. }
  76031. else
  76032. {
  76033. const float prop = jmin (0.9999f, amountAtEnd / len);
  76034. dx *= prop;
  76035. dy *= prop;
  76036. l.rx1 += dx;
  76037. l.ry1 += dy;
  76038. l.lx2 += dx;
  76039. l.ly2 += dy;
  76040. break;
  76041. }
  76042. }
  76043. while (amountAtStart > 0 && subPath.size() > 0)
  76044. {
  76045. LineSection& l = subPath.getReference (0);
  76046. float dx = l.rx2 - l.rx1;
  76047. float dy = l.ry2 - l.ry1;
  76048. const float len = juce_hypotf (dx, dy);
  76049. if (len <= amountAtStart && subPath.size() > 1)
  76050. {
  76051. LineSection& next = subPath.getReference (1);
  76052. next.x1 = l.x1;
  76053. next.y1 = l.y1;
  76054. subPath.remove (0);
  76055. amountAtStart -= len;
  76056. }
  76057. else
  76058. {
  76059. const float prop = jmin (0.9999f, amountAtStart / len);
  76060. dx *= prop;
  76061. dy *= prop;
  76062. l.rx2 -= dx;
  76063. l.ry2 -= dy;
  76064. l.lx1 -= dx;
  76065. l.ly1 -= dy;
  76066. break;
  76067. }
  76068. }
  76069. }
  76070. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  76071. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  76072. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  76073. const Arrowhead* const arrowhead)
  76074. {
  76075. jassert (subPath.size() > 0);
  76076. if (arrowhead != 0)
  76077. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  76078. const LineSection& firstLine = subPath.getReference (0);
  76079. float lastX1 = firstLine.lx1;
  76080. float lastY1 = firstLine.ly1;
  76081. float lastX2 = firstLine.lx2;
  76082. float lastY2 = firstLine.ly2;
  76083. if (isClosed)
  76084. {
  76085. destPath.startNewSubPath (lastX1, lastY1);
  76086. }
  76087. else
  76088. {
  76089. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  76090. if (arrowhead != 0)
  76091. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  76092. width, arrowhead->startWidth);
  76093. else
  76094. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  76095. }
  76096. int i;
  76097. for (i = 1; i < subPath.size(); ++i)
  76098. {
  76099. const LineSection& l = subPath.getReference (i);
  76100. addEdgeAndJoint (destPath, jointStyle,
  76101. maxMiterExtensionSquared, width,
  76102. lastX1, lastY1, lastX2, lastY2,
  76103. l.lx1, l.ly1, l.lx2, l.ly2,
  76104. l.x1, l.y1);
  76105. lastX1 = l.lx1;
  76106. lastY1 = l.ly1;
  76107. lastX2 = l.lx2;
  76108. lastY2 = l.ly2;
  76109. }
  76110. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76111. if (isClosed)
  76112. {
  76113. const LineSection& l = subPath.getReference (0);
  76114. addEdgeAndJoint (destPath, jointStyle,
  76115. maxMiterExtensionSquared, width,
  76116. lastX1, lastY1, lastX2, lastY2,
  76117. l.lx1, l.ly1, l.lx2, l.ly2,
  76118. l.x1, l.y1);
  76119. destPath.closeSubPath();
  76120. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76121. }
  76122. else
  76123. {
  76124. destPath.lineTo (lastX2, lastY2);
  76125. if (arrowhead != 0)
  76126. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76127. width, arrowhead->endWidth);
  76128. else
  76129. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76130. }
  76131. lastX1 = lastLine.rx1;
  76132. lastY1 = lastLine.ry1;
  76133. lastX2 = lastLine.rx2;
  76134. lastY2 = lastLine.ry2;
  76135. for (i = subPath.size() - 1; --i >= 0;)
  76136. {
  76137. const LineSection& l = subPath.getReference (i);
  76138. addEdgeAndJoint (destPath, jointStyle,
  76139. maxMiterExtensionSquared, width,
  76140. lastX1, lastY1, lastX2, lastY2,
  76141. l.rx1, l.ry1, l.rx2, l.ry2,
  76142. l.x2, l.y2);
  76143. lastX1 = l.rx1;
  76144. lastY1 = l.ry1;
  76145. lastX2 = l.rx2;
  76146. lastY2 = l.ry2;
  76147. }
  76148. if (isClosed)
  76149. {
  76150. addEdgeAndJoint (destPath, jointStyle,
  76151. maxMiterExtensionSquared, width,
  76152. lastX1, lastY1, lastX2, lastY2,
  76153. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76154. lastLine.x2, lastLine.y2);
  76155. }
  76156. else
  76157. {
  76158. // do the last line
  76159. destPath.lineTo (lastX2, lastY2);
  76160. }
  76161. destPath.closeSubPath();
  76162. }
  76163. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76164. const PathStrokeType::EndCapStyle endStyle,
  76165. Path& destPath, const Path& source,
  76166. const AffineTransform& transform,
  76167. const float extraAccuracy, const Arrowhead* const arrowhead)
  76168. {
  76169. if (thickness <= 0)
  76170. {
  76171. destPath.clear();
  76172. return;
  76173. }
  76174. const Path* sourcePath = &source;
  76175. Path temp;
  76176. if (sourcePath == &destPath)
  76177. {
  76178. destPath.swapWithPath (temp);
  76179. sourcePath = &temp;
  76180. }
  76181. else
  76182. {
  76183. destPath.clear();
  76184. }
  76185. destPath.setUsingNonZeroWinding (true);
  76186. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76187. const float width = 0.5f * thickness;
  76188. // Iterate the path, creating a list of the
  76189. // left/right-hand lines along either side of it...
  76190. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  76191. Array <LineSection> subPath;
  76192. subPath.ensureStorageAllocated (512);
  76193. LineSection l;
  76194. l.x1 = 0;
  76195. l.y1 = 0;
  76196. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  76197. while (it.next())
  76198. {
  76199. if (it.subPathIndex == 0)
  76200. {
  76201. if (subPath.size() > 0)
  76202. {
  76203. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76204. subPath.clearQuick();
  76205. }
  76206. l.x1 = it.x1;
  76207. l.y1 = it.y1;
  76208. }
  76209. l.x2 = it.x2;
  76210. l.y2 = it.y2;
  76211. float dx = l.x2 - l.x1;
  76212. float dy = l.y2 - l.y1;
  76213. const float hypotSquared = dx*dx + dy*dy;
  76214. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76215. {
  76216. const float len = std::sqrt (hypotSquared);
  76217. if (len == 0)
  76218. {
  76219. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76220. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76221. }
  76222. else
  76223. {
  76224. const float offset = width / len;
  76225. dx *= offset;
  76226. dy *= offset;
  76227. l.rx2 = l.x1 - dy;
  76228. l.ry2 = l.y1 + dx;
  76229. l.lx1 = l.x1 + dy;
  76230. l.ly1 = l.y1 - dx;
  76231. l.lx2 = l.x2 + dy;
  76232. l.ly2 = l.y2 - dx;
  76233. l.rx1 = l.x2 - dy;
  76234. l.ry1 = l.y2 + dx;
  76235. }
  76236. subPath.add (l);
  76237. if (it.closesSubPath)
  76238. {
  76239. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76240. subPath.clearQuick();
  76241. }
  76242. else
  76243. {
  76244. l.x1 = it.x2;
  76245. l.y1 = it.y2;
  76246. }
  76247. }
  76248. }
  76249. if (subPath.size() > 0)
  76250. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76251. }
  76252. }
  76253. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76254. const AffineTransform& transform, const float extraAccuracy) const
  76255. {
  76256. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76257. transform, extraAccuracy, 0);
  76258. }
  76259. void PathStrokeType::createDashedStroke (Path& destPath,
  76260. const Path& sourcePath,
  76261. const float* dashLengths,
  76262. int numDashLengths,
  76263. const AffineTransform& transform,
  76264. const float extraAccuracy) const
  76265. {
  76266. if (thickness <= 0)
  76267. return;
  76268. // this should really be an even number..
  76269. jassert ((numDashLengths & 1) == 0);
  76270. Path newDestPath;
  76271. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76272. bool first = true;
  76273. int dashNum = 0;
  76274. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76275. float dx = 0.0f, dy = 0.0f;
  76276. for (;;)
  76277. {
  76278. const bool isSolid = ((dashNum & 1) == 0);
  76279. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76280. jassert (dashLen > 0); // must be a positive increment!
  76281. if (dashLen <= 0)
  76282. break;
  76283. pos += dashLen;
  76284. while (pos > lineEndPos)
  76285. {
  76286. if (! it.next())
  76287. {
  76288. if (isSolid && ! first)
  76289. newDestPath.lineTo (it.x2, it.y2);
  76290. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76291. return;
  76292. }
  76293. if (isSolid && ! first)
  76294. newDestPath.lineTo (it.x1, it.y1);
  76295. else
  76296. newDestPath.startNewSubPath (it.x1, it.y1);
  76297. dx = it.x2 - it.x1;
  76298. dy = it.y2 - it.y1;
  76299. lineLen = juce_hypotf (dx, dy);
  76300. lineEndPos += lineLen;
  76301. first = it.closesSubPath;
  76302. }
  76303. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76304. if (isSolid)
  76305. newDestPath.lineTo (it.x1 + dx * alpha,
  76306. it.y1 + dy * alpha);
  76307. else
  76308. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76309. it.y1 + dy * alpha);
  76310. }
  76311. }
  76312. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76313. const Path& sourcePath,
  76314. const float arrowheadStartWidth, const float arrowheadStartLength,
  76315. const float arrowheadEndWidth, const float arrowheadEndLength,
  76316. const AffineTransform& transform,
  76317. const float extraAccuracy) const
  76318. {
  76319. PathStrokeHelpers::Arrowhead head;
  76320. head.startWidth = arrowheadStartWidth;
  76321. head.startLength = arrowheadStartLength;
  76322. head.endWidth = arrowheadEndWidth;
  76323. head.endLength = arrowheadEndLength;
  76324. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76325. destPath, sourcePath, transform, extraAccuracy, &head);
  76326. }
  76327. END_JUCE_NAMESPACE
  76328. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76329. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76330. BEGIN_JUCE_NAMESPACE
  76331. PositionedRectangle::PositionedRectangle() throw()
  76332. : x (0.0),
  76333. y (0.0),
  76334. w (0.0),
  76335. h (0.0),
  76336. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76337. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76338. wMode (absoluteSize),
  76339. hMode (absoluteSize)
  76340. {
  76341. }
  76342. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76343. : x (other.x),
  76344. y (other.y),
  76345. w (other.w),
  76346. h (other.h),
  76347. xMode (other.xMode),
  76348. yMode (other.yMode),
  76349. wMode (other.wMode),
  76350. hMode (other.hMode)
  76351. {
  76352. }
  76353. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76354. {
  76355. x = other.x;
  76356. y = other.y;
  76357. w = other.w;
  76358. h = other.h;
  76359. xMode = other.xMode;
  76360. yMode = other.yMode;
  76361. wMode = other.wMode;
  76362. hMode = other.hMode;
  76363. return *this;
  76364. }
  76365. PositionedRectangle::~PositionedRectangle() throw()
  76366. {
  76367. }
  76368. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76369. {
  76370. return x == other.x
  76371. && y == other.y
  76372. && w == other.w
  76373. && h == other.h
  76374. && xMode == other.xMode
  76375. && yMode == other.yMode
  76376. && wMode == other.wMode
  76377. && hMode == other.hMode;
  76378. }
  76379. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76380. {
  76381. return ! operator== (other);
  76382. }
  76383. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76384. {
  76385. StringArray tokens;
  76386. tokens.addTokens (stringVersion, false);
  76387. decodePosString (tokens [0], xMode, x);
  76388. decodePosString (tokens [1], yMode, y);
  76389. decodeSizeString (tokens [2], wMode, w);
  76390. decodeSizeString (tokens [3], hMode, h);
  76391. }
  76392. const String PositionedRectangle::toString() const throw()
  76393. {
  76394. String s;
  76395. s.preallocateStorage (12);
  76396. addPosDescription (s, xMode, x);
  76397. s << ' ';
  76398. addPosDescription (s, yMode, y);
  76399. s << ' ';
  76400. addSizeDescription (s, wMode, w);
  76401. s << ' ';
  76402. addSizeDescription (s, hMode, h);
  76403. return s;
  76404. }
  76405. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76406. {
  76407. jassert (! target.isEmpty());
  76408. double x_, y_, w_, h_;
  76409. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76410. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76411. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76412. roundToInt (w_), roundToInt (h_));
  76413. }
  76414. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76415. double& x_, double& y_,
  76416. double& w_, double& h_) const throw()
  76417. {
  76418. jassert (! target.isEmpty());
  76419. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76420. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76421. }
  76422. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76423. {
  76424. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76425. }
  76426. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76427. const Rectangle<int>& target) throw()
  76428. {
  76429. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76430. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76431. }
  76432. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76433. const double newW, const double newH,
  76434. const Rectangle<int>& target) throw()
  76435. {
  76436. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76437. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76438. }
  76439. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76440. {
  76441. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76442. updateFrom (comp.getBounds(), Rectangle<int>());
  76443. else
  76444. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76445. }
  76446. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76447. {
  76448. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76449. }
  76450. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76451. {
  76452. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76453. | absoluteFromParentBottomRight
  76454. | absoluteFromParentCentre
  76455. | proportionOfParentSize));
  76456. }
  76457. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76458. {
  76459. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76460. }
  76461. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76462. {
  76463. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76464. | absoluteFromParentBottomRight
  76465. | absoluteFromParentCentre
  76466. | proportionOfParentSize));
  76467. }
  76468. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76469. {
  76470. return (SizeMode) wMode;
  76471. }
  76472. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76473. {
  76474. return (SizeMode) hMode;
  76475. }
  76476. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76477. const PositionMode xMode_,
  76478. const AnchorPoint yAnchor,
  76479. const PositionMode yMode_,
  76480. const SizeMode widthMode,
  76481. const SizeMode heightMode,
  76482. const Rectangle<int>& target) throw()
  76483. {
  76484. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76485. {
  76486. double tx, tw;
  76487. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76488. xMode = (uint8) (xAnchor | xMode_);
  76489. wMode = (uint8) widthMode;
  76490. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76491. }
  76492. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76493. {
  76494. double ty, th;
  76495. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76496. yMode = (uint8) (yAnchor | yMode_);
  76497. hMode = (uint8) heightMode;
  76498. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76499. }
  76500. }
  76501. bool PositionedRectangle::isPositionAbsolute() const throw()
  76502. {
  76503. return xMode == absoluteFromParentTopLeft
  76504. && yMode == absoluteFromParentTopLeft
  76505. && wMode == absoluteSize
  76506. && hMode == absoluteSize;
  76507. }
  76508. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76509. {
  76510. if ((mode & proportionOfParentSize) != 0)
  76511. {
  76512. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76513. }
  76514. else
  76515. {
  76516. s << (roundToInt (value * 100.0) / 100.0);
  76517. if ((mode & absoluteFromParentBottomRight) != 0)
  76518. s << 'R';
  76519. else if ((mode & absoluteFromParentCentre) != 0)
  76520. s << 'C';
  76521. }
  76522. if ((mode & anchorAtRightOrBottom) != 0)
  76523. s << 'r';
  76524. else if ((mode & anchorAtCentre) != 0)
  76525. s << 'c';
  76526. }
  76527. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76528. {
  76529. if (mode == proportionalSize)
  76530. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76531. else if (mode == parentSizeMinusAbsolute)
  76532. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76533. else
  76534. s << (roundToInt (value * 100.0) / 100.0);
  76535. }
  76536. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76537. {
  76538. if (s.containsChar ('r'))
  76539. mode = anchorAtRightOrBottom;
  76540. else if (s.containsChar ('c'))
  76541. mode = anchorAtCentre;
  76542. else
  76543. mode = anchorAtLeftOrTop;
  76544. if (s.containsChar ('%'))
  76545. {
  76546. mode |= proportionOfParentSize;
  76547. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76548. }
  76549. else
  76550. {
  76551. if (s.containsChar ('R'))
  76552. mode |= absoluteFromParentBottomRight;
  76553. else if (s.containsChar ('C'))
  76554. mode |= absoluteFromParentCentre;
  76555. else
  76556. mode |= absoluteFromParentTopLeft;
  76557. value = s.removeCharacters ("rcRC").getDoubleValue();
  76558. }
  76559. }
  76560. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76561. {
  76562. if (s.containsChar ('%'))
  76563. {
  76564. mode = proportionalSize;
  76565. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76566. }
  76567. else if (s.containsChar ('M'))
  76568. {
  76569. mode = parentSizeMinusAbsolute;
  76570. value = s.getDoubleValue();
  76571. }
  76572. else
  76573. {
  76574. mode = absoluteSize;
  76575. value = s.getDoubleValue();
  76576. }
  76577. }
  76578. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76579. const double x_, const double w_,
  76580. const uint8 xMode_, const uint8 wMode_,
  76581. const int parentPos,
  76582. const int parentSize) const throw()
  76583. {
  76584. if (wMode_ == proportionalSize)
  76585. wOut = roundToInt (w_ * parentSize);
  76586. else if (wMode_ == parentSizeMinusAbsolute)
  76587. wOut = jmax (0, parentSize - roundToInt (w_));
  76588. else
  76589. wOut = roundToInt (w_);
  76590. if ((xMode_ & proportionOfParentSize) != 0)
  76591. xOut = parentPos + x_ * parentSize;
  76592. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76593. xOut = (parentPos + parentSize) - x_;
  76594. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76595. xOut = x_ + (parentPos + parentSize / 2);
  76596. else
  76597. xOut = x_ + parentPos;
  76598. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76599. xOut -= wOut;
  76600. else if ((xMode_ & anchorAtCentre) != 0)
  76601. xOut -= wOut / 2;
  76602. }
  76603. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76604. double x_, const double w_,
  76605. const uint8 xMode_, const uint8 wMode_,
  76606. const int parentPos,
  76607. const int parentSize) const throw()
  76608. {
  76609. if (wMode_ == proportionalSize)
  76610. {
  76611. if (parentSize > 0)
  76612. wOut = w_ / parentSize;
  76613. }
  76614. else if (wMode_ == parentSizeMinusAbsolute)
  76615. wOut = parentSize - w_;
  76616. else
  76617. wOut = w_;
  76618. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76619. x_ += w_;
  76620. else if ((xMode_ & anchorAtCentre) != 0)
  76621. x_ += w_ / 2;
  76622. if ((xMode_ & proportionOfParentSize) != 0)
  76623. {
  76624. if (parentSize > 0)
  76625. xOut = (x_ - parentPos) / parentSize;
  76626. }
  76627. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76628. xOut = (parentPos + parentSize) - x_;
  76629. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76630. xOut = x_ - (parentPos + parentSize / 2);
  76631. else
  76632. xOut = x_ - parentPos;
  76633. }
  76634. END_JUCE_NAMESPACE
  76635. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76636. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76637. BEGIN_JUCE_NAMESPACE
  76638. RectangleList::RectangleList() throw()
  76639. {
  76640. }
  76641. RectangleList::RectangleList (const Rectangle<int>& rect)
  76642. {
  76643. if (! rect.isEmpty())
  76644. rects.add (rect);
  76645. }
  76646. RectangleList::RectangleList (const RectangleList& other)
  76647. : rects (other.rects)
  76648. {
  76649. }
  76650. RectangleList& RectangleList::operator= (const RectangleList& other)
  76651. {
  76652. rects = other.rects;
  76653. return *this;
  76654. }
  76655. RectangleList::~RectangleList()
  76656. {
  76657. }
  76658. void RectangleList::clear()
  76659. {
  76660. rects.clearQuick();
  76661. }
  76662. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76663. {
  76664. if (((unsigned int) index) < (unsigned int) rects.size())
  76665. return rects.getReference (index);
  76666. return Rectangle<int>();
  76667. }
  76668. bool RectangleList::isEmpty() const throw()
  76669. {
  76670. return rects.size() == 0;
  76671. }
  76672. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76673. : current (0),
  76674. owner (list),
  76675. index (list.rects.size())
  76676. {
  76677. }
  76678. RectangleList::Iterator::~Iterator()
  76679. {
  76680. }
  76681. bool RectangleList::Iterator::next() throw()
  76682. {
  76683. if (--index >= 0)
  76684. {
  76685. current = & (owner.rects.getReference (index));
  76686. return true;
  76687. }
  76688. return false;
  76689. }
  76690. void RectangleList::add (const Rectangle<int>& rect)
  76691. {
  76692. if (! rect.isEmpty())
  76693. {
  76694. if (rects.size() == 0)
  76695. {
  76696. rects.add (rect);
  76697. }
  76698. else
  76699. {
  76700. bool anyOverlaps = false;
  76701. int i;
  76702. for (i = rects.size(); --i >= 0;)
  76703. {
  76704. Rectangle<int>& ourRect = rects.getReference (i);
  76705. if (rect.intersects (ourRect))
  76706. {
  76707. if (rect.contains (ourRect))
  76708. rects.remove (i);
  76709. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76710. anyOverlaps = true;
  76711. }
  76712. }
  76713. if (anyOverlaps && rects.size() > 0)
  76714. {
  76715. RectangleList r (rect);
  76716. for (i = rects.size(); --i >= 0;)
  76717. {
  76718. const Rectangle<int>& ourRect = rects.getReference (i);
  76719. if (rect.intersects (ourRect))
  76720. {
  76721. r.subtract (ourRect);
  76722. if (r.rects.size() == 0)
  76723. return;
  76724. }
  76725. }
  76726. for (i = r.getNumRectangles(); --i >= 0;)
  76727. rects.add (r.rects.getReference (i));
  76728. }
  76729. else
  76730. {
  76731. rects.add (rect);
  76732. }
  76733. }
  76734. }
  76735. }
  76736. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76737. {
  76738. if (! rect.isEmpty())
  76739. rects.add (rect);
  76740. }
  76741. void RectangleList::add (const int x, const int y, const int w, const int h)
  76742. {
  76743. if (rects.size() == 0)
  76744. {
  76745. if (w > 0 && h > 0)
  76746. rects.add (Rectangle<int> (x, y, w, h));
  76747. }
  76748. else
  76749. {
  76750. add (Rectangle<int> (x, y, w, h));
  76751. }
  76752. }
  76753. void RectangleList::add (const RectangleList& other)
  76754. {
  76755. for (int i = 0; i < other.rects.size(); ++i)
  76756. add (other.rects.getReference (i));
  76757. }
  76758. void RectangleList::subtract (const Rectangle<int>& rect)
  76759. {
  76760. const int originalNumRects = rects.size();
  76761. if (originalNumRects > 0)
  76762. {
  76763. const int x1 = rect.x;
  76764. const int y1 = rect.y;
  76765. const int x2 = x1 + rect.w;
  76766. const int y2 = y1 + rect.h;
  76767. for (int i = getNumRectangles(); --i >= 0;)
  76768. {
  76769. Rectangle<int>& r = rects.getReference (i);
  76770. const int rx1 = r.x;
  76771. const int ry1 = r.y;
  76772. const int rx2 = rx1 + r.w;
  76773. const int ry2 = ry1 + r.h;
  76774. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76775. {
  76776. if (x1 > rx1 && x1 < rx2)
  76777. {
  76778. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76779. {
  76780. r.w = x1 - rx1;
  76781. }
  76782. else
  76783. {
  76784. r.x = x1;
  76785. r.w = rx2 - x1;
  76786. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76787. i += 2;
  76788. }
  76789. }
  76790. else if (x2 > rx1 && x2 < rx2)
  76791. {
  76792. r.x = x2;
  76793. r.w = rx2 - x2;
  76794. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76795. {
  76796. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76797. i += 2;
  76798. }
  76799. }
  76800. else if (y1 > ry1 && y1 < ry2)
  76801. {
  76802. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76803. {
  76804. r.h = y1 - ry1;
  76805. }
  76806. else
  76807. {
  76808. r.y = y1;
  76809. r.h = ry2 - y1;
  76810. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76811. i += 2;
  76812. }
  76813. }
  76814. else if (y2 > ry1 && y2 < ry2)
  76815. {
  76816. r.y = y2;
  76817. r.h = ry2 - y2;
  76818. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76819. {
  76820. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76821. i += 2;
  76822. }
  76823. }
  76824. else
  76825. {
  76826. rects.remove (i);
  76827. }
  76828. }
  76829. }
  76830. }
  76831. }
  76832. bool RectangleList::subtract (const RectangleList& otherList)
  76833. {
  76834. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76835. subtract (otherList.rects.getReference (i));
  76836. return rects.size() > 0;
  76837. }
  76838. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76839. {
  76840. bool notEmpty = false;
  76841. if (rect.isEmpty())
  76842. {
  76843. clear();
  76844. }
  76845. else
  76846. {
  76847. for (int i = rects.size(); --i >= 0;)
  76848. {
  76849. Rectangle<int>& r = rects.getReference (i);
  76850. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76851. rects.remove (i);
  76852. else
  76853. notEmpty = true;
  76854. }
  76855. }
  76856. return notEmpty;
  76857. }
  76858. bool RectangleList::clipTo (const RectangleList& other)
  76859. {
  76860. if (rects.size() == 0)
  76861. return false;
  76862. RectangleList result;
  76863. for (int j = 0; j < rects.size(); ++j)
  76864. {
  76865. const Rectangle<int>& rect = rects.getReference (j);
  76866. for (int i = other.rects.size(); --i >= 0;)
  76867. {
  76868. Rectangle<int> r (other.rects.getReference (i));
  76869. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76870. result.rects.add (r);
  76871. }
  76872. }
  76873. swapWith (result);
  76874. return ! isEmpty();
  76875. }
  76876. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76877. {
  76878. destRegion.clear();
  76879. if (! rect.isEmpty())
  76880. {
  76881. for (int i = rects.size(); --i >= 0;)
  76882. {
  76883. Rectangle<int> r (rects.getReference (i));
  76884. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76885. destRegion.rects.add (r);
  76886. }
  76887. }
  76888. return destRegion.rects.size() > 0;
  76889. }
  76890. void RectangleList::swapWith (RectangleList& otherList) throw()
  76891. {
  76892. rects.swapWithArray (otherList.rects);
  76893. }
  76894. void RectangleList::consolidate()
  76895. {
  76896. int i;
  76897. for (i = 0; i < getNumRectangles() - 1; ++i)
  76898. {
  76899. Rectangle<int>& r = rects.getReference (i);
  76900. const int rx1 = r.x;
  76901. const int ry1 = r.y;
  76902. const int rx2 = rx1 + r.w;
  76903. const int ry2 = ry1 + r.h;
  76904. for (int j = rects.size(); --j > i;)
  76905. {
  76906. Rectangle<int>& r2 = rects.getReference (j);
  76907. const int jrx1 = r2.x;
  76908. const int jry1 = r2.y;
  76909. const int jrx2 = jrx1 + r2.w;
  76910. const int jry2 = jry1 + r2.h;
  76911. // if the vertical edges of any blocks are touching and their horizontals don't
  76912. // line up, split them horizontally..
  76913. if (jrx1 == rx2 || jrx2 == rx1)
  76914. {
  76915. if (jry1 > ry1 && jry1 < ry2)
  76916. {
  76917. r.h = jry1 - ry1;
  76918. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76919. i = -1;
  76920. break;
  76921. }
  76922. if (jry2 > ry1 && jry2 < ry2)
  76923. {
  76924. r.h = jry2 - ry1;
  76925. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76926. i = -1;
  76927. break;
  76928. }
  76929. else if (ry1 > jry1 && ry1 < jry2)
  76930. {
  76931. r2.h = ry1 - jry1;
  76932. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76933. i = -1;
  76934. break;
  76935. }
  76936. else if (ry2 > jry1 && ry2 < jry2)
  76937. {
  76938. r2.h = ry2 - jry1;
  76939. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76940. i = -1;
  76941. break;
  76942. }
  76943. }
  76944. }
  76945. }
  76946. for (i = 0; i < rects.size() - 1; ++i)
  76947. {
  76948. Rectangle<int>& r = rects.getReference (i);
  76949. for (int j = rects.size(); --j > i;)
  76950. {
  76951. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76952. {
  76953. rects.remove (j);
  76954. i = -1;
  76955. break;
  76956. }
  76957. }
  76958. }
  76959. }
  76960. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76961. {
  76962. for (int i = getNumRectangles(); --i >= 0;)
  76963. if (rects.getReference (i).contains (x, y))
  76964. return true;
  76965. return false;
  76966. }
  76967. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76968. {
  76969. if (rects.size() > 1)
  76970. {
  76971. RectangleList r (rectangleToCheck);
  76972. for (int i = rects.size(); --i >= 0;)
  76973. {
  76974. r.subtract (rects.getReference (i));
  76975. if (r.rects.size() == 0)
  76976. return true;
  76977. }
  76978. }
  76979. else if (rects.size() > 0)
  76980. {
  76981. return rects.getReference (0).contains (rectangleToCheck);
  76982. }
  76983. return false;
  76984. }
  76985. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76986. {
  76987. for (int i = rects.size(); --i >= 0;)
  76988. if (rects.getReference (i).intersects (rectangleToCheck))
  76989. return true;
  76990. return false;
  76991. }
  76992. bool RectangleList::intersects (const RectangleList& other) const throw()
  76993. {
  76994. for (int i = rects.size(); --i >= 0;)
  76995. if (other.intersectsRectangle (rects.getReference (i)))
  76996. return true;
  76997. return false;
  76998. }
  76999. const Rectangle<int> RectangleList::getBounds() const throw()
  77000. {
  77001. if (rects.size() <= 1)
  77002. {
  77003. if (rects.size() == 0)
  77004. return Rectangle<int>();
  77005. else
  77006. return rects.getReference (0);
  77007. }
  77008. else
  77009. {
  77010. const Rectangle<int>& r = rects.getReference (0);
  77011. int minX = r.x;
  77012. int minY = r.y;
  77013. int maxX = minX + r.w;
  77014. int maxY = minY + r.h;
  77015. for (int i = rects.size(); --i > 0;)
  77016. {
  77017. const Rectangle<int>& r2 = rects.getReference (i);
  77018. minX = jmin (minX, r2.x);
  77019. minY = jmin (minY, r2.y);
  77020. maxX = jmax (maxX, r2.getRight());
  77021. maxY = jmax (maxY, r2.getBottom());
  77022. }
  77023. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  77024. }
  77025. }
  77026. void RectangleList::offsetAll (const int dx, const int dy) throw()
  77027. {
  77028. for (int i = rects.size(); --i >= 0;)
  77029. {
  77030. Rectangle<int>& r = rects.getReference (i);
  77031. r.x += dx;
  77032. r.y += dy;
  77033. }
  77034. }
  77035. const Path RectangleList::toPath() const
  77036. {
  77037. Path p;
  77038. for (int i = rects.size(); --i >= 0;)
  77039. {
  77040. const Rectangle<int>& r = rects.getReference (i);
  77041. p.addRectangle ((float) r.x,
  77042. (float) r.y,
  77043. (float) r.w,
  77044. (float) r.h);
  77045. }
  77046. return p;
  77047. }
  77048. END_JUCE_NAMESPACE
  77049. /*** End of inlined file: juce_RectangleList.cpp ***/
  77050. /*** Start of inlined file: juce_Image.cpp ***/
  77051. BEGIN_JUCE_NAMESPACE
  77052. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  77053. : format (format_), width (width_), height (height_)
  77054. {
  77055. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  77056. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  77057. }
  77058. Image::SharedImage::~SharedImage()
  77059. {
  77060. }
  77061. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  77062. {
  77063. return imageData + lineStride * y + pixelStride * x;
  77064. }
  77065. class SoftwareSharedImage : public Image::SharedImage
  77066. {
  77067. public:
  77068. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  77069. : Image::SharedImage (format_, width_, height_)
  77070. {
  77071. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  77072. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  77073. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  77074. imageData = imageDataAllocated;
  77075. }
  77076. ~SoftwareSharedImage()
  77077. {
  77078. }
  77079. Image::ImageType getType() const
  77080. {
  77081. return Image::SoftwareImage;
  77082. }
  77083. LowLevelGraphicsContext* createLowLevelContext()
  77084. {
  77085. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  77086. }
  77087. SharedImage* clone()
  77088. {
  77089. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  77090. memcpy (s->imageData, imageData, lineStride * height);
  77091. return s;
  77092. }
  77093. private:
  77094. HeapBlock<uint8> imageDataAllocated;
  77095. };
  77096. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  77097. {
  77098. return new SoftwareSharedImage (format, width, height, clearImage);
  77099. }
  77100. class SubsectionSharedImage : public Image::SharedImage
  77101. {
  77102. public:
  77103. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  77104. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  77105. image (image_), area (area_)
  77106. {
  77107. pixelStride = image_->getPixelStride();
  77108. lineStride = image_->getLineStride();
  77109. imageData = image_->getPixelData (area_.getX(), area_.getY());
  77110. }
  77111. ~SubsectionSharedImage() {}
  77112. Image::ImageType getType() const
  77113. {
  77114. return Image::SoftwareImage;
  77115. }
  77116. LowLevelGraphicsContext* createLowLevelContext()
  77117. {
  77118. LowLevelGraphicsContext* g = image->createLowLevelContext();
  77119. g->clipToRectangle (area);
  77120. g->setOrigin (area.getX(), area.getY());
  77121. return g;
  77122. }
  77123. SharedImage* clone()
  77124. {
  77125. return new SubsectionSharedImage (image->clone(), area);
  77126. }
  77127. private:
  77128. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  77129. const Rectangle<int> area;
  77130. SubsectionSharedImage (const SubsectionSharedImage&);
  77131. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  77132. };
  77133. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77134. {
  77135. if (area.contains (getBounds()))
  77136. return *this;
  77137. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77138. if (validArea.isEmpty())
  77139. return Image::null;
  77140. return Image (new SubsectionSharedImage (image, validArea));
  77141. }
  77142. Image::Image()
  77143. {
  77144. }
  77145. Image::Image (SharedImage* const instance)
  77146. : image (instance)
  77147. {
  77148. }
  77149. Image::Image (const PixelFormat format,
  77150. const int width, const int height,
  77151. const bool clearImage, const ImageType type)
  77152. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77153. : new SoftwareSharedImage (format, width, height, clearImage))
  77154. {
  77155. }
  77156. Image::Image (const Image& other)
  77157. : image (other.image)
  77158. {
  77159. }
  77160. Image& Image::operator= (const Image& other)
  77161. {
  77162. image = other.image;
  77163. return *this;
  77164. }
  77165. Image::~Image()
  77166. {
  77167. }
  77168. const Image Image::null;
  77169. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77170. {
  77171. return image == 0 ? 0 : image->createLowLevelContext();
  77172. }
  77173. void Image::duplicateIfShared()
  77174. {
  77175. if (image != 0 && image->getReferenceCount() > 1)
  77176. image = image->clone();
  77177. }
  77178. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77179. {
  77180. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77181. return *this;
  77182. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77183. Graphics g (newImage);
  77184. g.setImageResamplingQuality (quality);
  77185. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77186. return newImage;
  77187. }
  77188. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77189. {
  77190. if (image == 0 || newFormat == image->format)
  77191. return *this;
  77192. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77193. if (newFormat == SingleChannel)
  77194. {
  77195. if (! hasAlphaChannel())
  77196. {
  77197. newImage.clear (getBounds(), Colours::black);
  77198. }
  77199. else
  77200. {
  77201. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77202. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77203. for (int y = 0; y < image->height; ++y)
  77204. {
  77205. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77206. uint8* dst = destData.getLinePointer (y);
  77207. for (int x = image->width; --x >= 0;)
  77208. {
  77209. *dst++ = src->getAlpha();
  77210. ++src;
  77211. }
  77212. }
  77213. }
  77214. }
  77215. else
  77216. {
  77217. if (hasAlphaChannel())
  77218. newImage.clear (getBounds());
  77219. Graphics g (newImage);
  77220. g.drawImageAt (*this, 0, 0);
  77221. }
  77222. return newImage;
  77223. }
  77224. const var Image::getTag() const
  77225. {
  77226. return image == 0 ? var::null : image->userTag;
  77227. }
  77228. void Image::setTag (const var& newTag)
  77229. {
  77230. if (image != 0)
  77231. image->userTag = newTag;
  77232. }
  77233. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77234. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77235. pixelFormat (image.getFormat()),
  77236. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77237. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77238. width (w),
  77239. height (h)
  77240. {
  77241. jassert (data != 0);
  77242. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77243. }
  77244. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77245. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77246. pixelFormat (image.getFormat()),
  77247. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77248. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77249. width (w),
  77250. height (h)
  77251. {
  77252. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77253. }
  77254. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77255. : data (image.image == 0 ? 0 : image.image->imageData),
  77256. pixelFormat (image.getFormat()),
  77257. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77258. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77259. width (image.getWidth()),
  77260. height (image.getHeight())
  77261. {
  77262. }
  77263. Image::BitmapData::~BitmapData()
  77264. {
  77265. }
  77266. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77267. {
  77268. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77269. const uint8* const pixel = getPixelPointer (x, y);
  77270. switch (pixelFormat)
  77271. {
  77272. case Image::ARGB:
  77273. {
  77274. PixelARGB p (*(const PixelARGB*) pixel);
  77275. p.unpremultiply();
  77276. return Colour (p.getARGB());
  77277. }
  77278. case Image::RGB:
  77279. return Colour (((const PixelRGB*) pixel)->getARGB());
  77280. case Image::SingleChannel:
  77281. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77282. default:
  77283. jassertfalse;
  77284. break;
  77285. }
  77286. return Colour();
  77287. }
  77288. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77289. {
  77290. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77291. uint8* const pixel = getPixelPointer (x, y);
  77292. const PixelARGB col (colour.getPixelARGB());
  77293. switch (pixelFormat)
  77294. {
  77295. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77296. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77297. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77298. default: jassertfalse; break;
  77299. }
  77300. }
  77301. void Image::setPixelData (int x, int y, int w, int h,
  77302. const uint8* const sourcePixelData, const int sourceLineStride)
  77303. {
  77304. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77305. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77306. {
  77307. const BitmapData dest (*this, x, y, w, h, true);
  77308. for (int i = 0; i < h; ++i)
  77309. {
  77310. memcpy (dest.getLinePointer(i),
  77311. sourcePixelData + sourceLineStride * i,
  77312. w * dest.pixelStride);
  77313. }
  77314. }
  77315. }
  77316. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77317. {
  77318. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77319. if (! clipped.isEmpty())
  77320. {
  77321. const PixelARGB col (colourToClearTo.getPixelARGB());
  77322. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77323. uint8* dest = destData.data;
  77324. int dh = clipped.getHeight();
  77325. while (--dh >= 0)
  77326. {
  77327. uint8* line = dest;
  77328. dest += destData.lineStride;
  77329. if (isARGB())
  77330. {
  77331. for (int x = clipped.getWidth(); --x >= 0;)
  77332. {
  77333. ((PixelARGB*) line)->set (col);
  77334. line += destData.pixelStride;
  77335. }
  77336. }
  77337. else if (isRGB())
  77338. {
  77339. for (int x = clipped.getWidth(); --x >= 0;)
  77340. {
  77341. ((PixelRGB*) line)->set (col);
  77342. line += destData.pixelStride;
  77343. }
  77344. }
  77345. else
  77346. {
  77347. for (int x = clipped.getWidth(); --x >= 0;)
  77348. {
  77349. *line = col.getAlpha();
  77350. line += destData.pixelStride;
  77351. }
  77352. }
  77353. }
  77354. }
  77355. }
  77356. const Colour Image::getPixelAt (const int x, const int y) const
  77357. {
  77358. if (((unsigned int) x) < (unsigned int) getWidth()
  77359. && ((unsigned int) y) < (unsigned int) getHeight())
  77360. {
  77361. const BitmapData srcData (*this, x, y, 1, 1);
  77362. return srcData.getPixelColour (0, 0);
  77363. }
  77364. return Colour();
  77365. }
  77366. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77367. {
  77368. if (((unsigned int) x) < (unsigned int) getWidth()
  77369. && ((unsigned int) y) < (unsigned int) getHeight())
  77370. {
  77371. const BitmapData destData (*this, x, y, 1, 1, true);
  77372. destData.setPixelColour (0, 0, colour);
  77373. }
  77374. }
  77375. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77376. {
  77377. if (((unsigned int) x) < (unsigned int) getWidth()
  77378. && ((unsigned int) y) < (unsigned int) getHeight()
  77379. && hasAlphaChannel())
  77380. {
  77381. const BitmapData destData (*this, x, y, 1, 1, true);
  77382. if (isARGB())
  77383. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77384. else
  77385. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77386. }
  77387. }
  77388. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77389. {
  77390. if (hasAlphaChannel())
  77391. {
  77392. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77393. if (isARGB())
  77394. {
  77395. for (int y = 0; y < destData.height; ++y)
  77396. {
  77397. uint8* p = destData.getLinePointer (y);
  77398. for (int x = 0; x < destData.width; ++x)
  77399. {
  77400. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77401. p += destData.pixelStride;
  77402. }
  77403. }
  77404. }
  77405. else
  77406. {
  77407. for (int y = 0; y < destData.height; ++y)
  77408. {
  77409. uint8* p = destData.getLinePointer (y);
  77410. for (int x = 0; x < destData.width; ++x)
  77411. {
  77412. *p = (uint8) (*p * amountToMultiplyBy);
  77413. p += destData.pixelStride;
  77414. }
  77415. }
  77416. }
  77417. }
  77418. else
  77419. {
  77420. jassertfalse; // can't do this without an alpha-channel!
  77421. }
  77422. }
  77423. void Image::desaturate()
  77424. {
  77425. if (isARGB() || isRGB())
  77426. {
  77427. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77428. if (isARGB())
  77429. {
  77430. for (int y = 0; y < destData.height; ++y)
  77431. {
  77432. uint8* p = destData.getLinePointer (y);
  77433. for (int x = 0; x < destData.width; ++x)
  77434. {
  77435. ((PixelARGB*) p)->desaturate();
  77436. p += destData.pixelStride;
  77437. }
  77438. }
  77439. }
  77440. else
  77441. {
  77442. for (int y = 0; y < destData.height; ++y)
  77443. {
  77444. uint8* p = destData.getLinePointer (y);
  77445. for (int x = 0; x < destData.width; ++x)
  77446. {
  77447. ((PixelRGB*) p)->desaturate();
  77448. p += destData.pixelStride;
  77449. }
  77450. }
  77451. }
  77452. }
  77453. }
  77454. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77455. {
  77456. if (hasAlphaChannel())
  77457. {
  77458. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77459. SparseSet<int> pixelsOnRow;
  77460. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77461. for (int y = 0; y < srcData.height; ++y)
  77462. {
  77463. pixelsOnRow.clear();
  77464. const uint8* lineData = srcData.getLinePointer (y);
  77465. if (isARGB())
  77466. {
  77467. for (int x = 0; x < srcData.width; ++x)
  77468. {
  77469. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77470. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77471. lineData += srcData.pixelStride;
  77472. }
  77473. }
  77474. else
  77475. {
  77476. for (int x = 0; x < srcData.width; ++x)
  77477. {
  77478. if (*lineData >= threshold)
  77479. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77480. lineData += srcData.pixelStride;
  77481. }
  77482. }
  77483. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77484. {
  77485. const Range<int> range (pixelsOnRow.getRange (i));
  77486. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77487. }
  77488. result.consolidate();
  77489. }
  77490. }
  77491. else
  77492. {
  77493. result.add (0, 0, getWidth(), getHeight());
  77494. }
  77495. }
  77496. void Image::moveImageSection (int dx, int dy,
  77497. int sx, int sy,
  77498. int w, int h)
  77499. {
  77500. if (dx < 0)
  77501. {
  77502. w += dx;
  77503. sx -= dx;
  77504. dx = 0;
  77505. }
  77506. if (dy < 0)
  77507. {
  77508. h += dy;
  77509. sy -= dy;
  77510. dy = 0;
  77511. }
  77512. if (sx < 0)
  77513. {
  77514. w += sx;
  77515. dx -= sx;
  77516. sx = 0;
  77517. }
  77518. if (sy < 0)
  77519. {
  77520. h += sy;
  77521. dy -= sy;
  77522. sy = 0;
  77523. }
  77524. const int minX = jmin (dx, sx);
  77525. const int minY = jmin (dy, sy);
  77526. w = jmin (w, getWidth() - jmax (sx, dx));
  77527. h = jmin (h, getHeight() - jmax (sy, dy));
  77528. if (w > 0 && h > 0)
  77529. {
  77530. const int maxX = jmax (dx, sx) + w;
  77531. const int maxY = jmax (dy, sy) + h;
  77532. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77533. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77534. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77535. const int lineSize = destData.pixelStride * w;
  77536. if (dy > sy)
  77537. {
  77538. while (--h >= 0)
  77539. {
  77540. const int offset = h * destData.lineStride;
  77541. memmove (dst + offset, src + offset, lineSize);
  77542. }
  77543. }
  77544. else if (dst != src)
  77545. {
  77546. while (--h >= 0)
  77547. {
  77548. memmove (dst, src, lineSize);
  77549. dst += destData.lineStride;
  77550. src += destData.lineStride;
  77551. }
  77552. }
  77553. }
  77554. }
  77555. END_JUCE_NAMESPACE
  77556. /*** End of inlined file: juce_Image.cpp ***/
  77557. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77558. BEGIN_JUCE_NAMESPACE
  77559. class ImageCache::Pimpl : public Timer,
  77560. public DeletedAtShutdown
  77561. {
  77562. public:
  77563. Pimpl()
  77564. : cacheTimeout (5000)
  77565. {
  77566. }
  77567. ~Pimpl()
  77568. {
  77569. clearSingletonInstance();
  77570. }
  77571. const Image getFromHashCode (const int64 hashCode)
  77572. {
  77573. const ScopedLock sl (lock);
  77574. for (int i = images.size(); --i >= 0;)
  77575. {
  77576. Item* const item = images.getUnchecked(i);
  77577. if (item->hashCode == hashCode)
  77578. return item->image;
  77579. }
  77580. return Image::null;
  77581. }
  77582. void addImageToCache (const Image& image, const int64 hashCode)
  77583. {
  77584. if (image.isValid())
  77585. {
  77586. if (! isTimerRunning())
  77587. startTimer (2000);
  77588. Item* const item = new Item();
  77589. item->hashCode = hashCode;
  77590. item->image = image;
  77591. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77592. const ScopedLock sl (lock);
  77593. images.add (item);
  77594. }
  77595. }
  77596. void timerCallback()
  77597. {
  77598. const uint32 now = Time::getApproximateMillisecondCounter();
  77599. const ScopedLock sl (lock);
  77600. for (int i = images.size(); --i >= 0;)
  77601. {
  77602. Item* const item = images.getUnchecked(i);
  77603. if (item->image.getReferenceCount() <= 1)
  77604. {
  77605. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77606. images.remove (i);
  77607. }
  77608. else
  77609. {
  77610. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77611. }
  77612. }
  77613. if (images.size() == 0)
  77614. stopTimer();
  77615. }
  77616. struct Item
  77617. {
  77618. Image image;
  77619. int64 hashCode;
  77620. uint32 lastUseTime;
  77621. };
  77622. int cacheTimeout;
  77623. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77624. private:
  77625. OwnedArray<Item> images;
  77626. CriticalSection lock;
  77627. Pimpl (const Pimpl&);
  77628. Pimpl& operator= (const Pimpl&);
  77629. };
  77630. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77631. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77632. {
  77633. if (Pimpl::getInstanceWithoutCreating() != 0)
  77634. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77635. return Image::null;
  77636. }
  77637. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77638. {
  77639. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77640. }
  77641. const Image ImageCache::getFromFile (const File& file)
  77642. {
  77643. const int64 hashCode = file.hashCode64();
  77644. Image image (getFromHashCode (hashCode));
  77645. if (image.isNull())
  77646. {
  77647. image = ImageFileFormat::loadFrom (file);
  77648. addImageToCache (image, hashCode);
  77649. }
  77650. return image;
  77651. }
  77652. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77653. {
  77654. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77655. Image image (getFromHashCode (hashCode));
  77656. if (image.isNull())
  77657. {
  77658. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77659. addImageToCache (image, hashCode);
  77660. }
  77661. return image;
  77662. }
  77663. void ImageCache::setCacheTimeout (const int millisecs)
  77664. {
  77665. Pimpl::getInstance()->cacheTimeout = millisecs;
  77666. }
  77667. END_JUCE_NAMESPACE
  77668. /*** End of inlined file: juce_ImageCache.cpp ***/
  77669. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77670. BEGIN_JUCE_NAMESPACE
  77671. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77672. : values (size_ * size_),
  77673. size (size_)
  77674. {
  77675. clear();
  77676. }
  77677. ImageConvolutionKernel::~ImageConvolutionKernel()
  77678. {
  77679. }
  77680. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77681. {
  77682. if (((unsigned int) x) < (unsigned int) size
  77683. && ((unsigned int) y) < (unsigned int) size)
  77684. {
  77685. return values [x + y * size];
  77686. }
  77687. else
  77688. {
  77689. jassertfalse;
  77690. return 0;
  77691. }
  77692. }
  77693. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77694. {
  77695. if (((unsigned int) x) < (unsigned int) size
  77696. && ((unsigned int) y) < (unsigned int) size)
  77697. {
  77698. values [x + y * size] = value;
  77699. }
  77700. else
  77701. {
  77702. jassertfalse;
  77703. }
  77704. }
  77705. void ImageConvolutionKernel::clear()
  77706. {
  77707. for (int i = size * size; --i >= 0;)
  77708. values[i] = 0;
  77709. }
  77710. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77711. {
  77712. double currentTotal = 0.0;
  77713. for (int i = size * size; --i >= 0;)
  77714. currentTotal += values[i];
  77715. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77716. }
  77717. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77718. {
  77719. for (int i = size * size; --i >= 0;)
  77720. values[i] *= multiplier;
  77721. }
  77722. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77723. {
  77724. const double radiusFactor = -1.0 / (radius * radius * 2);
  77725. const int centre = size >> 1;
  77726. for (int y = size; --y >= 0;)
  77727. {
  77728. for (int x = size; --x >= 0;)
  77729. {
  77730. const int cx = x - centre;
  77731. const int cy = y - centre;
  77732. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77733. }
  77734. }
  77735. setOverallSum (1.0f);
  77736. }
  77737. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77738. const Image& sourceImage,
  77739. const Rectangle<int>& destinationArea) const
  77740. {
  77741. if (sourceImage == destImage)
  77742. {
  77743. destImage.duplicateIfShared();
  77744. }
  77745. else
  77746. {
  77747. if (sourceImage.getWidth() != destImage.getWidth()
  77748. || sourceImage.getHeight() != destImage.getHeight()
  77749. || sourceImage.getFormat() != destImage.getFormat())
  77750. {
  77751. jassertfalse;
  77752. return;
  77753. }
  77754. }
  77755. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77756. if (area.isEmpty())
  77757. return;
  77758. const int right = area.getRight();
  77759. const int bottom = area.getBottom();
  77760. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77761. uint8* line = destData.data;
  77762. const Image::BitmapData srcData (sourceImage, false);
  77763. if (destData.pixelStride == 4)
  77764. {
  77765. for (int y = area.getY(); y < bottom; ++y)
  77766. {
  77767. uint8* dest = line;
  77768. line += destData.lineStride;
  77769. for (int x = area.getX(); x < right; ++x)
  77770. {
  77771. float c1 = 0;
  77772. float c2 = 0;
  77773. float c3 = 0;
  77774. float c4 = 0;
  77775. for (int yy = 0; yy < size; ++yy)
  77776. {
  77777. const int sy = y + yy - (size >> 1);
  77778. if (sy >= srcData.height)
  77779. break;
  77780. if (sy >= 0)
  77781. {
  77782. int sx = x - (size >> 1);
  77783. const uint8* src = srcData.getPixelPointer (sx, sy);
  77784. for (int xx = 0; xx < size; ++xx)
  77785. {
  77786. if (sx >= srcData.width)
  77787. break;
  77788. if (sx >= 0)
  77789. {
  77790. const float kernelMult = values [xx + yy * size];
  77791. c1 += kernelMult * *src++;
  77792. c2 += kernelMult * *src++;
  77793. c3 += kernelMult * *src++;
  77794. c4 += kernelMult * *src++;
  77795. }
  77796. else
  77797. {
  77798. src += 4;
  77799. }
  77800. ++sx;
  77801. }
  77802. }
  77803. }
  77804. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77805. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77806. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77807. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77808. }
  77809. }
  77810. }
  77811. else if (destData.pixelStride == 3)
  77812. {
  77813. for (int y = area.getY(); y < bottom; ++y)
  77814. {
  77815. uint8* dest = line;
  77816. line += destData.lineStride;
  77817. for (int x = area.getX(); x < right; ++x)
  77818. {
  77819. float c1 = 0;
  77820. float c2 = 0;
  77821. float c3 = 0;
  77822. for (int yy = 0; yy < size; ++yy)
  77823. {
  77824. const int sy = y + yy - (size >> 1);
  77825. if (sy >= srcData.height)
  77826. break;
  77827. if (sy >= 0)
  77828. {
  77829. int sx = x - (size >> 1);
  77830. const uint8* src = srcData.getPixelPointer (sx, sy);
  77831. for (int xx = 0; xx < size; ++xx)
  77832. {
  77833. if (sx >= srcData.width)
  77834. break;
  77835. if (sx >= 0)
  77836. {
  77837. const float kernelMult = values [xx + yy * size];
  77838. c1 += kernelMult * *src++;
  77839. c2 += kernelMult * *src++;
  77840. c3 += kernelMult * *src++;
  77841. }
  77842. else
  77843. {
  77844. src += 3;
  77845. }
  77846. ++sx;
  77847. }
  77848. }
  77849. }
  77850. *dest++ = (uint8) roundToInt (c1);
  77851. *dest++ = (uint8) roundToInt (c2);
  77852. *dest++ = (uint8) roundToInt (c3);
  77853. }
  77854. }
  77855. }
  77856. }
  77857. END_JUCE_NAMESPACE
  77858. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77859. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77860. BEGIN_JUCE_NAMESPACE
  77861. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77862. {
  77863. static PNGImageFormat png;
  77864. static JPEGImageFormat jpg;
  77865. static GIFImageFormat gif;
  77866. ImageFileFormat* formats[4];
  77867. int numFormats = 0;
  77868. formats [numFormats++] = &png;
  77869. formats [numFormats++] = &jpg;
  77870. formats [numFormats++] = &gif;
  77871. const int64 streamPos = input.getPosition();
  77872. for (int i = 0; i < numFormats; ++i)
  77873. {
  77874. const bool found = formats[i]->canUnderstand (input);
  77875. input.setPosition (streamPos);
  77876. if (found)
  77877. return formats[i];
  77878. }
  77879. return 0;
  77880. }
  77881. const Image ImageFileFormat::loadFrom (InputStream& input)
  77882. {
  77883. ImageFileFormat* const format = findImageFormatForStream (input);
  77884. if (format != 0)
  77885. return format->decodeImage (input);
  77886. return Image::null;
  77887. }
  77888. const Image ImageFileFormat::loadFrom (const File& file)
  77889. {
  77890. InputStream* const in = file.createInputStream();
  77891. if (in != 0)
  77892. {
  77893. BufferedInputStream b (in, 8192, true);
  77894. return loadFrom (b);
  77895. }
  77896. return Image::null;
  77897. }
  77898. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77899. {
  77900. if (rawData != 0 && numBytes > 4)
  77901. {
  77902. MemoryInputStream stream (rawData, numBytes, false);
  77903. return loadFrom (stream);
  77904. }
  77905. return Image::null;
  77906. }
  77907. END_JUCE_NAMESPACE
  77908. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77909. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77910. BEGIN_JUCE_NAMESPACE
  77911. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77912. const Image juce_loadWithCoreImage (InputStream& input);
  77913. #else
  77914. class GIFLoader
  77915. {
  77916. public:
  77917. GIFLoader (InputStream& in)
  77918. : input (in),
  77919. dataBlockIsZero (false),
  77920. fresh (false),
  77921. finished (false)
  77922. {
  77923. currentBit = lastBit = lastByteIndex = 0;
  77924. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77925. firstcode = oldcode = 0;
  77926. clearCode = end_code = 0;
  77927. int imageWidth, imageHeight;
  77928. int transparent = -1;
  77929. if (! getSizeFromHeader (imageWidth, imageHeight))
  77930. return;
  77931. if ((imageWidth <= 0) || (imageHeight <= 0))
  77932. return;
  77933. unsigned char buf [16];
  77934. if (in.read (buf, 3) != 3)
  77935. return;
  77936. int numColours = 2 << (buf[0] & 7);
  77937. if ((buf[0] & 0x80) != 0)
  77938. readPalette (numColours);
  77939. for (;;)
  77940. {
  77941. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77942. break;
  77943. if (buf[0] == '!')
  77944. {
  77945. if (input.read (buf, 1) != 1)
  77946. break;
  77947. if (processExtension (buf[0], transparent) < 0)
  77948. break;
  77949. continue;
  77950. }
  77951. if (buf[0] != ',')
  77952. continue;
  77953. if (input.read (buf, 9) != 9)
  77954. break;
  77955. imageWidth = makeWord (buf[4], buf[5]);
  77956. imageHeight = makeWord (buf[6], buf[7]);
  77957. numColours = 2 << (buf[8] & 7);
  77958. if ((buf[8] & 0x80) != 0)
  77959. if (! readPalette (numColours))
  77960. break;
  77961. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77962. imageWidth, imageHeight, (transparent >= 0));
  77963. readImage ((buf[8] & 0x40) != 0, transparent);
  77964. break;
  77965. }
  77966. }
  77967. ~GIFLoader() {}
  77968. Image image;
  77969. private:
  77970. InputStream& input;
  77971. uint8 buffer [300];
  77972. uint8 palette [256][4];
  77973. bool dataBlockIsZero, fresh, finished;
  77974. int currentBit, lastBit, lastByteIndex;
  77975. int codeSize, setCodeSize;
  77976. int maxCode, maxCodeSize;
  77977. int firstcode, oldcode;
  77978. int clearCode, end_code;
  77979. enum { maxGifCode = 1 << 12 };
  77980. int table [2] [maxGifCode];
  77981. int stack [2 * maxGifCode];
  77982. int *sp;
  77983. bool getSizeFromHeader (int& w, int& h)
  77984. {
  77985. char b[8];
  77986. if (input.read (b, 6) == 6)
  77987. {
  77988. if ((strncmp ("GIF87a", b, 6) == 0)
  77989. || (strncmp ("GIF89a", b, 6) == 0))
  77990. {
  77991. if (input.read (b, 4) == 4)
  77992. {
  77993. w = makeWord (b[0], b[1]);
  77994. h = makeWord (b[2], b[3]);
  77995. return true;
  77996. }
  77997. }
  77998. }
  77999. return false;
  78000. }
  78001. bool readPalette (const int numCols)
  78002. {
  78003. unsigned char rgb[4];
  78004. for (int i = 0; i < numCols; ++i)
  78005. {
  78006. input.read (rgb, 3);
  78007. palette [i][0] = rgb[0];
  78008. palette [i][1] = rgb[1];
  78009. palette [i][2] = rgb[2];
  78010. palette [i][3] = 0xff;
  78011. }
  78012. return true;
  78013. }
  78014. int readDataBlock (unsigned char* dest)
  78015. {
  78016. unsigned char n;
  78017. if (input.read (&n, 1) == 1)
  78018. {
  78019. dataBlockIsZero = (n == 0);
  78020. if (dataBlockIsZero || (input.read (dest, n) == n))
  78021. return n;
  78022. }
  78023. return -1;
  78024. }
  78025. int processExtension (const int type, int& transparent)
  78026. {
  78027. unsigned char b [300];
  78028. int n = 0;
  78029. if (type == 0xf9)
  78030. {
  78031. n = readDataBlock (b);
  78032. if (n < 0)
  78033. return 1;
  78034. if ((b[0] & 0x1) != 0)
  78035. transparent = b[3];
  78036. }
  78037. do
  78038. {
  78039. n = readDataBlock (b);
  78040. }
  78041. while (n > 0);
  78042. return n;
  78043. }
  78044. int readLZWByte (const bool initialise, const int inputCodeSize)
  78045. {
  78046. int code, incode, i;
  78047. if (initialise)
  78048. {
  78049. setCodeSize = inputCodeSize;
  78050. codeSize = setCodeSize + 1;
  78051. clearCode = 1 << setCodeSize;
  78052. end_code = clearCode + 1;
  78053. maxCodeSize = 2 * clearCode;
  78054. maxCode = clearCode + 2;
  78055. getCode (0, true);
  78056. fresh = true;
  78057. for (i = 0; i < clearCode; ++i)
  78058. {
  78059. table[0][i] = 0;
  78060. table[1][i] = i;
  78061. }
  78062. for (; i < maxGifCode; ++i)
  78063. {
  78064. table[0][i] = 0;
  78065. table[1][i] = 0;
  78066. }
  78067. sp = stack;
  78068. return 0;
  78069. }
  78070. else if (fresh)
  78071. {
  78072. fresh = false;
  78073. do
  78074. {
  78075. firstcode = oldcode
  78076. = getCode (codeSize, false);
  78077. }
  78078. while (firstcode == clearCode);
  78079. return firstcode;
  78080. }
  78081. if (sp > stack)
  78082. return *--sp;
  78083. while ((code = getCode (codeSize, false)) >= 0)
  78084. {
  78085. if (code == clearCode)
  78086. {
  78087. for (i = 0; i < clearCode; ++i)
  78088. {
  78089. table[0][i] = 0;
  78090. table[1][i] = i;
  78091. }
  78092. for (; i < maxGifCode; ++i)
  78093. {
  78094. table[0][i] = 0;
  78095. table[1][i] = 0;
  78096. }
  78097. codeSize = setCodeSize + 1;
  78098. maxCodeSize = 2 * clearCode;
  78099. maxCode = clearCode + 2;
  78100. sp = stack;
  78101. firstcode = oldcode = getCode (codeSize, false);
  78102. return firstcode;
  78103. }
  78104. else if (code == end_code)
  78105. {
  78106. if (dataBlockIsZero)
  78107. return -2;
  78108. unsigned char buf [260];
  78109. int n;
  78110. while ((n = readDataBlock (buf)) > 0)
  78111. {}
  78112. if (n != 0)
  78113. return -2;
  78114. }
  78115. incode = code;
  78116. if (code >= maxCode)
  78117. {
  78118. *sp++ = firstcode;
  78119. code = oldcode;
  78120. }
  78121. while (code >= clearCode)
  78122. {
  78123. *sp++ = table[1][code];
  78124. if (code == table[0][code])
  78125. return -2;
  78126. code = table[0][code];
  78127. }
  78128. *sp++ = firstcode = table[1][code];
  78129. if ((code = maxCode) < maxGifCode)
  78130. {
  78131. table[0][code] = oldcode;
  78132. table[1][code] = firstcode;
  78133. ++maxCode;
  78134. if ((maxCode >= maxCodeSize)
  78135. && (maxCodeSize < maxGifCode))
  78136. {
  78137. maxCodeSize <<= 1;
  78138. ++codeSize;
  78139. }
  78140. }
  78141. oldcode = incode;
  78142. if (sp > stack)
  78143. return *--sp;
  78144. }
  78145. return code;
  78146. }
  78147. int getCode (const int codeSize_, const bool initialise)
  78148. {
  78149. if (initialise)
  78150. {
  78151. currentBit = 0;
  78152. lastBit = 0;
  78153. finished = false;
  78154. return 0;
  78155. }
  78156. if ((currentBit + codeSize_) >= lastBit)
  78157. {
  78158. if (finished)
  78159. return -1;
  78160. buffer[0] = buffer [lastByteIndex - 2];
  78161. buffer[1] = buffer [lastByteIndex - 1];
  78162. const int n = readDataBlock (&buffer[2]);
  78163. if (n == 0)
  78164. finished = true;
  78165. lastByteIndex = 2 + n;
  78166. currentBit = (currentBit - lastBit) + 16;
  78167. lastBit = (2 + n) * 8 ;
  78168. }
  78169. int result = 0;
  78170. int i = currentBit;
  78171. for (int j = 0; j < codeSize_; ++j)
  78172. {
  78173. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78174. ++i;
  78175. }
  78176. currentBit += codeSize_;
  78177. return result;
  78178. }
  78179. bool readImage (const int interlace, const int transparent)
  78180. {
  78181. unsigned char c;
  78182. if (input.read (&c, 1) != 1
  78183. || readLZWByte (true, c) < 0)
  78184. return false;
  78185. if (transparent >= 0)
  78186. {
  78187. palette [transparent][0] = 0;
  78188. palette [transparent][1] = 0;
  78189. palette [transparent][2] = 0;
  78190. palette [transparent][3] = 0;
  78191. }
  78192. int index;
  78193. int xpos = 0, ypos = 0, pass = 0;
  78194. const Image::BitmapData destData (image, true);
  78195. uint8* p = destData.data;
  78196. const bool hasAlpha = image.hasAlphaChannel();
  78197. while ((index = readLZWByte (false, c)) >= 0)
  78198. {
  78199. const uint8* const paletteEntry = palette [index];
  78200. if (hasAlpha)
  78201. {
  78202. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78203. paletteEntry[0],
  78204. paletteEntry[1],
  78205. paletteEntry[2]);
  78206. ((PixelARGB*) p)->premultiply();
  78207. }
  78208. else
  78209. {
  78210. ((PixelRGB*) p)->setARGB (0,
  78211. paletteEntry[0],
  78212. paletteEntry[1],
  78213. paletteEntry[2]);
  78214. }
  78215. p += destData.pixelStride;
  78216. ++xpos;
  78217. if (xpos == destData.width)
  78218. {
  78219. xpos = 0;
  78220. if (interlace)
  78221. {
  78222. switch (pass)
  78223. {
  78224. case 0:
  78225. case 1: ypos += 8; break;
  78226. case 2: ypos += 4; break;
  78227. case 3: ypos += 2; break;
  78228. }
  78229. while (ypos >= destData.height)
  78230. {
  78231. ++pass;
  78232. switch (pass)
  78233. {
  78234. case 1: ypos = 4; break;
  78235. case 2: ypos = 2; break;
  78236. case 3: ypos = 1; break;
  78237. default: return true;
  78238. }
  78239. }
  78240. }
  78241. else
  78242. {
  78243. ++ypos;
  78244. }
  78245. p = destData.getPixelPointer (xpos, ypos);
  78246. }
  78247. if (ypos >= destData.height)
  78248. break;
  78249. }
  78250. return true;
  78251. }
  78252. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78253. GIFLoader (const GIFLoader&);
  78254. GIFLoader& operator= (const GIFLoader&);
  78255. };
  78256. #endif
  78257. GIFImageFormat::GIFImageFormat() {}
  78258. GIFImageFormat::~GIFImageFormat() {}
  78259. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78260. bool GIFImageFormat::canUnderstand (InputStream& in)
  78261. {
  78262. char header [4];
  78263. return (in.read (header, sizeof (header)) == sizeof (header))
  78264. && header[0] == 'G'
  78265. && header[1] == 'I'
  78266. && header[2] == 'F';
  78267. }
  78268. const Image GIFImageFormat::decodeImage (InputStream& in)
  78269. {
  78270. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78271. return juce_loadWithCoreImage (in);
  78272. #else
  78273. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78274. return loader->image;
  78275. #endif
  78276. }
  78277. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78278. {
  78279. jassertfalse; // writing isn't implemented for GIFs!
  78280. return false;
  78281. }
  78282. END_JUCE_NAMESPACE
  78283. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78284. #endif
  78285. //==============================================================================
  78286. // some files include lots of library code, so leave them to the end to avoid cluttering
  78287. // up the build for the clean files.
  78288. #if JUCE_BUILD_CORE
  78289. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78290. namespace zlibNamespace
  78291. {
  78292. #if JUCE_INCLUDE_ZLIB_CODE
  78293. #undef OS_CODE
  78294. #undef fdopen
  78295. /*** Start of inlined file: zlib.h ***/
  78296. #ifndef ZLIB_H
  78297. #define ZLIB_H
  78298. /*** Start of inlined file: zconf.h ***/
  78299. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78300. #ifndef ZCONF_H
  78301. #define ZCONF_H
  78302. // *** Just a few hacks here to make it compile nicely with Juce..
  78303. #define Z_PREFIX 1
  78304. #undef __MACTYPES__
  78305. #ifdef _MSC_VER
  78306. #pragma warning (disable : 4131 4127 4244 4267)
  78307. #endif
  78308. /*
  78309. * If you *really* need a unique prefix for all types and library functions,
  78310. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78311. */
  78312. #ifdef Z_PREFIX
  78313. # define deflateInit_ z_deflateInit_
  78314. # define deflate z_deflate
  78315. # define deflateEnd z_deflateEnd
  78316. # define inflateInit_ z_inflateInit_
  78317. # define inflate z_inflate
  78318. # define inflateEnd z_inflateEnd
  78319. # define inflatePrime z_inflatePrime
  78320. # define inflateGetHeader z_inflateGetHeader
  78321. # define adler32_combine z_adler32_combine
  78322. # define crc32_combine z_crc32_combine
  78323. # define deflateInit2_ z_deflateInit2_
  78324. # define deflateSetDictionary z_deflateSetDictionary
  78325. # define deflateCopy z_deflateCopy
  78326. # define deflateReset z_deflateReset
  78327. # define deflateParams z_deflateParams
  78328. # define deflateBound z_deflateBound
  78329. # define deflatePrime z_deflatePrime
  78330. # define inflateInit2_ z_inflateInit2_
  78331. # define inflateSetDictionary z_inflateSetDictionary
  78332. # define inflateSync z_inflateSync
  78333. # define inflateSyncPoint z_inflateSyncPoint
  78334. # define inflateCopy z_inflateCopy
  78335. # define inflateReset z_inflateReset
  78336. # define inflateBack z_inflateBack
  78337. # define inflateBackEnd z_inflateBackEnd
  78338. # define compress z_compress
  78339. # define compress2 z_compress2
  78340. # define compressBound z_compressBound
  78341. # define uncompress z_uncompress
  78342. # define adler32 z_adler32
  78343. # define crc32 z_crc32
  78344. # define get_crc_table z_get_crc_table
  78345. # define zError z_zError
  78346. # define alloc_func z_alloc_func
  78347. # define free_func z_free_func
  78348. # define in_func z_in_func
  78349. # define out_func z_out_func
  78350. # define Byte z_Byte
  78351. # define uInt z_uInt
  78352. # define uLong z_uLong
  78353. # define Bytef z_Bytef
  78354. # define charf z_charf
  78355. # define intf z_intf
  78356. # define uIntf z_uIntf
  78357. # define uLongf z_uLongf
  78358. # define voidpf z_voidpf
  78359. # define voidp z_voidp
  78360. #endif
  78361. #if defined(__MSDOS__) && !defined(MSDOS)
  78362. # define MSDOS
  78363. #endif
  78364. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78365. # define OS2
  78366. #endif
  78367. #if defined(_WINDOWS) && !defined(WINDOWS)
  78368. # define WINDOWS
  78369. #endif
  78370. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78371. # ifndef WIN32
  78372. # define WIN32
  78373. # endif
  78374. #endif
  78375. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78376. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78377. # ifndef SYS16BIT
  78378. # define SYS16BIT
  78379. # endif
  78380. # endif
  78381. #endif
  78382. /*
  78383. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78384. * than 64k bytes at a time (needed on systems with 16-bit int).
  78385. */
  78386. #ifdef SYS16BIT
  78387. # define MAXSEG_64K
  78388. #endif
  78389. #ifdef MSDOS
  78390. # define UNALIGNED_OK
  78391. #endif
  78392. #ifdef __STDC_VERSION__
  78393. # ifndef STDC
  78394. # define STDC
  78395. # endif
  78396. # if __STDC_VERSION__ >= 199901L
  78397. # ifndef STDC99
  78398. # define STDC99
  78399. # endif
  78400. # endif
  78401. #endif
  78402. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78403. # define STDC
  78404. #endif
  78405. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78406. # define STDC
  78407. #endif
  78408. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78409. # define STDC
  78410. #endif
  78411. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78412. # define STDC
  78413. #endif
  78414. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78415. # define STDC
  78416. #endif
  78417. #ifndef STDC
  78418. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78419. # define const /* note: need a more gentle solution here */
  78420. # endif
  78421. #endif
  78422. /* Some Mac compilers merge all .h files incorrectly: */
  78423. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78424. # define NO_DUMMY_DECL
  78425. #endif
  78426. /* Maximum value for memLevel in deflateInit2 */
  78427. #ifndef MAX_MEM_LEVEL
  78428. # ifdef MAXSEG_64K
  78429. # define MAX_MEM_LEVEL 8
  78430. # else
  78431. # define MAX_MEM_LEVEL 9
  78432. # endif
  78433. #endif
  78434. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78435. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78436. * created by gzip. (Files created by minigzip can still be extracted by
  78437. * gzip.)
  78438. */
  78439. #ifndef MAX_WBITS
  78440. # define MAX_WBITS 15 /* 32K LZ77 window */
  78441. #endif
  78442. /* The memory requirements for deflate are (in bytes):
  78443. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78444. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78445. plus a few kilobytes for small objects. For example, if you want to reduce
  78446. the default memory requirements from 256K to 128K, compile with
  78447. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78448. Of course this will generally degrade compression (there's no free lunch).
  78449. The memory requirements for inflate are (in bytes) 1 << windowBits
  78450. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78451. for small objects.
  78452. */
  78453. /* Type declarations */
  78454. #ifndef OF /* function prototypes */
  78455. # ifdef STDC
  78456. # define OF(args) args
  78457. # else
  78458. # define OF(args) ()
  78459. # endif
  78460. #endif
  78461. /* The following definitions for FAR are needed only for MSDOS mixed
  78462. * model programming (small or medium model with some far allocations).
  78463. * This was tested only with MSC; for other MSDOS compilers you may have
  78464. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78465. * just define FAR to be empty.
  78466. */
  78467. #ifdef SYS16BIT
  78468. # if defined(M_I86SM) || defined(M_I86MM)
  78469. /* MSC small or medium model */
  78470. # define SMALL_MEDIUM
  78471. # ifdef _MSC_VER
  78472. # define FAR _far
  78473. # else
  78474. # define FAR far
  78475. # endif
  78476. # endif
  78477. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78478. /* Turbo C small or medium model */
  78479. # define SMALL_MEDIUM
  78480. # ifdef __BORLANDC__
  78481. # define FAR _far
  78482. # else
  78483. # define FAR far
  78484. # endif
  78485. # endif
  78486. #endif
  78487. #if defined(WINDOWS) || defined(WIN32)
  78488. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78489. * This is not mandatory, but it offers a little performance increase.
  78490. */
  78491. # ifdef ZLIB_DLL
  78492. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78493. # ifdef ZLIB_INTERNAL
  78494. # define ZEXTERN extern __declspec(dllexport)
  78495. # else
  78496. # define ZEXTERN extern __declspec(dllimport)
  78497. # endif
  78498. # endif
  78499. # endif /* ZLIB_DLL */
  78500. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78501. * define ZLIB_WINAPI.
  78502. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78503. */
  78504. # ifdef ZLIB_WINAPI
  78505. # ifdef FAR
  78506. # undef FAR
  78507. # endif
  78508. # include <windows.h>
  78509. /* No need for _export, use ZLIB.DEF instead. */
  78510. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78511. # define ZEXPORT WINAPI
  78512. # ifdef WIN32
  78513. # define ZEXPORTVA WINAPIV
  78514. # else
  78515. # define ZEXPORTVA FAR CDECL
  78516. # endif
  78517. # endif
  78518. #endif
  78519. #if defined (__BEOS__)
  78520. # ifdef ZLIB_DLL
  78521. # ifdef ZLIB_INTERNAL
  78522. # define ZEXPORT __declspec(dllexport)
  78523. # define ZEXPORTVA __declspec(dllexport)
  78524. # else
  78525. # define ZEXPORT __declspec(dllimport)
  78526. # define ZEXPORTVA __declspec(dllimport)
  78527. # endif
  78528. # endif
  78529. #endif
  78530. #ifndef ZEXTERN
  78531. # define ZEXTERN extern
  78532. #endif
  78533. #ifndef ZEXPORT
  78534. # define ZEXPORT
  78535. #endif
  78536. #ifndef ZEXPORTVA
  78537. # define ZEXPORTVA
  78538. #endif
  78539. #ifndef FAR
  78540. # define FAR
  78541. #endif
  78542. #if !defined(__MACTYPES__)
  78543. typedef unsigned char Byte; /* 8 bits */
  78544. #endif
  78545. typedef unsigned int uInt; /* 16 bits or more */
  78546. typedef unsigned long uLong; /* 32 bits or more */
  78547. #ifdef SMALL_MEDIUM
  78548. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78549. # define Bytef Byte FAR
  78550. #else
  78551. typedef Byte FAR Bytef;
  78552. #endif
  78553. typedef char FAR charf;
  78554. typedef int FAR intf;
  78555. typedef uInt FAR uIntf;
  78556. typedef uLong FAR uLongf;
  78557. #ifdef STDC
  78558. typedef void const *voidpc;
  78559. typedef void FAR *voidpf;
  78560. typedef void *voidp;
  78561. #else
  78562. typedef Byte const *voidpc;
  78563. typedef Byte FAR *voidpf;
  78564. typedef Byte *voidp;
  78565. #endif
  78566. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78567. # include <sys/types.h> /* for off_t */
  78568. # include <unistd.h> /* for SEEK_* and off_t */
  78569. # ifdef VMS
  78570. # include <unixio.h> /* for off_t */
  78571. # endif
  78572. # define z_off_t off_t
  78573. #endif
  78574. #ifndef SEEK_SET
  78575. # define SEEK_SET 0 /* Seek from beginning of file. */
  78576. # define SEEK_CUR 1 /* Seek from current position. */
  78577. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78578. #endif
  78579. #ifndef z_off_t
  78580. # define z_off_t long
  78581. #endif
  78582. #if defined(__OS400__)
  78583. # define NO_vsnprintf
  78584. #endif
  78585. #if defined(__MVS__)
  78586. # define NO_vsnprintf
  78587. # ifdef FAR
  78588. # undef FAR
  78589. # endif
  78590. #endif
  78591. /* MVS linker does not support external names larger than 8 bytes */
  78592. #if defined(__MVS__)
  78593. # pragma map(deflateInit_,"DEIN")
  78594. # pragma map(deflateInit2_,"DEIN2")
  78595. # pragma map(deflateEnd,"DEEND")
  78596. # pragma map(deflateBound,"DEBND")
  78597. # pragma map(inflateInit_,"ININ")
  78598. # pragma map(inflateInit2_,"ININ2")
  78599. # pragma map(inflateEnd,"INEND")
  78600. # pragma map(inflateSync,"INSY")
  78601. # pragma map(inflateSetDictionary,"INSEDI")
  78602. # pragma map(compressBound,"CMBND")
  78603. # pragma map(inflate_table,"INTABL")
  78604. # pragma map(inflate_fast,"INFA")
  78605. # pragma map(inflate_copyright,"INCOPY")
  78606. #endif
  78607. #endif /* ZCONF_H */
  78608. /*** End of inlined file: zconf.h ***/
  78609. #ifdef __cplusplus
  78610. //extern "C" {
  78611. #endif
  78612. #define ZLIB_VERSION "1.2.3"
  78613. #define ZLIB_VERNUM 0x1230
  78614. /*
  78615. The 'zlib' compression library provides in-memory compression and
  78616. decompression functions, including integrity checks of the uncompressed
  78617. data. This version of the library supports only one compression method
  78618. (deflation) but other algorithms will be added later and will have the same
  78619. stream interface.
  78620. Compression can be done in a single step if the buffers are large
  78621. enough (for example if an input file is mmap'ed), or can be done by
  78622. repeated calls of the compression function. In the latter case, the
  78623. application must provide more input and/or consume the output
  78624. (providing more output space) before each call.
  78625. The compressed data format used by default by the in-memory functions is
  78626. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78627. around a deflate stream, which is itself documented in RFC 1951.
  78628. The library also supports reading and writing files in gzip (.gz) format
  78629. with an interface similar to that of stdio using the functions that start
  78630. with "gz". The gzip format is different from the zlib format. gzip is a
  78631. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78632. This library can optionally read and write gzip streams in memory as well.
  78633. The zlib format was designed to be compact and fast for use in memory
  78634. and on communications channels. The gzip format was designed for single-
  78635. file compression on file systems, has a larger header than zlib to maintain
  78636. directory information, and uses a different, slower check method than zlib.
  78637. The library does not install any signal handler. The decoder checks
  78638. the consistency of the compressed data, so the library should never
  78639. crash even in case of corrupted input.
  78640. */
  78641. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78642. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78643. struct internal_state;
  78644. typedef struct z_stream_s {
  78645. Bytef *next_in; /* next input byte */
  78646. uInt avail_in; /* number of bytes available at next_in */
  78647. uLong total_in; /* total nb of input bytes read so far */
  78648. Bytef *next_out; /* next output byte should be put there */
  78649. uInt avail_out; /* remaining free space at next_out */
  78650. uLong total_out; /* total nb of bytes output so far */
  78651. char *msg; /* last error message, NULL if no error */
  78652. struct internal_state FAR *state; /* not visible by applications */
  78653. alloc_func zalloc; /* used to allocate the internal state */
  78654. free_func zfree; /* used to free the internal state */
  78655. voidpf opaque; /* private data object passed to zalloc and zfree */
  78656. int data_type; /* best guess about the data type: binary or text */
  78657. uLong adler; /* adler32 value of the uncompressed data */
  78658. uLong reserved; /* reserved for future use */
  78659. } z_stream;
  78660. typedef z_stream FAR *z_streamp;
  78661. /*
  78662. gzip header information passed to and from zlib routines. See RFC 1952
  78663. for more details on the meanings of these fields.
  78664. */
  78665. typedef struct gz_header_s {
  78666. int text; /* true if compressed data believed to be text */
  78667. uLong time; /* modification time */
  78668. int xflags; /* extra flags (not used when writing a gzip file) */
  78669. int os; /* operating system */
  78670. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78671. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78672. uInt extra_max; /* space at extra (only when reading header) */
  78673. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78674. uInt name_max; /* space at name (only when reading header) */
  78675. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78676. uInt comm_max; /* space at comment (only when reading header) */
  78677. int hcrc; /* true if there was or will be a header crc */
  78678. int done; /* true when done reading gzip header (not used
  78679. when writing a gzip file) */
  78680. } gz_header;
  78681. typedef gz_header FAR *gz_headerp;
  78682. /*
  78683. The application must update next_in and avail_in when avail_in has
  78684. dropped to zero. It must update next_out and avail_out when avail_out
  78685. has dropped to zero. The application must initialize zalloc, zfree and
  78686. opaque before calling the init function. All other fields are set by the
  78687. compression library and must not be updated by the application.
  78688. The opaque value provided by the application will be passed as the first
  78689. parameter for calls of zalloc and zfree. This can be useful for custom
  78690. memory management. The compression library attaches no meaning to the
  78691. opaque value.
  78692. zalloc must return Z_NULL if there is not enough memory for the object.
  78693. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78694. thread safe.
  78695. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78696. exactly 65536 bytes, but will not be required to allocate more than this
  78697. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78698. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78699. have their offset normalized to zero. The default allocation function
  78700. provided by this library ensures this (see zutil.c). To reduce memory
  78701. requirements and avoid any allocation of 64K objects, at the expense of
  78702. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78703. The fields total_in and total_out can be used for statistics or
  78704. progress reports. After compression, total_in holds the total size of
  78705. the uncompressed data and may be saved for use in the decompressor
  78706. (particularly if the decompressor wants to decompress everything in
  78707. a single step).
  78708. */
  78709. /* constants */
  78710. #define Z_NO_FLUSH 0
  78711. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78712. #define Z_SYNC_FLUSH 2
  78713. #define Z_FULL_FLUSH 3
  78714. #define Z_FINISH 4
  78715. #define Z_BLOCK 5
  78716. /* Allowed flush values; see deflate() and inflate() below for details */
  78717. #define Z_OK 0
  78718. #define Z_STREAM_END 1
  78719. #define Z_NEED_DICT 2
  78720. #define Z_ERRNO (-1)
  78721. #define Z_STREAM_ERROR (-2)
  78722. #define Z_DATA_ERROR (-3)
  78723. #define Z_MEM_ERROR (-4)
  78724. #define Z_BUF_ERROR (-5)
  78725. #define Z_VERSION_ERROR (-6)
  78726. /* Return codes for the compression/decompression functions. Negative
  78727. * values are errors, positive values are used for special but normal events.
  78728. */
  78729. #define Z_NO_COMPRESSION 0
  78730. #define Z_BEST_SPEED 1
  78731. #define Z_BEST_COMPRESSION 9
  78732. #define Z_DEFAULT_COMPRESSION (-1)
  78733. /* compression levels */
  78734. #define Z_FILTERED 1
  78735. #define Z_HUFFMAN_ONLY 2
  78736. #define Z_RLE 3
  78737. #define Z_FIXED 4
  78738. #define Z_DEFAULT_STRATEGY 0
  78739. /* compression strategy; see deflateInit2() below for details */
  78740. #define Z_BINARY 0
  78741. #define Z_TEXT 1
  78742. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78743. #define Z_UNKNOWN 2
  78744. /* Possible values of the data_type field (though see inflate()) */
  78745. #define Z_DEFLATED 8
  78746. /* The deflate compression method (the only one supported in this version) */
  78747. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78748. #define zlib_version zlibVersion()
  78749. /* for compatibility with versions < 1.0.2 */
  78750. /* basic functions */
  78751. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78752. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78753. If the first character differs, the library code actually used is
  78754. not compatible with the zlib.h header file used by the application.
  78755. This check is automatically made by deflateInit and inflateInit.
  78756. */
  78757. /*
  78758. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78759. Initializes the internal stream state for compression. The fields
  78760. zalloc, zfree and opaque must be initialized before by the caller.
  78761. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78762. use default allocation functions.
  78763. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78764. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78765. all (the input data is simply copied a block at a time).
  78766. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78767. compression (currently equivalent to level 6).
  78768. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78769. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78770. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78771. with the version assumed by the caller (ZLIB_VERSION).
  78772. msg is set to null if there is no error message. deflateInit does not
  78773. perform any compression: this will be done by deflate().
  78774. */
  78775. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78776. /*
  78777. deflate compresses as much data as possible, and stops when the input
  78778. buffer becomes empty or the output buffer becomes full. It may introduce some
  78779. output latency (reading input without producing any output) except when
  78780. forced to flush.
  78781. The detailed semantics are as follows. deflate performs one or both of the
  78782. following actions:
  78783. - Compress more input starting at next_in and update next_in and avail_in
  78784. accordingly. If not all input can be processed (because there is not
  78785. enough room in the output buffer), next_in and avail_in are updated and
  78786. processing will resume at this point for the next call of deflate().
  78787. - Provide more output starting at next_out and update next_out and avail_out
  78788. accordingly. This action is forced if the parameter flush is non zero.
  78789. Forcing flush frequently degrades the compression ratio, so this parameter
  78790. should be set only when necessary (in interactive applications).
  78791. Some output may be provided even if flush is not set.
  78792. Before the call of deflate(), the application should ensure that at least
  78793. one of the actions is possible, by providing more input and/or consuming
  78794. more output, and updating avail_in or avail_out accordingly; avail_out
  78795. should never be zero before the call. The application can consume the
  78796. compressed output when it wants, for example when the output buffer is full
  78797. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78798. and with zero avail_out, it must be called again after making room in the
  78799. output buffer because there might be more output pending.
  78800. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78801. decide how much data to accumualte before producing output, in order to
  78802. maximize compression.
  78803. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78804. flushed to the output buffer and the output is aligned on a byte boundary, so
  78805. that the decompressor can get all input data available so far. (In particular
  78806. avail_in is zero after the call if enough output space has been provided
  78807. before the call.) Flushing may degrade compression for some compression
  78808. algorithms and so it should be used only when necessary.
  78809. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78810. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78811. restart from this point if previous compressed data has been damaged or if
  78812. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78813. compression.
  78814. If deflate returns with avail_out == 0, this function must be called again
  78815. with the same value of the flush parameter and more output space (updated
  78816. avail_out), until the flush is complete (deflate returns with non-zero
  78817. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78818. avail_out is greater than six to avoid repeated flush markers due to
  78819. avail_out == 0 on return.
  78820. If the parameter flush is set to Z_FINISH, pending input is processed,
  78821. pending output is flushed and deflate returns with Z_STREAM_END if there
  78822. was enough output space; if deflate returns with Z_OK, this function must be
  78823. called again with Z_FINISH and more output space (updated avail_out) but no
  78824. more input data, until it returns with Z_STREAM_END or an error. After
  78825. deflate has returned Z_STREAM_END, the only possible operations on the
  78826. stream are deflateReset or deflateEnd.
  78827. Z_FINISH can be used immediately after deflateInit if all the compression
  78828. is to be done in a single step. In this case, avail_out must be at least
  78829. the value returned by deflateBound (see below). If deflate does not return
  78830. Z_STREAM_END, then it must be called again as described above.
  78831. deflate() sets strm->adler to the adler32 checksum of all input read
  78832. so far (that is, total_in bytes).
  78833. deflate() may update strm->data_type if it can make a good guess about
  78834. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78835. binary. This field is only for information purposes and does not affect
  78836. the compression algorithm in any manner.
  78837. deflate() returns Z_OK if some progress has been made (more input
  78838. processed or more output produced), Z_STREAM_END if all input has been
  78839. consumed and all output has been produced (only when flush is set to
  78840. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78841. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78842. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78843. fatal, and deflate() can be called again with more input and more output
  78844. space to continue compressing.
  78845. */
  78846. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78847. /*
  78848. All dynamically allocated data structures for this stream are freed.
  78849. This function discards any unprocessed input and does not flush any
  78850. pending output.
  78851. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78852. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78853. prematurely (some input or output was discarded). In the error case,
  78854. msg may be set but then points to a static string (which must not be
  78855. deallocated).
  78856. */
  78857. /*
  78858. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78859. Initializes the internal stream state for decompression. The fields
  78860. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78861. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78862. value depends on the compression method), inflateInit determines the
  78863. compression method from the zlib header and allocates all data structures
  78864. accordingly; otherwise the allocation will be deferred to the first call of
  78865. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78866. use default allocation functions.
  78867. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78868. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78869. version assumed by the caller. msg is set to null if there is no error
  78870. message. inflateInit does not perform any decompression apart from reading
  78871. the zlib header if present: this will be done by inflate(). (So next_in and
  78872. avail_in may be modified, but next_out and avail_out are unchanged.)
  78873. */
  78874. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78875. /*
  78876. inflate decompresses as much data as possible, and stops when the input
  78877. buffer becomes empty or the output buffer becomes full. It may introduce
  78878. some output latency (reading input without producing any output) except when
  78879. forced to flush.
  78880. The detailed semantics are as follows. inflate performs one or both of the
  78881. following actions:
  78882. - Decompress more input starting at next_in and update next_in and avail_in
  78883. accordingly. If not all input can be processed (because there is not
  78884. enough room in the output buffer), next_in is updated and processing
  78885. will resume at this point for the next call of inflate().
  78886. - Provide more output starting at next_out and update next_out and avail_out
  78887. accordingly. inflate() provides as much output as possible, until there
  78888. is no more input data or no more space in the output buffer (see below
  78889. about the flush parameter).
  78890. Before the call of inflate(), the application should ensure that at least
  78891. one of the actions is possible, by providing more input and/or consuming
  78892. more output, and updating the next_* and avail_* values accordingly.
  78893. The application can consume the uncompressed output when it wants, for
  78894. example when the output buffer is full (avail_out == 0), or after each
  78895. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78896. must be called again after making room in the output buffer because there
  78897. might be more output pending.
  78898. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78899. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78900. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78901. if and when it gets to the next deflate block boundary. When decoding the
  78902. zlib or gzip format, this will cause inflate() to return immediately after
  78903. the header and before the first block. When doing a raw inflate, inflate()
  78904. will go ahead and process the first block, and will return when it gets to
  78905. the end of that block, or when it runs out of data.
  78906. The Z_BLOCK option assists in appending to or combining deflate streams.
  78907. Also to assist in this, on return inflate() will set strm->data_type to the
  78908. number of unused bits in the last byte taken from strm->next_in, plus 64
  78909. if inflate() is currently decoding the last block in the deflate stream,
  78910. plus 128 if inflate() returned immediately after decoding an end-of-block
  78911. code or decoding the complete header up to just before the first byte of the
  78912. deflate stream. The end-of-block will not be indicated until all of the
  78913. uncompressed data from that block has been written to strm->next_out. The
  78914. number of unused bits may in general be greater than seven, except when
  78915. bit 7 of data_type is set, in which case the number of unused bits will be
  78916. less than eight.
  78917. inflate() should normally be called until it returns Z_STREAM_END or an
  78918. error. However if all decompression is to be performed in a single step
  78919. (a single call of inflate), the parameter flush should be set to
  78920. Z_FINISH. In this case all pending input is processed and all pending
  78921. output is flushed; avail_out must be large enough to hold all the
  78922. uncompressed data. (The size of the uncompressed data may have been saved
  78923. by the compressor for this purpose.) The next operation on this stream must
  78924. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78925. is never required, but can be used to inform inflate that a faster approach
  78926. may be used for the single inflate() call.
  78927. In this implementation, inflate() always flushes as much output as
  78928. possible to the output buffer, and always uses the faster approach on the
  78929. first call. So the only effect of the flush parameter in this implementation
  78930. is on the return value of inflate(), as noted below, or when it returns early
  78931. because Z_BLOCK is used.
  78932. If a preset dictionary is needed after this call (see inflateSetDictionary
  78933. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78934. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78935. strm->adler to the adler32 checksum of all output produced so far (that is,
  78936. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78937. below. At the end of the stream, inflate() checks that its computed adler32
  78938. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78939. only if the checksum is correct.
  78940. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78941. deflate data. The header type is detected automatically. Any information
  78942. contained in the gzip header is not retained, so applications that need that
  78943. information should instead use raw inflate, see inflateInit2() below, or
  78944. inflateBack() and perform their own processing of the gzip header and
  78945. trailer.
  78946. inflate() returns Z_OK if some progress has been made (more input processed
  78947. or more output produced), Z_STREAM_END if the end of the compressed data has
  78948. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78949. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78950. corrupted (input stream not conforming to the zlib format or incorrect check
  78951. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78952. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78953. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78954. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78955. inflate() can be called again with more input and more output space to
  78956. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78957. call inflateSync() to look for a good compression block if a partial recovery
  78958. of the data is desired.
  78959. */
  78960. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78961. /*
  78962. All dynamically allocated data structures for this stream are freed.
  78963. This function discards any unprocessed input and does not flush any
  78964. pending output.
  78965. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78966. was inconsistent. In the error case, msg may be set but then points to a
  78967. static string (which must not be deallocated).
  78968. */
  78969. /* Advanced functions */
  78970. /*
  78971. The following functions are needed only in some special applications.
  78972. */
  78973. /*
  78974. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78975. int level,
  78976. int method,
  78977. int windowBits,
  78978. int memLevel,
  78979. int strategy));
  78980. This is another version of deflateInit with more compression options. The
  78981. fields next_in, zalloc, zfree and opaque must be initialized before by
  78982. the caller.
  78983. The method parameter is the compression method. It must be Z_DEFLATED in
  78984. this version of the library.
  78985. The windowBits parameter is the base two logarithm of the window size
  78986. (the size of the history buffer). It should be in the range 8..15 for this
  78987. version of the library. Larger values of this parameter result in better
  78988. compression at the expense of memory usage. The default value is 15 if
  78989. deflateInit is used instead.
  78990. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78991. determines the window size. deflate() will then generate raw deflate data
  78992. with no zlib header or trailer, and will not compute an adler32 check value.
  78993. windowBits can also be greater than 15 for optional gzip encoding. Add
  78994. 16 to windowBits to write a simple gzip header and trailer around the
  78995. compressed data instead of a zlib wrapper. The gzip header will have no
  78996. file name, no extra data, no comment, no modification time (set to zero),
  78997. no header crc, and the operating system will be set to 255 (unknown). If a
  78998. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78999. The memLevel parameter specifies how much memory should be allocated
  79000. for the internal compression state. memLevel=1 uses minimum memory but
  79001. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  79002. for optimal speed. The default value is 8. See zconf.h for total memory
  79003. usage as a function of windowBits and memLevel.
  79004. The strategy parameter is used to tune the compression algorithm. Use the
  79005. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  79006. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  79007. string match), or Z_RLE to limit match distances to one (run-length
  79008. encoding). Filtered data consists mostly of small values with a somewhat
  79009. random distribution. In this case, the compression algorithm is tuned to
  79010. compress them better. The effect of Z_FILTERED is to force more Huffman
  79011. coding and less string matching; it is somewhat intermediate between
  79012. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  79013. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  79014. parameter only affects the compression ratio but not the correctness of the
  79015. compressed output even if it is not set appropriately. Z_FIXED prevents the
  79016. use of dynamic Huffman codes, allowing for a simpler decoder for special
  79017. applications.
  79018. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79019. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  79020. method). msg is set to null if there is no error message. deflateInit2 does
  79021. not perform any compression: this will be done by deflate().
  79022. */
  79023. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  79024. const Bytef *dictionary,
  79025. uInt dictLength));
  79026. /*
  79027. Initializes the compression dictionary from the given byte sequence
  79028. without producing any compressed output. This function must be called
  79029. immediately after deflateInit, deflateInit2 or deflateReset, before any
  79030. call of deflate. The compressor and decompressor must use exactly the same
  79031. dictionary (see inflateSetDictionary).
  79032. The dictionary should consist of strings (byte sequences) that are likely
  79033. to be encountered later in the data to be compressed, with the most commonly
  79034. used strings preferably put towards the end of the dictionary. Using a
  79035. dictionary is most useful when the data to be compressed is short and can be
  79036. predicted with good accuracy; the data can then be compressed better than
  79037. with the default empty dictionary.
  79038. Depending on the size of the compression data structures selected by
  79039. deflateInit or deflateInit2, a part of the dictionary may in effect be
  79040. discarded, for example if the dictionary is larger than the window size in
  79041. deflate or deflate2. Thus the strings most likely to be useful should be
  79042. put at the end of the dictionary, not at the front. In addition, the
  79043. current implementation of deflate will use at most the window size minus
  79044. 262 bytes of the provided dictionary.
  79045. Upon return of this function, strm->adler is set to the adler32 value
  79046. of the dictionary; the decompressor may later use this value to determine
  79047. which dictionary has been used by the compressor. (The adler32 value
  79048. applies to the whole dictionary even if only a subset of the dictionary is
  79049. actually used by the compressor.) If a raw deflate was requested, then the
  79050. adler32 value is not computed and strm->adler is not set.
  79051. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  79052. parameter is invalid (such as NULL dictionary) or the stream state is
  79053. inconsistent (for example if deflate has already been called for this stream
  79054. or if the compression method is bsort). deflateSetDictionary does not
  79055. perform any compression: this will be done by deflate().
  79056. */
  79057. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  79058. z_streamp source));
  79059. /*
  79060. Sets the destination stream as a complete copy of the source stream.
  79061. This function can be useful when several compression strategies will be
  79062. tried, for example when there are several ways of pre-processing the input
  79063. data with a filter. The streams that will be discarded should then be freed
  79064. by calling deflateEnd. Note that deflateCopy duplicates the internal
  79065. compression state which can be quite large, so this strategy is slow and
  79066. can consume lots of memory.
  79067. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79068. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79069. (such as zalloc being NULL). msg is left unchanged in both source and
  79070. destination.
  79071. */
  79072. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  79073. /*
  79074. This function is equivalent to deflateEnd followed by deflateInit,
  79075. but does not free and reallocate all the internal compression state.
  79076. The stream will keep the same compression level and any other attributes
  79077. that may have been set by deflateInit2.
  79078. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79079. stream state was inconsistent (such as zalloc or state being NULL).
  79080. */
  79081. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  79082. int level,
  79083. int strategy));
  79084. /*
  79085. Dynamically update the compression level and compression strategy. The
  79086. interpretation of level and strategy is as in deflateInit2. This can be
  79087. used to switch between compression and straight copy of the input data, or
  79088. to switch to a different kind of input data requiring a different
  79089. strategy. If the compression level is changed, the input available so far
  79090. is compressed with the old level (and may be flushed); the new level will
  79091. take effect only at the next call of deflate().
  79092. Before the call of deflateParams, the stream state must be set as for
  79093. a call of deflate(), since the currently available input may have to
  79094. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  79095. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  79096. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  79097. if strm->avail_out was zero.
  79098. */
  79099. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  79100. int good_length,
  79101. int max_lazy,
  79102. int nice_length,
  79103. int max_chain));
  79104. /*
  79105. Fine tune deflate's internal compression parameters. This should only be
  79106. used by someone who understands the algorithm used by zlib's deflate for
  79107. searching for the best matching string, and even then only by the most
  79108. fanatic optimizer trying to squeeze out the last compressed bit for their
  79109. specific input data. Read the deflate.c source code for the meaning of the
  79110. max_lazy, good_length, nice_length, and max_chain parameters.
  79111. deflateTune() can be called after deflateInit() or deflateInit2(), and
  79112. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  79113. */
  79114. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  79115. uLong sourceLen));
  79116. /*
  79117. deflateBound() returns an upper bound on the compressed size after
  79118. deflation of sourceLen bytes. It must be called after deflateInit()
  79119. or deflateInit2(). This would be used to allocate an output buffer
  79120. for deflation in a single pass, and so would be called before deflate().
  79121. */
  79122. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  79123. int bits,
  79124. int value));
  79125. /*
  79126. deflatePrime() inserts bits in the deflate output stream. The intent
  79127. is that this function is used to start off the deflate output with the
  79128. bits leftover from a previous deflate stream when appending to it. As such,
  79129. this function can only be used for raw deflate, and must be used before the
  79130. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  79131. less than or equal to 16, and that many of the least significant bits of
  79132. value will be inserted in the output.
  79133. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79134. stream state was inconsistent.
  79135. */
  79136. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79137. gz_headerp head));
  79138. /*
  79139. deflateSetHeader() provides gzip header information for when a gzip
  79140. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79141. after deflateInit2() or deflateReset() and before the first call of
  79142. deflate(). The text, time, os, extra field, name, and comment information
  79143. in the provided gz_header structure are written to the gzip header (xflag is
  79144. ignored -- the extra flags are set according to the compression level). The
  79145. caller must assure that, if not Z_NULL, name and comment are terminated with
  79146. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79147. available there. If hcrc is true, a gzip header crc is included. Note that
  79148. the current versions of the command-line version of gzip (up through version
  79149. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79150. gzip file" and give up.
  79151. If deflateSetHeader is not used, the default gzip header has text false,
  79152. the time set to zero, and os set to 255, with no extra, name, or comment
  79153. fields. The gzip header is returned to the default state by deflateReset().
  79154. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79155. stream state was inconsistent.
  79156. */
  79157. /*
  79158. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79159. int windowBits));
  79160. This is another version of inflateInit with an extra parameter. The
  79161. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79162. before by the caller.
  79163. The windowBits parameter is the base two logarithm of the maximum window
  79164. size (the size of the history buffer). It should be in the range 8..15 for
  79165. this version of the library. The default value is 15 if inflateInit is used
  79166. instead. windowBits must be greater than or equal to the windowBits value
  79167. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79168. deflateInit2() was not used. If a compressed stream with a larger window
  79169. size is given as input, inflate() will return with the error code
  79170. Z_DATA_ERROR instead of trying to allocate a larger window.
  79171. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79172. determines the window size. inflate() will then process raw deflate data,
  79173. not looking for a zlib or gzip header, not generating a check value, and not
  79174. looking for any check values for comparison at the end of the stream. This
  79175. is for use with other formats that use the deflate compressed data format
  79176. such as zip. Those formats provide their own check values. If a custom
  79177. format is developed using the raw deflate format for compressed data, it is
  79178. recommended that a check value such as an adler32 or a crc32 be applied to
  79179. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79180. most applications, the zlib format should be used as is. Note that comments
  79181. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79182. windowBits can also be greater than 15 for optional gzip decoding. Add
  79183. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79184. detection, or add 16 to decode only the gzip format (the zlib format will
  79185. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79186. a crc32 instead of an adler32.
  79187. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79188. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79189. is set to null if there is no error message. inflateInit2 does not perform
  79190. any decompression apart from reading the zlib header if present: this will
  79191. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79192. and avail_out are unchanged.)
  79193. */
  79194. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79195. const Bytef *dictionary,
  79196. uInt dictLength));
  79197. /*
  79198. Initializes the decompression dictionary from the given uncompressed byte
  79199. sequence. This function must be called immediately after a call of inflate,
  79200. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79201. can be determined from the adler32 value returned by that call of inflate.
  79202. The compressor and decompressor must use exactly the same dictionary (see
  79203. deflateSetDictionary). For raw inflate, this function can be called
  79204. immediately after inflateInit2() or inflateReset() and before any call of
  79205. inflate() to set the dictionary. The application must insure that the
  79206. dictionary that was used for compression is provided.
  79207. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79208. parameter is invalid (such as NULL dictionary) or the stream state is
  79209. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79210. expected one (incorrect adler32 value). inflateSetDictionary does not
  79211. perform any decompression: this will be done by subsequent calls of
  79212. inflate().
  79213. */
  79214. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79215. /*
  79216. Skips invalid compressed data until a full flush point (see above the
  79217. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79218. available input is skipped. No output is provided.
  79219. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79220. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79221. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79222. case, the application may save the current current value of total_in which
  79223. indicates where valid compressed data was found. In the error case, the
  79224. application may repeatedly call inflateSync, providing more input each time,
  79225. until success or end of the input data.
  79226. */
  79227. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79228. z_streamp source));
  79229. /*
  79230. Sets the destination stream as a complete copy of the source stream.
  79231. This function can be useful when randomly accessing a large stream. The
  79232. first pass through the stream can periodically record the inflate state,
  79233. allowing restarting inflate at those points when randomly accessing the
  79234. stream.
  79235. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79236. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79237. (such as zalloc being NULL). msg is left unchanged in both source and
  79238. destination.
  79239. */
  79240. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79241. /*
  79242. This function is equivalent to inflateEnd followed by inflateInit,
  79243. but does not free and reallocate all the internal decompression state.
  79244. The stream will keep attributes that may have been set by inflateInit2.
  79245. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79246. stream state was inconsistent (such as zalloc or state being NULL).
  79247. */
  79248. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79249. int bits,
  79250. int value));
  79251. /*
  79252. This function inserts bits in the inflate input stream. The intent is
  79253. that this function is used to start inflating at a bit position in the
  79254. middle of a byte. The provided bits will be used before any bytes are used
  79255. from next_in. This function should only be used with raw inflate, and
  79256. should be used before the first inflate() call after inflateInit2() or
  79257. inflateReset(). bits must be less than or equal to 16, and that many of the
  79258. least significant bits of value will be inserted in the input.
  79259. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79260. stream state was inconsistent.
  79261. */
  79262. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79263. gz_headerp head));
  79264. /*
  79265. inflateGetHeader() requests that gzip header information be stored in the
  79266. provided gz_header structure. inflateGetHeader() may be called after
  79267. inflateInit2() or inflateReset(), and before the first call of inflate().
  79268. As inflate() processes the gzip stream, head->done is zero until the header
  79269. is completed, at which time head->done is set to one. If a zlib stream is
  79270. being decoded, then head->done is set to -1 to indicate that there will be
  79271. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79272. force inflate() to return immediately after header processing is complete
  79273. and before any actual data is decompressed.
  79274. The text, time, xflags, and os fields are filled in with the gzip header
  79275. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79276. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79277. contains the maximum number of bytes to write to extra. Once done is true,
  79278. extra_len contains the actual extra field length, and extra contains the
  79279. extra field, or that field truncated if extra_max is less than extra_len.
  79280. If name is not Z_NULL, then up to name_max characters are written there,
  79281. terminated with a zero unless the length is greater than name_max. If
  79282. comment is not Z_NULL, then up to comm_max characters are written there,
  79283. terminated with a zero unless the length is greater than comm_max. When
  79284. any of extra, name, or comment are not Z_NULL and the respective field is
  79285. not present in the header, then that field is set to Z_NULL to signal its
  79286. absence. This allows the use of deflateSetHeader() with the returned
  79287. structure to duplicate the header. However if those fields are set to
  79288. allocated memory, then the application will need to save those pointers
  79289. elsewhere so that they can be eventually freed.
  79290. If inflateGetHeader is not used, then the header information is simply
  79291. discarded. The header is always checked for validity, including the header
  79292. CRC if present. inflateReset() will reset the process to discard the header
  79293. information. The application would need to call inflateGetHeader() again to
  79294. retrieve the header from the next gzip stream.
  79295. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79296. stream state was inconsistent.
  79297. */
  79298. /*
  79299. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79300. unsigned char FAR *window));
  79301. Initialize the internal stream state for decompression using inflateBack()
  79302. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79303. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79304. derived memory allocation routines are used. windowBits is the base two
  79305. logarithm of the window size, in the range 8..15. window is a caller
  79306. supplied buffer of that size. Except for special applications where it is
  79307. assured that deflate was used with small window sizes, windowBits must be 15
  79308. and a 32K byte window must be supplied to be able to decompress general
  79309. deflate streams.
  79310. See inflateBack() for the usage of these routines.
  79311. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79312. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79313. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79314. match the version of the header file.
  79315. */
  79316. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79317. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79318. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79319. in_func in, void FAR *in_desc,
  79320. out_func out, void FAR *out_desc));
  79321. /*
  79322. inflateBack() does a raw inflate with a single call using a call-back
  79323. interface for input and output. This is more efficient than inflate() for
  79324. file i/o applications in that it avoids copying between the output and the
  79325. sliding window by simply making the window itself the output buffer. This
  79326. function trusts the application to not change the output buffer passed by
  79327. the output function, at least until inflateBack() returns.
  79328. inflateBackInit() must be called first to allocate the internal state
  79329. and to initialize the state with the user-provided window buffer.
  79330. inflateBack() may then be used multiple times to inflate a complete, raw
  79331. deflate stream with each call. inflateBackEnd() is then called to free
  79332. the allocated state.
  79333. A raw deflate stream is one with no zlib or gzip header or trailer.
  79334. This routine would normally be used in a utility that reads zip or gzip
  79335. files and writes out uncompressed files. The utility would decode the
  79336. header and process the trailer on its own, hence this routine expects
  79337. only the raw deflate stream to decompress. This is different from the
  79338. normal behavior of inflate(), which expects either a zlib or gzip header and
  79339. trailer around the deflate stream.
  79340. inflateBack() uses two subroutines supplied by the caller that are then
  79341. called by inflateBack() for input and output. inflateBack() calls those
  79342. routines until it reads a complete deflate stream and writes out all of the
  79343. uncompressed data, or until it encounters an error. The function's
  79344. parameters and return types are defined above in the in_func and out_func
  79345. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79346. number of bytes of provided input, and a pointer to that input in buf. If
  79347. there is no input available, in() must return zero--buf is ignored in that
  79348. case--and inflateBack() will return a buffer error. inflateBack() will call
  79349. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79350. should return zero on success, or non-zero on failure. If out() returns
  79351. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79352. are permitted to change the contents of the window provided to
  79353. inflateBackInit(), which is also the buffer that out() uses to write from.
  79354. The length written by out() will be at most the window size. Any non-zero
  79355. amount of input may be provided by in().
  79356. For convenience, inflateBack() can be provided input on the first call by
  79357. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79358. in() will be called. Therefore strm->next_in must be initialized before
  79359. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79360. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79361. must also be initialized, and then if strm->avail_in is not zero, input will
  79362. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79363. The in_desc and out_desc parameters of inflateBack() is passed as the
  79364. first parameter of in() and out() respectively when they are called. These
  79365. descriptors can be optionally used to pass any information that the caller-
  79366. supplied in() and out() functions need to do their job.
  79367. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79368. pass back any unused input that was provided by the last in() call. The
  79369. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79370. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79371. error in the deflate stream (in which case strm->msg is set to indicate the
  79372. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79373. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79374. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79375. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79376. out() returning non-zero. (in() will always be called before out(), so
  79377. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79378. that inflateBack() cannot return Z_OK.
  79379. */
  79380. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79381. /*
  79382. All memory allocated by inflateBackInit() is freed.
  79383. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79384. state was inconsistent.
  79385. */
  79386. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79387. /* Return flags indicating compile-time options.
  79388. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79389. 1.0: size of uInt
  79390. 3.2: size of uLong
  79391. 5.4: size of voidpf (pointer)
  79392. 7.6: size of z_off_t
  79393. Compiler, assembler, and debug options:
  79394. 8: DEBUG
  79395. 9: ASMV or ASMINF -- use ASM code
  79396. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79397. 11: 0 (reserved)
  79398. One-time table building (smaller code, but not thread-safe if true):
  79399. 12: BUILDFIXED -- build static block decoding tables when needed
  79400. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79401. 14,15: 0 (reserved)
  79402. Library content (indicates missing functionality):
  79403. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79404. deflate code when not needed)
  79405. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79406. and decode gzip streams (to avoid linking crc code)
  79407. 18-19: 0 (reserved)
  79408. Operation variations (changes in library functionality):
  79409. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79410. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79411. 22,23: 0 (reserved)
  79412. The sprintf variant used by gzprintf (zero is best):
  79413. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79414. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79415. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79416. Remainder:
  79417. 27-31: 0 (reserved)
  79418. */
  79419. /* utility functions */
  79420. /*
  79421. The following utility functions are implemented on top of the
  79422. basic stream-oriented functions. To simplify the interface, some
  79423. default options are assumed (compression level and memory usage,
  79424. standard memory allocation functions). The source code of these
  79425. utility functions can easily be modified if you need special options.
  79426. */
  79427. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79428. const Bytef *source, uLong sourceLen));
  79429. /*
  79430. Compresses the source buffer into the destination buffer. sourceLen is
  79431. the byte length of the source buffer. Upon entry, destLen is the total
  79432. size of the destination buffer, which must be at least the value returned
  79433. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79434. compressed buffer.
  79435. This function can be used to compress a whole file at once if the
  79436. input file is mmap'ed.
  79437. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79438. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79439. buffer.
  79440. */
  79441. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79442. const Bytef *source, uLong sourceLen,
  79443. int level));
  79444. /*
  79445. Compresses the source buffer into the destination buffer. The level
  79446. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79447. length of the source buffer. Upon entry, destLen is the total size of the
  79448. destination buffer, which must be at least the value returned by
  79449. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79450. compressed buffer.
  79451. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79452. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79453. Z_STREAM_ERROR if the level parameter is invalid.
  79454. */
  79455. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79456. /*
  79457. compressBound() returns an upper bound on the compressed size after
  79458. compress() or compress2() on sourceLen bytes. It would be used before
  79459. a compress() or compress2() call to allocate the destination buffer.
  79460. */
  79461. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79462. const Bytef *source, uLong sourceLen));
  79463. /*
  79464. Decompresses the source buffer into the destination buffer. sourceLen is
  79465. the byte length of the source buffer. Upon entry, destLen is the total
  79466. size of the destination buffer, which must be large enough to hold the
  79467. entire uncompressed data. (The size of the uncompressed data must have
  79468. been saved previously by the compressor and transmitted to the decompressor
  79469. by some mechanism outside the scope of this compression library.)
  79470. Upon exit, destLen is the actual size of the compressed buffer.
  79471. This function can be used to decompress a whole file at once if the
  79472. input file is mmap'ed.
  79473. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79474. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79475. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79476. */
  79477. typedef voidp gzFile;
  79478. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79479. /*
  79480. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79481. is as in fopen ("rb" or "wb") but can also include a compression level
  79482. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79483. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79484. as in "wb1R". (See the description of deflateInit2 for more information
  79485. about the strategy parameter.)
  79486. gzopen can be used to read a file which is not in gzip format; in this
  79487. case gzread will directly read from the file without decompression.
  79488. gzopen returns NULL if the file could not be opened or if there was
  79489. insufficient memory to allocate the (de)compression state; errno
  79490. can be checked to distinguish the two cases (if errno is zero, the
  79491. zlib error is Z_MEM_ERROR). */
  79492. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79493. /*
  79494. gzdopen() associates a gzFile with the file descriptor fd. File
  79495. descriptors are obtained from calls like open, dup, creat, pipe or
  79496. fileno (in the file has been previously opened with fopen).
  79497. The mode parameter is as in gzopen.
  79498. The next call of gzclose on the returned gzFile will also close the
  79499. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79500. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79501. gzdopen returns NULL if there was insufficient memory to allocate
  79502. the (de)compression state.
  79503. */
  79504. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79505. /*
  79506. Dynamically update the compression level or strategy. See the description
  79507. of deflateInit2 for the meaning of these parameters.
  79508. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79509. opened for writing.
  79510. */
  79511. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79512. /*
  79513. Reads the given number of uncompressed bytes from the compressed file.
  79514. If the input file was not in gzip format, gzread copies the given number
  79515. of bytes into the buffer.
  79516. gzread returns the number of uncompressed bytes actually read (0 for
  79517. end of file, -1 for error). */
  79518. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79519. voidpc buf, unsigned len));
  79520. /*
  79521. Writes the given number of uncompressed bytes into the compressed file.
  79522. gzwrite returns the number of uncompressed bytes actually written
  79523. (0 in case of error).
  79524. */
  79525. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79526. /*
  79527. Converts, formats, and writes the args to the compressed file under
  79528. control of the format string, as in fprintf. gzprintf returns the number of
  79529. uncompressed bytes actually written (0 in case of error). The number of
  79530. uncompressed bytes written is limited to 4095. The caller should assure that
  79531. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79532. return an error (0) with nothing written. In this case, there may also be a
  79533. buffer overflow with unpredictable consequences, which is possible only if
  79534. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79535. because the secure snprintf() or vsnprintf() functions were not available.
  79536. */
  79537. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79538. /*
  79539. Writes the given null-terminated string to the compressed file, excluding
  79540. the terminating null character.
  79541. gzputs returns the number of characters written, or -1 in case of error.
  79542. */
  79543. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79544. /*
  79545. Reads bytes from the compressed file until len-1 characters are read, or
  79546. a newline character is read and transferred to buf, or an end-of-file
  79547. condition is encountered. The string is then terminated with a null
  79548. character.
  79549. gzgets returns buf, or Z_NULL in case of error.
  79550. */
  79551. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79552. /*
  79553. Writes c, converted to an unsigned char, into the compressed file.
  79554. gzputc returns the value that was written, or -1 in case of error.
  79555. */
  79556. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79557. /*
  79558. Reads one byte from the compressed file. gzgetc returns this byte
  79559. or -1 in case of end of file or error.
  79560. */
  79561. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79562. /*
  79563. Push one character back onto the stream to be read again later.
  79564. Only one character of push-back is allowed. gzungetc() returns the
  79565. character pushed, or -1 on failure. gzungetc() will fail if a
  79566. character has been pushed but not read yet, or if c is -1. The pushed
  79567. character will be discarded if the stream is repositioned with gzseek()
  79568. or gzrewind().
  79569. */
  79570. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79571. /*
  79572. Flushes all pending output into the compressed file. The parameter
  79573. flush is as in the deflate() function. The return value is the zlib
  79574. error number (see function gzerror below). gzflush returns Z_OK if
  79575. the flush parameter is Z_FINISH and all output could be flushed.
  79576. gzflush should be called only when strictly necessary because it can
  79577. degrade compression.
  79578. */
  79579. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79580. z_off_t offset, int whence));
  79581. /*
  79582. Sets the starting position for the next gzread or gzwrite on the
  79583. given compressed file. The offset represents a number of bytes in the
  79584. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79585. the value SEEK_END is not supported.
  79586. If the file is opened for reading, this function is emulated but can be
  79587. extremely slow. If the file is opened for writing, only forward seeks are
  79588. supported; gzseek then compresses a sequence of zeroes up to the new
  79589. starting position.
  79590. gzseek returns the resulting offset location as measured in bytes from
  79591. the beginning of the uncompressed stream, or -1 in case of error, in
  79592. particular if the file is opened for writing and the new starting position
  79593. would be before the current position.
  79594. */
  79595. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79596. /*
  79597. Rewinds the given file. This function is supported only for reading.
  79598. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79599. */
  79600. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79601. /*
  79602. Returns the starting position for the next gzread or gzwrite on the
  79603. given compressed file. This position represents a number of bytes in the
  79604. uncompressed data stream.
  79605. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79606. */
  79607. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79608. /*
  79609. Returns 1 when EOF has previously been detected reading the given
  79610. input stream, otherwise zero.
  79611. */
  79612. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79613. /*
  79614. Returns 1 if file is being read directly without decompression, otherwise
  79615. zero.
  79616. */
  79617. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79618. /*
  79619. Flushes all pending output if necessary, closes the compressed file
  79620. and deallocates all the (de)compression state. The return value is the zlib
  79621. error number (see function gzerror below).
  79622. */
  79623. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79624. /*
  79625. Returns the error message for the last error which occurred on the
  79626. given compressed file. errnum is set to zlib error number. If an
  79627. error occurred in the file system and not in the compression library,
  79628. errnum is set to Z_ERRNO and the application may consult errno
  79629. to get the exact error code.
  79630. */
  79631. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79632. /*
  79633. Clears the error and end-of-file flags for file. This is analogous to the
  79634. clearerr() function in stdio. This is useful for continuing to read a gzip
  79635. file that is being written concurrently.
  79636. */
  79637. /* checksum functions */
  79638. /*
  79639. These functions are not related to compression but are exported
  79640. anyway because they might be useful in applications using the
  79641. compression library.
  79642. */
  79643. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79644. /*
  79645. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79646. return the updated checksum. If buf is NULL, this function returns
  79647. the required initial value for the checksum.
  79648. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79649. much faster. Usage example:
  79650. uLong adler = adler32(0L, Z_NULL, 0);
  79651. while (read_buffer(buffer, length) != EOF) {
  79652. adler = adler32(adler, buffer, length);
  79653. }
  79654. if (adler != original_adler) error();
  79655. */
  79656. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79657. z_off_t len2));
  79658. /*
  79659. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79660. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79661. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79662. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79663. */
  79664. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79665. /*
  79666. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79667. updated CRC-32. If buf is NULL, this function returns the required initial
  79668. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79669. performed within this function so it shouldn't be done by the application.
  79670. Usage example:
  79671. uLong crc = crc32(0L, Z_NULL, 0);
  79672. while (read_buffer(buffer, length) != EOF) {
  79673. crc = crc32(crc, buffer, length);
  79674. }
  79675. if (crc != original_crc) error();
  79676. */
  79677. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79678. /*
  79679. Combine two CRC-32 check values into one. For two sequences of bytes,
  79680. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79681. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79682. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79683. len2.
  79684. */
  79685. /* various hacks, don't look :) */
  79686. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79687. * and the compiler's view of z_stream:
  79688. */
  79689. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79690. const char *version, int stream_size));
  79691. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79692. const char *version, int stream_size));
  79693. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79694. int windowBits, int memLevel,
  79695. int strategy, const char *version,
  79696. int stream_size));
  79697. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79698. const char *version, int stream_size));
  79699. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79700. unsigned char FAR *window,
  79701. const char *version,
  79702. int stream_size));
  79703. #define deflateInit(strm, level) \
  79704. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79705. #define inflateInit(strm) \
  79706. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79707. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79708. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79709. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79710. #define inflateInit2(strm, windowBits) \
  79711. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79712. #define inflateBackInit(strm, windowBits, window) \
  79713. inflateBackInit_((strm), (windowBits), (window), \
  79714. ZLIB_VERSION, sizeof(z_stream))
  79715. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79716. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79717. #endif
  79718. ZEXTERN const char * ZEXPORT zError OF((int));
  79719. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79720. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79721. #ifdef __cplusplus
  79722. //}
  79723. #endif
  79724. #endif /* ZLIB_H */
  79725. /*** End of inlined file: zlib.h ***/
  79726. #undef OS_CODE
  79727. #else
  79728. #include <zlib.h>
  79729. #endif
  79730. }
  79731. BEGIN_JUCE_NAMESPACE
  79732. // internal helper object that holds the zlib structures so they don't have to be
  79733. // included publicly.
  79734. class GZIPCompressorHelper
  79735. {
  79736. public:
  79737. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79738. : data (0),
  79739. dataSize (0),
  79740. compLevel (compressionLevel),
  79741. strategy (0),
  79742. setParams (true),
  79743. streamIsValid (false),
  79744. finished (false),
  79745. shouldFinish (false)
  79746. {
  79747. using namespace zlibNamespace;
  79748. zerostruct (stream);
  79749. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79750. nowrap ? -MAX_WBITS : MAX_WBITS,
  79751. 8, strategy) == Z_OK);
  79752. }
  79753. ~GZIPCompressorHelper()
  79754. {
  79755. using namespace zlibNamespace;
  79756. if (streamIsValid)
  79757. deflateEnd (&stream);
  79758. }
  79759. bool needsInput() const throw()
  79760. {
  79761. return dataSize <= 0;
  79762. }
  79763. void setInput (const uint8* const newData, const int size) throw()
  79764. {
  79765. data = newData;
  79766. dataSize = size;
  79767. }
  79768. int doNextBlock (uint8* const dest, const int destSize) throw()
  79769. {
  79770. using namespace zlibNamespace;
  79771. if (streamIsValid)
  79772. {
  79773. stream.next_in = const_cast <uint8*> (data);
  79774. stream.next_out = dest;
  79775. stream.avail_in = dataSize;
  79776. stream.avail_out = destSize;
  79777. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79778. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79779. setParams = false;
  79780. switch (result)
  79781. {
  79782. case Z_STREAM_END:
  79783. finished = true;
  79784. // Deliberate fall-through..
  79785. case Z_OK:
  79786. data += dataSize - stream.avail_in;
  79787. dataSize = stream.avail_in;
  79788. return destSize - stream.avail_out;
  79789. default:
  79790. break;
  79791. }
  79792. }
  79793. return 0;
  79794. }
  79795. private:
  79796. zlibNamespace::z_stream stream;
  79797. const uint8* data;
  79798. int dataSize, compLevel, strategy;
  79799. bool setParams, streamIsValid;
  79800. public:
  79801. bool finished, shouldFinish;
  79802. };
  79803. const int gzipCompBufferSize = 32768;
  79804. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79805. int compressionLevel,
  79806. const bool deleteDestStream,
  79807. const bool noWrap)
  79808. : destStream (destStream_),
  79809. streamToDelete (deleteDestStream ? destStream_ : 0),
  79810. buffer (gzipCompBufferSize)
  79811. {
  79812. if (compressionLevel < 1 || compressionLevel > 9)
  79813. compressionLevel = -1;
  79814. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79815. }
  79816. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79817. {
  79818. flush();
  79819. }
  79820. void GZIPCompressorOutputStream::flush()
  79821. {
  79822. if (! helper->finished)
  79823. {
  79824. helper->shouldFinish = true;
  79825. while (! helper->finished)
  79826. doNextBlock();
  79827. }
  79828. destStream->flush();
  79829. }
  79830. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79831. {
  79832. if (! helper->finished)
  79833. {
  79834. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79835. while (! helper->needsInput())
  79836. {
  79837. if (! doNextBlock())
  79838. return false;
  79839. }
  79840. }
  79841. return true;
  79842. }
  79843. bool GZIPCompressorOutputStream::doNextBlock()
  79844. {
  79845. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79846. if (len > 0)
  79847. return destStream->write (buffer, len);
  79848. else
  79849. return true;
  79850. }
  79851. int64 GZIPCompressorOutputStream::getPosition()
  79852. {
  79853. return destStream->getPosition();
  79854. }
  79855. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79856. {
  79857. jassertfalse; // can't do it!
  79858. return false;
  79859. }
  79860. END_JUCE_NAMESPACE
  79861. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79862. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79863. #if JUCE_MSVC
  79864. #pragma warning (push)
  79865. #pragma warning (disable: 4309 4305)
  79866. #endif
  79867. namespace zlibNamespace
  79868. {
  79869. #if JUCE_INCLUDE_ZLIB_CODE
  79870. #undef OS_CODE
  79871. #undef fdopen
  79872. #define ZLIB_INTERNAL
  79873. #define NO_DUMMY_DECL
  79874. /*** Start of inlined file: adler32.c ***/
  79875. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79876. #define ZLIB_INTERNAL
  79877. #define BASE 65521UL /* largest prime smaller than 65536 */
  79878. #define NMAX 5552
  79879. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79880. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79881. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79882. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79883. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79884. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79885. /* use NO_DIVIDE if your processor does not do division in hardware */
  79886. #ifdef NO_DIVIDE
  79887. # define MOD(a) \
  79888. do { \
  79889. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79890. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79891. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79892. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79893. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79894. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79895. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79896. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79897. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79898. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79899. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79900. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79901. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79902. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79903. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79904. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79905. if (a >= BASE) a -= BASE; \
  79906. } while (0)
  79907. # define MOD4(a) \
  79908. do { \
  79909. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79910. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79911. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79912. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79913. if (a >= BASE) a -= BASE; \
  79914. } while (0)
  79915. #else
  79916. # define MOD(a) a %= BASE
  79917. # define MOD4(a) a %= BASE
  79918. #endif
  79919. /* ========================================================================= */
  79920. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79921. {
  79922. unsigned long sum2;
  79923. unsigned n;
  79924. /* split Adler-32 into component sums */
  79925. sum2 = (adler >> 16) & 0xffff;
  79926. adler &= 0xffff;
  79927. /* in case user likes doing a byte at a time, keep it fast */
  79928. if (len == 1) {
  79929. adler += buf[0];
  79930. if (adler >= BASE)
  79931. adler -= BASE;
  79932. sum2 += adler;
  79933. if (sum2 >= BASE)
  79934. sum2 -= BASE;
  79935. return adler | (sum2 << 16);
  79936. }
  79937. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79938. if (buf == Z_NULL)
  79939. return 1L;
  79940. /* in case short lengths are provided, keep it somewhat fast */
  79941. if (len < 16) {
  79942. while (len--) {
  79943. adler += *buf++;
  79944. sum2 += adler;
  79945. }
  79946. if (adler >= BASE)
  79947. adler -= BASE;
  79948. MOD4(sum2); /* only added so many BASE's */
  79949. return adler | (sum2 << 16);
  79950. }
  79951. /* do length NMAX blocks -- requires just one modulo operation */
  79952. while (len >= NMAX) {
  79953. len -= NMAX;
  79954. n = NMAX / 16; /* NMAX is divisible by 16 */
  79955. do {
  79956. DO16(buf); /* 16 sums unrolled */
  79957. buf += 16;
  79958. } while (--n);
  79959. MOD(adler);
  79960. MOD(sum2);
  79961. }
  79962. /* do remaining bytes (less than NMAX, still just one modulo) */
  79963. if (len) { /* avoid modulos if none remaining */
  79964. while (len >= 16) {
  79965. len -= 16;
  79966. DO16(buf);
  79967. buf += 16;
  79968. }
  79969. while (len--) {
  79970. adler += *buf++;
  79971. sum2 += adler;
  79972. }
  79973. MOD(adler);
  79974. MOD(sum2);
  79975. }
  79976. /* return recombined sums */
  79977. return adler | (sum2 << 16);
  79978. }
  79979. /* ========================================================================= */
  79980. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79981. {
  79982. unsigned long sum1;
  79983. unsigned long sum2;
  79984. unsigned rem;
  79985. /* the derivation of this formula is left as an exercise for the reader */
  79986. rem = (unsigned)(len2 % BASE);
  79987. sum1 = adler1 & 0xffff;
  79988. sum2 = rem * sum1;
  79989. MOD(sum2);
  79990. sum1 += (adler2 & 0xffff) + BASE - 1;
  79991. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79992. if (sum1 > BASE) sum1 -= BASE;
  79993. if (sum1 > BASE) sum1 -= BASE;
  79994. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79995. if (sum2 > BASE) sum2 -= BASE;
  79996. return sum1 | (sum2 << 16);
  79997. }
  79998. /*** End of inlined file: adler32.c ***/
  79999. /*** Start of inlined file: compress.c ***/
  80000. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80001. #define ZLIB_INTERNAL
  80002. /* ===========================================================================
  80003. Compresses the source buffer into the destination buffer. The level
  80004. parameter has the same meaning as in deflateInit. sourceLen is the byte
  80005. length of the source buffer. Upon entry, destLen is the total size of the
  80006. destination buffer, which must be at least 0.1% larger than sourceLen plus
  80007. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  80008. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  80009. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  80010. Z_STREAM_ERROR if the level parameter is invalid.
  80011. */
  80012. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  80013. uLong sourceLen, int level)
  80014. {
  80015. z_stream stream;
  80016. int err;
  80017. stream.next_in = (Bytef*)source;
  80018. stream.avail_in = (uInt)sourceLen;
  80019. #ifdef MAXSEG_64K
  80020. /* Check for source > 64K on 16-bit machine: */
  80021. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  80022. #endif
  80023. stream.next_out = dest;
  80024. stream.avail_out = (uInt)*destLen;
  80025. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  80026. stream.zalloc = (alloc_func)0;
  80027. stream.zfree = (free_func)0;
  80028. stream.opaque = (voidpf)0;
  80029. err = deflateInit(&stream, level);
  80030. if (err != Z_OK) return err;
  80031. err = deflate(&stream, Z_FINISH);
  80032. if (err != Z_STREAM_END) {
  80033. deflateEnd(&stream);
  80034. return err == Z_OK ? Z_BUF_ERROR : err;
  80035. }
  80036. *destLen = stream.total_out;
  80037. err = deflateEnd(&stream);
  80038. return err;
  80039. }
  80040. /* ===========================================================================
  80041. */
  80042. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  80043. {
  80044. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  80045. }
  80046. /* ===========================================================================
  80047. If the default memLevel or windowBits for deflateInit() is changed, then
  80048. this function needs to be updated.
  80049. */
  80050. uLong ZEXPORT compressBound (uLong sourceLen)
  80051. {
  80052. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  80053. }
  80054. /*** End of inlined file: compress.c ***/
  80055. #undef DO1
  80056. #undef DO8
  80057. /*** Start of inlined file: crc32.c ***/
  80058. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80059. /*
  80060. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  80061. protection on the static variables used to control the first-use generation
  80062. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  80063. first call get_crc_table() to initialize the tables before allowing more than
  80064. one thread to use crc32().
  80065. */
  80066. #ifdef MAKECRCH
  80067. # include <stdio.h>
  80068. # ifndef DYNAMIC_CRC_TABLE
  80069. # define DYNAMIC_CRC_TABLE
  80070. # endif /* !DYNAMIC_CRC_TABLE */
  80071. #endif /* MAKECRCH */
  80072. /*** Start of inlined file: zutil.h ***/
  80073. /* WARNING: this file should *not* be used by applications. It is
  80074. part of the implementation of the compression library and is
  80075. subject to change. Applications should only use zlib.h.
  80076. */
  80077. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80078. #ifndef ZUTIL_H
  80079. #define ZUTIL_H
  80080. #define ZLIB_INTERNAL
  80081. #ifdef STDC
  80082. # ifndef _WIN32_WCE
  80083. # include <stddef.h>
  80084. # endif
  80085. # include <string.h>
  80086. # include <stdlib.h>
  80087. #endif
  80088. #ifdef NO_ERRNO_H
  80089. # ifdef _WIN32_WCE
  80090. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80091. * errno. We define it as a global variable to simplify porting.
  80092. * Its value is always 0 and should not be used. We rename it to
  80093. * avoid conflict with other libraries that use the same workaround.
  80094. */
  80095. # define errno z_errno
  80096. # endif
  80097. extern int errno;
  80098. #else
  80099. # ifndef _WIN32_WCE
  80100. # include <errno.h>
  80101. # endif
  80102. #endif
  80103. #ifndef local
  80104. # define local static
  80105. #endif
  80106. /* compile with -Dlocal if your debugger can't find static symbols */
  80107. typedef unsigned char uch;
  80108. typedef uch FAR uchf;
  80109. typedef unsigned short ush;
  80110. typedef ush FAR ushf;
  80111. typedef unsigned long ulg;
  80112. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  80113. /* (size given to avoid silly warnings with Visual C++) */
  80114. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80115. #define ERR_RETURN(strm,err) \
  80116. return (strm->msg = (char*)ERR_MSG(err), (err))
  80117. /* To be used only when the state is known to be valid */
  80118. /* common constants */
  80119. #ifndef DEF_WBITS
  80120. # define DEF_WBITS MAX_WBITS
  80121. #endif
  80122. /* default windowBits for decompression. MAX_WBITS is for compression only */
  80123. #if MAX_MEM_LEVEL >= 8
  80124. # define DEF_MEM_LEVEL 8
  80125. #else
  80126. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  80127. #endif
  80128. /* default memLevel */
  80129. #define STORED_BLOCK 0
  80130. #define STATIC_TREES 1
  80131. #define DYN_TREES 2
  80132. /* The three kinds of block type */
  80133. #define MIN_MATCH 3
  80134. #define MAX_MATCH 258
  80135. /* The minimum and maximum match lengths */
  80136. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80137. /* target dependencies */
  80138. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80139. # define OS_CODE 0x00
  80140. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80141. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80142. /* Allow compilation with ANSI keywords only enabled */
  80143. void _Cdecl farfree( void *block );
  80144. void *_Cdecl farmalloc( unsigned long nbytes );
  80145. # else
  80146. # include <alloc.h>
  80147. # endif
  80148. # else /* MSC or DJGPP */
  80149. # include <malloc.h>
  80150. # endif
  80151. #endif
  80152. #ifdef AMIGA
  80153. # define OS_CODE 0x01
  80154. #endif
  80155. #if defined(VAXC) || defined(VMS)
  80156. # define OS_CODE 0x02
  80157. # define F_OPEN(name, mode) \
  80158. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80159. #endif
  80160. #if defined(ATARI) || defined(atarist)
  80161. # define OS_CODE 0x05
  80162. #endif
  80163. #ifdef OS2
  80164. # define OS_CODE 0x06
  80165. # ifdef M_I86
  80166. #include <malloc.h>
  80167. # endif
  80168. #endif
  80169. #if defined(MACOS) || TARGET_OS_MAC
  80170. # define OS_CODE 0x07
  80171. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80172. # include <unix.h> /* for fdopen */
  80173. # else
  80174. # ifndef fdopen
  80175. # define fdopen(fd,mode) NULL /* No fdopen() */
  80176. # endif
  80177. # endif
  80178. #endif
  80179. #ifdef TOPS20
  80180. # define OS_CODE 0x0a
  80181. #endif
  80182. #ifdef WIN32
  80183. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80184. # define OS_CODE 0x0b
  80185. # endif
  80186. #endif
  80187. #ifdef __50SERIES /* Prime/PRIMOS */
  80188. # define OS_CODE 0x0f
  80189. #endif
  80190. #if defined(_BEOS_) || defined(RISCOS)
  80191. # define fdopen(fd,mode) NULL /* No fdopen() */
  80192. #endif
  80193. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80194. # if defined(_WIN32_WCE)
  80195. # define fdopen(fd,mode) NULL /* No fdopen() */
  80196. # ifndef _PTRDIFF_T_DEFINED
  80197. typedef int ptrdiff_t;
  80198. # define _PTRDIFF_T_DEFINED
  80199. # endif
  80200. # else
  80201. # define fdopen(fd,type) _fdopen(fd,type)
  80202. # endif
  80203. #endif
  80204. /* common defaults */
  80205. #ifndef OS_CODE
  80206. # define OS_CODE 0x03 /* assume Unix */
  80207. #endif
  80208. #ifndef F_OPEN
  80209. # define F_OPEN(name, mode) fopen((name), (mode))
  80210. #endif
  80211. /* functions */
  80212. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80213. # ifndef HAVE_VSNPRINTF
  80214. # define HAVE_VSNPRINTF
  80215. # endif
  80216. #endif
  80217. #if defined(__CYGWIN__)
  80218. # ifndef HAVE_VSNPRINTF
  80219. # define HAVE_VSNPRINTF
  80220. # endif
  80221. #endif
  80222. #ifndef HAVE_VSNPRINTF
  80223. # ifdef MSDOS
  80224. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80225. but for now we just assume it doesn't. */
  80226. # define NO_vsnprintf
  80227. # endif
  80228. # ifdef __TURBOC__
  80229. # define NO_vsnprintf
  80230. # endif
  80231. # ifdef WIN32
  80232. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80233. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80234. # define vsnprintf _vsnprintf
  80235. # endif
  80236. # endif
  80237. # ifdef __SASC
  80238. # define NO_vsnprintf
  80239. # endif
  80240. #endif
  80241. #ifdef VMS
  80242. # define NO_vsnprintf
  80243. #endif
  80244. #if defined(pyr)
  80245. # define NO_MEMCPY
  80246. #endif
  80247. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80248. /* Use our own functions for small and medium model with MSC <= 5.0.
  80249. * You may have to use the same strategy for Borland C (untested).
  80250. * The __SC__ check is for Symantec.
  80251. */
  80252. # define NO_MEMCPY
  80253. #endif
  80254. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80255. # define HAVE_MEMCPY
  80256. #endif
  80257. #ifdef HAVE_MEMCPY
  80258. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80259. # define zmemcpy _fmemcpy
  80260. # define zmemcmp _fmemcmp
  80261. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80262. # else
  80263. # define zmemcpy memcpy
  80264. # define zmemcmp memcmp
  80265. # define zmemzero(dest, len) memset(dest, 0, len)
  80266. # endif
  80267. #else
  80268. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80269. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80270. extern void zmemzero OF((Bytef* dest, uInt len));
  80271. #endif
  80272. /* Diagnostic functions */
  80273. #ifdef DEBUG
  80274. # include <stdio.h>
  80275. extern int z_verbose;
  80276. extern void z_error OF((const char *m));
  80277. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80278. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80279. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80280. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80281. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80282. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80283. #else
  80284. # define Assert(cond,msg)
  80285. # define Trace(x)
  80286. # define Tracev(x)
  80287. # define Tracevv(x)
  80288. # define Tracec(c,x)
  80289. # define Tracecv(c,x)
  80290. #endif
  80291. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80292. void zcfree OF((voidpf opaque, voidpf ptr));
  80293. #define ZALLOC(strm, items, size) \
  80294. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80295. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80296. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80297. #endif /* ZUTIL_H */
  80298. /*** End of inlined file: zutil.h ***/
  80299. /* for STDC and FAR definitions */
  80300. #define local static
  80301. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80302. #ifndef NOBYFOUR
  80303. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80304. # include <limits.h>
  80305. # define BYFOUR
  80306. # if (UINT_MAX == 0xffffffffUL)
  80307. typedef unsigned int u4;
  80308. # else
  80309. # if (ULONG_MAX == 0xffffffffUL)
  80310. typedef unsigned long u4;
  80311. # else
  80312. # if (USHRT_MAX == 0xffffffffUL)
  80313. typedef unsigned short u4;
  80314. # else
  80315. # undef BYFOUR /* can't find a four-byte integer type! */
  80316. # endif
  80317. # endif
  80318. # endif
  80319. # endif /* STDC */
  80320. #endif /* !NOBYFOUR */
  80321. /* Definitions for doing the crc four data bytes at a time. */
  80322. #ifdef BYFOUR
  80323. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80324. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80325. local unsigned long crc32_little OF((unsigned long,
  80326. const unsigned char FAR *, unsigned));
  80327. local unsigned long crc32_big OF((unsigned long,
  80328. const unsigned char FAR *, unsigned));
  80329. # define TBLS 8
  80330. #else
  80331. # define TBLS 1
  80332. #endif /* BYFOUR */
  80333. /* Local functions for crc concatenation */
  80334. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80335. unsigned long vec));
  80336. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80337. #ifdef DYNAMIC_CRC_TABLE
  80338. local volatile int crc_table_empty = 1;
  80339. local unsigned long FAR crc_table[TBLS][256];
  80340. local void make_crc_table OF((void));
  80341. #ifdef MAKECRCH
  80342. local void write_table OF((FILE *, const unsigned long FAR *));
  80343. #endif /* MAKECRCH */
  80344. /*
  80345. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80346. 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.
  80347. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80348. with the lowest powers in the most significant bit. Then adding polynomials
  80349. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80350. one. If we call the above polynomial p, and represent a byte as the
  80351. polynomial q, also with the lowest power in the most significant bit (so the
  80352. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80353. where a mod b means the remainder after dividing a by b.
  80354. This calculation is done using the shift-register method of multiplying and
  80355. taking the remainder. The register is initialized to zero, and for each
  80356. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80357. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80358. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80359. out is a one). We start with the highest power (least significant bit) of
  80360. q and repeat for all eight bits of q.
  80361. The first table is simply the CRC of all possible eight bit values. This is
  80362. all the information needed to generate CRCs on data a byte at a time for all
  80363. combinations of CRC register values and incoming bytes. The remaining tables
  80364. allow for word-at-a-time CRC calculation for both big-endian and little-
  80365. endian machines, where a word is four bytes.
  80366. */
  80367. local void make_crc_table()
  80368. {
  80369. unsigned long c;
  80370. int n, k;
  80371. unsigned long poly; /* polynomial exclusive-or pattern */
  80372. /* terms of polynomial defining this crc (except x^32): */
  80373. static volatile int first = 1; /* flag to limit concurrent making */
  80374. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80375. /* See if another task is already doing this (not thread-safe, but better
  80376. than nothing -- significantly reduces duration of vulnerability in
  80377. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80378. if (first) {
  80379. first = 0;
  80380. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80381. poly = 0UL;
  80382. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80383. poly |= 1UL << (31 - p[n]);
  80384. /* generate a crc for every 8-bit value */
  80385. for (n = 0; n < 256; n++) {
  80386. c = (unsigned long)n;
  80387. for (k = 0; k < 8; k++)
  80388. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80389. crc_table[0][n] = c;
  80390. }
  80391. #ifdef BYFOUR
  80392. /* generate crc for each value followed by one, two, and three zeros,
  80393. and then the byte reversal of those as well as the first table */
  80394. for (n = 0; n < 256; n++) {
  80395. c = crc_table[0][n];
  80396. crc_table[4][n] = REV(c);
  80397. for (k = 1; k < 4; k++) {
  80398. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80399. crc_table[k][n] = c;
  80400. crc_table[k + 4][n] = REV(c);
  80401. }
  80402. }
  80403. #endif /* BYFOUR */
  80404. crc_table_empty = 0;
  80405. }
  80406. else { /* not first */
  80407. /* wait for the other guy to finish (not efficient, but rare) */
  80408. while (crc_table_empty)
  80409. ;
  80410. }
  80411. #ifdef MAKECRCH
  80412. /* write out CRC tables to crc32.h */
  80413. {
  80414. FILE *out;
  80415. out = fopen("crc32.h", "w");
  80416. if (out == NULL) return;
  80417. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80418. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80419. fprintf(out, "local const unsigned long FAR ");
  80420. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80421. write_table(out, crc_table[0]);
  80422. # ifdef BYFOUR
  80423. fprintf(out, "#ifdef BYFOUR\n");
  80424. for (k = 1; k < 8; k++) {
  80425. fprintf(out, " },\n {\n");
  80426. write_table(out, crc_table[k]);
  80427. }
  80428. fprintf(out, "#endif\n");
  80429. # endif /* BYFOUR */
  80430. fprintf(out, " }\n};\n");
  80431. fclose(out);
  80432. }
  80433. #endif /* MAKECRCH */
  80434. }
  80435. #ifdef MAKECRCH
  80436. local void write_table(out, table)
  80437. FILE *out;
  80438. const unsigned long FAR *table;
  80439. {
  80440. int n;
  80441. for (n = 0; n < 256; n++)
  80442. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80443. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80444. }
  80445. #endif /* MAKECRCH */
  80446. #else /* !DYNAMIC_CRC_TABLE */
  80447. /* ========================================================================
  80448. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80449. */
  80450. /*** Start of inlined file: crc32.h ***/
  80451. local const unsigned long FAR crc_table[TBLS][256] =
  80452. {
  80453. {
  80454. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80455. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80456. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80457. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80458. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80459. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80460. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80461. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80462. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80463. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80464. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80465. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80466. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80467. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80468. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80469. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80470. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80471. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80472. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80473. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80474. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80475. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80476. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80477. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80478. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80479. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80480. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80481. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80482. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80483. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80484. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80485. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80486. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80487. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80488. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80489. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80490. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80491. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80492. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80493. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80494. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80495. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80496. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80497. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80498. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80499. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80500. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80501. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80502. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80503. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80504. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80505. 0x2d02ef8dUL
  80506. #ifdef BYFOUR
  80507. },
  80508. {
  80509. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80510. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80511. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80512. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80513. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80514. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80515. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80516. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80517. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80518. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80519. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80520. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80521. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80522. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80523. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80524. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80525. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80526. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80527. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80528. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80529. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80530. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80531. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80532. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80533. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80534. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80535. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80536. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80537. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80538. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80539. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80540. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80541. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80542. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80543. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80544. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80545. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80546. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80547. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80548. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80549. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80550. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80551. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80552. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80553. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80554. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80555. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80556. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80557. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80558. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80559. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80560. 0x9324fd72UL
  80561. },
  80562. {
  80563. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80564. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80565. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80566. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80567. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80568. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80569. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80570. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80571. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80572. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80573. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80574. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80575. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80576. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80577. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80578. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80579. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80580. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80581. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80582. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80583. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80584. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80585. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80586. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80587. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80588. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80589. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80590. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80591. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80592. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80593. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80594. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80595. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80596. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80597. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80598. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80599. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80600. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80601. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80602. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80603. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80604. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80605. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80606. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80607. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80608. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80609. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80610. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80611. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80612. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80613. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80614. 0xbe9834edUL
  80615. },
  80616. {
  80617. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80618. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80619. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80620. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80621. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80622. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80623. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80624. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80625. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80626. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80627. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80628. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80629. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80630. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80631. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80632. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80633. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80634. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80635. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80636. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80637. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80638. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80639. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80640. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80641. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80642. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80643. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80644. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80645. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80646. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80647. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80648. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80649. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80650. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80651. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80652. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80653. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80654. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80655. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80656. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80657. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80658. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80659. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80660. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80661. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80662. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80663. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80664. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80665. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80666. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80667. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80668. 0xde0506f1UL
  80669. },
  80670. {
  80671. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80672. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80673. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80674. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80675. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80676. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80677. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80678. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80679. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80680. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80681. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80682. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80683. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80684. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80685. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80686. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80687. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80688. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80689. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80690. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80691. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80692. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80693. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80694. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80695. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80696. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80697. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80698. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80699. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80700. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80701. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80702. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80703. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80704. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80705. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80706. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80707. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80708. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80709. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80710. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80711. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80712. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80713. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80714. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80715. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80716. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80717. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80718. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80719. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80720. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80721. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80722. 0x8def022dUL
  80723. },
  80724. {
  80725. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80726. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80727. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80728. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80729. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80730. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80731. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80732. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80733. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80734. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80735. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80736. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80737. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80738. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80739. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80740. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80741. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80742. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80743. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80744. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80745. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80746. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80747. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80748. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80749. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80750. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80751. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80752. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80753. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80754. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80755. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80756. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80757. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80758. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80759. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80760. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80761. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80762. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80763. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80764. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80765. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80766. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80767. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80768. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80769. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80770. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80771. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80772. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80773. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80774. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80775. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80776. 0x72fd2493UL
  80777. },
  80778. {
  80779. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80780. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80781. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80782. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80783. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80784. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80785. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80786. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80787. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80788. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80789. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80790. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80791. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80792. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80793. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80794. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80795. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80796. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80797. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80798. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80799. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80800. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80801. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80802. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80803. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80804. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80805. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80806. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80807. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80808. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80809. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80810. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80811. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80812. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80813. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80814. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80815. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80816. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80817. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80818. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80819. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80820. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80821. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80822. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80823. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80824. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80825. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80826. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80827. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80828. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80829. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80830. 0xed3498beUL
  80831. },
  80832. {
  80833. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80834. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80835. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80836. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80837. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80838. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80839. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80840. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80841. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80842. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80843. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80844. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80845. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80846. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80847. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80848. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80849. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80850. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80851. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80852. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80853. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80854. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80855. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80856. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80857. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80858. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80859. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80860. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80861. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80862. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80863. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80864. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80865. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80866. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80867. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80868. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80869. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80870. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80871. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80872. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80873. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80874. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80875. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80876. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80877. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80878. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80879. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80880. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80881. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80882. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80883. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80884. 0xf10605deUL
  80885. #endif
  80886. }
  80887. };
  80888. /*** End of inlined file: crc32.h ***/
  80889. #endif /* DYNAMIC_CRC_TABLE */
  80890. /* =========================================================================
  80891. * This function can be used by asm versions of crc32()
  80892. */
  80893. const unsigned long FAR * ZEXPORT get_crc_table()
  80894. {
  80895. #ifdef DYNAMIC_CRC_TABLE
  80896. if (crc_table_empty)
  80897. make_crc_table();
  80898. #endif /* DYNAMIC_CRC_TABLE */
  80899. return (const unsigned long FAR *)crc_table;
  80900. }
  80901. /* ========================================================================= */
  80902. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80903. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80904. /* ========================================================================= */
  80905. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80906. {
  80907. if (buf == Z_NULL) return 0UL;
  80908. #ifdef DYNAMIC_CRC_TABLE
  80909. if (crc_table_empty)
  80910. make_crc_table();
  80911. #endif /* DYNAMIC_CRC_TABLE */
  80912. #ifdef BYFOUR
  80913. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80914. u4 endian;
  80915. endian = 1;
  80916. if (*((unsigned char *)(&endian)))
  80917. return crc32_little(crc, buf, len);
  80918. else
  80919. return crc32_big(crc, buf, len);
  80920. }
  80921. #endif /* BYFOUR */
  80922. crc = crc ^ 0xffffffffUL;
  80923. while (len >= 8) {
  80924. DO8;
  80925. len -= 8;
  80926. }
  80927. if (len) do {
  80928. DO1;
  80929. } while (--len);
  80930. return crc ^ 0xffffffffUL;
  80931. }
  80932. #ifdef BYFOUR
  80933. /* ========================================================================= */
  80934. #define DOLIT4 c ^= *buf4++; \
  80935. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80936. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80937. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80938. /* ========================================================================= */
  80939. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80940. {
  80941. register u4 c;
  80942. register const u4 FAR *buf4;
  80943. c = (u4)crc;
  80944. c = ~c;
  80945. while (len && ((ptrdiff_t)buf & 3)) {
  80946. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80947. len--;
  80948. }
  80949. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80950. while (len >= 32) {
  80951. DOLIT32;
  80952. len -= 32;
  80953. }
  80954. while (len >= 4) {
  80955. DOLIT4;
  80956. len -= 4;
  80957. }
  80958. buf = (const unsigned char FAR *)buf4;
  80959. if (len) do {
  80960. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80961. } while (--len);
  80962. c = ~c;
  80963. return (unsigned long)c;
  80964. }
  80965. /* ========================================================================= */
  80966. #define DOBIG4 c ^= *++buf4; \
  80967. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80968. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80969. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80970. /* ========================================================================= */
  80971. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80972. {
  80973. register u4 c;
  80974. register const u4 FAR *buf4;
  80975. c = REV((u4)crc);
  80976. c = ~c;
  80977. while (len && ((ptrdiff_t)buf & 3)) {
  80978. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80979. len--;
  80980. }
  80981. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80982. buf4--;
  80983. while (len >= 32) {
  80984. DOBIG32;
  80985. len -= 32;
  80986. }
  80987. while (len >= 4) {
  80988. DOBIG4;
  80989. len -= 4;
  80990. }
  80991. buf4++;
  80992. buf = (const unsigned char FAR *)buf4;
  80993. if (len) do {
  80994. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80995. } while (--len);
  80996. c = ~c;
  80997. return (unsigned long)(REV(c));
  80998. }
  80999. #endif /* BYFOUR */
  81000. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  81001. /* ========================================================================= */
  81002. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  81003. {
  81004. unsigned long sum;
  81005. sum = 0;
  81006. while (vec) {
  81007. if (vec & 1)
  81008. sum ^= *mat;
  81009. vec >>= 1;
  81010. mat++;
  81011. }
  81012. return sum;
  81013. }
  81014. /* ========================================================================= */
  81015. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  81016. {
  81017. int n;
  81018. for (n = 0; n < GF2_DIM; n++)
  81019. square[n] = gf2_matrix_times(mat, mat[n]);
  81020. }
  81021. /* ========================================================================= */
  81022. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  81023. {
  81024. int n;
  81025. unsigned long row;
  81026. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  81027. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  81028. /* degenerate case */
  81029. if (len2 == 0)
  81030. return crc1;
  81031. /* put operator for one zero bit in odd */
  81032. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  81033. row = 1;
  81034. for (n = 1; n < GF2_DIM; n++) {
  81035. odd[n] = row;
  81036. row <<= 1;
  81037. }
  81038. /* put operator for two zero bits in even */
  81039. gf2_matrix_square(even, odd);
  81040. /* put operator for four zero bits in odd */
  81041. gf2_matrix_square(odd, even);
  81042. /* apply len2 zeros to crc1 (first square will put the operator for one
  81043. zero byte, eight zero bits, in even) */
  81044. do {
  81045. /* apply zeros operator for this bit of len2 */
  81046. gf2_matrix_square(even, odd);
  81047. if (len2 & 1)
  81048. crc1 = gf2_matrix_times(even, crc1);
  81049. len2 >>= 1;
  81050. /* if no more bits set, then done */
  81051. if (len2 == 0)
  81052. break;
  81053. /* another iteration of the loop with odd and even swapped */
  81054. gf2_matrix_square(odd, even);
  81055. if (len2 & 1)
  81056. crc1 = gf2_matrix_times(odd, crc1);
  81057. len2 >>= 1;
  81058. /* if no more bits set, then done */
  81059. } while (len2 != 0);
  81060. /* return combined crc */
  81061. crc1 ^= crc2;
  81062. return crc1;
  81063. }
  81064. /*** End of inlined file: crc32.c ***/
  81065. /*** Start of inlined file: deflate.c ***/
  81066. /*
  81067. * ALGORITHM
  81068. *
  81069. * The "deflation" process depends on being able to identify portions
  81070. * of the input text which are identical to earlier input (within a
  81071. * sliding window trailing behind the input currently being processed).
  81072. *
  81073. * The most straightforward technique turns out to be the fastest for
  81074. * most input files: try all possible matches and select the longest.
  81075. * The key feature of this algorithm is that insertions into the string
  81076. * dictionary are very simple and thus fast, and deletions are avoided
  81077. * completely. Insertions are performed at each input character, whereas
  81078. * string matches are performed only when the previous match ends. So it
  81079. * is preferable to spend more time in matches to allow very fast string
  81080. * insertions and avoid deletions. The matching algorithm for small
  81081. * strings is inspired from that of Rabin & Karp. A brute force approach
  81082. * is used to find longer strings when a small match has been found.
  81083. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  81084. * (by Leonid Broukhis).
  81085. * A previous version of this file used a more sophisticated algorithm
  81086. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  81087. * time, but has a larger average cost, uses more memory and is patented.
  81088. * However the F&G algorithm may be faster for some highly redundant
  81089. * files if the parameter max_chain_length (described below) is too large.
  81090. *
  81091. * ACKNOWLEDGEMENTS
  81092. *
  81093. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  81094. * I found it in 'freeze' written by Leonid Broukhis.
  81095. * Thanks to many people for bug reports and testing.
  81096. *
  81097. * REFERENCES
  81098. *
  81099. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  81100. * Available in http://www.ietf.org/rfc/rfc1951.txt
  81101. *
  81102. * A description of the Rabin and Karp algorithm is given in the book
  81103. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  81104. *
  81105. * Fiala,E.R., and Greene,D.H.
  81106. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  81107. *
  81108. */
  81109. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81110. /*** Start of inlined file: deflate.h ***/
  81111. /* WARNING: this file should *not* be used by applications. It is
  81112. part of the implementation of the compression library and is
  81113. subject to change. Applications should only use zlib.h.
  81114. */
  81115. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81116. #ifndef DEFLATE_H
  81117. #define DEFLATE_H
  81118. /* define NO_GZIP when compiling if you want to disable gzip header and
  81119. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  81120. the crc code when it is not needed. For shared libraries, gzip encoding
  81121. should be left enabled. */
  81122. #ifndef NO_GZIP
  81123. # define GZIP
  81124. #endif
  81125. #define NO_DUMMY_DECL
  81126. /* ===========================================================================
  81127. * Internal compression state.
  81128. */
  81129. #define LENGTH_CODES 29
  81130. /* number of length codes, not counting the special END_BLOCK code */
  81131. #define LITERALS 256
  81132. /* number of literal bytes 0..255 */
  81133. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81134. /* number of Literal or Length codes, including the END_BLOCK code */
  81135. #define D_CODES 30
  81136. /* number of distance codes */
  81137. #define BL_CODES 19
  81138. /* number of codes used to transfer the bit lengths */
  81139. #define HEAP_SIZE (2*L_CODES+1)
  81140. /* maximum heap size */
  81141. #define MAX_BITS 15
  81142. /* All codes must not exceed MAX_BITS bits */
  81143. #define INIT_STATE 42
  81144. #define EXTRA_STATE 69
  81145. #define NAME_STATE 73
  81146. #define COMMENT_STATE 91
  81147. #define HCRC_STATE 103
  81148. #define BUSY_STATE 113
  81149. #define FINISH_STATE 666
  81150. /* Stream status */
  81151. /* Data structure describing a single value and its code string. */
  81152. typedef struct ct_data_s {
  81153. union {
  81154. ush freq; /* frequency count */
  81155. ush code; /* bit string */
  81156. } fc;
  81157. union {
  81158. ush dad; /* father node in Huffman tree */
  81159. ush len; /* length of bit string */
  81160. } dl;
  81161. } FAR ct_data;
  81162. #define Freq fc.freq
  81163. #define Code fc.code
  81164. #define Dad dl.dad
  81165. #define Len dl.len
  81166. typedef struct static_tree_desc_s static_tree_desc;
  81167. typedef struct tree_desc_s {
  81168. ct_data *dyn_tree; /* the dynamic tree */
  81169. int max_code; /* largest code with non zero frequency */
  81170. static_tree_desc *stat_desc; /* the corresponding static tree */
  81171. } FAR tree_desc;
  81172. typedef ush Pos;
  81173. typedef Pos FAR Posf;
  81174. typedef unsigned IPos;
  81175. /* A Pos is an index in the character window. We use short instead of int to
  81176. * save space in the various tables. IPos is used only for parameter passing.
  81177. */
  81178. typedef struct internal_state {
  81179. z_streamp strm; /* pointer back to this zlib stream */
  81180. int status; /* as the name implies */
  81181. Bytef *pending_buf; /* output still pending */
  81182. ulg pending_buf_size; /* size of pending_buf */
  81183. Bytef *pending_out; /* next pending byte to output to the stream */
  81184. uInt pending; /* nb of bytes in the pending buffer */
  81185. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81186. gz_headerp gzhead; /* gzip header information to write */
  81187. uInt gzindex; /* where in extra, name, or comment */
  81188. Byte method; /* STORED (for zip only) or DEFLATED */
  81189. int last_flush; /* value of flush param for previous deflate call */
  81190. /* used by deflate.c: */
  81191. uInt w_size; /* LZ77 window size (32K by default) */
  81192. uInt w_bits; /* log2(w_size) (8..16) */
  81193. uInt w_mask; /* w_size - 1 */
  81194. Bytef *window;
  81195. /* Sliding window. Input bytes are read into the second half of the window,
  81196. * and move to the first half later to keep a dictionary of at least wSize
  81197. * bytes. With this organization, matches are limited to a distance of
  81198. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81199. * performed with a length multiple of the block size. Also, it limits
  81200. * the window size to 64K, which is quite useful on MSDOS.
  81201. * To do: use the user input buffer as sliding window.
  81202. */
  81203. ulg window_size;
  81204. /* Actual size of window: 2*wSize, except when the user input buffer
  81205. * is directly used as sliding window.
  81206. */
  81207. Posf *prev;
  81208. /* Link to older string with same hash index. To limit the size of this
  81209. * array to 64K, this link is maintained only for the last 32K strings.
  81210. * An index in this array is thus a window index modulo 32K.
  81211. */
  81212. Posf *head; /* Heads of the hash chains or NIL. */
  81213. uInt ins_h; /* hash index of string to be inserted */
  81214. uInt hash_size; /* number of elements in hash table */
  81215. uInt hash_bits; /* log2(hash_size) */
  81216. uInt hash_mask; /* hash_size-1 */
  81217. uInt hash_shift;
  81218. /* Number of bits by which ins_h must be shifted at each input
  81219. * step. It must be such that after MIN_MATCH steps, the oldest
  81220. * byte no longer takes part in the hash key, that is:
  81221. * hash_shift * MIN_MATCH >= hash_bits
  81222. */
  81223. long block_start;
  81224. /* Window position at the beginning of the current output block. Gets
  81225. * negative when the window is moved backwards.
  81226. */
  81227. uInt match_length; /* length of best match */
  81228. IPos prev_match; /* previous match */
  81229. int match_available; /* set if previous match exists */
  81230. uInt strstart; /* start of string to insert */
  81231. uInt match_start; /* start of matching string */
  81232. uInt lookahead; /* number of valid bytes ahead in window */
  81233. uInt prev_length;
  81234. /* Length of the best match at previous step. Matches not greater than this
  81235. * are discarded. This is used in the lazy match evaluation.
  81236. */
  81237. uInt max_chain_length;
  81238. /* To speed up deflation, hash chains are never searched beyond this
  81239. * length. A higher limit improves compression ratio but degrades the
  81240. * speed.
  81241. */
  81242. uInt max_lazy_match;
  81243. /* Attempt to find a better match only when the current match is strictly
  81244. * smaller than this value. This mechanism is used only for compression
  81245. * levels >= 4.
  81246. */
  81247. # define max_insert_length max_lazy_match
  81248. /* Insert new strings in the hash table only if the match length is not
  81249. * greater than this length. This saves time but degrades compression.
  81250. * max_insert_length is used only for compression levels <= 3.
  81251. */
  81252. int level; /* compression level (1..9) */
  81253. int strategy; /* favor or force Huffman coding*/
  81254. uInt good_match;
  81255. /* Use a faster search when the previous match is longer than this */
  81256. int nice_match; /* Stop searching when current match exceeds this */
  81257. /* used by trees.c: */
  81258. /* Didn't use ct_data typedef below to supress compiler warning */
  81259. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81260. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81261. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81262. struct tree_desc_s l_desc; /* desc. for literal tree */
  81263. struct tree_desc_s d_desc; /* desc. for distance tree */
  81264. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81265. ush bl_count[MAX_BITS+1];
  81266. /* number of codes at each bit length for an optimal tree */
  81267. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81268. int heap_len; /* number of elements in the heap */
  81269. int heap_max; /* element of largest frequency */
  81270. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81271. * The same heap array is used to build all trees.
  81272. */
  81273. uch depth[2*L_CODES+1];
  81274. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81275. */
  81276. uchf *l_buf; /* buffer for literals or lengths */
  81277. uInt lit_bufsize;
  81278. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81279. * limiting lit_bufsize to 64K:
  81280. * - frequencies can be kept in 16 bit counters
  81281. * - if compression is not successful for the first block, all input
  81282. * data is still in the window so we can still emit a stored block even
  81283. * when input comes from standard input. (This can also be done for
  81284. * all blocks if lit_bufsize is not greater than 32K.)
  81285. * - if compression is not successful for a file smaller than 64K, we can
  81286. * even emit a stored file instead of a stored block (saving 5 bytes).
  81287. * This is applicable only for zip (not gzip or zlib).
  81288. * - creating new Huffman trees less frequently may not provide fast
  81289. * adaptation to changes in the input data statistics. (Take for
  81290. * example a binary file with poorly compressible code followed by
  81291. * a highly compressible string table.) Smaller buffer sizes give
  81292. * fast adaptation but have of course the overhead of transmitting
  81293. * trees more frequently.
  81294. * - I can't count above 4
  81295. */
  81296. uInt last_lit; /* running index in l_buf */
  81297. ushf *d_buf;
  81298. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81299. * the same number of elements. To use different lengths, an extra flag
  81300. * array would be necessary.
  81301. */
  81302. ulg opt_len; /* bit length of current block with optimal trees */
  81303. ulg static_len; /* bit length of current block with static trees */
  81304. uInt matches; /* number of string matches in current block */
  81305. int last_eob_len; /* bit length of EOB code for last block */
  81306. #ifdef DEBUG
  81307. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81308. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81309. #endif
  81310. ush bi_buf;
  81311. /* Output buffer. bits are inserted starting at the bottom (least
  81312. * significant bits).
  81313. */
  81314. int bi_valid;
  81315. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81316. * are always zero.
  81317. */
  81318. } FAR deflate_state;
  81319. /* Output a byte on the stream.
  81320. * IN assertion: there is enough room in pending_buf.
  81321. */
  81322. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81323. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81324. /* Minimum amount of lookahead, except at the end of the input file.
  81325. * See deflate.c for comments about the MIN_MATCH+1.
  81326. */
  81327. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81328. /* In order to simplify the code, particularly on 16 bit machines, match
  81329. * distances are limited to MAX_DIST instead of WSIZE.
  81330. */
  81331. /* in trees.c */
  81332. void _tr_init OF((deflate_state *s));
  81333. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81334. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81335. int eof));
  81336. void _tr_align OF((deflate_state *s));
  81337. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81338. int eof));
  81339. #define d_code(dist) \
  81340. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81341. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81342. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81343. * used.
  81344. */
  81345. #ifndef DEBUG
  81346. /* Inline versions of _tr_tally for speed: */
  81347. #if defined(GEN_TREES_H) || !defined(STDC)
  81348. extern uch _length_code[];
  81349. extern uch _dist_code[];
  81350. #else
  81351. extern const uch _length_code[];
  81352. extern const uch _dist_code[];
  81353. #endif
  81354. # define _tr_tally_lit(s, c, flush) \
  81355. { uch cc = (c); \
  81356. s->d_buf[s->last_lit] = 0; \
  81357. s->l_buf[s->last_lit++] = cc; \
  81358. s->dyn_ltree[cc].Freq++; \
  81359. flush = (s->last_lit == s->lit_bufsize-1); \
  81360. }
  81361. # define _tr_tally_dist(s, distance, length, flush) \
  81362. { uch len = (length); \
  81363. ush dist = (distance); \
  81364. s->d_buf[s->last_lit] = dist; \
  81365. s->l_buf[s->last_lit++] = len; \
  81366. dist--; \
  81367. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81368. s->dyn_dtree[d_code(dist)].Freq++; \
  81369. flush = (s->last_lit == s->lit_bufsize-1); \
  81370. }
  81371. #else
  81372. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81373. # define _tr_tally_dist(s, distance, length, flush) \
  81374. flush = _tr_tally(s, distance, length)
  81375. #endif
  81376. #endif /* DEFLATE_H */
  81377. /*** End of inlined file: deflate.h ***/
  81378. const char deflate_copyright[] =
  81379. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81380. /*
  81381. If you use the zlib library in a product, an acknowledgment is welcome
  81382. in the documentation of your product. If for some reason you cannot
  81383. include such an acknowledgment, I would appreciate that you keep this
  81384. copyright string in the executable of your product.
  81385. */
  81386. /* ===========================================================================
  81387. * Function prototypes.
  81388. */
  81389. typedef enum {
  81390. need_more, /* block not completed, need more input or more output */
  81391. block_done, /* block flush performed */
  81392. finish_started, /* finish started, need only more output at next deflate */
  81393. finish_done /* finish done, accept no more input or output */
  81394. } block_state;
  81395. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81396. /* Compression function. Returns the block state after the call. */
  81397. local void fill_window OF((deflate_state *s));
  81398. local block_state deflate_stored OF((deflate_state *s, int flush));
  81399. local block_state deflate_fast OF((deflate_state *s, int flush));
  81400. #ifndef FASTEST
  81401. local block_state deflate_slow OF((deflate_state *s, int flush));
  81402. #endif
  81403. local void lm_init OF((deflate_state *s));
  81404. local void putShortMSB OF((deflate_state *s, uInt b));
  81405. local void flush_pending OF((z_streamp strm));
  81406. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81407. #ifndef FASTEST
  81408. #ifdef ASMV
  81409. void match_init OF((void)); /* asm code initialization */
  81410. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81411. #else
  81412. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81413. #endif
  81414. #endif
  81415. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81416. #ifdef DEBUG
  81417. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81418. int length));
  81419. #endif
  81420. /* ===========================================================================
  81421. * Local data
  81422. */
  81423. #define NIL 0
  81424. /* Tail of hash chains */
  81425. #ifndef TOO_FAR
  81426. # define TOO_FAR 4096
  81427. #endif
  81428. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81429. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81430. /* Minimum amount of lookahead, except at the end of the input file.
  81431. * See deflate.c for comments about the MIN_MATCH+1.
  81432. */
  81433. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81434. * the desired pack level (0..9). The values given below have been tuned to
  81435. * exclude worst case performance for pathological files. Better values may be
  81436. * found for specific files.
  81437. */
  81438. typedef struct config_s {
  81439. ush good_length; /* reduce lazy search above this match length */
  81440. ush max_lazy; /* do not perform lazy search above this match length */
  81441. ush nice_length; /* quit search above this match length */
  81442. ush max_chain;
  81443. compress_func func;
  81444. } config;
  81445. #ifdef FASTEST
  81446. local const config configuration_table[2] = {
  81447. /* good lazy nice chain */
  81448. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81449. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81450. #else
  81451. local const config configuration_table[10] = {
  81452. /* good lazy nice chain */
  81453. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81454. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81455. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81456. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81457. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81458. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81459. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81460. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81461. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81462. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81463. #endif
  81464. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81465. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81466. * meaning.
  81467. */
  81468. #define EQUAL 0
  81469. /* result of memcmp for equal strings */
  81470. #ifndef NO_DUMMY_DECL
  81471. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81472. #endif
  81473. /* ===========================================================================
  81474. * Update a hash value with the given input byte
  81475. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81476. * input characters, so that a running hash key can be computed from the
  81477. * previous key instead of complete recalculation each time.
  81478. */
  81479. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81480. /* ===========================================================================
  81481. * Insert string str in the dictionary and set match_head to the previous head
  81482. * of the hash chain (the most recent string with same hash key). Return
  81483. * the previous length of the hash chain.
  81484. * If this file is compiled with -DFASTEST, the compression level is forced
  81485. * to 1, and no hash chains are maintained.
  81486. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81487. * input characters and the first MIN_MATCH bytes of str are valid
  81488. * (except for the last MIN_MATCH-1 bytes of the input file).
  81489. */
  81490. #ifdef FASTEST
  81491. #define INSERT_STRING(s, str, match_head) \
  81492. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81493. match_head = s->head[s->ins_h], \
  81494. s->head[s->ins_h] = (Pos)(str))
  81495. #else
  81496. #define INSERT_STRING(s, str, match_head) \
  81497. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81498. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81499. s->head[s->ins_h] = (Pos)(str))
  81500. #endif
  81501. /* ===========================================================================
  81502. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81503. * prev[] will be initialized on the fly.
  81504. */
  81505. #define CLEAR_HASH(s) \
  81506. s->head[s->hash_size-1] = NIL; \
  81507. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81508. /* ========================================================================= */
  81509. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81510. {
  81511. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81512. Z_DEFAULT_STRATEGY, version, stream_size);
  81513. /* To do: ignore strm->next_in if we use it as window */
  81514. }
  81515. /* ========================================================================= */
  81516. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81517. {
  81518. deflate_state *s;
  81519. int wrap = 1;
  81520. static const char my_version[] = ZLIB_VERSION;
  81521. ushf *overlay;
  81522. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81523. * output size for (length,distance) codes is <= 24 bits.
  81524. */
  81525. if (version == Z_NULL || version[0] != my_version[0] ||
  81526. stream_size != sizeof(z_stream)) {
  81527. return Z_VERSION_ERROR;
  81528. }
  81529. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81530. strm->msg = Z_NULL;
  81531. if (strm->zalloc == (alloc_func)0) {
  81532. strm->zalloc = zcalloc;
  81533. strm->opaque = (voidpf)0;
  81534. }
  81535. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81536. #ifdef FASTEST
  81537. if (level != 0) level = 1;
  81538. #else
  81539. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81540. #endif
  81541. if (windowBits < 0) { /* suppress zlib wrapper */
  81542. wrap = 0;
  81543. windowBits = -windowBits;
  81544. }
  81545. #ifdef GZIP
  81546. else if (windowBits > 15) {
  81547. wrap = 2; /* write gzip wrapper instead */
  81548. windowBits -= 16;
  81549. }
  81550. #endif
  81551. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81552. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81553. strategy < 0 || strategy > Z_FIXED) {
  81554. return Z_STREAM_ERROR;
  81555. }
  81556. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81557. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81558. if (s == Z_NULL) return Z_MEM_ERROR;
  81559. strm->state = (struct internal_state FAR *)s;
  81560. s->strm = strm;
  81561. s->wrap = wrap;
  81562. s->gzhead = Z_NULL;
  81563. s->w_bits = windowBits;
  81564. s->w_size = 1 << s->w_bits;
  81565. s->w_mask = s->w_size - 1;
  81566. s->hash_bits = memLevel + 7;
  81567. s->hash_size = 1 << s->hash_bits;
  81568. s->hash_mask = s->hash_size - 1;
  81569. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81570. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81571. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81572. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81573. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81574. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81575. s->pending_buf = (uchf *) overlay;
  81576. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81577. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81578. s->pending_buf == Z_NULL) {
  81579. s->status = FINISH_STATE;
  81580. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81581. deflateEnd (strm);
  81582. return Z_MEM_ERROR;
  81583. }
  81584. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81585. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81586. s->level = level;
  81587. s->strategy = strategy;
  81588. s->method = (Byte)method;
  81589. return deflateReset(strm);
  81590. }
  81591. /* ========================================================================= */
  81592. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81593. {
  81594. deflate_state *s;
  81595. uInt length = dictLength;
  81596. uInt n;
  81597. IPos hash_head = 0;
  81598. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81599. strm->state->wrap == 2 ||
  81600. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81601. return Z_STREAM_ERROR;
  81602. s = strm->state;
  81603. if (s->wrap)
  81604. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81605. if (length < MIN_MATCH) return Z_OK;
  81606. if (length > MAX_DIST(s)) {
  81607. length = MAX_DIST(s);
  81608. dictionary += dictLength - length; /* use the tail of the dictionary */
  81609. }
  81610. zmemcpy(s->window, dictionary, length);
  81611. s->strstart = length;
  81612. s->block_start = (long)length;
  81613. /* Insert all strings in the hash table (except for the last two bytes).
  81614. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81615. * call of fill_window.
  81616. */
  81617. s->ins_h = s->window[0];
  81618. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81619. for (n = 0; n <= length - MIN_MATCH; n++) {
  81620. INSERT_STRING(s, n, hash_head);
  81621. }
  81622. if (hash_head) hash_head = 0; /* to make compiler happy */
  81623. return Z_OK;
  81624. }
  81625. /* ========================================================================= */
  81626. int ZEXPORT deflateReset (z_streamp strm)
  81627. {
  81628. deflate_state *s;
  81629. if (strm == Z_NULL || strm->state == Z_NULL ||
  81630. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81631. return Z_STREAM_ERROR;
  81632. }
  81633. strm->total_in = strm->total_out = 0;
  81634. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81635. strm->data_type = Z_UNKNOWN;
  81636. s = (deflate_state *)strm->state;
  81637. s->pending = 0;
  81638. s->pending_out = s->pending_buf;
  81639. if (s->wrap < 0) {
  81640. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81641. }
  81642. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81643. strm->adler =
  81644. #ifdef GZIP
  81645. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81646. #endif
  81647. adler32(0L, Z_NULL, 0);
  81648. s->last_flush = Z_NO_FLUSH;
  81649. _tr_init(s);
  81650. lm_init(s);
  81651. return Z_OK;
  81652. }
  81653. /* ========================================================================= */
  81654. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81655. {
  81656. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81657. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81658. strm->state->gzhead = head;
  81659. return Z_OK;
  81660. }
  81661. /* ========================================================================= */
  81662. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81663. {
  81664. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81665. strm->state->bi_valid = bits;
  81666. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81667. return Z_OK;
  81668. }
  81669. /* ========================================================================= */
  81670. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81671. {
  81672. deflate_state *s;
  81673. compress_func func;
  81674. int err = Z_OK;
  81675. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81676. s = strm->state;
  81677. #ifdef FASTEST
  81678. if (level != 0) level = 1;
  81679. #else
  81680. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81681. #endif
  81682. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81683. return Z_STREAM_ERROR;
  81684. }
  81685. func = configuration_table[s->level].func;
  81686. if (func != configuration_table[level].func && strm->total_in != 0) {
  81687. /* Flush the last buffer: */
  81688. err = deflate(strm, Z_PARTIAL_FLUSH);
  81689. }
  81690. if (s->level != level) {
  81691. s->level = level;
  81692. s->max_lazy_match = configuration_table[level].max_lazy;
  81693. s->good_match = configuration_table[level].good_length;
  81694. s->nice_match = configuration_table[level].nice_length;
  81695. s->max_chain_length = configuration_table[level].max_chain;
  81696. }
  81697. s->strategy = strategy;
  81698. return err;
  81699. }
  81700. /* ========================================================================= */
  81701. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81702. {
  81703. deflate_state *s;
  81704. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81705. s = strm->state;
  81706. s->good_match = good_length;
  81707. s->max_lazy_match = max_lazy;
  81708. s->nice_match = nice_length;
  81709. s->max_chain_length = max_chain;
  81710. return Z_OK;
  81711. }
  81712. /* =========================================================================
  81713. * For the default windowBits of 15 and memLevel of 8, this function returns
  81714. * a close to exact, as well as small, upper bound on the compressed size.
  81715. * They are coded as constants here for a reason--if the #define's are
  81716. * changed, then this function needs to be changed as well. The return
  81717. * value for 15 and 8 only works for those exact settings.
  81718. *
  81719. * For any setting other than those defaults for windowBits and memLevel,
  81720. * the value returned is a conservative worst case for the maximum expansion
  81721. * resulting from using fixed blocks instead of stored blocks, which deflate
  81722. * can emit on compressed data for some combinations of the parameters.
  81723. *
  81724. * This function could be more sophisticated to provide closer upper bounds
  81725. * for every combination of windowBits and memLevel, as well as wrap.
  81726. * But even the conservative upper bound of about 14% expansion does not
  81727. * seem onerous for output buffer allocation.
  81728. */
  81729. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81730. {
  81731. deflate_state *s;
  81732. uLong destLen;
  81733. /* conservative upper bound */
  81734. destLen = sourceLen +
  81735. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81736. /* if can't get parameters, return conservative bound */
  81737. if (strm == Z_NULL || strm->state == Z_NULL)
  81738. return destLen;
  81739. /* if not default parameters, return conservative bound */
  81740. s = strm->state;
  81741. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81742. return destLen;
  81743. /* default settings: return tight bound for that case */
  81744. return compressBound(sourceLen);
  81745. }
  81746. /* =========================================================================
  81747. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81748. * IN assertion: the stream state is correct and there is enough room in
  81749. * pending_buf.
  81750. */
  81751. local void putShortMSB (deflate_state *s, uInt b)
  81752. {
  81753. put_byte(s, (Byte)(b >> 8));
  81754. put_byte(s, (Byte)(b & 0xff));
  81755. }
  81756. /* =========================================================================
  81757. * Flush as much pending output as possible. All deflate() output goes
  81758. * through this function so some applications may wish to modify it
  81759. * to avoid allocating a large strm->next_out buffer and copying into it.
  81760. * (See also read_buf()).
  81761. */
  81762. local void flush_pending (z_streamp strm)
  81763. {
  81764. unsigned len = strm->state->pending;
  81765. if (len > strm->avail_out) len = strm->avail_out;
  81766. if (len == 0) return;
  81767. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81768. strm->next_out += len;
  81769. strm->state->pending_out += len;
  81770. strm->total_out += len;
  81771. strm->avail_out -= len;
  81772. strm->state->pending -= len;
  81773. if (strm->state->pending == 0) {
  81774. strm->state->pending_out = strm->state->pending_buf;
  81775. }
  81776. }
  81777. /* ========================================================================= */
  81778. int ZEXPORT deflate (z_streamp strm, int flush)
  81779. {
  81780. int old_flush; /* value of flush param for previous deflate call */
  81781. deflate_state *s;
  81782. if (strm == Z_NULL || strm->state == Z_NULL ||
  81783. flush > Z_FINISH || flush < 0) {
  81784. return Z_STREAM_ERROR;
  81785. }
  81786. s = strm->state;
  81787. if (strm->next_out == Z_NULL ||
  81788. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81789. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81790. ERR_RETURN(strm, Z_STREAM_ERROR);
  81791. }
  81792. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81793. s->strm = strm; /* just in case */
  81794. old_flush = s->last_flush;
  81795. s->last_flush = flush;
  81796. /* Write the header */
  81797. if (s->status == INIT_STATE) {
  81798. #ifdef GZIP
  81799. if (s->wrap == 2) {
  81800. strm->adler = crc32(0L, Z_NULL, 0);
  81801. put_byte(s, 31);
  81802. put_byte(s, 139);
  81803. put_byte(s, 8);
  81804. if (s->gzhead == NULL) {
  81805. put_byte(s, 0);
  81806. put_byte(s, 0);
  81807. put_byte(s, 0);
  81808. put_byte(s, 0);
  81809. put_byte(s, 0);
  81810. put_byte(s, s->level == 9 ? 2 :
  81811. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81812. 4 : 0));
  81813. put_byte(s, OS_CODE);
  81814. s->status = BUSY_STATE;
  81815. }
  81816. else {
  81817. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81818. (s->gzhead->hcrc ? 2 : 0) +
  81819. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81820. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81821. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81822. );
  81823. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81824. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81825. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81826. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81827. put_byte(s, s->level == 9 ? 2 :
  81828. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81829. 4 : 0));
  81830. put_byte(s, s->gzhead->os & 0xff);
  81831. if (s->gzhead->extra != NULL) {
  81832. put_byte(s, s->gzhead->extra_len & 0xff);
  81833. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81834. }
  81835. if (s->gzhead->hcrc)
  81836. strm->adler = crc32(strm->adler, s->pending_buf,
  81837. s->pending);
  81838. s->gzindex = 0;
  81839. s->status = EXTRA_STATE;
  81840. }
  81841. }
  81842. else
  81843. #endif
  81844. {
  81845. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81846. uInt level_flags;
  81847. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81848. level_flags = 0;
  81849. else if (s->level < 6)
  81850. level_flags = 1;
  81851. else if (s->level == 6)
  81852. level_flags = 2;
  81853. else
  81854. level_flags = 3;
  81855. header |= (level_flags << 6);
  81856. if (s->strstart != 0) header |= PRESET_DICT;
  81857. header += 31 - (header % 31);
  81858. s->status = BUSY_STATE;
  81859. putShortMSB(s, header);
  81860. /* Save the adler32 of the preset dictionary: */
  81861. if (s->strstart != 0) {
  81862. putShortMSB(s, (uInt)(strm->adler >> 16));
  81863. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81864. }
  81865. strm->adler = adler32(0L, Z_NULL, 0);
  81866. }
  81867. }
  81868. #ifdef GZIP
  81869. if (s->status == EXTRA_STATE) {
  81870. if (s->gzhead->extra != NULL) {
  81871. uInt beg = s->pending; /* start of bytes to update crc */
  81872. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81873. if (s->pending == s->pending_buf_size) {
  81874. if (s->gzhead->hcrc && s->pending > beg)
  81875. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81876. s->pending - beg);
  81877. flush_pending(strm);
  81878. beg = s->pending;
  81879. if (s->pending == s->pending_buf_size)
  81880. break;
  81881. }
  81882. put_byte(s, s->gzhead->extra[s->gzindex]);
  81883. s->gzindex++;
  81884. }
  81885. if (s->gzhead->hcrc && s->pending > beg)
  81886. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81887. s->pending - beg);
  81888. if (s->gzindex == s->gzhead->extra_len) {
  81889. s->gzindex = 0;
  81890. s->status = NAME_STATE;
  81891. }
  81892. }
  81893. else
  81894. s->status = NAME_STATE;
  81895. }
  81896. if (s->status == NAME_STATE) {
  81897. if (s->gzhead->name != NULL) {
  81898. uInt beg = s->pending; /* start of bytes to update crc */
  81899. int val;
  81900. do {
  81901. if (s->pending == s->pending_buf_size) {
  81902. if (s->gzhead->hcrc && s->pending > beg)
  81903. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81904. s->pending - beg);
  81905. flush_pending(strm);
  81906. beg = s->pending;
  81907. if (s->pending == s->pending_buf_size) {
  81908. val = 1;
  81909. break;
  81910. }
  81911. }
  81912. val = s->gzhead->name[s->gzindex++];
  81913. put_byte(s, val);
  81914. } while (val != 0);
  81915. if (s->gzhead->hcrc && s->pending > beg)
  81916. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81917. s->pending - beg);
  81918. if (val == 0) {
  81919. s->gzindex = 0;
  81920. s->status = COMMENT_STATE;
  81921. }
  81922. }
  81923. else
  81924. s->status = COMMENT_STATE;
  81925. }
  81926. if (s->status == COMMENT_STATE) {
  81927. if (s->gzhead->comment != NULL) {
  81928. uInt beg = s->pending; /* start of bytes to update crc */
  81929. int val;
  81930. do {
  81931. if (s->pending == s->pending_buf_size) {
  81932. if (s->gzhead->hcrc && s->pending > beg)
  81933. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81934. s->pending - beg);
  81935. flush_pending(strm);
  81936. beg = s->pending;
  81937. if (s->pending == s->pending_buf_size) {
  81938. val = 1;
  81939. break;
  81940. }
  81941. }
  81942. val = s->gzhead->comment[s->gzindex++];
  81943. put_byte(s, val);
  81944. } while (val != 0);
  81945. if (s->gzhead->hcrc && s->pending > beg)
  81946. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81947. s->pending - beg);
  81948. if (val == 0)
  81949. s->status = HCRC_STATE;
  81950. }
  81951. else
  81952. s->status = HCRC_STATE;
  81953. }
  81954. if (s->status == HCRC_STATE) {
  81955. if (s->gzhead->hcrc) {
  81956. if (s->pending + 2 > s->pending_buf_size)
  81957. flush_pending(strm);
  81958. if (s->pending + 2 <= s->pending_buf_size) {
  81959. put_byte(s, (Byte)(strm->adler & 0xff));
  81960. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81961. strm->adler = crc32(0L, Z_NULL, 0);
  81962. s->status = BUSY_STATE;
  81963. }
  81964. }
  81965. else
  81966. s->status = BUSY_STATE;
  81967. }
  81968. #endif
  81969. /* Flush as much pending output as possible */
  81970. if (s->pending != 0) {
  81971. flush_pending(strm);
  81972. if (strm->avail_out == 0) {
  81973. /* Since avail_out is 0, deflate will be called again with
  81974. * more output space, but possibly with both pending and
  81975. * avail_in equal to zero. There won't be anything to do,
  81976. * but this is not an error situation so make sure we
  81977. * return OK instead of BUF_ERROR at next call of deflate:
  81978. */
  81979. s->last_flush = -1;
  81980. return Z_OK;
  81981. }
  81982. /* Make sure there is something to do and avoid duplicate consecutive
  81983. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81984. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81985. */
  81986. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81987. flush != Z_FINISH) {
  81988. ERR_RETURN(strm, Z_BUF_ERROR);
  81989. }
  81990. /* User must not provide more input after the first FINISH: */
  81991. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81992. ERR_RETURN(strm, Z_BUF_ERROR);
  81993. }
  81994. /* Start a new block or continue the current one.
  81995. */
  81996. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81997. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81998. block_state bstate;
  81999. bstate = (*(configuration_table[s->level].func))(s, flush);
  82000. if (bstate == finish_started || bstate == finish_done) {
  82001. s->status = FINISH_STATE;
  82002. }
  82003. if (bstate == need_more || bstate == finish_started) {
  82004. if (strm->avail_out == 0) {
  82005. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  82006. }
  82007. return Z_OK;
  82008. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  82009. * of deflate should use the same flush parameter to make sure
  82010. * that the flush is complete. So we don't have to output an
  82011. * empty block here, this will be done at next call. This also
  82012. * ensures that for a very small output buffer, we emit at most
  82013. * one empty block.
  82014. */
  82015. }
  82016. if (bstate == block_done) {
  82017. if (flush == Z_PARTIAL_FLUSH) {
  82018. _tr_align(s);
  82019. } else { /* FULL_FLUSH or SYNC_FLUSH */
  82020. _tr_stored_block(s, (char*)0, 0L, 0);
  82021. /* For a full flush, this empty block will be recognized
  82022. * as a special marker by inflate_sync().
  82023. */
  82024. if (flush == Z_FULL_FLUSH) {
  82025. CLEAR_HASH(s); /* forget history */
  82026. }
  82027. }
  82028. flush_pending(strm);
  82029. if (strm->avail_out == 0) {
  82030. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  82031. return Z_OK;
  82032. }
  82033. }
  82034. }
  82035. Assert(strm->avail_out > 0, "bug2");
  82036. if (flush != Z_FINISH) return Z_OK;
  82037. if (s->wrap <= 0) return Z_STREAM_END;
  82038. /* Write the trailer */
  82039. #ifdef GZIP
  82040. if (s->wrap == 2) {
  82041. put_byte(s, (Byte)(strm->adler & 0xff));
  82042. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82043. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  82044. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  82045. put_byte(s, (Byte)(strm->total_in & 0xff));
  82046. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  82047. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  82048. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  82049. }
  82050. else
  82051. #endif
  82052. {
  82053. putShortMSB(s, (uInt)(strm->adler >> 16));
  82054. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  82055. }
  82056. flush_pending(strm);
  82057. /* If avail_out is zero, the application will call deflate again
  82058. * to flush the rest.
  82059. */
  82060. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  82061. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  82062. }
  82063. /* ========================================================================= */
  82064. int ZEXPORT deflateEnd (z_streamp strm)
  82065. {
  82066. int status;
  82067. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82068. status = strm->state->status;
  82069. if (status != INIT_STATE &&
  82070. status != EXTRA_STATE &&
  82071. status != NAME_STATE &&
  82072. status != COMMENT_STATE &&
  82073. status != HCRC_STATE &&
  82074. status != BUSY_STATE &&
  82075. status != FINISH_STATE) {
  82076. return Z_STREAM_ERROR;
  82077. }
  82078. /* Deallocate in reverse order of allocations: */
  82079. TRY_FREE(strm, strm->state->pending_buf);
  82080. TRY_FREE(strm, strm->state->head);
  82081. TRY_FREE(strm, strm->state->prev);
  82082. TRY_FREE(strm, strm->state->window);
  82083. ZFREE(strm, strm->state);
  82084. strm->state = Z_NULL;
  82085. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  82086. }
  82087. /* =========================================================================
  82088. * Copy the source state to the destination state.
  82089. * To simplify the source, this is not supported for 16-bit MSDOS (which
  82090. * doesn't have enough memory anyway to duplicate compression states).
  82091. */
  82092. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  82093. {
  82094. #ifdef MAXSEG_64K
  82095. return Z_STREAM_ERROR;
  82096. #else
  82097. deflate_state *ds;
  82098. deflate_state *ss;
  82099. ushf *overlay;
  82100. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  82101. return Z_STREAM_ERROR;
  82102. }
  82103. ss = source->state;
  82104. zmemcpy(dest, source, sizeof(z_stream));
  82105. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  82106. if (ds == Z_NULL) return Z_MEM_ERROR;
  82107. dest->state = (struct internal_state FAR *) ds;
  82108. zmemcpy(ds, ss, sizeof(deflate_state));
  82109. ds->strm = dest;
  82110. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  82111. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  82112. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  82113. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  82114. ds->pending_buf = (uchf *) overlay;
  82115. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  82116. ds->pending_buf == Z_NULL) {
  82117. deflateEnd (dest);
  82118. return Z_MEM_ERROR;
  82119. }
  82120. /* following zmemcpy do not work for 16-bit MSDOS */
  82121. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  82122. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  82123. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  82124. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  82125. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  82126. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  82127. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  82128. ds->l_desc.dyn_tree = ds->dyn_ltree;
  82129. ds->d_desc.dyn_tree = ds->dyn_dtree;
  82130. ds->bl_desc.dyn_tree = ds->bl_tree;
  82131. return Z_OK;
  82132. #endif /* MAXSEG_64K */
  82133. }
  82134. /* ===========================================================================
  82135. * Read a new buffer from the current input stream, update the adler32
  82136. * and total number of bytes read. All deflate() input goes through
  82137. * this function so some applications may wish to modify it to avoid
  82138. * allocating a large strm->next_in buffer and copying from it.
  82139. * (See also flush_pending()).
  82140. */
  82141. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82142. {
  82143. unsigned len = strm->avail_in;
  82144. if (len > size) len = size;
  82145. if (len == 0) return 0;
  82146. strm->avail_in -= len;
  82147. if (strm->state->wrap == 1) {
  82148. strm->adler = adler32(strm->adler, strm->next_in, len);
  82149. }
  82150. #ifdef GZIP
  82151. else if (strm->state->wrap == 2) {
  82152. strm->adler = crc32(strm->adler, strm->next_in, len);
  82153. }
  82154. #endif
  82155. zmemcpy(buf, strm->next_in, len);
  82156. strm->next_in += len;
  82157. strm->total_in += len;
  82158. return (int)len;
  82159. }
  82160. /* ===========================================================================
  82161. * Initialize the "longest match" routines for a new zlib stream
  82162. */
  82163. local void lm_init (deflate_state *s)
  82164. {
  82165. s->window_size = (ulg)2L*s->w_size;
  82166. CLEAR_HASH(s);
  82167. /* Set the default configuration parameters:
  82168. */
  82169. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82170. s->good_match = configuration_table[s->level].good_length;
  82171. s->nice_match = configuration_table[s->level].nice_length;
  82172. s->max_chain_length = configuration_table[s->level].max_chain;
  82173. s->strstart = 0;
  82174. s->block_start = 0L;
  82175. s->lookahead = 0;
  82176. s->match_length = s->prev_length = MIN_MATCH-1;
  82177. s->match_available = 0;
  82178. s->ins_h = 0;
  82179. #ifndef FASTEST
  82180. #ifdef ASMV
  82181. match_init(); /* initialize the asm code */
  82182. #endif
  82183. #endif
  82184. }
  82185. #ifndef FASTEST
  82186. /* ===========================================================================
  82187. * Set match_start to the longest match starting at the given string and
  82188. * return its length. Matches shorter or equal to prev_length are discarded,
  82189. * in which case the result is equal to prev_length and match_start is
  82190. * garbage.
  82191. * IN assertions: cur_match is the head of the hash chain for the current
  82192. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82193. * OUT assertion: the match length is not greater than s->lookahead.
  82194. */
  82195. #ifndef ASMV
  82196. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82197. * match.S. The code will be functionally equivalent.
  82198. */
  82199. local uInt longest_match(deflate_state *s, IPos cur_match)
  82200. {
  82201. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82202. register Bytef *scan = s->window + s->strstart; /* current string */
  82203. register Bytef *match; /* matched string */
  82204. register int len; /* length of current match */
  82205. int best_len = s->prev_length; /* best match length so far */
  82206. int nice_match = s->nice_match; /* stop if match long enough */
  82207. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82208. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82209. /* Stop when cur_match becomes <= limit. To simplify the code,
  82210. * we prevent matches with the string of window index 0.
  82211. */
  82212. Posf *prev = s->prev;
  82213. uInt wmask = s->w_mask;
  82214. #ifdef UNALIGNED_OK
  82215. /* Compare two bytes at a time. Note: this is not always beneficial.
  82216. * Try with and without -DUNALIGNED_OK to check.
  82217. */
  82218. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82219. register ush scan_start = *(ushf*)scan;
  82220. register ush scan_end = *(ushf*)(scan+best_len-1);
  82221. #else
  82222. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82223. register Byte scan_end1 = scan[best_len-1];
  82224. register Byte scan_end = scan[best_len];
  82225. #endif
  82226. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82227. * It is easy to get rid of this optimization if necessary.
  82228. */
  82229. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82230. /* Do not waste too much time if we already have a good match: */
  82231. if (s->prev_length >= s->good_match) {
  82232. chain_length >>= 2;
  82233. }
  82234. /* Do not look for matches beyond the end of the input. This is necessary
  82235. * to make deflate deterministic.
  82236. */
  82237. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82238. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82239. do {
  82240. Assert(cur_match < s->strstart, "no future");
  82241. match = s->window + cur_match;
  82242. /* Skip to next match if the match length cannot increase
  82243. * or if the match length is less than 2. Note that the checks below
  82244. * for insufficient lookahead only occur occasionally for performance
  82245. * reasons. Therefore uninitialized memory will be accessed, and
  82246. * conditional jumps will be made that depend on those values.
  82247. * However the length of the match is limited to the lookahead, so
  82248. * the output of deflate is not affected by the uninitialized values.
  82249. */
  82250. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82251. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82252. * UNALIGNED_OK if your compiler uses a different size.
  82253. */
  82254. if (*(ushf*)(match+best_len-1) != scan_end ||
  82255. *(ushf*)match != scan_start) continue;
  82256. /* It is not necessary to compare scan[2] and match[2] since they are
  82257. * always equal when the other bytes match, given that the hash keys
  82258. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82259. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82260. * lookahead only every 4th comparison; the 128th check will be made
  82261. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82262. * necessary to put more guard bytes at the end of the window, or
  82263. * to check more often for insufficient lookahead.
  82264. */
  82265. Assert(scan[2] == match[2], "scan[2]?");
  82266. scan++, match++;
  82267. do {
  82268. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82269. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82270. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82271. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82272. scan < strend);
  82273. /* The funny "do {}" generates better code on most compilers */
  82274. /* Here, scan <= window+strstart+257 */
  82275. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82276. if (*scan == *match) scan++;
  82277. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82278. scan = strend - (MAX_MATCH-1);
  82279. #else /* UNALIGNED_OK */
  82280. if (match[best_len] != scan_end ||
  82281. match[best_len-1] != scan_end1 ||
  82282. *match != *scan ||
  82283. *++match != scan[1]) continue;
  82284. /* The check at best_len-1 can be removed because it will be made
  82285. * again later. (This heuristic is not always a win.)
  82286. * It is not necessary to compare scan[2] and match[2] since they
  82287. * are always equal when the other bytes match, given that
  82288. * the hash keys are equal and that HASH_BITS >= 8.
  82289. */
  82290. scan += 2, match++;
  82291. Assert(*scan == *match, "match[2]?");
  82292. /* We check for insufficient lookahead only every 8th comparison;
  82293. * the 256th check will be made at strstart+258.
  82294. */
  82295. do {
  82296. } while (*++scan == *++match && *++scan == *++match &&
  82297. *++scan == *++match && *++scan == *++match &&
  82298. *++scan == *++match && *++scan == *++match &&
  82299. *++scan == *++match && *++scan == *++match &&
  82300. scan < strend);
  82301. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82302. len = MAX_MATCH - (int)(strend - scan);
  82303. scan = strend - MAX_MATCH;
  82304. #endif /* UNALIGNED_OK */
  82305. if (len > best_len) {
  82306. s->match_start = cur_match;
  82307. best_len = len;
  82308. if (len >= nice_match) break;
  82309. #ifdef UNALIGNED_OK
  82310. scan_end = *(ushf*)(scan+best_len-1);
  82311. #else
  82312. scan_end1 = scan[best_len-1];
  82313. scan_end = scan[best_len];
  82314. #endif
  82315. }
  82316. } while ((cur_match = prev[cur_match & wmask]) > limit
  82317. && --chain_length != 0);
  82318. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82319. return s->lookahead;
  82320. }
  82321. #endif /* ASMV */
  82322. #endif /* FASTEST */
  82323. /* ---------------------------------------------------------------------------
  82324. * Optimized version for level == 1 or strategy == Z_RLE only
  82325. */
  82326. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82327. {
  82328. register Bytef *scan = s->window + s->strstart; /* current string */
  82329. register Bytef *match; /* matched string */
  82330. register int len; /* length of current match */
  82331. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82332. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82333. * It is easy to get rid of this optimization if necessary.
  82334. */
  82335. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82336. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82337. Assert(cur_match < s->strstart, "no future");
  82338. match = s->window + cur_match;
  82339. /* Return failure if the match length is less than 2:
  82340. */
  82341. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82342. /* The check at best_len-1 can be removed because it will be made
  82343. * again later. (This heuristic is not always a win.)
  82344. * It is not necessary to compare scan[2] and match[2] since they
  82345. * are always equal when the other bytes match, given that
  82346. * the hash keys are equal and that HASH_BITS >= 8.
  82347. */
  82348. scan += 2, match += 2;
  82349. Assert(*scan == *match, "match[2]?");
  82350. /* We check for insufficient lookahead only every 8th comparison;
  82351. * the 256th check will be made at strstart+258.
  82352. */
  82353. do {
  82354. } while (*++scan == *++match && *++scan == *++match &&
  82355. *++scan == *++match && *++scan == *++match &&
  82356. *++scan == *++match && *++scan == *++match &&
  82357. *++scan == *++match && *++scan == *++match &&
  82358. scan < strend);
  82359. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82360. len = MAX_MATCH - (int)(strend - scan);
  82361. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82362. s->match_start = cur_match;
  82363. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82364. }
  82365. #ifdef DEBUG
  82366. /* ===========================================================================
  82367. * Check that the match at match_start is indeed a match.
  82368. */
  82369. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82370. {
  82371. /* check that the match is indeed a match */
  82372. if (zmemcmp(s->window + match,
  82373. s->window + start, length) != EQUAL) {
  82374. fprintf(stderr, " start %u, match %u, length %d\n",
  82375. start, match, length);
  82376. do {
  82377. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82378. } while (--length != 0);
  82379. z_error("invalid match");
  82380. }
  82381. if (z_verbose > 1) {
  82382. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82383. do { putc(s->window[start++], stderr); } while (--length != 0);
  82384. }
  82385. }
  82386. #else
  82387. # define check_match(s, start, match, length)
  82388. #endif /* DEBUG */
  82389. /* ===========================================================================
  82390. * Fill the window when the lookahead becomes insufficient.
  82391. * Updates strstart and lookahead.
  82392. *
  82393. * IN assertion: lookahead < MIN_LOOKAHEAD
  82394. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82395. * At least one byte has been read, or avail_in == 0; reads are
  82396. * performed for at least two bytes (required for the zip translate_eol
  82397. * option -- not supported here).
  82398. */
  82399. local void fill_window (deflate_state *s)
  82400. {
  82401. register unsigned n, m;
  82402. register Posf *p;
  82403. unsigned more; /* Amount of free space at the end of the window. */
  82404. uInt wsize = s->w_size;
  82405. do {
  82406. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82407. /* Deal with !@#$% 64K limit: */
  82408. if (sizeof(int) <= 2) {
  82409. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82410. more = wsize;
  82411. } else if (more == (unsigned)(-1)) {
  82412. /* Very unlikely, but possible on 16 bit machine if
  82413. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82414. */
  82415. more--;
  82416. }
  82417. }
  82418. /* If the window is almost full and there is insufficient lookahead,
  82419. * move the upper half to the lower one to make room in the upper half.
  82420. */
  82421. if (s->strstart >= wsize+MAX_DIST(s)) {
  82422. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82423. s->match_start -= wsize;
  82424. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82425. s->block_start -= (long) wsize;
  82426. /* Slide the hash table (could be avoided with 32 bit values
  82427. at the expense of memory usage). We slide even when level == 0
  82428. to keep the hash table consistent if we switch back to level > 0
  82429. later. (Using level 0 permanently is not an optimal usage of
  82430. zlib, so we don't care about this pathological case.)
  82431. */
  82432. /* %%% avoid this when Z_RLE */
  82433. n = s->hash_size;
  82434. p = &s->head[n];
  82435. do {
  82436. m = *--p;
  82437. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82438. } while (--n);
  82439. n = wsize;
  82440. #ifndef FASTEST
  82441. p = &s->prev[n];
  82442. do {
  82443. m = *--p;
  82444. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82445. /* If n is not on any hash chain, prev[n] is garbage but
  82446. * its value will never be used.
  82447. */
  82448. } while (--n);
  82449. #endif
  82450. more += wsize;
  82451. }
  82452. if (s->strm->avail_in == 0) return;
  82453. /* If there was no sliding:
  82454. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82455. * more == window_size - lookahead - strstart
  82456. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82457. * => more >= window_size - 2*WSIZE + 2
  82458. * In the BIG_MEM or MMAP case (not yet supported),
  82459. * window_size == input_size + MIN_LOOKAHEAD &&
  82460. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82461. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82462. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82463. */
  82464. Assert(more >= 2, "more < 2");
  82465. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82466. s->lookahead += n;
  82467. /* Initialize the hash value now that we have some input: */
  82468. if (s->lookahead >= MIN_MATCH) {
  82469. s->ins_h = s->window[s->strstart];
  82470. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82471. #if MIN_MATCH != 3
  82472. Call UPDATE_HASH() MIN_MATCH-3 more times
  82473. #endif
  82474. }
  82475. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82476. * but this is not important since only literal bytes will be emitted.
  82477. */
  82478. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82479. }
  82480. /* ===========================================================================
  82481. * Flush the current block, with given end-of-file flag.
  82482. * IN assertion: strstart is set to the end of the current match.
  82483. */
  82484. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82485. _tr_flush_block(s, (s->block_start >= 0L ? \
  82486. (charf *)&s->window[(unsigned)s->block_start] : \
  82487. (charf *)Z_NULL), \
  82488. (ulg)((long)s->strstart - s->block_start), \
  82489. (eof)); \
  82490. s->block_start = s->strstart; \
  82491. flush_pending(s->strm); \
  82492. Tracev((stderr,"[FLUSH]")); \
  82493. }
  82494. /* Same but force premature exit if necessary. */
  82495. #define FLUSH_BLOCK(s, eof) { \
  82496. FLUSH_BLOCK_ONLY(s, eof); \
  82497. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82498. }
  82499. /* ===========================================================================
  82500. * Copy without compression as much as possible from the input stream, return
  82501. * the current block state.
  82502. * This function does not insert new strings in the dictionary since
  82503. * uncompressible data is probably not useful. This function is used
  82504. * only for the level=0 compression option.
  82505. * NOTE: this function should be optimized to avoid extra copying from
  82506. * window to pending_buf.
  82507. */
  82508. local block_state deflate_stored(deflate_state *s, int flush)
  82509. {
  82510. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82511. * to pending_buf_size, and each stored block has a 5 byte header:
  82512. */
  82513. ulg max_block_size = 0xffff;
  82514. ulg max_start;
  82515. if (max_block_size > s->pending_buf_size - 5) {
  82516. max_block_size = s->pending_buf_size - 5;
  82517. }
  82518. /* Copy as much as possible from input to output: */
  82519. for (;;) {
  82520. /* Fill the window as much as possible: */
  82521. if (s->lookahead <= 1) {
  82522. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82523. s->block_start >= (long)s->w_size, "slide too late");
  82524. fill_window(s);
  82525. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82526. if (s->lookahead == 0) break; /* flush the current block */
  82527. }
  82528. Assert(s->block_start >= 0L, "block gone");
  82529. s->strstart += s->lookahead;
  82530. s->lookahead = 0;
  82531. /* Emit a stored block if pending_buf will be full: */
  82532. max_start = s->block_start + max_block_size;
  82533. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82534. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82535. s->lookahead = (uInt)(s->strstart - max_start);
  82536. s->strstart = (uInt)max_start;
  82537. FLUSH_BLOCK(s, 0);
  82538. }
  82539. /* Flush if we may have to slide, otherwise block_start may become
  82540. * negative and the data will be gone:
  82541. */
  82542. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82543. FLUSH_BLOCK(s, 0);
  82544. }
  82545. }
  82546. FLUSH_BLOCK(s, flush == Z_FINISH);
  82547. return flush == Z_FINISH ? finish_done : block_done;
  82548. }
  82549. /* ===========================================================================
  82550. * Compress as much as possible from the input stream, return the current
  82551. * block state.
  82552. * This function does not perform lazy evaluation of matches and inserts
  82553. * new strings in the dictionary only for unmatched strings or for short
  82554. * matches. It is used only for the fast compression options.
  82555. */
  82556. local block_state deflate_fast(deflate_state *s, int flush)
  82557. {
  82558. IPos hash_head = NIL; /* head of the hash chain */
  82559. int bflush; /* set if current block must be flushed */
  82560. for (;;) {
  82561. /* Make sure that we always have enough lookahead, except
  82562. * at the end of the input file. We need MAX_MATCH bytes
  82563. * for the next match, plus MIN_MATCH bytes to insert the
  82564. * string following the next match.
  82565. */
  82566. if (s->lookahead < MIN_LOOKAHEAD) {
  82567. fill_window(s);
  82568. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82569. return need_more;
  82570. }
  82571. if (s->lookahead == 0) break; /* flush the current block */
  82572. }
  82573. /* Insert the string window[strstart .. strstart+2] in the
  82574. * dictionary, and set hash_head to the head of the hash chain:
  82575. */
  82576. if (s->lookahead >= MIN_MATCH) {
  82577. INSERT_STRING(s, s->strstart, hash_head);
  82578. }
  82579. /* Find the longest match, discarding those <= prev_length.
  82580. * At this point we have always match_length < MIN_MATCH
  82581. */
  82582. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82583. /* To simplify the code, we prevent matches with the string
  82584. * of window index 0 (in particular we have to avoid a match
  82585. * of the string with itself at the start of the input file).
  82586. */
  82587. #ifdef FASTEST
  82588. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82589. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82590. s->match_length = longest_match_fast (s, hash_head);
  82591. }
  82592. #else
  82593. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82594. s->match_length = longest_match (s, hash_head);
  82595. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82596. s->match_length = longest_match_fast (s, hash_head);
  82597. }
  82598. #endif
  82599. /* longest_match() or longest_match_fast() sets match_start */
  82600. }
  82601. if (s->match_length >= MIN_MATCH) {
  82602. check_match(s, s->strstart, s->match_start, s->match_length);
  82603. _tr_tally_dist(s, s->strstart - s->match_start,
  82604. s->match_length - MIN_MATCH, bflush);
  82605. s->lookahead -= s->match_length;
  82606. /* Insert new strings in the hash table only if the match length
  82607. * is not too large. This saves time but degrades compression.
  82608. */
  82609. #ifndef FASTEST
  82610. if (s->match_length <= s->max_insert_length &&
  82611. s->lookahead >= MIN_MATCH) {
  82612. s->match_length--; /* string at strstart already in table */
  82613. do {
  82614. s->strstart++;
  82615. INSERT_STRING(s, s->strstart, hash_head);
  82616. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82617. * always MIN_MATCH bytes ahead.
  82618. */
  82619. } while (--s->match_length != 0);
  82620. s->strstart++;
  82621. } else
  82622. #endif
  82623. {
  82624. s->strstart += s->match_length;
  82625. s->match_length = 0;
  82626. s->ins_h = s->window[s->strstart];
  82627. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82628. #if MIN_MATCH != 3
  82629. Call UPDATE_HASH() MIN_MATCH-3 more times
  82630. #endif
  82631. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82632. * matter since it will be recomputed at next deflate call.
  82633. */
  82634. }
  82635. } else {
  82636. /* No match, output a literal byte */
  82637. Tracevv((stderr,"%c", s->window[s->strstart]));
  82638. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82639. s->lookahead--;
  82640. s->strstart++;
  82641. }
  82642. if (bflush) FLUSH_BLOCK(s, 0);
  82643. }
  82644. FLUSH_BLOCK(s, flush == Z_FINISH);
  82645. return flush == Z_FINISH ? finish_done : block_done;
  82646. }
  82647. #ifndef FASTEST
  82648. /* ===========================================================================
  82649. * Same as above, but achieves better compression. We use a lazy
  82650. * evaluation for matches: a match is finally adopted only if there is
  82651. * no better match at the next window position.
  82652. */
  82653. local block_state deflate_slow(deflate_state *s, int flush)
  82654. {
  82655. IPos hash_head = NIL; /* head of hash chain */
  82656. int bflush; /* set if current block must be flushed */
  82657. /* Process the input block. */
  82658. for (;;) {
  82659. /* Make sure that we always have enough lookahead, except
  82660. * at the end of the input file. We need MAX_MATCH bytes
  82661. * for the next match, plus MIN_MATCH bytes to insert the
  82662. * string following the next match.
  82663. */
  82664. if (s->lookahead < MIN_LOOKAHEAD) {
  82665. fill_window(s);
  82666. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82667. return need_more;
  82668. }
  82669. if (s->lookahead == 0) break; /* flush the current block */
  82670. }
  82671. /* Insert the string window[strstart .. strstart+2] in the
  82672. * dictionary, and set hash_head to the head of the hash chain:
  82673. */
  82674. if (s->lookahead >= MIN_MATCH) {
  82675. INSERT_STRING(s, s->strstart, hash_head);
  82676. }
  82677. /* Find the longest match, discarding those <= prev_length.
  82678. */
  82679. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82680. s->match_length = MIN_MATCH-1;
  82681. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82682. s->strstart - hash_head <= MAX_DIST(s)) {
  82683. /* To simplify the code, we prevent matches with the string
  82684. * of window index 0 (in particular we have to avoid a match
  82685. * of the string with itself at the start of the input file).
  82686. */
  82687. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82688. s->match_length = longest_match (s, hash_head);
  82689. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82690. s->match_length = longest_match_fast (s, hash_head);
  82691. }
  82692. /* longest_match() or longest_match_fast() sets match_start */
  82693. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82694. #if TOO_FAR <= 32767
  82695. || (s->match_length == MIN_MATCH &&
  82696. s->strstart - s->match_start > TOO_FAR)
  82697. #endif
  82698. )) {
  82699. /* If prev_match is also MIN_MATCH, match_start is garbage
  82700. * but we will ignore the current match anyway.
  82701. */
  82702. s->match_length = MIN_MATCH-1;
  82703. }
  82704. }
  82705. /* If there was a match at the previous step and the current
  82706. * match is not better, output the previous match:
  82707. */
  82708. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82709. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82710. /* Do not insert strings in hash table beyond this. */
  82711. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82712. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82713. s->prev_length - MIN_MATCH, bflush);
  82714. /* Insert in hash table all strings up to the end of the match.
  82715. * strstart-1 and strstart are already inserted. If there is not
  82716. * enough lookahead, the last two strings are not inserted in
  82717. * the hash table.
  82718. */
  82719. s->lookahead -= s->prev_length-1;
  82720. s->prev_length -= 2;
  82721. do {
  82722. if (++s->strstart <= max_insert) {
  82723. INSERT_STRING(s, s->strstart, hash_head);
  82724. }
  82725. } while (--s->prev_length != 0);
  82726. s->match_available = 0;
  82727. s->match_length = MIN_MATCH-1;
  82728. s->strstart++;
  82729. if (bflush) FLUSH_BLOCK(s, 0);
  82730. } else if (s->match_available) {
  82731. /* If there was no match at the previous position, output a
  82732. * single literal. If there was a match but the current match
  82733. * is longer, truncate the previous match to a single literal.
  82734. */
  82735. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82736. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82737. if (bflush) {
  82738. FLUSH_BLOCK_ONLY(s, 0);
  82739. }
  82740. s->strstart++;
  82741. s->lookahead--;
  82742. if (s->strm->avail_out == 0) return need_more;
  82743. } else {
  82744. /* There is no previous match to compare with, wait for
  82745. * the next step to decide.
  82746. */
  82747. s->match_available = 1;
  82748. s->strstart++;
  82749. s->lookahead--;
  82750. }
  82751. }
  82752. Assert (flush != Z_NO_FLUSH, "no flush?");
  82753. if (s->match_available) {
  82754. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82755. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82756. s->match_available = 0;
  82757. }
  82758. FLUSH_BLOCK(s, flush == Z_FINISH);
  82759. return flush == Z_FINISH ? finish_done : block_done;
  82760. }
  82761. #endif /* FASTEST */
  82762. #if 0
  82763. /* ===========================================================================
  82764. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82765. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82766. * deflate switches away from Z_RLE.)
  82767. */
  82768. local block_state deflate_rle(s, flush)
  82769. deflate_state *s;
  82770. int flush;
  82771. {
  82772. int bflush; /* set if current block must be flushed */
  82773. uInt run; /* length of run */
  82774. uInt max; /* maximum length of run */
  82775. uInt prev; /* byte at distance one to match */
  82776. Bytef *scan; /* scan for end of run */
  82777. for (;;) {
  82778. /* Make sure that we always have enough lookahead, except
  82779. * at the end of the input file. We need MAX_MATCH bytes
  82780. * for the longest encodable run.
  82781. */
  82782. if (s->lookahead < MAX_MATCH) {
  82783. fill_window(s);
  82784. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82785. return need_more;
  82786. }
  82787. if (s->lookahead == 0) break; /* flush the current block */
  82788. }
  82789. /* See how many times the previous byte repeats */
  82790. run = 0;
  82791. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82792. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82793. scan = s->window + s->strstart - 1;
  82794. prev = *scan++;
  82795. do {
  82796. if (*scan++ != prev)
  82797. break;
  82798. } while (++run < max);
  82799. }
  82800. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82801. if (run >= MIN_MATCH) {
  82802. check_match(s, s->strstart, s->strstart - 1, run);
  82803. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82804. s->lookahead -= run;
  82805. s->strstart += run;
  82806. } else {
  82807. /* No match, output a literal byte */
  82808. Tracevv((stderr,"%c", s->window[s->strstart]));
  82809. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82810. s->lookahead--;
  82811. s->strstart++;
  82812. }
  82813. if (bflush) FLUSH_BLOCK(s, 0);
  82814. }
  82815. FLUSH_BLOCK(s, flush == Z_FINISH);
  82816. return flush == Z_FINISH ? finish_done : block_done;
  82817. }
  82818. #endif
  82819. /*** End of inlined file: deflate.c ***/
  82820. /*** Start of inlined file: inffast.c ***/
  82821. /*** Start of inlined file: inftrees.h ***/
  82822. /* WARNING: this file should *not* be used by applications. It is
  82823. part of the implementation of the compression library and is
  82824. subject to change. Applications should only use zlib.h.
  82825. */
  82826. #ifndef _INFTREES_H_
  82827. #define _INFTREES_H_
  82828. /* Structure for decoding tables. Each entry provides either the
  82829. information needed to do the operation requested by the code that
  82830. indexed that table entry, or it provides a pointer to another
  82831. table that indexes more bits of the code. op indicates whether
  82832. the entry is a pointer to another table, a literal, a length or
  82833. distance, an end-of-block, or an invalid code. For a table
  82834. pointer, the low four bits of op is the number of index bits of
  82835. that table. For a length or distance, the low four bits of op
  82836. is the number of extra bits to get after the code. bits is
  82837. the number of bits in this code or part of the code to drop off
  82838. of the bit buffer. val is the actual byte to output in the case
  82839. of a literal, the base length or distance, or the offset from
  82840. the current table to the next table. Each entry is four bytes. */
  82841. typedef struct {
  82842. unsigned char op; /* operation, extra bits, table bits */
  82843. unsigned char bits; /* bits in this part of the code */
  82844. unsigned short val; /* offset in table or code value */
  82845. } code;
  82846. /* op values as set by inflate_table():
  82847. 00000000 - literal
  82848. 0000tttt - table link, tttt != 0 is the number of table index bits
  82849. 0001eeee - length or distance, eeee is the number of extra bits
  82850. 01100000 - end of block
  82851. 01000000 - invalid code
  82852. */
  82853. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82854. exhaustive search was 1444 code structures (852 for length/literals
  82855. and 592 for distances, the latter actually the result of an
  82856. exhaustive search). The true maximum is not known, but the value
  82857. below is more than safe. */
  82858. #define ENOUGH 2048
  82859. #define MAXD 592
  82860. /* Type of code to build for inftable() */
  82861. typedef enum {
  82862. CODES,
  82863. LENS,
  82864. DISTS
  82865. } codetype;
  82866. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82867. unsigned codes, code FAR * FAR *table,
  82868. unsigned FAR *bits, unsigned short FAR *work));
  82869. #endif
  82870. /*** End of inlined file: inftrees.h ***/
  82871. /*** Start of inlined file: inflate.h ***/
  82872. /* WARNING: this file should *not* be used by applications. It is
  82873. part of the implementation of the compression library and is
  82874. subject to change. Applications should only use zlib.h.
  82875. */
  82876. #ifndef _INFLATE_H_
  82877. #define _INFLATE_H_
  82878. /* define NO_GZIP when compiling if you want to disable gzip header and
  82879. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82880. the crc code when it is not needed. For shared libraries, gzip decoding
  82881. should be left enabled. */
  82882. #ifndef NO_GZIP
  82883. # define GUNZIP
  82884. #endif
  82885. /* Possible inflate modes between inflate() calls */
  82886. typedef enum {
  82887. HEAD, /* i: waiting for magic header */
  82888. FLAGS, /* i: waiting for method and flags (gzip) */
  82889. TIME, /* i: waiting for modification time (gzip) */
  82890. OS, /* i: waiting for extra flags and operating system (gzip) */
  82891. EXLEN, /* i: waiting for extra length (gzip) */
  82892. EXTRA, /* i: waiting for extra bytes (gzip) */
  82893. NAME, /* i: waiting for end of file name (gzip) */
  82894. COMMENT, /* i: waiting for end of comment (gzip) */
  82895. HCRC, /* i: waiting for header crc (gzip) */
  82896. DICTID, /* i: waiting for dictionary check value */
  82897. DICT, /* waiting for inflateSetDictionary() call */
  82898. TYPE, /* i: waiting for type bits, including last-flag bit */
  82899. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82900. STORED, /* i: waiting for stored size (length and complement) */
  82901. COPY, /* i/o: waiting for input or output to copy stored block */
  82902. TABLE, /* i: waiting for dynamic block table lengths */
  82903. LENLENS, /* i: waiting for code length code lengths */
  82904. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82905. LEN, /* i: waiting for length/lit code */
  82906. LENEXT, /* i: waiting for length extra bits */
  82907. DIST, /* i: waiting for distance code */
  82908. DISTEXT, /* i: waiting for distance extra bits */
  82909. MATCH, /* o: waiting for output space to copy string */
  82910. LIT, /* o: waiting for output space to write literal */
  82911. CHECK, /* i: waiting for 32-bit check value */
  82912. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82913. DONE, /* finished check, done -- remain here until reset */
  82914. BAD, /* got a data error -- remain here until reset */
  82915. MEM, /* got an inflate() memory error -- remain here until reset */
  82916. SYNC /* looking for synchronization bytes to restart inflate() */
  82917. } inflate_mode;
  82918. /*
  82919. State transitions between above modes -
  82920. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82921. Process header:
  82922. HEAD -> (gzip) or (zlib)
  82923. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82924. NAME -> COMMENT -> HCRC -> TYPE
  82925. (zlib) -> DICTID or TYPE
  82926. DICTID -> DICT -> TYPE
  82927. Read deflate blocks:
  82928. TYPE -> STORED or TABLE or LEN or CHECK
  82929. STORED -> COPY -> TYPE
  82930. TABLE -> LENLENS -> CODELENS -> LEN
  82931. Read deflate codes:
  82932. LEN -> LENEXT or LIT or TYPE
  82933. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82934. LIT -> LEN
  82935. Process trailer:
  82936. CHECK -> LENGTH -> DONE
  82937. */
  82938. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82939. struct inflate_state {
  82940. inflate_mode mode; /* current inflate mode */
  82941. int last; /* true if processing last block */
  82942. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82943. int havedict; /* true if dictionary provided */
  82944. int flags; /* gzip header method and flags (0 if zlib) */
  82945. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82946. unsigned long check; /* protected copy of check value */
  82947. unsigned long total; /* protected copy of output count */
  82948. gz_headerp head; /* where to save gzip header information */
  82949. /* sliding window */
  82950. unsigned wbits; /* log base 2 of requested window size */
  82951. unsigned wsize; /* window size or zero if not using window */
  82952. unsigned whave; /* valid bytes in the window */
  82953. unsigned write; /* window write index */
  82954. unsigned char FAR *window; /* allocated sliding window, if needed */
  82955. /* bit accumulator */
  82956. unsigned long hold; /* input bit accumulator */
  82957. unsigned bits; /* number of bits in "in" */
  82958. /* for string and stored block copying */
  82959. unsigned length; /* literal or length of data to copy */
  82960. unsigned offset; /* distance back to copy string from */
  82961. /* for table and code decoding */
  82962. unsigned extra; /* extra bits needed */
  82963. /* fixed and dynamic code tables */
  82964. code const FAR *lencode; /* starting table for length/literal codes */
  82965. code const FAR *distcode; /* starting table for distance codes */
  82966. unsigned lenbits; /* index bits for lencode */
  82967. unsigned distbits; /* index bits for distcode */
  82968. /* dynamic table building */
  82969. unsigned ncode; /* number of code length code lengths */
  82970. unsigned nlen; /* number of length code lengths */
  82971. unsigned ndist; /* number of distance code lengths */
  82972. unsigned have; /* number of code lengths in lens[] */
  82973. code FAR *next; /* next available space in codes[] */
  82974. unsigned short lens[320]; /* temporary storage for code lengths */
  82975. unsigned short work[288]; /* work area for code table building */
  82976. code codes[ENOUGH]; /* space for code tables */
  82977. };
  82978. #endif
  82979. /*** End of inlined file: inflate.h ***/
  82980. /*** Start of inlined file: inffast.h ***/
  82981. /* WARNING: this file should *not* be used by applications. It is
  82982. part of the implementation of the compression library and is
  82983. subject to change. Applications should only use zlib.h.
  82984. */
  82985. void inflate_fast OF((z_streamp strm, unsigned start));
  82986. /*** End of inlined file: inffast.h ***/
  82987. #ifndef ASMINF
  82988. /* Allow machine dependent optimization for post-increment or pre-increment.
  82989. Based on testing to date,
  82990. Pre-increment preferred for:
  82991. - PowerPC G3 (Adler)
  82992. - MIPS R5000 (Randers-Pehrson)
  82993. Post-increment preferred for:
  82994. - none
  82995. No measurable difference:
  82996. - Pentium III (Anderson)
  82997. - M68060 (Nikl)
  82998. */
  82999. #ifdef POSTINC
  83000. # define OFF 0
  83001. # define PUP(a) *(a)++
  83002. #else
  83003. # define OFF 1
  83004. # define PUP(a) *++(a)
  83005. #endif
  83006. /*
  83007. Decode literal, length, and distance codes and write out the resulting
  83008. literal and match bytes until either not enough input or output is
  83009. available, an end-of-block is encountered, or a data error is encountered.
  83010. When large enough input and output buffers are supplied to inflate(), for
  83011. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  83012. inflate execution time is spent in this routine.
  83013. Entry assumptions:
  83014. state->mode == LEN
  83015. strm->avail_in >= 6
  83016. strm->avail_out >= 258
  83017. start >= strm->avail_out
  83018. state->bits < 8
  83019. On return, state->mode is one of:
  83020. LEN -- ran out of enough output space or enough available input
  83021. TYPE -- reached end of block code, inflate() to interpret next block
  83022. BAD -- error in block data
  83023. Notes:
  83024. - The maximum input bits used by a length/distance pair is 15 bits for the
  83025. length code, 5 bits for the length extra, 15 bits for the distance code,
  83026. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  83027. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  83028. checking for available input while decoding.
  83029. - The maximum bytes that a single length/distance pair can output is 258
  83030. bytes, which is the maximum length that can be coded. inflate_fast()
  83031. requires strm->avail_out >= 258 for each loop to avoid checking for
  83032. output space.
  83033. */
  83034. void inflate_fast (z_streamp strm, unsigned start)
  83035. {
  83036. struct inflate_state FAR *state;
  83037. unsigned char FAR *in; /* local strm->next_in */
  83038. unsigned char FAR *last; /* while in < last, enough input available */
  83039. unsigned char FAR *out; /* local strm->next_out */
  83040. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  83041. unsigned char FAR *end; /* while out < end, enough space available */
  83042. #ifdef INFLATE_STRICT
  83043. unsigned dmax; /* maximum distance from zlib header */
  83044. #endif
  83045. unsigned wsize; /* window size or zero if not using window */
  83046. unsigned whave; /* valid bytes in the window */
  83047. unsigned write; /* window write index */
  83048. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  83049. unsigned long hold; /* local strm->hold */
  83050. unsigned bits; /* local strm->bits */
  83051. code const FAR *lcode; /* local strm->lencode */
  83052. code const FAR *dcode; /* local strm->distcode */
  83053. unsigned lmask; /* mask for first level of length codes */
  83054. unsigned dmask; /* mask for first level of distance codes */
  83055. code thisx; /* retrieved table entry */
  83056. unsigned op; /* code bits, operation, extra bits, or */
  83057. /* window position, window bytes to copy */
  83058. unsigned len; /* match length, unused bytes */
  83059. unsigned dist; /* match distance */
  83060. unsigned char FAR *from; /* where to copy match from */
  83061. /* copy state to local variables */
  83062. state = (struct inflate_state FAR *)strm->state;
  83063. in = strm->next_in - OFF;
  83064. last = in + (strm->avail_in - 5);
  83065. out = strm->next_out - OFF;
  83066. beg = out - (start - strm->avail_out);
  83067. end = out + (strm->avail_out - 257);
  83068. #ifdef INFLATE_STRICT
  83069. dmax = state->dmax;
  83070. #endif
  83071. wsize = state->wsize;
  83072. whave = state->whave;
  83073. write = state->write;
  83074. window = state->window;
  83075. hold = state->hold;
  83076. bits = state->bits;
  83077. lcode = state->lencode;
  83078. dcode = state->distcode;
  83079. lmask = (1U << state->lenbits) - 1;
  83080. dmask = (1U << state->distbits) - 1;
  83081. /* decode literals and length/distances until end-of-block or not enough
  83082. input data or output space */
  83083. do {
  83084. if (bits < 15) {
  83085. hold += (unsigned long)(PUP(in)) << bits;
  83086. bits += 8;
  83087. hold += (unsigned long)(PUP(in)) << bits;
  83088. bits += 8;
  83089. }
  83090. thisx = lcode[hold & lmask];
  83091. dolen:
  83092. op = (unsigned)(thisx.bits);
  83093. hold >>= op;
  83094. bits -= op;
  83095. op = (unsigned)(thisx.op);
  83096. if (op == 0) { /* literal */
  83097. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83098. "inflate: literal '%c'\n" :
  83099. "inflate: literal 0x%02x\n", thisx.val));
  83100. PUP(out) = (unsigned char)(thisx.val);
  83101. }
  83102. else if (op & 16) { /* length base */
  83103. len = (unsigned)(thisx.val);
  83104. op &= 15; /* number of extra bits */
  83105. if (op) {
  83106. if (bits < op) {
  83107. hold += (unsigned long)(PUP(in)) << bits;
  83108. bits += 8;
  83109. }
  83110. len += (unsigned)hold & ((1U << op) - 1);
  83111. hold >>= op;
  83112. bits -= op;
  83113. }
  83114. Tracevv((stderr, "inflate: length %u\n", len));
  83115. if (bits < 15) {
  83116. hold += (unsigned long)(PUP(in)) << bits;
  83117. bits += 8;
  83118. hold += (unsigned long)(PUP(in)) << bits;
  83119. bits += 8;
  83120. }
  83121. thisx = dcode[hold & dmask];
  83122. dodist:
  83123. op = (unsigned)(thisx.bits);
  83124. hold >>= op;
  83125. bits -= op;
  83126. op = (unsigned)(thisx.op);
  83127. if (op & 16) { /* distance base */
  83128. dist = (unsigned)(thisx.val);
  83129. op &= 15; /* number of extra bits */
  83130. if (bits < op) {
  83131. hold += (unsigned long)(PUP(in)) << bits;
  83132. bits += 8;
  83133. if (bits < op) {
  83134. hold += (unsigned long)(PUP(in)) << bits;
  83135. bits += 8;
  83136. }
  83137. }
  83138. dist += (unsigned)hold & ((1U << op) - 1);
  83139. #ifdef INFLATE_STRICT
  83140. if (dist > dmax) {
  83141. strm->msg = (char *)"invalid distance too far back";
  83142. state->mode = BAD;
  83143. break;
  83144. }
  83145. #endif
  83146. hold >>= op;
  83147. bits -= op;
  83148. Tracevv((stderr, "inflate: distance %u\n", dist));
  83149. op = (unsigned)(out - beg); /* max distance in output */
  83150. if (dist > op) { /* see if copy from window */
  83151. op = dist - op; /* distance back in window */
  83152. if (op > whave) {
  83153. strm->msg = (char *)"invalid distance too far back";
  83154. state->mode = BAD;
  83155. break;
  83156. }
  83157. from = window - OFF;
  83158. if (write == 0) { /* very common case */
  83159. from += wsize - op;
  83160. if (op < len) { /* some from window */
  83161. len -= op;
  83162. do {
  83163. PUP(out) = PUP(from);
  83164. } while (--op);
  83165. from = out - dist; /* rest from output */
  83166. }
  83167. }
  83168. else if (write < op) { /* wrap around window */
  83169. from += wsize + write - op;
  83170. op -= write;
  83171. if (op < len) { /* some from end of window */
  83172. len -= op;
  83173. do {
  83174. PUP(out) = PUP(from);
  83175. } while (--op);
  83176. from = window - OFF;
  83177. if (write < len) { /* some from start of window */
  83178. op = write;
  83179. len -= op;
  83180. do {
  83181. PUP(out) = PUP(from);
  83182. } while (--op);
  83183. from = out - dist; /* rest from output */
  83184. }
  83185. }
  83186. }
  83187. else { /* contiguous in window */
  83188. from += write - op;
  83189. if (op < len) { /* some from window */
  83190. len -= op;
  83191. do {
  83192. PUP(out) = PUP(from);
  83193. } while (--op);
  83194. from = out - dist; /* rest from output */
  83195. }
  83196. }
  83197. while (len > 2) {
  83198. PUP(out) = PUP(from);
  83199. PUP(out) = PUP(from);
  83200. PUP(out) = PUP(from);
  83201. len -= 3;
  83202. }
  83203. if (len) {
  83204. PUP(out) = PUP(from);
  83205. if (len > 1)
  83206. PUP(out) = PUP(from);
  83207. }
  83208. }
  83209. else {
  83210. from = out - dist; /* copy direct from output */
  83211. do { /* minimum length is three */
  83212. PUP(out) = PUP(from);
  83213. PUP(out) = PUP(from);
  83214. PUP(out) = PUP(from);
  83215. len -= 3;
  83216. } while (len > 2);
  83217. if (len) {
  83218. PUP(out) = PUP(from);
  83219. if (len > 1)
  83220. PUP(out) = PUP(from);
  83221. }
  83222. }
  83223. }
  83224. else if ((op & 64) == 0) { /* 2nd level distance code */
  83225. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83226. goto dodist;
  83227. }
  83228. else {
  83229. strm->msg = (char *)"invalid distance code";
  83230. state->mode = BAD;
  83231. break;
  83232. }
  83233. }
  83234. else if ((op & 64) == 0) { /* 2nd level length code */
  83235. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83236. goto dolen;
  83237. }
  83238. else if (op & 32) { /* end-of-block */
  83239. Tracevv((stderr, "inflate: end of block\n"));
  83240. state->mode = TYPE;
  83241. break;
  83242. }
  83243. else {
  83244. strm->msg = (char *)"invalid literal/length code";
  83245. state->mode = BAD;
  83246. break;
  83247. }
  83248. } while (in < last && out < end);
  83249. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83250. len = bits >> 3;
  83251. in -= len;
  83252. bits -= len << 3;
  83253. hold &= (1U << bits) - 1;
  83254. /* update state and return */
  83255. strm->next_in = in + OFF;
  83256. strm->next_out = out + OFF;
  83257. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83258. strm->avail_out = (unsigned)(out < end ?
  83259. 257 + (end - out) : 257 - (out - end));
  83260. state->hold = hold;
  83261. state->bits = bits;
  83262. return;
  83263. }
  83264. /*
  83265. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83266. - Using bit fields for code structure
  83267. - Different op definition to avoid & for extra bits (do & for table bits)
  83268. - Three separate decoding do-loops for direct, window, and write == 0
  83269. - Special case for distance > 1 copies to do overlapped load and store copy
  83270. - Explicit branch predictions (based on measured branch probabilities)
  83271. - Deferring match copy and interspersed it with decoding subsequent codes
  83272. - Swapping literal/length else
  83273. - Swapping window/direct else
  83274. - Larger unrolled copy loops (three is about right)
  83275. - Moving len -= 3 statement into middle of loop
  83276. */
  83277. #endif /* !ASMINF */
  83278. /*** End of inlined file: inffast.c ***/
  83279. #undef PULLBYTE
  83280. #undef LOAD
  83281. #undef RESTORE
  83282. #undef INITBITS
  83283. #undef NEEDBITS
  83284. #undef DROPBITS
  83285. #undef BYTEBITS
  83286. /*** Start of inlined file: inflate.c ***/
  83287. /*
  83288. * Change history:
  83289. *
  83290. * 1.2.beta0 24 Nov 2002
  83291. * - First version -- complete rewrite of inflate to simplify code, avoid
  83292. * creation of window when not needed, minimize use of window when it is
  83293. * needed, make inffast.c even faster, implement gzip decoding, and to
  83294. * improve code readability and style over the previous zlib inflate code
  83295. *
  83296. * 1.2.beta1 25 Nov 2002
  83297. * - Use pointers for available input and output checking in inffast.c
  83298. * - Remove input and output counters in inffast.c
  83299. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83300. * - Remove unnecessary second byte pull from length extra in inffast.c
  83301. * - Unroll direct copy to three copies per loop in inffast.c
  83302. *
  83303. * 1.2.beta2 4 Dec 2002
  83304. * - Change external routine names to reduce potential conflicts
  83305. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83306. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83307. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83308. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83309. *
  83310. * 1.2.beta3 22 Dec 2002
  83311. * - Add comments on state->bits assertion in inffast.c
  83312. * - Add comments on op field in inftrees.h
  83313. * - Fix bug in reuse of allocated window after inflateReset()
  83314. * - Remove bit fields--back to byte structure for speed
  83315. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83316. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83317. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83318. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83319. * - Use local copies of stream next and avail values, as well as local bit
  83320. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83321. *
  83322. * 1.2.beta4 1 Jan 2003
  83323. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83324. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83325. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83326. * - Rearrange window copies in inflate_fast() for speed and simplification
  83327. * - Unroll last copy for window match in inflate_fast()
  83328. * - Use local copies of window variables in inflate_fast() for speed
  83329. * - Pull out common write == 0 case for speed in inflate_fast()
  83330. * - Make op and len in inflate_fast() unsigned for consistency
  83331. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83332. * - Simplified bad distance check in inflate_fast()
  83333. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83334. * source file infback.c to provide a call-back interface to inflate for
  83335. * programs like gzip and unzip -- uses window as output buffer to avoid
  83336. * window copying
  83337. *
  83338. * 1.2.beta5 1 Jan 2003
  83339. * - Improved inflateBack() interface to allow the caller to provide initial
  83340. * input in strm.
  83341. * - Fixed stored blocks bug in inflateBack()
  83342. *
  83343. * 1.2.beta6 4 Jan 2003
  83344. * - Added comments in inffast.c on effectiveness of POSTINC
  83345. * - Typecasting all around to reduce compiler warnings
  83346. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83347. * make compilers happy
  83348. * - Changed type of window in inflateBackInit() to unsigned char *
  83349. *
  83350. * 1.2.beta7 27 Jan 2003
  83351. * - Changed many types to unsigned or unsigned short to avoid warnings
  83352. * - Added inflateCopy() function
  83353. *
  83354. * 1.2.0 9 Mar 2003
  83355. * - Changed inflateBack() interface to provide separate opaque descriptors
  83356. * for the in() and out() functions
  83357. * - Changed inflateBack() argument and in_func typedef to swap the length
  83358. * and buffer address return values for the input function
  83359. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83360. *
  83361. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83362. */
  83363. /*** Start of inlined file: inffast.h ***/
  83364. /* WARNING: this file should *not* be used by applications. It is
  83365. part of the implementation of the compression library and is
  83366. subject to change. Applications should only use zlib.h.
  83367. */
  83368. void inflate_fast OF((z_streamp strm, unsigned start));
  83369. /*** End of inlined file: inffast.h ***/
  83370. #ifdef MAKEFIXED
  83371. # ifndef BUILDFIXED
  83372. # define BUILDFIXED
  83373. # endif
  83374. #endif
  83375. /* function prototypes */
  83376. local void fixedtables OF((struct inflate_state FAR *state));
  83377. local int updatewindow OF((z_streamp strm, unsigned out));
  83378. #ifdef BUILDFIXED
  83379. void makefixed OF((void));
  83380. #endif
  83381. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83382. unsigned len));
  83383. int ZEXPORT inflateReset (z_streamp strm)
  83384. {
  83385. struct inflate_state FAR *state;
  83386. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83387. state = (struct inflate_state FAR *)strm->state;
  83388. strm->total_in = strm->total_out = state->total = 0;
  83389. strm->msg = Z_NULL;
  83390. strm->adler = 1; /* to support ill-conceived Java test suite */
  83391. state->mode = HEAD;
  83392. state->last = 0;
  83393. state->havedict = 0;
  83394. state->dmax = 32768U;
  83395. state->head = Z_NULL;
  83396. state->wsize = 0;
  83397. state->whave = 0;
  83398. state->write = 0;
  83399. state->hold = 0;
  83400. state->bits = 0;
  83401. state->lencode = state->distcode = state->next = state->codes;
  83402. Tracev((stderr, "inflate: reset\n"));
  83403. return Z_OK;
  83404. }
  83405. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83406. {
  83407. struct inflate_state FAR *state;
  83408. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83409. state = (struct inflate_state FAR *)strm->state;
  83410. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83411. value &= (1L << bits) - 1;
  83412. state->hold += value << state->bits;
  83413. state->bits += bits;
  83414. return Z_OK;
  83415. }
  83416. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83417. {
  83418. struct inflate_state FAR *state;
  83419. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83420. stream_size != (int)(sizeof(z_stream)))
  83421. return Z_VERSION_ERROR;
  83422. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83423. strm->msg = Z_NULL; /* in case we return an error */
  83424. if (strm->zalloc == (alloc_func)0) {
  83425. strm->zalloc = zcalloc;
  83426. strm->opaque = (voidpf)0;
  83427. }
  83428. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83429. state = (struct inflate_state FAR *)
  83430. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83431. if (state == Z_NULL) return Z_MEM_ERROR;
  83432. Tracev((stderr, "inflate: allocated\n"));
  83433. strm->state = (struct internal_state FAR *)state;
  83434. if (windowBits < 0) {
  83435. state->wrap = 0;
  83436. windowBits = -windowBits;
  83437. }
  83438. else {
  83439. state->wrap = (windowBits >> 4) + 1;
  83440. #ifdef GUNZIP
  83441. if (windowBits < 48) windowBits &= 15;
  83442. #endif
  83443. }
  83444. if (windowBits < 8 || windowBits > 15) {
  83445. ZFREE(strm, state);
  83446. strm->state = Z_NULL;
  83447. return Z_STREAM_ERROR;
  83448. }
  83449. state->wbits = (unsigned)windowBits;
  83450. state->window = Z_NULL;
  83451. return inflateReset(strm);
  83452. }
  83453. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83454. {
  83455. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83456. }
  83457. /*
  83458. Return state with length and distance decoding tables and index sizes set to
  83459. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83460. If BUILDFIXED is defined, then instead this routine builds the tables the
  83461. first time it's called, and returns those tables the first time and
  83462. thereafter. This reduces the size of the code by about 2K bytes, in
  83463. exchange for a little execution time. However, BUILDFIXED should not be
  83464. used for threaded applications, since the rewriting of the tables and virgin
  83465. may not be thread-safe.
  83466. */
  83467. local void fixedtables (struct inflate_state FAR *state)
  83468. {
  83469. #ifdef BUILDFIXED
  83470. static int virgin = 1;
  83471. static code *lenfix, *distfix;
  83472. static code fixed[544];
  83473. /* build fixed huffman tables if first call (may not be thread safe) */
  83474. if (virgin) {
  83475. unsigned sym, bits;
  83476. static code *next;
  83477. /* literal/length table */
  83478. sym = 0;
  83479. while (sym < 144) state->lens[sym++] = 8;
  83480. while (sym < 256) state->lens[sym++] = 9;
  83481. while (sym < 280) state->lens[sym++] = 7;
  83482. while (sym < 288) state->lens[sym++] = 8;
  83483. next = fixed;
  83484. lenfix = next;
  83485. bits = 9;
  83486. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83487. /* distance table */
  83488. sym = 0;
  83489. while (sym < 32) state->lens[sym++] = 5;
  83490. distfix = next;
  83491. bits = 5;
  83492. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83493. /* do this just once */
  83494. virgin = 0;
  83495. }
  83496. #else /* !BUILDFIXED */
  83497. /*** Start of inlined file: inffixed.h ***/
  83498. /* WARNING: this file should *not* be used by applications. It
  83499. is part of the implementation of the compression library and
  83500. is subject to change. Applications should only use zlib.h.
  83501. */
  83502. static const code lenfix[512] = {
  83503. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83504. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83505. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83506. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83507. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83508. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83509. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83510. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83511. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83512. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83513. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83514. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83515. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83516. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83517. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83518. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83519. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83520. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83521. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83522. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83523. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83524. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83525. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83526. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83527. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83528. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83529. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83530. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83531. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83532. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83533. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83534. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83535. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83536. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83537. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83538. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83539. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83540. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83541. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83542. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83543. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83544. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83545. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83546. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83547. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83548. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83549. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83550. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83551. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83552. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83553. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83554. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83555. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83556. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83557. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83558. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83559. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83560. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83561. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83562. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83563. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83564. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83565. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83566. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83567. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83568. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83569. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83570. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83571. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83572. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83573. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83574. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83575. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83576. {0,9,255}
  83577. };
  83578. static const code distfix[32] = {
  83579. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83580. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83581. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83582. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83583. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83584. {22,5,193},{64,5,0}
  83585. };
  83586. /*** End of inlined file: inffixed.h ***/
  83587. #endif /* BUILDFIXED */
  83588. state->lencode = lenfix;
  83589. state->lenbits = 9;
  83590. state->distcode = distfix;
  83591. state->distbits = 5;
  83592. }
  83593. #ifdef MAKEFIXED
  83594. #include <stdio.h>
  83595. /*
  83596. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83597. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83598. those tables to stdout, which would be piped to inffixed.h. A small program
  83599. can simply call makefixed to do this:
  83600. void makefixed(void);
  83601. int main(void)
  83602. {
  83603. makefixed();
  83604. return 0;
  83605. }
  83606. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83607. a.out > inffixed.h
  83608. */
  83609. void makefixed()
  83610. {
  83611. unsigned low, size;
  83612. struct inflate_state state;
  83613. fixedtables(&state);
  83614. puts(" /* inffixed.h -- table for decoding fixed codes");
  83615. puts(" * Generated automatically by makefixed().");
  83616. puts(" */");
  83617. puts("");
  83618. puts(" /* WARNING: this file should *not* be used by applications.");
  83619. puts(" It is part of the implementation of this library and is");
  83620. puts(" subject to change. Applications should only use zlib.h.");
  83621. puts(" */");
  83622. puts("");
  83623. size = 1U << 9;
  83624. printf(" static const code lenfix[%u] = {", size);
  83625. low = 0;
  83626. for (;;) {
  83627. if ((low % 7) == 0) printf("\n ");
  83628. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83629. state.lencode[low].val);
  83630. if (++low == size) break;
  83631. putchar(',');
  83632. }
  83633. puts("\n };");
  83634. size = 1U << 5;
  83635. printf("\n static const code distfix[%u] = {", size);
  83636. low = 0;
  83637. for (;;) {
  83638. if ((low % 6) == 0) printf("\n ");
  83639. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83640. state.distcode[low].val);
  83641. if (++low == size) break;
  83642. putchar(',');
  83643. }
  83644. puts("\n };");
  83645. }
  83646. #endif /* MAKEFIXED */
  83647. /*
  83648. Update the window with the last wsize (normally 32K) bytes written before
  83649. returning. If window does not exist yet, create it. This is only called
  83650. when a window is already in use, or when output has been written during this
  83651. inflate call, but the end of the deflate stream has not been reached yet.
  83652. It is also called to create a window for dictionary data when a dictionary
  83653. is loaded.
  83654. Providing output buffers larger than 32K to inflate() should provide a speed
  83655. advantage, since only the last 32K of output is copied to the sliding window
  83656. upon return from inflate(), and since all distances after the first 32K of
  83657. output will fall in the output data, making match copies simpler and faster.
  83658. The advantage may be dependent on the size of the processor's data caches.
  83659. */
  83660. local int updatewindow (z_streamp strm, unsigned out)
  83661. {
  83662. struct inflate_state FAR *state;
  83663. unsigned copy, dist;
  83664. state = (struct inflate_state FAR *)strm->state;
  83665. /* if it hasn't been done already, allocate space for the window */
  83666. if (state->window == Z_NULL) {
  83667. state->window = (unsigned char FAR *)
  83668. ZALLOC(strm, 1U << state->wbits,
  83669. sizeof(unsigned char));
  83670. if (state->window == Z_NULL) return 1;
  83671. }
  83672. /* if window not in use yet, initialize */
  83673. if (state->wsize == 0) {
  83674. state->wsize = 1U << state->wbits;
  83675. state->write = 0;
  83676. state->whave = 0;
  83677. }
  83678. /* copy state->wsize or less output bytes into the circular window */
  83679. copy = out - strm->avail_out;
  83680. if (copy >= state->wsize) {
  83681. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83682. state->write = 0;
  83683. state->whave = state->wsize;
  83684. }
  83685. else {
  83686. dist = state->wsize - state->write;
  83687. if (dist > copy) dist = copy;
  83688. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83689. copy -= dist;
  83690. if (copy) {
  83691. zmemcpy(state->window, strm->next_out - copy, copy);
  83692. state->write = copy;
  83693. state->whave = state->wsize;
  83694. }
  83695. else {
  83696. state->write += dist;
  83697. if (state->write == state->wsize) state->write = 0;
  83698. if (state->whave < state->wsize) state->whave += dist;
  83699. }
  83700. }
  83701. return 0;
  83702. }
  83703. /* Macros for inflate(): */
  83704. /* check function to use adler32() for zlib or crc32() for gzip */
  83705. #ifdef GUNZIP
  83706. # define UPDATE(check, buf, len) \
  83707. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83708. #else
  83709. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83710. #endif
  83711. /* check macros for header crc */
  83712. #ifdef GUNZIP
  83713. # define CRC2(check, word) \
  83714. do { \
  83715. hbuf[0] = (unsigned char)(word); \
  83716. hbuf[1] = (unsigned char)((word) >> 8); \
  83717. check = crc32(check, hbuf, 2); \
  83718. } while (0)
  83719. # define CRC4(check, word) \
  83720. do { \
  83721. hbuf[0] = (unsigned char)(word); \
  83722. hbuf[1] = (unsigned char)((word) >> 8); \
  83723. hbuf[2] = (unsigned char)((word) >> 16); \
  83724. hbuf[3] = (unsigned char)((word) >> 24); \
  83725. check = crc32(check, hbuf, 4); \
  83726. } while (0)
  83727. #endif
  83728. /* Load registers with state in inflate() for speed */
  83729. #define LOAD() \
  83730. do { \
  83731. put = strm->next_out; \
  83732. left = strm->avail_out; \
  83733. next = strm->next_in; \
  83734. have = strm->avail_in; \
  83735. hold = state->hold; \
  83736. bits = state->bits; \
  83737. } while (0)
  83738. /* Restore state from registers in inflate() */
  83739. #define RESTORE() \
  83740. do { \
  83741. strm->next_out = put; \
  83742. strm->avail_out = left; \
  83743. strm->next_in = next; \
  83744. strm->avail_in = have; \
  83745. state->hold = hold; \
  83746. state->bits = bits; \
  83747. } while (0)
  83748. /* Clear the input bit accumulator */
  83749. #define INITBITS() \
  83750. do { \
  83751. hold = 0; \
  83752. bits = 0; \
  83753. } while (0)
  83754. /* Get a byte of input into the bit accumulator, or return from inflate()
  83755. if there is no input available. */
  83756. #define PULLBYTE() \
  83757. do { \
  83758. if (have == 0) goto inf_leave; \
  83759. have--; \
  83760. hold += (unsigned long)(*next++) << bits; \
  83761. bits += 8; \
  83762. } while (0)
  83763. /* Assure that there are at least n bits in the bit accumulator. If there is
  83764. not enough available input to do that, then return from inflate(). */
  83765. #define NEEDBITS(n) \
  83766. do { \
  83767. while (bits < (unsigned)(n)) \
  83768. PULLBYTE(); \
  83769. } while (0)
  83770. /* Return the low n bits of the bit accumulator (n < 16) */
  83771. #define BITS(n) \
  83772. ((unsigned)hold & ((1U << (n)) - 1))
  83773. /* Remove n bits from the bit accumulator */
  83774. #define DROPBITS(n) \
  83775. do { \
  83776. hold >>= (n); \
  83777. bits -= (unsigned)(n); \
  83778. } while (0)
  83779. /* Remove zero to seven bits as needed to go to a byte boundary */
  83780. #define BYTEBITS() \
  83781. do { \
  83782. hold >>= bits & 7; \
  83783. bits -= bits & 7; \
  83784. } while (0)
  83785. /* Reverse the bytes in a 32-bit value */
  83786. #define REVERSE(q) \
  83787. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83788. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83789. /*
  83790. inflate() uses a state machine to process as much input data and generate as
  83791. much output data as possible before returning. The state machine is
  83792. structured roughly as follows:
  83793. for (;;) switch (state) {
  83794. ...
  83795. case STATEn:
  83796. if (not enough input data or output space to make progress)
  83797. return;
  83798. ... make progress ...
  83799. state = STATEm;
  83800. break;
  83801. ...
  83802. }
  83803. so when inflate() is called again, the same case is attempted again, and
  83804. if the appropriate resources are provided, the machine proceeds to the
  83805. next state. The NEEDBITS() macro is usually the way the state evaluates
  83806. whether it can proceed or should return. NEEDBITS() does the return if
  83807. the requested bits are not available. The typical use of the BITS macros
  83808. is:
  83809. NEEDBITS(n);
  83810. ... do something with BITS(n) ...
  83811. DROPBITS(n);
  83812. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83813. input left to load n bits into the accumulator, or it continues. BITS(n)
  83814. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83815. the low n bits off the accumulator. INITBITS() clears the accumulator
  83816. and sets the number of available bits to zero. BYTEBITS() discards just
  83817. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83818. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83819. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83820. if there is no input available. The decoding of variable length codes uses
  83821. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83822. code, and no more.
  83823. Some states loop until they get enough input, making sure that enough
  83824. state information is maintained to continue the loop where it left off
  83825. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83826. would all have to actually be part of the saved state in case NEEDBITS()
  83827. returns:
  83828. case STATEw:
  83829. while (want < need) {
  83830. NEEDBITS(n);
  83831. keep[want++] = BITS(n);
  83832. DROPBITS(n);
  83833. }
  83834. state = STATEx;
  83835. case STATEx:
  83836. As shown above, if the next state is also the next case, then the break
  83837. is omitted.
  83838. A state may also return if there is not enough output space available to
  83839. complete that state. Those states are copying stored data, writing a
  83840. literal byte, and copying a matching string.
  83841. When returning, a "goto inf_leave" is used to update the total counters,
  83842. update the check value, and determine whether any progress has been made
  83843. during that inflate() call in order to return the proper return code.
  83844. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83845. When there is a window, goto inf_leave will update the window with the last
  83846. output written. If a goto inf_leave occurs in the middle of decompression
  83847. and there is no window currently, goto inf_leave will create one and copy
  83848. output to the window for the next call of inflate().
  83849. In this implementation, the flush parameter of inflate() only affects the
  83850. return code (per zlib.h). inflate() always writes as much as possible to
  83851. strm->next_out, given the space available and the provided input--the effect
  83852. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83853. the allocation of and copying into a sliding window until necessary, which
  83854. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83855. stream available. So the only thing the flush parameter actually does is:
  83856. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83857. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83858. */
  83859. int ZEXPORT inflate (z_streamp strm, int flush)
  83860. {
  83861. struct inflate_state FAR *state;
  83862. unsigned char FAR *next; /* next input */
  83863. unsigned char FAR *put; /* next output */
  83864. unsigned have, left; /* available input and output */
  83865. unsigned long hold; /* bit buffer */
  83866. unsigned bits; /* bits in bit buffer */
  83867. unsigned in, out; /* save starting available input and output */
  83868. unsigned copy; /* number of stored or match bytes to copy */
  83869. unsigned char FAR *from; /* where to copy match bytes from */
  83870. code thisx; /* current decoding table entry */
  83871. code last; /* parent table entry */
  83872. unsigned len; /* length to copy for repeats, bits to drop */
  83873. int ret; /* return code */
  83874. #ifdef GUNZIP
  83875. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83876. #endif
  83877. static const unsigned short order[19] = /* permutation of code lengths */
  83878. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83879. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83880. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83881. return Z_STREAM_ERROR;
  83882. state = (struct inflate_state FAR *)strm->state;
  83883. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83884. LOAD();
  83885. in = have;
  83886. out = left;
  83887. ret = Z_OK;
  83888. for (;;)
  83889. switch (state->mode) {
  83890. case HEAD:
  83891. if (state->wrap == 0) {
  83892. state->mode = TYPEDO;
  83893. break;
  83894. }
  83895. NEEDBITS(16);
  83896. #ifdef GUNZIP
  83897. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83898. state->check = crc32(0L, Z_NULL, 0);
  83899. CRC2(state->check, hold);
  83900. INITBITS();
  83901. state->mode = FLAGS;
  83902. break;
  83903. }
  83904. state->flags = 0; /* expect zlib header */
  83905. if (state->head != Z_NULL)
  83906. state->head->done = -1;
  83907. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83908. #else
  83909. if (
  83910. #endif
  83911. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83912. strm->msg = (char *)"incorrect header check";
  83913. state->mode = BAD;
  83914. break;
  83915. }
  83916. if (BITS(4) != Z_DEFLATED) {
  83917. strm->msg = (char *)"unknown compression method";
  83918. state->mode = BAD;
  83919. break;
  83920. }
  83921. DROPBITS(4);
  83922. len = BITS(4) + 8;
  83923. if (len > state->wbits) {
  83924. strm->msg = (char *)"invalid window size";
  83925. state->mode = BAD;
  83926. break;
  83927. }
  83928. state->dmax = 1U << len;
  83929. Tracev((stderr, "inflate: zlib header ok\n"));
  83930. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83931. state->mode = hold & 0x200 ? DICTID : TYPE;
  83932. INITBITS();
  83933. break;
  83934. #ifdef GUNZIP
  83935. case FLAGS:
  83936. NEEDBITS(16);
  83937. state->flags = (int)(hold);
  83938. if ((state->flags & 0xff) != Z_DEFLATED) {
  83939. strm->msg = (char *)"unknown compression method";
  83940. state->mode = BAD;
  83941. break;
  83942. }
  83943. if (state->flags & 0xe000) {
  83944. strm->msg = (char *)"unknown header flags set";
  83945. state->mode = BAD;
  83946. break;
  83947. }
  83948. if (state->head != Z_NULL)
  83949. state->head->text = (int)((hold >> 8) & 1);
  83950. if (state->flags & 0x0200) CRC2(state->check, hold);
  83951. INITBITS();
  83952. state->mode = TIME;
  83953. case TIME:
  83954. NEEDBITS(32);
  83955. if (state->head != Z_NULL)
  83956. state->head->time = hold;
  83957. if (state->flags & 0x0200) CRC4(state->check, hold);
  83958. INITBITS();
  83959. state->mode = OS;
  83960. case OS:
  83961. NEEDBITS(16);
  83962. if (state->head != Z_NULL) {
  83963. state->head->xflags = (int)(hold & 0xff);
  83964. state->head->os = (int)(hold >> 8);
  83965. }
  83966. if (state->flags & 0x0200) CRC2(state->check, hold);
  83967. INITBITS();
  83968. state->mode = EXLEN;
  83969. case EXLEN:
  83970. if (state->flags & 0x0400) {
  83971. NEEDBITS(16);
  83972. state->length = (unsigned)(hold);
  83973. if (state->head != Z_NULL)
  83974. state->head->extra_len = (unsigned)hold;
  83975. if (state->flags & 0x0200) CRC2(state->check, hold);
  83976. INITBITS();
  83977. }
  83978. else if (state->head != Z_NULL)
  83979. state->head->extra = Z_NULL;
  83980. state->mode = EXTRA;
  83981. case EXTRA:
  83982. if (state->flags & 0x0400) {
  83983. copy = state->length;
  83984. if (copy > have) copy = have;
  83985. if (copy) {
  83986. if (state->head != Z_NULL &&
  83987. state->head->extra != Z_NULL) {
  83988. len = state->head->extra_len - state->length;
  83989. zmemcpy(state->head->extra + len, next,
  83990. len + copy > state->head->extra_max ?
  83991. state->head->extra_max - len : copy);
  83992. }
  83993. if (state->flags & 0x0200)
  83994. state->check = crc32(state->check, next, copy);
  83995. have -= copy;
  83996. next += copy;
  83997. state->length -= copy;
  83998. }
  83999. if (state->length) goto inf_leave;
  84000. }
  84001. state->length = 0;
  84002. state->mode = NAME;
  84003. case NAME:
  84004. if (state->flags & 0x0800) {
  84005. if (have == 0) goto inf_leave;
  84006. copy = 0;
  84007. do {
  84008. len = (unsigned)(next[copy++]);
  84009. if (state->head != Z_NULL &&
  84010. state->head->name != Z_NULL &&
  84011. state->length < state->head->name_max)
  84012. state->head->name[state->length++] = len;
  84013. } while (len && copy < have);
  84014. if (state->flags & 0x0200)
  84015. state->check = crc32(state->check, next, copy);
  84016. have -= copy;
  84017. next += copy;
  84018. if (len) goto inf_leave;
  84019. }
  84020. else if (state->head != Z_NULL)
  84021. state->head->name = Z_NULL;
  84022. state->length = 0;
  84023. state->mode = COMMENT;
  84024. case COMMENT:
  84025. if (state->flags & 0x1000) {
  84026. if (have == 0) goto inf_leave;
  84027. copy = 0;
  84028. do {
  84029. len = (unsigned)(next[copy++]);
  84030. if (state->head != Z_NULL &&
  84031. state->head->comment != Z_NULL &&
  84032. state->length < state->head->comm_max)
  84033. state->head->comment[state->length++] = len;
  84034. } while (len && copy < have);
  84035. if (state->flags & 0x0200)
  84036. state->check = crc32(state->check, next, copy);
  84037. have -= copy;
  84038. next += copy;
  84039. if (len) goto inf_leave;
  84040. }
  84041. else if (state->head != Z_NULL)
  84042. state->head->comment = Z_NULL;
  84043. state->mode = HCRC;
  84044. case HCRC:
  84045. if (state->flags & 0x0200) {
  84046. NEEDBITS(16);
  84047. if (hold != (state->check & 0xffff)) {
  84048. strm->msg = (char *)"header crc mismatch";
  84049. state->mode = BAD;
  84050. break;
  84051. }
  84052. INITBITS();
  84053. }
  84054. if (state->head != Z_NULL) {
  84055. state->head->hcrc = (int)((state->flags >> 9) & 1);
  84056. state->head->done = 1;
  84057. }
  84058. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  84059. state->mode = TYPE;
  84060. break;
  84061. #endif
  84062. case DICTID:
  84063. NEEDBITS(32);
  84064. strm->adler = state->check = REVERSE(hold);
  84065. INITBITS();
  84066. state->mode = DICT;
  84067. case DICT:
  84068. if (state->havedict == 0) {
  84069. RESTORE();
  84070. return Z_NEED_DICT;
  84071. }
  84072. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  84073. state->mode = TYPE;
  84074. case TYPE:
  84075. if (flush == Z_BLOCK) goto inf_leave;
  84076. case TYPEDO:
  84077. if (state->last) {
  84078. BYTEBITS();
  84079. state->mode = CHECK;
  84080. break;
  84081. }
  84082. NEEDBITS(3);
  84083. state->last = BITS(1);
  84084. DROPBITS(1);
  84085. switch (BITS(2)) {
  84086. case 0: /* stored block */
  84087. Tracev((stderr, "inflate: stored block%s\n",
  84088. state->last ? " (last)" : ""));
  84089. state->mode = STORED;
  84090. break;
  84091. case 1: /* fixed block */
  84092. fixedtables(state);
  84093. Tracev((stderr, "inflate: fixed codes block%s\n",
  84094. state->last ? " (last)" : ""));
  84095. state->mode = LEN; /* decode codes */
  84096. break;
  84097. case 2: /* dynamic block */
  84098. Tracev((stderr, "inflate: dynamic codes block%s\n",
  84099. state->last ? " (last)" : ""));
  84100. state->mode = TABLE;
  84101. break;
  84102. case 3:
  84103. strm->msg = (char *)"invalid block type";
  84104. state->mode = BAD;
  84105. }
  84106. DROPBITS(2);
  84107. break;
  84108. case STORED:
  84109. BYTEBITS(); /* go to byte boundary */
  84110. NEEDBITS(32);
  84111. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  84112. strm->msg = (char *)"invalid stored block lengths";
  84113. state->mode = BAD;
  84114. break;
  84115. }
  84116. state->length = (unsigned)hold & 0xffff;
  84117. Tracev((stderr, "inflate: stored length %u\n",
  84118. state->length));
  84119. INITBITS();
  84120. state->mode = COPY;
  84121. case COPY:
  84122. copy = state->length;
  84123. if (copy) {
  84124. if (copy > have) copy = have;
  84125. if (copy > left) copy = left;
  84126. if (copy == 0) goto inf_leave;
  84127. zmemcpy(put, next, copy);
  84128. have -= copy;
  84129. next += copy;
  84130. left -= copy;
  84131. put += copy;
  84132. state->length -= copy;
  84133. break;
  84134. }
  84135. Tracev((stderr, "inflate: stored end\n"));
  84136. state->mode = TYPE;
  84137. break;
  84138. case TABLE:
  84139. NEEDBITS(14);
  84140. state->nlen = BITS(5) + 257;
  84141. DROPBITS(5);
  84142. state->ndist = BITS(5) + 1;
  84143. DROPBITS(5);
  84144. state->ncode = BITS(4) + 4;
  84145. DROPBITS(4);
  84146. #ifndef PKZIP_BUG_WORKAROUND
  84147. if (state->nlen > 286 || state->ndist > 30) {
  84148. strm->msg = (char *)"too many length or distance symbols";
  84149. state->mode = BAD;
  84150. break;
  84151. }
  84152. #endif
  84153. Tracev((stderr, "inflate: table sizes ok\n"));
  84154. state->have = 0;
  84155. state->mode = LENLENS;
  84156. case LENLENS:
  84157. while (state->have < state->ncode) {
  84158. NEEDBITS(3);
  84159. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84160. DROPBITS(3);
  84161. }
  84162. while (state->have < 19)
  84163. state->lens[order[state->have++]] = 0;
  84164. state->next = state->codes;
  84165. state->lencode = (code const FAR *)(state->next);
  84166. state->lenbits = 7;
  84167. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84168. &(state->lenbits), state->work);
  84169. if (ret) {
  84170. strm->msg = (char *)"invalid code lengths set";
  84171. state->mode = BAD;
  84172. break;
  84173. }
  84174. Tracev((stderr, "inflate: code lengths ok\n"));
  84175. state->have = 0;
  84176. state->mode = CODELENS;
  84177. case CODELENS:
  84178. while (state->have < state->nlen + state->ndist) {
  84179. for (;;) {
  84180. thisx = state->lencode[BITS(state->lenbits)];
  84181. if ((unsigned)(thisx.bits) <= bits) break;
  84182. PULLBYTE();
  84183. }
  84184. if (thisx.val < 16) {
  84185. NEEDBITS(thisx.bits);
  84186. DROPBITS(thisx.bits);
  84187. state->lens[state->have++] = thisx.val;
  84188. }
  84189. else {
  84190. if (thisx.val == 16) {
  84191. NEEDBITS(thisx.bits + 2);
  84192. DROPBITS(thisx.bits);
  84193. if (state->have == 0) {
  84194. strm->msg = (char *)"invalid bit length repeat";
  84195. state->mode = BAD;
  84196. break;
  84197. }
  84198. len = state->lens[state->have - 1];
  84199. copy = 3 + BITS(2);
  84200. DROPBITS(2);
  84201. }
  84202. else if (thisx.val == 17) {
  84203. NEEDBITS(thisx.bits + 3);
  84204. DROPBITS(thisx.bits);
  84205. len = 0;
  84206. copy = 3 + BITS(3);
  84207. DROPBITS(3);
  84208. }
  84209. else {
  84210. NEEDBITS(thisx.bits + 7);
  84211. DROPBITS(thisx.bits);
  84212. len = 0;
  84213. copy = 11 + BITS(7);
  84214. DROPBITS(7);
  84215. }
  84216. if (state->have + copy > state->nlen + state->ndist) {
  84217. strm->msg = (char *)"invalid bit length repeat";
  84218. state->mode = BAD;
  84219. break;
  84220. }
  84221. while (copy--)
  84222. state->lens[state->have++] = (unsigned short)len;
  84223. }
  84224. }
  84225. /* handle error breaks in while */
  84226. if (state->mode == BAD) break;
  84227. /* build code tables */
  84228. state->next = state->codes;
  84229. state->lencode = (code const FAR *)(state->next);
  84230. state->lenbits = 9;
  84231. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84232. &(state->lenbits), state->work);
  84233. if (ret) {
  84234. strm->msg = (char *)"invalid literal/lengths set";
  84235. state->mode = BAD;
  84236. break;
  84237. }
  84238. state->distcode = (code const FAR *)(state->next);
  84239. state->distbits = 6;
  84240. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84241. &(state->next), &(state->distbits), state->work);
  84242. if (ret) {
  84243. strm->msg = (char *)"invalid distances set";
  84244. state->mode = BAD;
  84245. break;
  84246. }
  84247. Tracev((stderr, "inflate: codes ok\n"));
  84248. state->mode = LEN;
  84249. case LEN:
  84250. if (have >= 6 && left >= 258) {
  84251. RESTORE();
  84252. inflate_fast(strm, out);
  84253. LOAD();
  84254. break;
  84255. }
  84256. for (;;) {
  84257. thisx = state->lencode[BITS(state->lenbits)];
  84258. if ((unsigned)(thisx.bits) <= bits) break;
  84259. PULLBYTE();
  84260. }
  84261. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84262. last = thisx;
  84263. for (;;) {
  84264. thisx = state->lencode[last.val +
  84265. (BITS(last.bits + last.op) >> last.bits)];
  84266. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84267. PULLBYTE();
  84268. }
  84269. DROPBITS(last.bits);
  84270. }
  84271. DROPBITS(thisx.bits);
  84272. state->length = (unsigned)thisx.val;
  84273. if ((int)(thisx.op) == 0) {
  84274. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84275. "inflate: literal '%c'\n" :
  84276. "inflate: literal 0x%02x\n", thisx.val));
  84277. state->mode = LIT;
  84278. break;
  84279. }
  84280. if (thisx.op & 32) {
  84281. Tracevv((stderr, "inflate: end of block\n"));
  84282. state->mode = TYPE;
  84283. break;
  84284. }
  84285. if (thisx.op & 64) {
  84286. strm->msg = (char *)"invalid literal/length code";
  84287. state->mode = BAD;
  84288. break;
  84289. }
  84290. state->extra = (unsigned)(thisx.op) & 15;
  84291. state->mode = LENEXT;
  84292. case LENEXT:
  84293. if (state->extra) {
  84294. NEEDBITS(state->extra);
  84295. state->length += BITS(state->extra);
  84296. DROPBITS(state->extra);
  84297. }
  84298. Tracevv((stderr, "inflate: length %u\n", state->length));
  84299. state->mode = DIST;
  84300. case DIST:
  84301. for (;;) {
  84302. thisx = state->distcode[BITS(state->distbits)];
  84303. if ((unsigned)(thisx.bits) <= bits) break;
  84304. PULLBYTE();
  84305. }
  84306. if ((thisx.op & 0xf0) == 0) {
  84307. last = thisx;
  84308. for (;;) {
  84309. thisx = state->distcode[last.val +
  84310. (BITS(last.bits + last.op) >> last.bits)];
  84311. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84312. PULLBYTE();
  84313. }
  84314. DROPBITS(last.bits);
  84315. }
  84316. DROPBITS(thisx.bits);
  84317. if (thisx.op & 64) {
  84318. strm->msg = (char *)"invalid distance code";
  84319. state->mode = BAD;
  84320. break;
  84321. }
  84322. state->offset = (unsigned)thisx.val;
  84323. state->extra = (unsigned)(thisx.op) & 15;
  84324. state->mode = DISTEXT;
  84325. case DISTEXT:
  84326. if (state->extra) {
  84327. NEEDBITS(state->extra);
  84328. state->offset += BITS(state->extra);
  84329. DROPBITS(state->extra);
  84330. }
  84331. #ifdef INFLATE_STRICT
  84332. if (state->offset > state->dmax) {
  84333. strm->msg = (char *)"invalid distance too far back";
  84334. state->mode = BAD;
  84335. break;
  84336. }
  84337. #endif
  84338. if (state->offset > state->whave + out - left) {
  84339. strm->msg = (char *)"invalid distance too far back";
  84340. state->mode = BAD;
  84341. break;
  84342. }
  84343. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84344. state->mode = MATCH;
  84345. case MATCH:
  84346. if (left == 0) goto inf_leave;
  84347. copy = out - left;
  84348. if (state->offset > copy) { /* copy from window */
  84349. copy = state->offset - copy;
  84350. if (copy > state->write) {
  84351. copy -= state->write;
  84352. from = state->window + (state->wsize - copy);
  84353. }
  84354. else
  84355. from = state->window + (state->write - copy);
  84356. if (copy > state->length) copy = state->length;
  84357. }
  84358. else { /* copy from output */
  84359. from = put - state->offset;
  84360. copy = state->length;
  84361. }
  84362. if (copy > left) copy = left;
  84363. left -= copy;
  84364. state->length -= copy;
  84365. do {
  84366. *put++ = *from++;
  84367. } while (--copy);
  84368. if (state->length == 0) state->mode = LEN;
  84369. break;
  84370. case LIT:
  84371. if (left == 0) goto inf_leave;
  84372. *put++ = (unsigned char)(state->length);
  84373. left--;
  84374. state->mode = LEN;
  84375. break;
  84376. case CHECK:
  84377. if (state->wrap) {
  84378. NEEDBITS(32);
  84379. out -= left;
  84380. strm->total_out += out;
  84381. state->total += out;
  84382. if (out)
  84383. strm->adler = state->check =
  84384. UPDATE(state->check, put - out, out);
  84385. out = left;
  84386. if ((
  84387. #ifdef GUNZIP
  84388. state->flags ? hold :
  84389. #endif
  84390. REVERSE(hold)) != state->check) {
  84391. strm->msg = (char *)"incorrect data check";
  84392. state->mode = BAD;
  84393. break;
  84394. }
  84395. INITBITS();
  84396. Tracev((stderr, "inflate: check matches trailer\n"));
  84397. }
  84398. #ifdef GUNZIP
  84399. state->mode = LENGTH;
  84400. case LENGTH:
  84401. if (state->wrap && state->flags) {
  84402. NEEDBITS(32);
  84403. if (hold != (state->total & 0xffffffffUL)) {
  84404. strm->msg = (char *)"incorrect length check";
  84405. state->mode = BAD;
  84406. break;
  84407. }
  84408. INITBITS();
  84409. Tracev((stderr, "inflate: length matches trailer\n"));
  84410. }
  84411. #endif
  84412. state->mode = DONE;
  84413. case DONE:
  84414. ret = Z_STREAM_END;
  84415. goto inf_leave;
  84416. case BAD:
  84417. ret = Z_DATA_ERROR;
  84418. goto inf_leave;
  84419. case MEM:
  84420. return Z_MEM_ERROR;
  84421. case SYNC:
  84422. default:
  84423. return Z_STREAM_ERROR;
  84424. }
  84425. /*
  84426. Return from inflate(), updating the total counts and the check value.
  84427. If there was no progress during the inflate() call, return a buffer
  84428. error. Call updatewindow() to create and/or update the window state.
  84429. Note: a memory error from inflate() is non-recoverable.
  84430. */
  84431. inf_leave:
  84432. RESTORE();
  84433. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84434. if (updatewindow(strm, out)) {
  84435. state->mode = MEM;
  84436. return Z_MEM_ERROR;
  84437. }
  84438. in -= strm->avail_in;
  84439. out -= strm->avail_out;
  84440. strm->total_in += in;
  84441. strm->total_out += out;
  84442. state->total += out;
  84443. if (state->wrap && out)
  84444. strm->adler = state->check =
  84445. UPDATE(state->check, strm->next_out - out, out);
  84446. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84447. (state->mode == TYPE ? 128 : 0);
  84448. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84449. ret = Z_BUF_ERROR;
  84450. return ret;
  84451. }
  84452. int ZEXPORT inflateEnd (z_streamp strm)
  84453. {
  84454. struct inflate_state FAR *state;
  84455. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84456. return Z_STREAM_ERROR;
  84457. state = (struct inflate_state FAR *)strm->state;
  84458. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84459. ZFREE(strm, strm->state);
  84460. strm->state = Z_NULL;
  84461. Tracev((stderr, "inflate: end\n"));
  84462. return Z_OK;
  84463. }
  84464. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84465. {
  84466. struct inflate_state FAR *state;
  84467. unsigned long id_;
  84468. /* check state */
  84469. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84470. state = (struct inflate_state FAR *)strm->state;
  84471. if (state->wrap != 0 && state->mode != DICT)
  84472. return Z_STREAM_ERROR;
  84473. /* check for correct dictionary id */
  84474. if (state->mode == DICT) {
  84475. id_ = adler32(0L, Z_NULL, 0);
  84476. id_ = adler32(id_, dictionary, dictLength);
  84477. if (id_ != state->check)
  84478. return Z_DATA_ERROR;
  84479. }
  84480. /* copy dictionary to window */
  84481. if (updatewindow(strm, strm->avail_out)) {
  84482. state->mode = MEM;
  84483. return Z_MEM_ERROR;
  84484. }
  84485. if (dictLength > state->wsize) {
  84486. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84487. state->wsize);
  84488. state->whave = state->wsize;
  84489. }
  84490. else {
  84491. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84492. dictLength);
  84493. state->whave = dictLength;
  84494. }
  84495. state->havedict = 1;
  84496. Tracev((stderr, "inflate: dictionary set\n"));
  84497. return Z_OK;
  84498. }
  84499. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84500. {
  84501. struct inflate_state FAR *state;
  84502. /* check state */
  84503. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84504. state = (struct inflate_state FAR *)strm->state;
  84505. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84506. /* save header structure */
  84507. state->head = head;
  84508. head->done = 0;
  84509. return Z_OK;
  84510. }
  84511. /*
  84512. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84513. or when out of input. When called, *have is the number of pattern bytes
  84514. found in order so far, in 0..3. On return *have is updated to the new
  84515. state. If on return *have equals four, then the pattern was found and the
  84516. return value is how many bytes were read including the last byte of the
  84517. pattern. If *have is less than four, then the pattern has not been found
  84518. yet and the return value is len. In the latter case, syncsearch() can be
  84519. called again with more data and the *have state. *have is initialized to
  84520. zero for the first call.
  84521. */
  84522. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84523. {
  84524. unsigned got;
  84525. unsigned next;
  84526. got = *have;
  84527. next = 0;
  84528. while (next < len && got < 4) {
  84529. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84530. got++;
  84531. else if (buf[next])
  84532. got = 0;
  84533. else
  84534. got = 4 - got;
  84535. next++;
  84536. }
  84537. *have = got;
  84538. return next;
  84539. }
  84540. int ZEXPORT inflateSync (z_streamp strm)
  84541. {
  84542. unsigned len; /* number of bytes to look at or looked at */
  84543. unsigned long in, out; /* temporary to save total_in and total_out */
  84544. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84545. struct inflate_state FAR *state;
  84546. /* check parameters */
  84547. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84548. state = (struct inflate_state FAR *)strm->state;
  84549. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84550. /* if first time, start search in bit buffer */
  84551. if (state->mode != SYNC) {
  84552. state->mode = SYNC;
  84553. state->hold <<= state->bits & 7;
  84554. state->bits -= state->bits & 7;
  84555. len = 0;
  84556. while (state->bits >= 8) {
  84557. buf[len++] = (unsigned char)(state->hold);
  84558. state->hold >>= 8;
  84559. state->bits -= 8;
  84560. }
  84561. state->have = 0;
  84562. syncsearch(&(state->have), buf, len);
  84563. }
  84564. /* search available input */
  84565. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84566. strm->avail_in -= len;
  84567. strm->next_in += len;
  84568. strm->total_in += len;
  84569. /* return no joy or set up to restart inflate() on a new block */
  84570. if (state->have != 4) return Z_DATA_ERROR;
  84571. in = strm->total_in; out = strm->total_out;
  84572. inflateReset(strm);
  84573. strm->total_in = in; strm->total_out = out;
  84574. state->mode = TYPE;
  84575. return Z_OK;
  84576. }
  84577. /*
  84578. Returns true if inflate is currently at the end of a block generated by
  84579. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84580. implementation to provide an additional safety check. PPP uses
  84581. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84582. block. When decompressing, PPP checks that at the end of input packet,
  84583. inflate is waiting for these length bytes.
  84584. */
  84585. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84586. {
  84587. struct inflate_state FAR *state;
  84588. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84589. state = (struct inflate_state FAR *)strm->state;
  84590. return state->mode == STORED && state->bits == 0;
  84591. }
  84592. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84593. {
  84594. struct inflate_state FAR *state;
  84595. struct inflate_state FAR *copy;
  84596. unsigned char FAR *window;
  84597. unsigned wsize;
  84598. /* check input */
  84599. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84600. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84601. return Z_STREAM_ERROR;
  84602. state = (struct inflate_state FAR *)source->state;
  84603. /* allocate space */
  84604. copy = (struct inflate_state FAR *)
  84605. ZALLOC(source, 1, sizeof(struct inflate_state));
  84606. if (copy == Z_NULL) return Z_MEM_ERROR;
  84607. window = Z_NULL;
  84608. if (state->window != Z_NULL) {
  84609. window = (unsigned char FAR *)
  84610. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84611. if (window == Z_NULL) {
  84612. ZFREE(source, copy);
  84613. return Z_MEM_ERROR;
  84614. }
  84615. }
  84616. /* copy state */
  84617. zmemcpy(dest, source, sizeof(z_stream));
  84618. zmemcpy(copy, state, sizeof(struct inflate_state));
  84619. if (state->lencode >= state->codes &&
  84620. state->lencode <= state->codes + ENOUGH - 1) {
  84621. copy->lencode = copy->codes + (state->lencode - state->codes);
  84622. copy->distcode = copy->codes + (state->distcode - state->codes);
  84623. }
  84624. copy->next = copy->codes + (state->next - state->codes);
  84625. if (window != Z_NULL) {
  84626. wsize = 1U << state->wbits;
  84627. zmemcpy(window, state->window, wsize);
  84628. }
  84629. copy->window = window;
  84630. dest->state = (struct internal_state FAR *)copy;
  84631. return Z_OK;
  84632. }
  84633. /*** End of inlined file: inflate.c ***/
  84634. /*** Start of inlined file: inftrees.c ***/
  84635. #define MAXBITS 15
  84636. const char inflate_copyright[] =
  84637. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84638. /*
  84639. If you use the zlib library in a product, an acknowledgment is welcome
  84640. in the documentation of your product. If for some reason you cannot
  84641. include such an acknowledgment, I would appreciate that you keep this
  84642. copyright string in the executable of your product.
  84643. */
  84644. /*
  84645. Build a set of tables to decode the provided canonical Huffman code.
  84646. The code lengths are lens[0..codes-1]. The result starts at *table,
  84647. whose indices are 0..2^bits-1. work is a writable array of at least
  84648. lens shorts, which is used as a work area. type is the type of code
  84649. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84650. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84651. on return points to the next available entry's address. bits is the
  84652. requested root table index bits, and on return it is the actual root
  84653. table index bits. It will differ if the request is greater than the
  84654. longest code or if it is less than the shortest code.
  84655. */
  84656. int inflate_table (codetype type,
  84657. unsigned short FAR *lens,
  84658. unsigned codes,
  84659. code FAR * FAR *table,
  84660. unsigned FAR *bits,
  84661. unsigned short FAR *work)
  84662. {
  84663. unsigned len; /* a code's length in bits */
  84664. unsigned sym; /* index of code symbols */
  84665. unsigned min, max; /* minimum and maximum code lengths */
  84666. unsigned root; /* number of index bits for root table */
  84667. unsigned curr; /* number of index bits for current table */
  84668. unsigned drop; /* code bits to drop for sub-table */
  84669. int left; /* number of prefix codes available */
  84670. unsigned used; /* code entries in table used */
  84671. unsigned huff; /* Huffman code */
  84672. unsigned incr; /* for incrementing code, index */
  84673. unsigned fill; /* index for replicating entries */
  84674. unsigned low; /* low bits for current root entry */
  84675. unsigned mask; /* mask for low root bits */
  84676. code thisx; /* table entry for duplication */
  84677. code FAR *next; /* next available space in table */
  84678. const unsigned short FAR *base; /* base value table to use */
  84679. const unsigned short FAR *extra; /* extra bits table to use */
  84680. int end; /* use base and extra for symbol > end */
  84681. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84682. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84683. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84684. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84685. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84686. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84687. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84688. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84689. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84690. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84691. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84692. 8193, 12289, 16385, 24577, 0, 0};
  84693. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84694. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84695. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84696. 28, 28, 29, 29, 64, 64};
  84697. /*
  84698. Process a set of code lengths to create a canonical Huffman code. The
  84699. code lengths are lens[0..codes-1]. Each length corresponds to the
  84700. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84701. symbols by length from short to long, and retaining the symbol order
  84702. for codes with equal lengths. Then the code starts with all zero bits
  84703. for the first code of the shortest length, and the codes are integer
  84704. increments for the same length, and zeros are appended as the length
  84705. increases. For the deflate format, these bits are stored backwards
  84706. from their more natural integer increment ordering, and so when the
  84707. decoding tables are built in the large loop below, the integer codes
  84708. are incremented backwards.
  84709. This routine assumes, but does not check, that all of the entries in
  84710. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84711. 1..MAXBITS is interpreted as that code length. zero means that that
  84712. symbol does not occur in this code.
  84713. The codes are sorted by computing a count of codes for each length,
  84714. creating from that a table of starting indices for each length in the
  84715. sorted table, and then entering the symbols in order in the sorted
  84716. table. The sorted table is work[], with that space being provided by
  84717. the caller.
  84718. The length counts are used for other purposes as well, i.e. finding
  84719. the minimum and maximum length codes, determining if there are any
  84720. codes at all, checking for a valid set of lengths, and looking ahead
  84721. at length counts to determine sub-table sizes when building the
  84722. decoding tables.
  84723. */
  84724. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84725. for (len = 0; len <= MAXBITS; len++)
  84726. count[len] = 0;
  84727. for (sym = 0; sym < codes; sym++)
  84728. count[lens[sym]]++;
  84729. /* bound code lengths, force root to be within code lengths */
  84730. root = *bits;
  84731. for (max = MAXBITS; max >= 1; max--)
  84732. if (count[max] != 0) break;
  84733. if (root > max) root = max;
  84734. if (max == 0) { /* no symbols to code at all */
  84735. thisx.op = (unsigned char)64; /* invalid code marker */
  84736. thisx.bits = (unsigned char)1;
  84737. thisx.val = (unsigned short)0;
  84738. *(*table)++ = thisx; /* make a table to force an error */
  84739. *(*table)++ = thisx;
  84740. *bits = 1;
  84741. return 0; /* no symbols, but wait for decoding to report error */
  84742. }
  84743. for (min = 1; min <= MAXBITS; min++)
  84744. if (count[min] != 0) break;
  84745. if (root < min) root = min;
  84746. /* check for an over-subscribed or incomplete set of lengths */
  84747. left = 1;
  84748. for (len = 1; len <= MAXBITS; len++) {
  84749. left <<= 1;
  84750. left -= count[len];
  84751. if (left < 0) return -1; /* over-subscribed */
  84752. }
  84753. if (left > 0 && (type == CODES || max != 1))
  84754. return -1; /* incomplete set */
  84755. /* generate offsets into symbol table for each length for sorting */
  84756. offs[1] = 0;
  84757. for (len = 1; len < MAXBITS; len++)
  84758. offs[len + 1] = offs[len] + count[len];
  84759. /* sort symbols by length, by symbol order within each length */
  84760. for (sym = 0; sym < codes; sym++)
  84761. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84762. /*
  84763. Create and fill in decoding tables. In this loop, the table being
  84764. filled is at next and has curr index bits. The code being used is huff
  84765. with length len. That code is converted to an index by dropping drop
  84766. bits off of the bottom. For codes where len is less than drop + curr,
  84767. those top drop + curr - len bits are incremented through all values to
  84768. fill the table with replicated entries.
  84769. root is the number of index bits for the root table. When len exceeds
  84770. root, sub-tables are created pointed to by the root entry with an index
  84771. of the low root bits of huff. This is saved in low to check for when a
  84772. new sub-table should be started. drop is zero when the root table is
  84773. being filled, and drop is root when sub-tables are being filled.
  84774. When a new sub-table is needed, it is necessary to look ahead in the
  84775. code lengths to determine what size sub-table is needed. The length
  84776. counts are used for this, and so count[] is decremented as codes are
  84777. entered in the tables.
  84778. used keeps track of how many table entries have been allocated from the
  84779. provided *table space. It is checked when a LENS table is being made
  84780. against the space in *table, ENOUGH, minus the maximum space needed by
  84781. the worst case distance code, MAXD. This should never happen, but the
  84782. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84783. This assumes that when type == LENS, bits == 9.
  84784. sym increments through all symbols, and the loop terminates when
  84785. all codes of length max, i.e. all codes, have been processed. This
  84786. routine permits incomplete codes, so another loop after this one fills
  84787. in the rest of the decoding tables with invalid code markers.
  84788. */
  84789. /* set up for code type */
  84790. switch (type) {
  84791. case CODES:
  84792. base = extra = work; /* dummy value--not used */
  84793. end = 19;
  84794. break;
  84795. case LENS:
  84796. base = lbase;
  84797. base -= 257;
  84798. extra = lext;
  84799. extra -= 257;
  84800. end = 256;
  84801. break;
  84802. default: /* DISTS */
  84803. base = dbase;
  84804. extra = dext;
  84805. end = -1;
  84806. }
  84807. /* initialize state for loop */
  84808. huff = 0; /* starting code */
  84809. sym = 0; /* starting code symbol */
  84810. len = min; /* starting code length */
  84811. next = *table; /* current table to fill in */
  84812. curr = root; /* current table index bits */
  84813. drop = 0; /* current bits to drop from code for index */
  84814. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84815. used = 1U << root; /* use root table entries */
  84816. mask = used - 1; /* mask for comparing low */
  84817. /* check available table space */
  84818. if (type == LENS && used >= ENOUGH - MAXD)
  84819. return 1;
  84820. /* process all codes and make table entries */
  84821. for (;;) {
  84822. /* create table entry */
  84823. thisx.bits = (unsigned char)(len - drop);
  84824. if ((int)(work[sym]) < end) {
  84825. thisx.op = (unsigned char)0;
  84826. thisx.val = work[sym];
  84827. }
  84828. else if ((int)(work[sym]) > end) {
  84829. thisx.op = (unsigned char)(extra[work[sym]]);
  84830. thisx.val = base[work[sym]];
  84831. }
  84832. else {
  84833. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84834. thisx.val = 0;
  84835. }
  84836. /* replicate for those indices with low len bits equal to huff */
  84837. incr = 1U << (len - drop);
  84838. fill = 1U << curr;
  84839. min = fill; /* save offset to next table */
  84840. do {
  84841. fill -= incr;
  84842. next[(huff >> drop) + fill] = thisx;
  84843. } while (fill != 0);
  84844. /* backwards increment the len-bit code huff */
  84845. incr = 1U << (len - 1);
  84846. while (huff & incr)
  84847. incr >>= 1;
  84848. if (incr != 0) {
  84849. huff &= incr - 1;
  84850. huff += incr;
  84851. }
  84852. else
  84853. huff = 0;
  84854. /* go to next symbol, update count, len */
  84855. sym++;
  84856. if (--(count[len]) == 0) {
  84857. if (len == max) break;
  84858. len = lens[work[sym]];
  84859. }
  84860. /* create new sub-table if needed */
  84861. if (len > root && (huff & mask) != low) {
  84862. /* if first time, transition to sub-tables */
  84863. if (drop == 0)
  84864. drop = root;
  84865. /* increment past last table */
  84866. next += min; /* here min is 1 << curr */
  84867. /* determine length of next table */
  84868. curr = len - drop;
  84869. left = (int)(1 << curr);
  84870. while (curr + drop < max) {
  84871. left -= count[curr + drop];
  84872. if (left <= 0) break;
  84873. curr++;
  84874. left <<= 1;
  84875. }
  84876. /* check for enough space */
  84877. used += 1U << curr;
  84878. if (type == LENS && used >= ENOUGH - MAXD)
  84879. return 1;
  84880. /* point entry in root table to sub-table */
  84881. low = huff & mask;
  84882. (*table)[low].op = (unsigned char)curr;
  84883. (*table)[low].bits = (unsigned char)root;
  84884. (*table)[low].val = (unsigned short)(next - *table);
  84885. }
  84886. }
  84887. /*
  84888. Fill in rest of table for incomplete codes. This loop is similar to the
  84889. loop above in incrementing huff for table indices. It is assumed that
  84890. len is equal to curr + drop, so there is no loop needed to increment
  84891. through high index bits. When the current sub-table is filled, the loop
  84892. drops back to the root table to fill in any remaining entries there.
  84893. */
  84894. thisx.op = (unsigned char)64; /* invalid code marker */
  84895. thisx.bits = (unsigned char)(len - drop);
  84896. thisx.val = (unsigned short)0;
  84897. while (huff != 0) {
  84898. /* when done with sub-table, drop back to root table */
  84899. if (drop != 0 && (huff & mask) != low) {
  84900. drop = 0;
  84901. len = root;
  84902. next = *table;
  84903. thisx.bits = (unsigned char)len;
  84904. }
  84905. /* put invalid code marker in table */
  84906. next[huff >> drop] = thisx;
  84907. /* backwards increment the len-bit code huff */
  84908. incr = 1U << (len - 1);
  84909. while (huff & incr)
  84910. incr >>= 1;
  84911. if (incr != 0) {
  84912. huff &= incr - 1;
  84913. huff += incr;
  84914. }
  84915. else
  84916. huff = 0;
  84917. }
  84918. /* set return parameters */
  84919. *table += used;
  84920. *bits = root;
  84921. return 0;
  84922. }
  84923. /*** End of inlined file: inftrees.c ***/
  84924. /*** Start of inlined file: trees.c ***/
  84925. /*
  84926. * ALGORITHM
  84927. *
  84928. * The "deflation" process uses several Huffman trees. The more
  84929. * common source values are represented by shorter bit sequences.
  84930. *
  84931. * Each code tree is stored in a compressed form which is itself
  84932. * a Huffman encoding of the lengths of all the code strings (in
  84933. * ascending order by source values). The actual code strings are
  84934. * reconstructed from the lengths in the inflate process, as described
  84935. * in the deflate specification.
  84936. *
  84937. * REFERENCES
  84938. *
  84939. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84940. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84941. *
  84942. * Storer, James A.
  84943. * Data Compression: Methods and Theory, pp. 49-50.
  84944. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84945. *
  84946. * Sedgewick, R.
  84947. * Algorithms, p290.
  84948. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84949. */
  84950. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84951. /* #define GEN_TREES_H */
  84952. #ifdef DEBUG
  84953. # include <ctype.h>
  84954. #endif
  84955. /* ===========================================================================
  84956. * Constants
  84957. */
  84958. #define MAX_BL_BITS 7
  84959. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84960. #define END_BLOCK 256
  84961. /* end of block literal code */
  84962. #define REP_3_6 16
  84963. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84964. #define REPZ_3_10 17
  84965. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84966. #define REPZ_11_138 18
  84967. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84968. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84969. = {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};
  84970. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84971. = {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};
  84972. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84973. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84974. local const uch bl_order[BL_CODES]
  84975. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84976. /* The lengths of the bit length codes are sent in order of decreasing
  84977. * probability, to avoid transmitting the lengths for unused bit length codes.
  84978. */
  84979. #define Buf_size (8 * 2*sizeof(char))
  84980. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84981. * more than 16 bits on some systems.)
  84982. */
  84983. /* ===========================================================================
  84984. * Local data. These are initialized only once.
  84985. */
  84986. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84987. #if defined(GEN_TREES_H) || !defined(STDC)
  84988. /* non ANSI compilers may not accept trees.h */
  84989. local ct_data static_ltree[L_CODES+2];
  84990. /* The static literal tree. Since the bit lengths are imposed, there is no
  84991. * need for the L_CODES extra codes used during heap construction. However
  84992. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84993. * below).
  84994. */
  84995. local ct_data static_dtree[D_CODES];
  84996. /* The static distance tree. (Actually a trivial tree since all codes use
  84997. * 5 bits.)
  84998. */
  84999. uch _dist_code[DIST_CODE_LEN];
  85000. /* Distance codes. The first 256 values correspond to the distances
  85001. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  85002. * the 15 bit distances.
  85003. */
  85004. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  85005. /* length code for each normalized match length (0 == MIN_MATCH) */
  85006. local int base_length[LENGTH_CODES];
  85007. /* First normalized length for each code (0 = MIN_MATCH) */
  85008. local int base_dist[D_CODES];
  85009. /* First normalized distance for each code (0 = distance of 1) */
  85010. #else
  85011. /*** Start of inlined file: trees.h ***/
  85012. local const ct_data static_ltree[L_CODES+2] = {
  85013. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  85014. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  85015. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  85016. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  85017. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  85018. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  85019. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  85020. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  85021. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  85022. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  85023. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  85024. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  85025. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  85026. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  85027. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  85028. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  85029. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  85030. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  85031. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  85032. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  85033. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  85034. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  85035. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  85036. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  85037. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  85038. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  85039. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  85040. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  85041. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  85042. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  85043. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  85044. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  85045. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  85046. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  85047. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  85048. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  85049. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  85050. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  85051. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  85052. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  85053. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  85054. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  85055. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  85056. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  85057. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  85058. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  85059. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  85060. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  85061. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  85062. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  85063. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  85064. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  85065. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  85066. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  85067. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  85068. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  85069. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  85070. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  85071. };
  85072. local const ct_data static_dtree[D_CODES] = {
  85073. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  85074. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  85075. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  85076. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  85077. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  85078. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  85079. };
  85080. const uch _dist_code[DIST_CODE_LEN] = {
  85081. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  85082. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  85083. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  85084. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  85085. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  85086. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  85087. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85088. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85089. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85090. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  85091. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85092. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85093. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  85094. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  85095. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85096. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85097. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85098. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  85099. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85100. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85101. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85102. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85103. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85104. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85105. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85106. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  85107. };
  85108. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  85109. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  85110. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  85111. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  85112. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  85113. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  85114. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  85115. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85116. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85117. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85118. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  85119. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85120. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85121. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  85122. };
  85123. local const int base_length[LENGTH_CODES] = {
  85124. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  85125. 64, 80, 96, 112, 128, 160, 192, 224, 0
  85126. };
  85127. local const int base_dist[D_CODES] = {
  85128. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  85129. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  85130. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  85131. };
  85132. /*** End of inlined file: trees.h ***/
  85133. #endif /* GEN_TREES_H */
  85134. struct static_tree_desc_s {
  85135. const ct_data *static_tree; /* static tree or NULL */
  85136. const intf *extra_bits; /* extra bits for each code or NULL */
  85137. int extra_base; /* base index for extra_bits */
  85138. int elems; /* max number of elements in the tree */
  85139. int max_length; /* max bit length for the codes */
  85140. };
  85141. local static_tree_desc static_l_desc =
  85142. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85143. local static_tree_desc static_d_desc =
  85144. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85145. local static_tree_desc static_bl_desc =
  85146. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85147. /* ===========================================================================
  85148. * Local (static) routines in this file.
  85149. */
  85150. local void tr_static_init OF((void));
  85151. local void init_block OF((deflate_state *s));
  85152. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85153. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85154. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85155. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85156. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85157. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85158. local int build_bl_tree OF((deflate_state *s));
  85159. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85160. int blcodes));
  85161. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85162. ct_data *dtree));
  85163. local void set_data_type OF((deflate_state *s));
  85164. local unsigned bi_reverse OF((unsigned value, int length));
  85165. local void bi_windup OF((deflate_state *s));
  85166. local void bi_flush OF((deflate_state *s));
  85167. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85168. int header));
  85169. #ifdef GEN_TREES_H
  85170. local void gen_trees_header OF((void));
  85171. #endif
  85172. #ifndef DEBUG
  85173. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85174. /* Send a code of the given tree. c and tree must not have side effects */
  85175. #else /* DEBUG */
  85176. # define send_code(s, c, tree) \
  85177. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85178. send_bits(s, tree[c].Code, tree[c].Len); }
  85179. #endif
  85180. /* ===========================================================================
  85181. * Output a short LSB first on the stream.
  85182. * IN assertion: there is enough room in pendingBuf.
  85183. */
  85184. #define put_short(s, w) { \
  85185. put_byte(s, (uch)((w) & 0xff)); \
  85186. put_byte(s, (uch)((ush)(w) >> 8)); \
  85187. }
  85188. /* ===========================================================================
  85189. * Send a value on a given number of bits.
  85190. * IN assertion: length <= 16 and value fits in length bits.
  85191. */
  85192. #ifdef DEBUG
  85193. local void send_bits OF((deflate_state *s, int value, int length));
  85194. local void send_bits (deflate_state *s, int value, int length)
  85195. {
  85196. Tracevv((stderr," l %2d v %4x ", length, value));
  85197. Assert(length > 0 && length <= 15, "invalid length");
  85198. s->bits_sent += (ulg)length;
  85199. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85200. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85201. * unused bits in value.
  85202. */
  85203. if (s->bi_valid > (int)Buf_size - length) {
  85204. s->bi_buf |= (value << s->bi_valid);
  85205. put_short(s, s->bi_buf);
  85206. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85207. s->bi_valid += length - Buf_size;
  85208. } else {
  85209. s->bi_buf |= value << s->bi_valid;
  85210. s->bi_valid += length;
  85211. }
  85212. }
  85213. #else /* !DEBUG */
  85214. #define send_bits(s, value, length) \
  85215. { int len = length;\
  85216. if (s->bi_valid > (int)Buf_size - len) {\
  85217. int val = value;\
  85218. s->bi_buf |= (val << s->bi_valid);\
  85219. put_short(s, s->bi_buf);\
  85220. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85221. s->bi_valid += len - Buf_size;\
  85222. } else {\
  85223. s->bi_buf |= (value) << s->bi_valid;\
  85224. s->bi_valid += len;\
  85225. }\
  85226. }
  85227. #endif /* DEBUG */
  85228. /* the arguments must not have side effects */
  85229. /* ===========================================================================
  85230. * Initialize the various 'constant' tables.
  85231. */
  85232. local void tr_static_init()
  85233. {
  85234. #if defined(GEN_TREES_H) || !defined(STDC)
  85235. static int static_init_done = 0;
  85236. int n; /* iterates over tree elements */
  85237. int bits; /* bit counter */
  85238. int length; /* length value */
  85239. int code; /* code value */
  85240. int dist; /* distance index */
  85241. ush bl_count[MAX_BITS+1];
  85242. /* number of codes at each bit length for an optimal tree */
  85243. if (static_init_done) return;
  85244. /* For some embedded targets, global variables are not initialized: */
  85245. static_l_desc.static_tree = static_ltree;
  85246. static_l_desc.extra_bits = extra_lbits;
  85247. static_d_desc.static_tree = static_dtree;
  85248. static_d_desc.extra_bits = extra_dbits;
  85249. static_bl_desc.extra_bits = extra_blbits;
  85250. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85251. length = 0;
  85252. for (code = 0; code < LENGTH_CODES-1; code++) {
  85253. base_length[code] = length;
  85254. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85255. _length_code[length++] = (uch)code;
  85256. }
  85257. }
  85258. Assert (length == 256, "tr_static_init: length != 256");
  85259. /* Note that the length 255 (match length 258) can be represented
  85260. * in two different ways: code 284 + 5 bits or code 285, so we
  85261. * overwrite length_code[255] to use the best encoding:
  85262. */
  85263. _length_code[length-1] = (uch)code;
  85264. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85265. dist = 0;
  85266. for (code = 0 ; code < 16; code++) {
  85267. base_dist[code] = dist;
  85268. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85269. _dist_code[dist++] = (uch)code;
  85270. }
  85271. }
  85272. Assert (dist == 256, "tr_static_init: dist != 256");
  85273. dist >>= 7; /* from now on, all distances are divided by 128 */
  85274. for ( ; code < D_CODES; code++) {
  85275. base_dist[code] = dist << 7;
  85276. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85277. _dist_code[256 + dist++] = (uch)code;
  85278. }
  85279. }
  85280. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85281. /* Construct the codes of the static literal tree */
  85282. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85283. n = 0;
  85284. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85285. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85286. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85287. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85288. /* Codes 286 and 287 do not exist, but we must include them in the
  85289. * tree construction to get a canonical Huffman tree (longest code
  85290. * all ones)
  85291. */
  85292. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85293. /* The static distance tree is trivial: */
  85294. for (n = 0; n < D_CODES; n++) {
  85295. static_dtree[n].Len = 5;
  85296. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85297. }
  85298. static_init_done = 1;
  85299. # ifdef GEN_TREES_H
  85300. gen_trees_header();
  85301. # endif
  85302. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85303. }
  85304. /* ===========================================================================
  85305. * Genererate the file trees.h describing the static trees.
  85306. */
  85307. #ifdef GEN_TREES_H
  85308. # ifndef DEBUG
  85309. # include <stdio.h>
  85310. # endif
  85311. # define SEPARATOR(i, last, width) \
  85312. ((i) == (last)? "\n};\n\n" : \
  85313. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85314. void gen_trees_header()
  85315. {
  85316. FILE *header = fopen("trees.h", "w");
  85317. int i;
  85318. Assert (header != NULL, "Can't open trees.h");
  85319. fprintf(header,
  85320. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85321. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85322. for (i = 0; i < L_CODES+2; i++) {
  85323. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85324. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85325. }
  85326. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85327. for (i = 0; i < D_CODES; i++) {
  85328. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85329. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85330. }
  85331. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85332. for (i = 0; i < DIST_CODE_LEN; i++) {
  85333. fprintf(header, "%2u%s", _dist_code[i],
  85334. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85335. }
  85336. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85337. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85338. fprintf(header, "%2u%s", _length_code[i],
  85339. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85340. }
  85341. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85342. for (i = 0; i < LENGTH_CODES; i++) {
  85343. fprintf(header, "%1u%s", base_length[i],
  85344. SEPARATOR(i, LENGTH_CODES-1, 20));
  85345. }
  85346. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85347. for (i = 0; i < D_CODES; i++) {
  85348. fprintf(header, "%5u%s", base_dist[i],
  85349. SEPARATOR(i, D_CODES-1, 10));
  85350. }
  85351. fclose(header);
  85352. }
  85353. #endif /* GEN_TREES_H */
  85354. /* ===========================================================================
  85355. * Initialize the tree data structures for a new zlib stream.
  85356. */
  85357. void _tr_init(deflate_state *s)
  85358. {
  85359. tr_static_init();
  85360. s->l_desc.dyn_tree = s->dyn_ltree;
  85361. s->l_desc.stat_desc = &static_l_desc;
  85362. s->d_desc.dyn_tree = s->dyn_dtree;
  85363. s->d_desc.stat_desc = &static_d_desc;
  85364. s->bl_desc.dyn_tree = s->bl_tree;
  85365. s->bl_desc.stat_desc = &static_bl_desc;
  85366. s->bi_buf = 0;
  85367. s->bi_valid = 0;
  85368. s->last_eob_len = 8; /* enough lookahead for inflate */
  85369. #ifdef DEBUG
  85370. s->compressed_len = 0L;
  85371. s->bits_sent = 0L;
  85372. #endif
  85373. /* Initialize the first block of the first file: */
  85374. init_block(s);
  85375. }
  85376. /* ===========================================================================
  85377. * Initialize a new block.
  85378. */
  85379. local void init_block (deflate_state *s)
  85380. {
  85381. int n; /* iterates over tree elements */
  85382. /* Initialize the trees. */
  85383. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85384. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85385. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85386. s->dyn_ltree[END_BLOCK].Freq = 1;
  85387. s->opt_len = s->static_len = 0L;
  85388. s->last_lit = s->matches = 0;
  85389. }
  85390. #define SMALLEST 1
  85391. /* Index within the heap array of least frequent node in the Huffman tree */
  85392. /* ===========================================================================
  85393. * Remove the smallest element from the heap and recreate the heap with
  85394. * one less element. Updates heap and heap_len.
  85395. */
  85396. #define pqremove(s, tree, top) \
  85397. {\
  85398. top = s->heap[SMALLEST]; \
  85399. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85400. pqdownheap(s, tree, SMALLEST); \
  85401. }
  85402. /* ===========================================================================
  85403. * Compares to subtrees, using the tree depth as tie breaker when
  85404. * the subtrees have equal frequency. This minimizes the worst case length.
  85405. */
  85406. #define smaller(tree, n, m, depth) \
  85407. (tree[n].Freq < tree[m].Freq || \
  85408. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85409. /* ===========================================================================
  85410. * Restore the heap property by moving down the tree starting at node k,
  85411. * exchanging a node with the smallest of its two sons if necessary, stopping
  85412. * when the heap property is re-established (each father smaller than its
  85413. * two sons).
  85414. */
  85415. local void pqdownheap (deflate_state *s,
  85416. ct_data *tree, /* the tree to restore */
  85417. int k) /* node to move down */
  85418. {
  85419. int v = s->heap[k];
  85420. int j = k << 1; /* left son of k */
  85421. while (j <= s->heap_len) {
  85422. /* Set j to the smallest of the two sons: */
  85423. if (j < s->heap_len &&
  85424. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85425. j++;
  85426. }
  85427. /* Exit if v is smaller than both sons */
  85428. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85429. /* Exchange v with the smallest son */
  85430. s->heap[k] = s->heap[j]; k = j;
  85431. /* And continue down the tree, setting j to the left son of k */
  85432. j <<= 1;
  85433. }
  85434. s->heap[k] = v;
  85435. }
  85436. /* ===========================================================================
  85437. * Compute the optimal bit lengths for a tree and update the total bit length
  85438. * for the current block.
  85439. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85440. * above are the tree nodes sorted by increasing frequency.
  85441. * OUT assertions: the field len is set to the optimal bit length, the
  85442. * array bl_count contains the frequencies for each bit length.
  85443. * The length opt_len is updated; static_len is also updated if stree is
  85444. * not null.
  85445. */
  85446. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85447. {
  85448. ct_data *tree = desc->dyn_tree;
  85449. int max_code = desc->max_code;
  85450. const ct_data *stree = desc->stat_desc->static_tree;
  85451. const intf *extra = desc->stat_desc->extra_bits;
  85452. int base = desc->stat_desc->extra_base;
  85453. int max_length = desc->stat_desc->max_length;
  85454. int h; /* heap index */
  85455. int n, m; /* iterate over the tree elements */
  85456. int bits; /* bit length */
  85457. int xbits; /* extra bits */
  85458. ush f; /* frequency */
  85459. int overflow = 0; /* number of elements with bit length too large */
  85460. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85461. /* In a first pass, compute the optimal bit lengths (which may
  85462. * overflow in the case of the bit length tree).
  85463. */
  85464. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85465. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85466. n = s->heap[h];
  85467. bits = tree[tree[n].Dad].Len + 1;
  85468. if (bits > max_length) bits = max_length, overflow++;
  85469. tree[n].Len = (ush)bits;
  85470. /* We overwrite tree[n].Dad which is no longer needed */
  85471. if (n > max_code) continue; /* not a leaf node */
  85472. s->bl_count[bits]++;
  85473. xbits = 0;
  85474. if (n >= base) xbits = extra[n-base];
  85475. f = tree[n].Freq;
  85476. s->opt_len += (ulg)f * (bits + xbits);
  85477. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85478. }
  85479. if (overflow == 0) return;
  85480. Trace((stderr,"\nbit length overflow\n"));
  85481. /* This happens for example on obj2 and pic of the Calgary corpus */
  85482. /* Find the first bit length which could increase: */
  85483. do {
  85484. bits = max_length-1;
  85485. while (s->bl_count[bits] == 0) bits--;
  85486. s->bl_count[bits]--; /* move one leaf down the tree */
  85487. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85488. s->bl_count[max_length]--;
  85489. /* The brother of the overflow item also moves one step up,
  85490. * but this does not affect bl_count[max_length]
  85491. */
  85492. overflow -= 2;
  85493. } while (overflow > 0);
  85494. /* Now recompute all bit lengths, scanning in increasing frequency.
  85495. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85496. * lengths instead of fixing only the wrong ones. This idea is taken
  85497. * from 'ar' written by Haruhiko Okumura.)
  85498. */
  85499. for (bits = max_length; bits != 0; bits--) {
  85500. n = s->bl_count[bits];
  85501. while (n != 0) {
  85502. m = s->heap[--h];
  85503. if (m > max_code) continue;
  85504. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85505. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85506. s->opt_len += ((long)bits - (long)tree[m].Len)
  85507. *(long)tree[m].Freq;
  85508. tree[m].Len = (ush)bits;
  85509. }
  85510. n--;
  85511. }
  85512. }
  85513. }
  85514. /* ===========================================================================
  85515. * Generate the codes for a given tree and bit counts (which need not be
  85516. * optimal).
  85517. * IN assertion: the array bl_count contains the bit length statistics for
  85518. * the given tree and the field len is set for all tree elements.
  85519. * OUT assertion: the field code is set for all tree elements of non
  85520. * zero code length.
  85521. */
  85522. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85523. int max_code, /* largest code with non zero frequency */
  85524. ushf *bl_count) /* number of codes at each bit length */
  85525. {
  85526. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85527. ush code = 0; /* running code value */
  85528. int bits; /* bit index */
  85529. int n; /* code index */
  85530. /* The distribution counts are first used to generate the code values
  85531. * without bit reversal.
  85532. */
  85533. for (bits = 1; bits <= MAX_BITS; bits++) {
  85534. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85535. }
  85536. /* Check that the bit counts in bl_count are consistent. The last code
  85537. * must be all ones.
  85538. */
  85539. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85540. "inconsistent bit counts");
  85541. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85542. for (n = 0; n <= max_code; n++) {
  85543. int len = tree[n].Len;
  85544. if (len == 0) continue;
  85545. /* Now reverse the bits */
  85546. tree[n].Code = bi_reverse(next_code[len]++, len);
  85547. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85548. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85549. }
  85550. }
  85551. /* ===========================================================================
  85552. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85553. * Update the total bit length for the current block.
  85554. * IN assertion: the field freq is set for all tree elements.
  85555. * OUT assertions: the fields len and code are set to the optimal bit length
  85556. * and corresponding code. The length opt_len is updated; static_len is
  85557. * also updated if stree is not null. The field max_code is set.
  85558. */
  85559. local void build_tree (deflate_state *s,
  85560. tree_desc *desc) /* the tree descriptor */
  85561. {
  85562. ct_data *tree = desc->dyn_tree;
  85563. const ct_data *stree = desc->stat_desc->static_tree;
  85564. int elems = desc->stat_desc->elems;
  85565. int n, m; /* iterate over heap elements */
  85566. int max_code = -1; /* largest code with non zero frequency */
  85567. int node; /* new node being created */
  85568. /* Construct the initial heap, with least frequent element in
  85569. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85570. * heap[0] is not used.
  85571. */
  85572. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85573. for (n = 0; n < elems; n++) {
  85574. if (tree[n].Freq != 0) {
  85575. s->heap[++(s->heap_len)] = max_code = n;
  85576. s->depth[n] = 0;
  85577. } else {
  85578. tree[n].Len = 0;
  85579. }
  85580. }
  85581. /* The pkzip format requires that at least one distance code exists,
  85582. * and that at least one bit should be sent even if there is only one
  85583. * possible code. So to avoid special checks later on we force at least
  85584. * two codes of non zero frequency.
  85585. */
  85586. while (s->heap_len < 2) {
  85587. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85588. tree[node].Freq = 1;
  85589. s->depth[node] = 0;
  85590. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85591. /* node is 0 or 1 so it does not have extra bits */
  85592. }
  85593. desc->max_code = max_code;
  85594. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85595. * establish sub-heaps of increasing lengths:
  85596. */
  85597. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85598. /* Construct the Huffman tree by repeatedly combining the least two
  85599. * frequent nodes.
  85600. */
  85601. node = elems; /* next internal node of the tree */
  85602. do {
  85603. pqremove(s, tree, n); /* n = node of least frequency */
  85604. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85605. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85606. s->heap[--(s->heap_max)] = m;
  85607. /* Create a new node father of n and m */
  85608. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85609. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85610. s->depth[n] : s->depth[m]) + 1);
  85611. tree[n].Dad = tree[m].Dad = (ush)node;
  85612. #ifdef DUMP_BL_TREE
  85613. if (tree == s->bl_tree) {
  85614. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85615. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85616. }
  85617. #endif
  85618. /* and insert the new node in the heap */
  85619. s->heap[SMALLEST] = node++;
  85620. pqdownheap(s, tree, SMALLEST);
  85621. } while (s->heap_len >= 2);
  85622. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85623. /* At this point, the fields freq and dad are set. We can now
  85624. * generate the bit lengths.
  85625. */
  85626. gen_bitlen(s, (tree_desc *)desc);
  85627. /* The field len is now set, we can generate the bit codes */
  85628. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85629. }
  85630. /* ===========================================================================
  85631. * Scan a literal or distance tree to determine the frequencies of the codes
  85632. * in the bit length tree.
  85633. */
  85634. local void scan_tree (deflate_state *s,
  85635. ct_data *tree, /* the tree to be scanned */
  85636. int max_code) /* and its largest code of non zero frequency */
  85637. {
  85638. int n; /* iterates over all tree elements */
  85639. int prevlen = -1; /* last emitted length */
  85640. int curlen; /* length of current code */
  85641. int nextlen = tree[0].Len; /* length of next code */
  85642. int count = 0; /* repeat count of the current code */
  85643. int max_count = 7; /* max repeat count */
  85644. int min_count = 4; /* min repeat count */
  85645. if (nextlen == 0) max_count = 138, min_count = 3;
  85646. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85647. for (n = 0; n <= max_code; n++) {
  85648. curlen = nextlen; nextlen = tree[n+1].Len;
  85649. if (++count < max_count && curlen == nextlen) {
  85650. continue;
  85651. } else if (count < min_count) {
  85652. s->bl_tree[curlen].Freq += count;
  85653. } else if (curlen != 0) {
  85654. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85655. s->bl_tree[REP_3_6].Freq++;
  85656. } else if (count <= 10) {
  85657. s->bl_tree[REPZ_3_10].Freq++;
  85658. } else {
  85659. s->bl_tree[REPZ_11_138].Freq++;
  85660. }
  85661. count = 0; prevlen = curlen;
  85662. if (nextlen == 0) {
  85663. max_count = 138, min_count = 3;
  85664. } else if (curlen == nextlen) {
  85665. max_count = 6, min_count = 3;
  85666. } else {
  85667. max_count = 7, min_count = 4;
  85668. }
  85669. }
  85670. }
  85671. /* ===========================================================================
  85672. * Send a literal or distance tree in compressed form, using the codes in
  85673. * bl_tree.
  85674. */
  85675. local void send_tree (deflate_state *s,
  85676. ct_data *tree, /* the tree to be scanned */
  85677. int max_code) /* and its largest code of non zero frequency */
  85678. {
  85679. int n; /* iterates over all tree elements */
  85680. int prevlen = -1; /* last emitted length */
  85681. int curlen; /* length of current code */
  85682. int nextlen = tree[0].Len; /* length of next code */
  85683. int count = 0; /* repeat count of the current code */
  85684. int max_count = 7; /* max repeat count */
  85685. int min_count = 4; /* min repeat count */
  85686. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85687. if (nextlen == 0) max_count = 138, min_count = 3;
  85688. for (n = 0; n <= max_code; n++) {
  85689. curlen = nextlen; nextlen = tree[n+1].Len;
  85690. if (++count < max_count && curlen == nextlen) {
  85691. continue;
  85692. } else if (count < min_count) {
  85693. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85694. } else if (curlen != 0) {
  85695. if (curlen != prevlen) {
  85696. send_code(s, curlen, s->bl_tree); count--;
  85697. }
  85698. Assert(count >= 3 && count <= 6, " 3_6?");
  85699. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85700. } else if (count <= 10) {
  85701. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85702. } else {
  85703. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85704. }
  85705. count = 0; prevlen = curlen;
  85706. if (nextlen == 0) {
  85707. max_count = 138, min_count = 3;
  85708. } else if (curlen == nextlen) {
  85709. max_count = 6, min_count = 3;
  85710. } else {
  85711. max_count = 7, min_count = 4;
  85712. }
  85713. }
  85714. }
  85715. /* ===========================================================================
  85716. * Construct the Huffman tree for the bit lengths and return the index in
  85717. * bl_order of the last bit length code to send.
  85718. */
  85719. local int build_bl_tree (deflate_state *s)
  85720. {
  85721. int max_blindex; /* index of last bit length code of non zero freq */
  85722. /* Determine the bit length frequencies for literal and distance trees */
  85723. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85724. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85725. /* Build the bit length tree: */
  85726. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85727. /* opt_len now includes the length of the tree representations, except
  85728. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85729. */
  85730. /* Determine the number of bit length codes to send. The pkzip format
  85731. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85732. * 3 but the actual value used is 4.)
  85733. */
  85734. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85735. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85736. }
  85737. /* Update opt_len to include the bit length tree and counts */
  85738. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85739. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85740. s->opt_len, s->static_len));
  85741. return max_blindex;
  85742. }
  85743. /* ===========================================================================
  85744. * Send the header for a block using dynamic Huffman trees: the counts, the
  85745. * lengths of the bit length codes, the literal tree and the distance tree.
  85746. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85747. */
  85748. local void send_all_trees (deflate_state *s,
  85749. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85750. {
  85751. int rank; /* index in bl_order */
  85752. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85753. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85754. "too many codes");
  85755. Tracev((stderr, "\nbl counts: "));
  85756. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85757. send_bits(s, dcodes-1, 5);
  85758. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85759. for (rank = 0; rank < blcodes; rank++) {
  85760. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85761. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85762. }
  85763. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85764. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85765. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85766. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85767. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85768. }
  85769. /* ===========================================================================
  85770. * Send a stored block
  85771. */
  85772. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85773. {
  85774. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85775. #ifdef DEBUG
  85776. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85777. s->compressed_len += (stored_len + 4) << 3;
  85778. #endif
  85779. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85780. }
  85781. /* ===========================================================================
  85782. * Send one empty static block to give enough lookahead for inflate.
  85783. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85784. * The current inflate code requires 9 bits of lookahead. If the
  85785. * last two codes for the previous block (real code plus EOB) were coded
  85786. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85787. * the last real code. In this case we send two empty static blocks instead
  85788. * of one. (There are no problems if the previous block is stored or fixed.)
  85789. * To simplify the code, we assume the worst case of last real code encoded
  85790. * on one bit only.
  85791. */
  85792. void _tr_align (deflate_state *s)
  85793. {
  85794. send_bits(s, STATIC_TREES<<1, 3);
  85795. send_code(s, END_BLOCK, static_ltree);
  85796. #ifdef DEBUG
  85797. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85798. #endif
  85799. bi_flush(s);
  85800. /* Of the 10 bits for the empty block, we have already sent
  85801. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85802. * the EOB of the previous block) was thus at least one plus the length
  85803. * of the EOB plus what we have just sent of the empty static block.
  85804. */
  85805. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85806. send_bits(s, STATIC_TREES<<1, 3);
  85807. send_code(s, END_BLOCK, static_ltree);
  85808. #ifdef DEBUG
  85809. s->compressed_len += 10L;
  85810. #endif
  85811. bi_flush(s);
  85812. }
  85813. s->last_eob_len = 7;
  85814. }
  85815. /* ===========================================================================
  85816. * Determine the best encoding for the current block: dynamic trees, static
  85817. * trees or store, and output the encoded block to the zip file.
  85818. */
  85819. void _tr_flush_block (deflate_state *s,
  85820. charf *buf, /* input block, or NULL if too old */
  85821. ulg stored_len, /* length of input block */
  85822. int eof) /* true if this is the last block for a file */
  85823. {
  85824. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85825. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85826. /* Build the Huffman trees unless a stored block is forced */
  85827. if (s->level > 0) {
  85828. /* Check if the file is binary or text */
  85829. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85830. set_data_type(s);
  85831. /* Construct the literal and distance trees */
  85832. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85833. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85834. s->static_len));
  85835. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85836. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85837. s->static_len));
  85838. /* At this point, opt_len and static_len are the total bit lengths of
  85839. * the compressed block data, excluding the tree representations.
  85840. */
  85841. /* Build the bit length tree for the above two trees, and get the index
  85842. * in bl_order of the last bit length code to send.
  85843. */
  85844. max_blindex = build_bl_tree(s);
  85845. /* Determine the best encoding. Compute the block lengths in bytes. */
  85846. opt_lenb = (s->opt_len+3+7)>>3;
  85847. static_lenb = (s->static_len+3+7)>>3;
  85848. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85849. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85850. s->last_lit));
  85851. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85852. } else {
  85853. Assert(buf != (char*)0, "lost buf");
  85854. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85855. }
  85856. #ifdef FORCE_STORED
  85857. if (buf != (char*)0) { /* force stored block */
  85858. #else
  85859. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85860. /* 4: two words for the lengths */
  85861. #endif
  85862. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85863. * Otherwise we can't have processed more than WSIZE input bytes since
  85864. * the last block flush, because compression would have been
  85865. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85866. * transform a block into a stored block.
  85867. */
  85868. _tr_stored_block(s, buf, stored_len, eof);
  85869. #ifdef FORCE_STATIC
  85870. } else if (static_lenb >= 0) { /* force static trees */
  85871. #else
  85872. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85873. #endif
  85874. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85875. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85876. #ifdef DEBUG
  85877. s->compressed_len += 3 + s->static_len;
  85878. #endif
  85879. } else {
  85880. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85881. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85882. max_blindex+1);
  85883. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85884. #ifdef DEBUG
  85885. s->compressed_len += 3 + s->opt_len;
  85886. #endif
  85887. }
  85888. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85889. /* The above check is made mod 2^32, for files larger than 512 MB
  85890. * and uLong implemented on 32 bits.
  85891. */
  85892. init_block(s);
  85893. if (eof) {
  85894. bi_windup(s);
  85895. #ifdef DEBUG
  85896. s->compressed_len += 7; /* align on byte boundary */
  85897. #endif
  85898. }
  85899. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85900. s->compressed_len-7*eof));
  85901. }
  85902. /* ===========================================================================
  85903. * Save the match info and tally the frequency counts. Return true if
  85904. * the current block must be flushed.
  85905. */
  85906. int _tr_tally (deflate_state *s,
  85907. unsigned dist, /* distance of matched string */
  85908. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85909. {
  85910. s->d_buf[s->last_lit] = (ush)dist;
  85911. s->l_buf[s->last_lit++] = (uch)lc;
  85912. if (dist == 0) {
  85913. /* lc is the unmatched char */
  85914. s->dyn_ltree[lc].Freq++;
  85915. } else {
  85916. s->matches++;
  85917. /* Here, lc is the match length - MIN_MATCH */
  85918. dist--; /* dist = match distance - 1 */
  85919. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85920. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85921. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85922. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85923. s->dyn_dtree[d_code(dist)].Freq++;
  85924. }
  85925. #ifdef TRUNCATE_BLOCK
  85926. /* Try to guess if it is profitable to stop the current block here */
  85927. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85928. /* Compute an upper bound for the compressed length */
  85929. ulg out_length = (ulg)s->last_lit*8L;
  85930. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85931. int dcode;
  85932. for (dcode = 0; dcode < D_CODES; dcode++) {
  85933. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85934. (5L+extra_dbits[dcode]);
  85935. }
  85936. out_length >>= 3;
  85937. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85938. s->last_lit, in_length, out_length,
  85939. 100L - out_length*100L/in_length));
  85940. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85941. }
  85942. #endif
  85943. return (s->last_lit == s->lit_bufsize-1);
  85944. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85945. * on 16 bit machines and because stored blocks are restricted to
  85946. * 64K-1 bytes.
  85947. */
  85948. }
  85949. /* ===========================================================================
  85950. * Send the block data compressed using the given Huffman trees
  85951. */
  85952. local void compress_block (deflate_state *s,
  85953. ct_data *ltree, /* literal tree */
  85954. ct_data *dtree) /* distance tree */
  85955. {
  85956. unsigned dist; /* distance of matched string */
  85957. int lc; /* match length or unmatched char (if dist == 0) */
  85958. unsigned lx = 0; /* running index in l_buf */
  85959. unsigned code; /* the code to send */
  85960. int extra; /* number of extra bits to send */
  85961. if (s->last_lit != 0) do {
  85962. dist = s->d_buf[lx];
  85963. lc = s->l_buf[lx++];
  85964. if (dist == 0) {
  85965. send_code(s, lc, ltree); /* send a literal byte */
  85966. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85967. } else {
  85968. /* Here, lc is the match length - MIN_MATCH */
  85969. code = _length_code[lc];
  85970. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85971. extra = extra_lbits[code];
  85972. if (extra != 0) {
  85973. lc -= base_length[code];
  85974. send_bits(s, lc, extra); /* send the extra length bits */
  85975. }
  85976. dist--; /* dist is now the match distance - 1 */
  85977. code = d_code(dist);
  85978. Assert (code < D_CODES, "bad d_code");
  85979. send_code(s, code, dtree); /* send the distance code */
  85980. extra = extra_dbits[code];
  85981. if (extra != 0) {
  85982. dist -= base_dist[code];
  85983. send_bits(s, dist, extra); /* send the extra distance bits */
  85984. }
  85985. } /* literal or match pair ? */
  85986. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85987. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85988. "pendingBuf overflow");
  85989. } while (lx < s->last_lit);
  85990. send_code(s, END_BLOCK, ltree);
  85991. s->last_eob_len = ltree[END_BLOCK].Len;
  85992. }
  85993. /* ===========================================================================
  85994. * Set the data type to BINARY or TEXT, using a crude approximation:
  85995. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85996. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85997. * IN assertion: the fields Freq of dyn_ltree are set.
  85998. */
  85999. local void set_data_type (deflate_state *s)
  86000. {
  86001. int n;
  86002. for (n = 0; n < 9; n++)
  86003. if (s->dyn_ltree[n].Freq != 0)
  86004. break;
  86005. if (n == 9)
  86006. for (n = 14; n < 32; n++)
  86007. if (s->dyn_ltree[n].Freq != 0)
  86008. break;
  86009. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  86010. }
  86011. /* ===========================================================================
  86012. * Reverse the first len bits of a code, using straightforward code (a faster
  86013. * method would use a table)
  86014. * IN assertion: 1 <= len <= 15
  86015. */
  86016. local unsigned bi_reverse (unsigned code, int len)
  86017. {
  86018. register unsigned res = 0;
  86019. do {
  86020. res |= code & 1;
  86021. code >>= 1, res <<= 1;
  86022. } while (--len > 0);
  86023. return res >> 1;
  86024. }
  86025. /* ===========================================================================
  86026. * Flush the bit buffer, keeping at most 7 bits in it.
  86027. */
  86028. local void bi_flush (deflate_state *s)
  86029. {
  86030. if (s->bi_valid == 16) {
  86031. put_short(s, s->bi_buf);
  86032. s->bi_buf = 0;
  86033. s->bi_valid = 0;
  86034. } else if (s->bi_valid >= 8) {
  86035. put_byte(s, (Byte)s->bi_buf);
  86036. s->bi_buf >>= 8;
  86037. s->bi_valid -= 8;
  86038. }
  86039. }
  86040. /* ===========================================================================
  86041. * Flush the bit buffer and align the output on a byte boundary
  86042. */
  86043. local void bi_windup (deflate_state *s)
  86044. {
  86045. if (s->bi_valid > 8) {
  86046. put_short(s, s->bi_buf);
  86047. } else if (s->bi_valid > 0) {
  86048. put_byte(s, (Byte)s->bi_buf);
  86049. }
  86050. s->bi_buf = 0;
  86051. s->bi_valid = 0;
  86052. #ifdef DEBUG
  86053. s->bits_sent = (s->bits_sent+7) & ~7;
  86054. #endif
  86055. }
  86056. /* ===========================================================================
  86057. * Copy a stored block, storing first the length and its
  86058. * one's complement if requested.
  86059. */
  86060. local void copy_block(deflate_state *s,
  86061. charf *buf, /* the input data */
  86062. unsigned len, /* its length */
  86063. int header) /* true if block header must be written */
  86064. {
  86065. bi_windup(s); /* align on byte boundary */
  86066. s->last_eob_len = 8; /* enough lookahead for inflate */
  86067. if (header) {
  86068. put_short(s, (ush)len);
  86069. put_short(s, (ush)~len);
  86070. #ifdef DEBUG
  86071. s->bits_sent += 2*16;
  86072. #endif
  86073. }
  86074. #ifdef DEBUG
  86075. s->bits_sent += (ulg)len<<3;
  86076. #endif
  86077. while (len--) {
  86078. put_byte(s, *buf++);
  86079. }
  86080. }
  86081. /*** End of inlined file: trees.c ***/
  86082. /*** Start of inlined file: zutil.c ***/
  86083. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  86084. #ifndef NO_DUMMY_DECL
  86085. struct internal_state {int dummy;}; /* for buggy compilers */
  86086. #endif
  86087. const char * const z_errmsg[10] = {
  86088. "need dictionary", /* Z_NEED_DICT 2 */
  86089. "stream end", /* Z_STREAM_END 1 */
  86090. "", /* Z_OK 0 */
  86091. "file error", /* Z_ERRNO (-1) */
  86092. "stream error", /* Z_STREAM_ERROR (-2) */
  86093. "data error", /* Z_DATA_ERROR (-3) */
  86094. "insufficient memory", /* Z_MEM_ERROR (-4) */
  86095. "buffer error", /* Z_BUF_ERROR (-5) */
  86096. "incompatible version",/* Z_VERSION_ERROR (-6) */
  86097. ""};
  86098. /*const char * ZEXPORT zlibVersion()
  86099. {
  86100. return ZLIB_VERSION;
  86101. }
  86102. uLong ZEXPORT zlibCompileFlags()
  86103. {
  86104. uLong flags;
  86105. flags = 0;
  86106. switch (sizeof(uInt)) {
  86107. case 2: break;
  86108. case 4: flags += 1; break;
  86109. case 8: flags += 2; break;
  86110. default: flags += 3;
  86111. }
  86112. switch (sizeof(uLong)) {
  86113. case 2: break;
  86114. case 4: flags += 1 << 2; break;
  86115. case 8: flags += 2 << 2; break;
  86116. default: flags += 3 << 2;
  86117. }
  86118. switch (sizeof(voidpf)) {
  86119. case 2: break;
  86120. case 4: flags += 1 << 4; break;
  86121. case 8: flags += 2 << 4; break;
  86122. default: flags += 3 << 4;
  86123. }
  86124. switch (sizeof(z_off_t)) {
  86125. case 2: break;
  86126. case 4: flags += 1 << 6; break;
  86127. case 8: flags += 2 << 6; break;
  86128. default: flags += 3 << 6;
  86129. }
  86130. #ifdef DEBUG
  86131. flags += 1 << 8;
  86132. #endif
  86133. #if defined(ASMV) || defined(ASMINF)
  86134. flags += 1 << 9;
  86135. #endif
  86136. #ifdef ZLIB_WINAPI
  86137. flags += 1 << 10;
  86138. #endif
  86139. #ifdef BUILDFIXED
  86140. flags += 1 << 12;
  86141. #endif
  86142. #ifdef DYNAMIC_CRC_TABLE
  86143. flags += 1 << 13;
  86144. #endif
  86145. #ifdef NO_GZCOMPRESS
  86146. flags += 1L << 16;
  86147. #endif
  86148. #ifdef NO_GZIP
  86149. flags += 1L << 17;
  86150. #endif
  86151. #ifdef PKZIP_BUG_WORKAROUND
  86152. flags += 1L << 20;
  86153. #endif
  86154. #ifdef FASTEST
  86155. flags += 1L << 21;
  86156. #endif
  86157. #ifdef STDC
  86158. # ifdef NO_vsnprintf
  86159. flags += 1L << 25;
  86160. # ifdef HAS_vsprintf_void
  86161. flags += 1L << 26;
  86162. # endif
  86163. # else
  86164. # ifdef HAS_vsnprintf_void
  86165. flags += 1L << 26;
  86166. # endif
  86167. # endif
  86168. #else
  86169. flags += 1L << 24;
  86170. # ifdef NO_snprintf
  86171. flags += 1L << 25;
  86172. # ifdef HAS_sprintf_void
  86173. flags += 1L << 26;
  86174. # endif
  86175. # else
  86176. # ifdef HAS_snprintf_void
  86177. flags += 1L << 26;
  86178. # endif
  86179. # endif
  86180. #endif
  86181. return flags;
  86182. }*/
  86183. #ifdef DEBUG
  86184. # ifndef verbose
  86185. # define verbose 0
  86186. # endif
  86187. int z_verbose = verbose;
  86188. void z_error (const char *m)
  86189. {
  86190. fprintf(stderr, "%s\n", m);
  86191. exit(1);
  86192. }
  86193. #endif
  86194. /* exported to allow conversion of error code to string for compress() and
  86195. * uncompress()
  86196. */
  86197. const char * ZEXPORT zError(int err)
  86198. {
  86199. return ERR_MSG(err);
  86200. }
  86201. #if defined(_WIN32_WCE)
  86202. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86203. * errno. We define it as a global variable to simplify porting.
  86204. * Its value is always 0 and should not be used.
  86205. */
  86206. int errno = 0;
  86207. #endif
  86208. #ifndef HAVE_MEMCPY
  86209. void zmemcpy(dest, source, len)
  86210. Bytef* dest;
  86211. const Bytef* source;
  86212. uInt len;
  86213. {
  86214. if (len == 0) return;
  86215. do {
  86216. *dest++ = *source++; /* ??? to be unrolled */
  86217. } while (--len != 0);
  86218. }
  86219. int zmemcmp(s1, s2, len)
  86220. const Bytef* s1;
  86221. const Bytef* s2;
  86222. uInt len;
  86223. {
  86224. uInt j;
  86225. for (j = 0; j < len; j++) {
  86226. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86227. }
  86228. return 0;
  86229. }
  86230. void zmemzero(dest, len)
  86231. Bytef* dest;
  86232. uInt len;
  86233. {
  86234. if (len == 0) return;
  86235. do {
  86236. *dest++ = 0; /* ??? to be unrolled */
  86237. } while (--len != 0);
  86238. }
  86239. #endif
  86240. #ifdef SYS16BIT
  86241. #ifdef __TURBOC__
  86242. /* Turbo C in 16-bit mode */
  86243. # define MY_ZCALLOC
  86244. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86245. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86246. * must fix the pointer. Warning: the pointer must be put back to its
  86247. * original form in order to free it, use zcfree().
  86248. */
  86249. #define MAX_PTR 10
  86250. /* 10*64K = 640K */
  86251. local int next_ptr = 0;
  86252. typedef struct ptr_table_s {
  86253. voidpf org_ptr;
  86254. voidpf new_ptr;
  86255. } ptr_table;
  86256. local ptr_table table[MAX_PTR];
  86257. /* This table is used to remember the original form of pointers
  86258. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86259. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86260. * protected from concurrent access. This hack doesn't work anyway on
  86261. * a protected system like OS/2. Use Microsoft C instead.
  86262. */
  86263. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86264. {
  86265. voidpf buf = opaque; /* just to make some compilers happy */
  86266. ulg bsize = (ulg)items*size;
  86267. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86268. * will return a usable pointer which doesn't have to be normalized.
  86269. */
  86270. if (bsize < 65520L) {
  86271. buf = farmalloc(bsize);
  86272. if (*(ush*)&buf != 0) return buf;
  86273. } else {
  86274. buf = farmalloc(bsize + 16L);
  86275. }
  86276. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86277. table[next_ptr].org_ptr = buf;
  86278. /* Normalize the pointer to seg:0 */
  86279. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86280. *(ush*)&buf = 0;
  86281. table[next_ptr++].new_ptr = buf;
  86282. return buf;
  86283. }
  86284. void zcfree (voidpf opaque, voidpf ptr)
  86285. {
  86286. int n;
  86287. if (*(ush*)&ptr != 0) { /* object < 64K */
  86288. farfree(ptr);
  86289. return;
  86290. }
  86291. /* Find the original pointer */
  86292. for (n = 0; n < next_ptr; n++) {
  86293. if (ptr != table[n].new_ptr) continue;
  86294. farfree(table[n].org_ptr);
  86295. while (++n < next_ptr) {
  86296. table[n-1] = table[n];
  86297. }
  86298. next_ptr--;
  86299. return;
  86300. }
  86301. ptr = opaque; /* just to make some compilers happy */
  86302. Assert(0, "zcfree: ptr not found");
  86303. }
  86304. #endif /* __TURBOC__ */
  86305. #ifdef M_I86
  86306. /* Microsoft C in 16-bit mode */
  86307. # define MY_ZCALLOC
  86308. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86309. # define _halloc halloc
  86310. # define _hfree hfree
  86311. #endif
  86312. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86313. {
  86314. if (opaque) opaque = 0; /* to make compiler happy */
  86315. return _halloc((long)items, size);
  86316. }
  86317. void zcfree (voidpf opaque, voidpf ptr)
  86318. {
  86319. if (opaque) opaque = 0; /* to make compiler happy */
  86320. _hfree(ptr);
  86321. }
  86322. #endif /* M_I86 */
  86323. #endif /* SYS16BIT */
  86324. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86325. #ifndef STDC
  86326. extern voidp malloc OF((uInt size));
  86327. extern voidp calloc OF((uInt items, uInt size));
  86328. extern void free OF((voidpf ptr));
  86329. #endif
  86330. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86331. {
  86332. if (opaque) items += size - size; /* make compiler happy */
  86333. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86334. (voidpf)calloc(items, size);
  86335. }
  86336. void zcfree (voidpf opaque, voidpf ptr)
  86337. {
  86338. free(ptr);
  86339. if (opaque) return; /* make compiler happy */
  86340. }
  86341. #endif /* MY_ZCALLOC */
  86342. /*** End of inlined file: zutil.c ***/
  86343. #undef Byte
  86344. #else
  86345. #include <zlib.h>
  86346. #endif
  86347. }
  86348. #if JUCE_MSVC
  86349. #pragma warning (pop)
  86350. #endif
  86351. BEGIN_JUCE_NAMESPACE
  86352. // internal helper object that holds the zlib structures so they don't have to be
  86353. // included publicly.
  86354. class GZIPDecompressHelper
  86355. {
  86356. public:
  86357. GZIPDecompressHelper (const bool noWrap)
  86358. : finished (true),
  86359. needsDictionary (false),
  86360. error (true),
  86361. streamIsValid (false),
  86362. data (0),
  86363. dataSize (0)
  86364. {
  86365. using namespace zlibNamespace;
  86366. zerostruct (stream);
  86367. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86368. finished = error = ! streamIsValid;
  86369. }
  86370. ~GZIPDecompressHelper()
  86371. {
  86372. using namespace zlibNamespace;
  86373. if (streamIsValid)
  86374. inflateEnd (&stream);
  86375. }
  86376. bool needsInput() const throw() { return dataSize <= 0; }
  86377. void setInput (uint8* const data_, const int size) throw()
  86378. {
  86379. data = data_;
  86380. dataSize = size;
  86381. }
  86382. int doNextBlock (uint8* const dest, const int destSize)
  86383. {
  86384. using namespace zlibNamespace;
  86385. if (streamIsValid && data != 0 && ! finished)
  86386. {
  86387. stream.next_in = data;
  86388. stream.next_out = dest;
  86389. stream.avail_in = dataSize;
  86390. stream.avail_out = destSize;
  86391. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86392. {
  86393. case Z_STREAM_END:
  86394. finished = true;
  86395. // deliberate fall-through
  86396. case Z_OK:
  86397. data += dataSize - stream.avail_in;
  86398. dataSize = stream.avail_in;
  86399. return destSize - stream.avail_out;
  86400. case Z_NEED_DICT:
  86401. needsDictionary = true;
  86402. data += dataSize - stream.avail_in;
  86403. dataSize = stream.avail_in;
  86404. break;
  86405. case Z_DATA_ERROR:
  86406. case Z_MEM_ERROR:
  86407. error = true;
  86408. default:
  86409. break;
  86410. }
  86411. }
  86412. return 0;
  86413. }
  86414. bool finished, needsDictionary, error, streamIsValid;
  86415. private:
  86416. zlibNamespace::z_stream stream;
  86417. uint8* data;
  86418. int dataSize;
  86419. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86420. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86421. };
  86422. const int gzipDecompBufferSize = 32768;
  86423. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86424. const bool deleteSourceWhenDestroyed,
  86425. const bool noWrap_,
  86426. const int64 uncompressedStreamLength_)
  86427. : sourceStream (sourceStream_),
  86428. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86429. uncompressedStreamLength (uncompressedStreamLength_),
  86430. noWrap (noWrap_),
  86431. isEof (false),
  86432. activeBufferSize (0),
  86433. originalSourcePos (sourceStream_->getPosition()),
  86434. currentPos (0),
  86435. buffer (gzipDecompBufferSize),
  86436. helper (new GZIPDecompressHelper (noWrap_))
  86437. {
  86438. }
  86439. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86440. {
  86441. }
  86442. int64 GZIPDecompressorInputStream::getTotalLength()
  86443. {
  86444. return uncompressedStreamLength;
  86445. }
  86446. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86447. {
  86448. if ((howMany > 0) && ! isEof)
  86449. {
  86450. jassert (destBuffer != 0);
  86451. if (destBuffer != 0)
  86452. {
  86453. int numRead = 0;
  86454. uint8* d = static_cast <uint8*> (destBuffer);
  86455. while (! helper->error)
  86456. {
  86457. const int n = helper->doNextBlock (d, howMany);
  86458. currentPos += n;
  86459. if (n == 0)
  86460. {
  86461. if (helper->finished || helper->needsDictionary)
  86462. {
  86463. isEof = true;
  86464. return numRead;
  86465. }
  86466. if (helper->needsInput())
  86467. {
  86468. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  86469. if (activeBufferSize > 0)
  86470. {
  86471. helper->setInput (buffer, activeBufferSize);
  86472. }
  86473. else
  86474. {
  86475. isEof = true;
  86476. return numRead;
  86477. }
  86478. }
  86479. }
  86480. else
  86481. {
  86482. numRead += n;
  86483. howMany -= n;
  86484. d += n;
  86485. if (howMany <= 0)
  86486. return numRead;
  86487. }
  86488. }
  86489. }
  86490. }
  86491. return 0;
  86492. }
  86493. bool GZIPDecompressorInputStream::isExhausted()
  86494. {
  86495. return helper->error || isEof;
  86496. }
  86497. int64 GZIPDecompressorInputStream::getPosition()
  86498. {
  86499. return currentPos;
  86500. }
  86501. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86502. {
  86503. if (newPos < currentPos)
  86504. {
  86505. // to go backwards, reset the stream and start again..
  86506. isEof = false;
  86507. activeBufferSize = 0;
  86508. currentPos = 0;
  86509. helper = new GZIPDecompressHelper (noWrap);
  86510. sourceStream->setPosition (originalSourcePos);
  86511. }
  86512. skipNextBytes (newPos - currentPos);
  86513. return true;
  86514. }
  86515. END_JUCE_NAMESPACE
  86516. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86517. #endif
  86518. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86519. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86520. #if JUCE_USE_FLAC
  86521. #if JUCE_WINDOWS
  86522. #include <windows.h>
  86523. #endif
  86524. namespace FlacNamespace
  86525. {
  86526. #if JUCE_INCLUDE_FLAC_CODE
  86527. #if JUCE_MSVC
  86528. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86529. #endif
  86530. #define FLAC__NO_DLL 1
  86531. #if ! defined (SIZE_MAX)
  86532. #define SIZE_MAX 0xffffffff
  86533. #endif
  86534. #define __STDC_LIMIT_MACROS 1
  86535. /*** Start of inlined file: all.h ***/
  86536. #ifndef FLAC__ALL_H
  86537. #define FLAC__ALL_H
  86538. /*** Start of inlined file: export.h ***/
  86539. #ifndef FLAC__EXPORT_H
  86540. #define FLAC__EXPORT_H
  86541. /** \file include/FLAC/export.h
  86542. *
  86543. * \brief
  86544. * This module contains #defines and symbols for exporting function
  86545. * calls, and providing version information and compiled-in features.
  86546. *
  86547. * See the \link flac_export export \endlink module.
  86548. */
  86549. /** \defgroup flac_export FLAC/export.h: export symbols
  86550. * \ingroup flac
  86551. *
  86552. * \brief
  86553. * This module contains #defines and symbols for exporting function
  86554. * calls, and providing version information and compiled-in features.
  86555. *
  86556. * If you are compiling with MSVC and will link to the static library
  86557. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86558. * make sure the symbols are exported properly.
  86559. *
  86560. * \{
  86561. */
  86562. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86563. #define FLAC_API
  86564. #else
  86565. #ifdef FLAC_API_EXPORTS
  86566. #define FLAC_API _declspec(dllexport)
  86567. #else
  86568. #define FLAC_API _declspec(dllimport)
  86569. #endif
  86570. #endif
  86571. /** These #defines will mirror the libtool-based library version number, see
  86572. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86573. */
  86574. #define FLAC_API_VERSION_CURRENT 10
  86575. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86576. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86577. #ifdef __cplusplus
  86578. extern "C" {
  86579. #endif
  86580. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86581. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86582. #ifdef __cplusplus
  86583. }
  86584. #endif
  86585. /* \} */
  86586. #endif
  86587. /*** End of inlined file: export.h ***/
  86588. /*** Start of inlined file: assert.h ***/
  86589. #ifndef FLAC__ASSERT_H
  86590. #define FLAC__ASSERT_H
  86591. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86592. #ifdef DEBUG
  86593. #include <assert.h>
  86594. #define FLAC__ASSERT(x) assert(x)
  86595. #define FLAC__ASSERT_DECLARATION(x) x
  86596. #else
  86597. #define FLAC__ASSERT(x)
  86598. #define FLAC__ASSERT_DECLARATION(x)
  86599. #endif
  86600. #endif
  86601. /*** End of inlined file: assert.h ***/
  86602. /*** Start of inlined file: callback.h ***/
  86603. #ifndef FLAC__CALLBACK_H
  86604. #define FLAC__CALLBACK_H
  86605. /*** Start of inlined file: ordinals.h ***/
  86606. #ifndef FLAC__ORDINALS_H
  86607. #define FLAC__ORDINALS_H
  86608. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86609. #include <inttypes.h>
  86610. #endif
  86611. typedef signed char FLAC__int8;
  86612. typedef unsigned char FLAC__uint8;
  86613. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86614. typedef __int16 FLAC__int16;
  86615. typedef __int32 FLAC__int32;
  86616. typedef __int64 FLAC__int64;
  86617. typedef unsigned __int16 FLAC__uint16;
  86618. typedef unsigned __int32 FLAC__uint32;
  86619. typedef unsigned __int64 FLAC__uint64;
  86620. #elif defined(__EMX__)
  86621. typedef short FLAC__int16;
  86622. typedef long FLAC__int32;
  86623. typedef long long FLAC__int64;
  86624. typedef unsigned short FLAC__uint16;
  86625. typedef unsigned long FLAC__uint32;
  86626. typedef unsigned long long FLAC__uint64;
  86627. #else
  86628. typedef int16_t FLAC__int16;
  86629. typedef int32_t FLAC__int32;
  86630. typedef int64_t FLAC__int64;
  86631. typedef uint16_t FLAC__uint16;
  86632. typedef uint32_t FLAC__uint32;
  86633. typedef uint64_t FLAC__uint64;
  86634. #endif
  86635. typedef int FLAC__bool;
  86636. typedef FLAC__uint8 FLAC__byte;
  86637. #ifdef true
  86638. #undef true
  86639. #endif
  86640. #ifdef false
  86641. #undef false
  86642. #endif
  86643. #ifndef __cplusplus
  86644. #define true 1
  86645. #define false 0
  86646. #endif
  86647. #endif
  86648. /*** End of inlined file: ordinals.h ***/
  86649. #include <stdlib.h> /* for size_t */
  86650. /** \file include/FLAC/callback.h
  86651. *
  86652. * \brief
  86653. * This module defines the structures for describing I/O callbacks
  86654. * to the other FLAC interfaces.
  86655. *
  86656. * See the detailed documentation for callbacks in the
  86657. * \link flac_callbacks callbacks \endlink module.
  86658. */
  86659. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86660. * \ingroup flac
  86661. *
  86662. * \brief
  86663. * This module defines the structures for describing I/O callbacks
  86664. * to the other FLAC interfaces.
  86665. *
  86666. * The purpose of the I/O callback functions is to create a common way
  86667. * for the metadata interfaces to handle I/O.
  86668. *
  86669. * Originally the metadata interfaces required filenames as the way of
  86670. * specifying FLAC files to operate on. This is problematic in some
  86671. * environments so there is an additional option to specify a set of
  86672. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86673. *
  86674. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86675. * opaque structure for a data source.
  86676. *
  86677. * The callback function prototypes are similar (but not identical) to the
  86678. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86679. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86680. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86681. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86682. * is required. \warning You generally CANNOT directly use fseek or ftell
  86683. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86684. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86685. * large files. You will have to find an equivalent function (e.g. ftello),
  86686. * or write a wrapper. The same is true for feof() since this is usually
  86687. * implemented as a macro, not as a function whose address can be taken.
  86688. *
  86689. * \{
  86690. */
  86691. #ifdef __cplusplus
  86692. extern "C" {
  86693. #endif
  86694. /** This is the opaque handle type used by the callbacks. Typically
  86695. * this is a \c FILE* or address of a file descriptor.
  86696. */
  86697. typedef void* FLAC__IOHandle;
  86698. /** Signature for the read callback.
  86699. * The signature and semantics match POSIX fread() implementations
  86700. * and can generally be used interchangeably.
  86701. *
  86702. * \param ptr The address of the read buffer.
  86703. * \param size The size of the records to be read.
  86704. * \param nmemb The number of records to be read.
  86705. * \param handle The handle to the data source.
  86706. * \retval size_t
  86707. * The number of records read.
  86708. */
  86709. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86710. /** Signature for the write callback.
  86711. * The signature and semantics match POSIX fwrite() implementations
  86712. * and can generally be used interchangeably.
  86713. *
  86714. * \param ptr The address of the write buffer.
  86715. * \param size The size of the records to be written.
  86716. * \param nmemb The number of records to be written.
  86717. * \param handle The handle to the data source.
  86718. * \retval size_t
  86719. * The number of records written.
  86720. */
  86721. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86722. /** Signature for the seek callback.
  86723. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86724. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86725. * and 32-bits wide.
  86726. *
  86727. * \param handle The handle to the data source.
  86728. * \param offset The new position, relative to \a whence
  86729. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86730. * \retval int
  86731. * \c 0 on success, \c -1 on error.
  86732. */
  86733. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86734. /** Signature for the tell callback.
  86735. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86736. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86737. * and 32-bits wide.
  86738. *
  86739. * \param handle The handle to the data source.
  86740. * \retval FLAC__int64
  86741. * The current position on success, \c -1 on error.
  86742. */
  86743. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86744. /** Signature for the EOF callback.
  86745. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86746. * on many systems, feof() is a macro, so in this case a wrapper function
  86747. * must be provided instead.
  86748. *
  86749. * \param handle The handle to the data source.
  86750. * \retval int
  86751. * \c 0 if not at end of file, nonzero if at end of file.
  86752. */
  86753. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86754. /** Signature for the close callback.
  86755. * The signature and semantics match POSIX fclose() implementations
  86756. * and can generally be used interchangeably.
  86757. *
  86758. * \param handle The handle to the data source.
  86759. * \retval int
  86760. * \c 0 on success, \c EOF on error.
  86761. */
  86762. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86763. /** A structure for holding a set of callbacks.
  86764. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86765. * describe which of the callbacks are required. The ones that are not
  86766. * required may be set to NULL.
  86767. *
  86768. * If the seek requirement for an interface is optional, you can signify that
  86769. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86770. */
  86771. typedef struct {
  86772. FLAC__IOCallback_Read read;
  86773. FLAC__IOCallback_Write write;
  86774. FLAC__IOCallback_Seek seek;
  86775. FLAC__IOCallback_Tell tell;
  86776. FLAC__IOCallback_Eof eof;
  86777. FLAC__IOCallback_Close close;
  86778. } FLAC__IOCallbacks;
  86779. /* \} */
  86780. #ifdef __cplusplus
  86781. }
  86782. #endif
  86783. #endif
  86784. /*** End of inlined file: callback.h ***/
  86785. /*** Start of inlined file: format.h ***/
  86786. #ifndef FLAC__FORMAT_H
  86787. #define FLAC__FORMAT_H
  86788. #ifdef __cplusplus
  86789. extern "C" {
  86790. #endif
  86791. /** \file include/FLAC/format.h
  86792. *
  86793. * \brief
  86794. * This module contains structure definitions for the representation
  86795. * of FLAC format components in memory. These are the basic
  86796. * structures used by the rest of the interfaces.
  86797. *
  86798. * See the detailed documentation in the
  86799. * \link flac_format format \endlink module.
  86800. */
  86801. /** \defgroup flac_format FLAC/format.h: format components
  86802. * \ingroup flac
  86803. *
  86804. * \brief
  86805. * This module contains structure definitions for the representation
  86806. * of FLAC format components in memory. These are the basic
  86807. * structures used by the rest of the interfaces.
  86808. *
  86809. * First, you should be familiar with the
  86810. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86811. * follow directly from the specification. As a user of libFLAC, the
  86812. * interesting parts really are the structures that describe the frame
  86813. * header and metadata blocks.
  86814. *
  86815. * The format structures here are very primitive, designed to store
  86816. * information in an efficient way. Reading information from the
  86817. * structures is easy but creating or modifying them directly is
  86818. * more complex. For the most part, as a user of a library, editing
  86819. * is not necessary; however, for metadata blocks it is, so there are
  86820. * convenience functions provided in the \link flac_metadata metadata
  86821. * module \endlink to simplify the manipulation of metadata blocks.
  86822. *
  86823. * \note
  86824. * It's not the best convention, but symbols ending in _LEN are in bits
  86825. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86826. * global variables because they are usually used when declaring byte
  86827. * arrays and some compilers require compile-time knowledge of array
  86828. * sizes when declared on the stack.
  86829. *
  86830. * \{
  86831. */
  86832. /*
  86833. Most of the values described in this file are defined by the FLAC
  86834. format specification. There is nothing to tune here.
  86835. */
  86836. /** The largest legal metadata type code. */
  86837. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86838. /** The minimum block size, in samples, permitted by the format. */
  86839. #define FLAC__MIN_BLOCK_SIZE (16u)
  86840. /** The maximum block size, in samples, permitted by the format. */
  86841. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86842. /** The maximum block size, in samples, permitted by the FLAC subset for
  86843. * sample rates up to 48kHz. */
  86844. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86845. /** The maximum number of channels permitted by the format. */
  86846. #define FLAC__MAX_CHANNELS (8u)
  86847. /** The minimum sample resolution permitted by the format. */
  86848. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86849. /** The maximum sample resolution permitted by the format. */
  86850. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86851. /** The maximum sample resolution permitted by libFLAC.
  86852. *
  86853. * \warning
  86854. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86855. * the reference encoder/decoder is currently limited to 24 bits because
  86856. * of prevalent 32-bit math, so make sure and use this value when
  86857. * appropriate.
  86858. */
  86859. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86860. /** The maximum sample rate permitted by the format. The value is
  86861. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86862. * as to why.
  86863. */
  86864. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86865. /** The maximum LPC order permitted by the format. */
  86866. #define FLAC__MAX_LPC_ORDER (32u)
  86867. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86868. * up to 48kHz. */
  86869. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86870. /** The minimum quantized linear predictor coefficient precision
  86871. * permitted by the format.
  86872. */
  86873. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86874. /** The maximum quantized linear predictor coefficient precision
  86875. * permitted by the format.
  86876. */
  86877. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86878. /** The maximum order of the fixed predictors permitted by the format. */
  86879. #define FLAC__MAX_FIXED_ORDER (4u)
  86880. /** The maximum Rice partition order permitted by the format. */
  86881. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86882. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86883. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86884. /** The version string of the release, stamped onto the libraries and binaries.
  86885. *
  86886. * \note
  86887. * This does not correspond to the shared library version number, which
  86888. * is used to determine binary compatibility.
  86889. */
  86890. extern FLAC_API const char *FLAC__VERSION_STRING;
  86891. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86892. * This is a NUL-terminated ASCII string; when inserted into the
  86893. * VORBIS_COMMENT the trailing null is stripped.
  86894. */
  86895. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86896. /** The byte string representation of the beginning of a FLAC stream. */
  86897. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86898. /** The 32-bit integer big-endian representation of the beginning of
  86899. * a FLAC stream.
  86900. */
  86901. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86902. /** The length of the FLAC signature in bits. */
  86903. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86904. /** The length of the FLAC signature in bytes. */
  86905. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86906. /*****************************************************************************
  86907. *
  86908. * Subframe structures
  86909. *
  86910. *****************************************************************************/
  86911. /*****************************************************************************/
  86912. /** An enumeration of the available entropy coding methods. */
  86913. typedef enum {
  86914. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86915. /**< Residual is coded by partitioning into contexts, each with it's own
  86916. * 4-bit Rice parameter. */
  86917. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86918. /**< Residual is coded by partitioning into contexts, each with it's own
  86919. * 5-bit Rice parameter. */
  86920. } FLAC__EntropyCodingMethodType;
  86921. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86922. *
  86923. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86924. * give the string equivalent. The contents should not be modified.
  86925. */
  86926. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86927. /** Contents of a Rice partitioned residual
  86928. */
  86929. typedef struct {
  86930. unsigned *parameters;
  86931. /**< The Rice parameters for each context. */
  86932. unsigned *raw_bits;
  86933. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86934. * partitions and zero for unescaped partitions.
  86935. */
  86936. unsigned capacity_by_order;
  86937. /**< The capacity of the \a parameters and \a raw_bits arrays
  86938. * specified as an order, i.e. the number of array elements
  86939. * allocated is 2 ^ \a capacity_by_order.
  86940. */
  86941. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86942. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86943. */
  86944. typedef struct {
  86945. unsigned order;
  86946. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86947. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86948. /**< The context's Rice parameters and/or raw bits. */
  86949. } FLAC__EntropyCodingMethod_PartitionedRice;
  86950. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86951. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86952. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86953. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86954. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86955. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86956. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86957. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86958. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86959. */
  86960. typedef struct {
  86961. FLAC__EntropyCodingMethodType type;
  86962. union {
  86963. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86964. } data;
  86965. } FLAC__EntropyCodingMethod;
  86966. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86967. /*****************************************************************************/
  86968. /** An enumeration of the available subframe types. */
  86969. typedef enum {
  86970. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86971. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86972. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86973. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86974. } FLAC__SubframeType;
  86975. /** Maps a FLAC__SubframeType to a C string.
  86976. *
  86977. * Using a FLAC__SubframeType as the index to this array will
  86978. * give the string equivalent. The contents should not be modified.
  86979. */
  86980. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86981. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86982. */
  86983. typedef struct {
  86984. FLAC__int32 value; /**< The constant signal value. */
  86985. } FLAC__Subframe_Constant;
  86986. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86987. */
  86988. typedef struct {
  86989. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86990. } FLAC__Subframe_Verbatim;
  86991. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86992. */
  86993. typedef struct {
  86994. FLAC__EntropyCodingMethod entropy_coding_method;
  86995. /**< The residual coding method. */
  86996. unsigned order;
  86997. /**< The polynomial order. */
  86998. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86999. /**< Warmup samples to prime the predictor, length == order. */
  87000. const FLAC__int32 *residual;
  87001. /**< The residual signal, length == (blocksize minus order) samples. */
  87002. } FLAC__Subframe_Fixed;
  87003. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  87004. */
  87005. typedef struct {
  87006. FLAC__EntropyCodingMethod entropy_coding_method;
  87007. /**< The residual coding method. */
  87008. unsigned order;
  87009. /**< The FIR order. */
  87010. unsigned qlp_coeff_precision;
  87011. /**< Quantized FIR filter coefficient precision in bits. */
  87012. int quantization_level;
  87013. /**< The qlp coeff shift needed. */
  87014. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  87015. /**< FIR filter coefficients. */
  87016. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  87017. /**< Warmup samples to prime the predictor, length == order. */
  87018. const FLAC__int32 *residual;
  87019. /**< The residual signal, length == (blocksize minus order) samples. */
  87020. } FLAC__Subframe_LPC;
  87021. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  87022. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  87023. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  87024. */
  87025. typedef struct {
  87026. FLAC__SubframeType type;
  87027. union {
  87028. FLAC__Subframe_Constant constant;
  87029. FLAC__Subframe_Fixed fixed;
  87030. FLAC__Subframe_LPC lpc;
  87031. FLAC__Subframe_Verbatim verbatim;
  87032. } data;
  87033. unsigned wasted_bits;
  87034. } FLAC__Subframe;
  87035. /** == 1 (bit)
  87036. *
  87037. * This used to be a zero-padding bit (hence the name
  87038. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  87039. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  87040. * to mean something else.
  87041. */
  87042. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  87043. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  87044. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  87045. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  87046. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  87047. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  87048. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  87049. /*****************************************************************************/
  87050. /*****************************************************************************
  87051. *
  87052. * Frame structures
  87053. *
  87054. *****************************************************************************/
  87055. /** An enumeration of the available channel assignments. */
  87056. typedef enum {
  87057. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  87058. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  87059. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  87060. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  87061. } FLAC__ChannelAssignment;
  87062. /** Maps a FLAC__ChannelAssignment to a C string.
  87063. *
  87064. * Using a FLAC__ChannelAssignment as the index to this array will
  87065. * give the string equivalent. The contents should not be modified.
  87066. */
  87067. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  87068. /** An enumeration of the possible frame numbering methods. */
  87069. typedef enum {
  87070. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  87071. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  87072. } FLAC__FrameNumberType;
  87073. /** Maps a FLAC__FrameNumberType to a C string.
  87074. *
  87075. * Using a FLAC__FrameNumberType as the index to this array will
  87076. * give the string equivalent. The contents should not be modified.
  87077. */
  87078. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  87079. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  87080. */
  87081. typedef struct {
  87082. unsigned blocksize;
  87083. /**< The number of samples per subframe. */
  87084. unsigned sample_rate;
  87085. /**< The sample rate in Hz. */
  87086. unsigned channels;
  87087. /**< The number of channels (== number of subframes). */
  87088. FLAC__ChannelAssignment channel_assignment;
  87089. /**< The channel assignment for the frame. */
  87090. unsigned bits_per_sample;
  87091. /**< The sample resolution. */
  87092. FLAC__FrameNumberType number_type;
  87093. /**< The numbering scheme used for the frame. As a convenience, the
  87094. * decoder will always convert a frame number to a sample number because
  87095. * the rules are complex. */
  87096. union {
  87097. FLAC__uint32 frame_number;
  87098. FLAC__uint64 sample_number;
  87099. } number;
  87100. /**< The frame number or sample number of first sample in frame;
  87101. * use the \a number_type value to determine which to use. */
  87102. FLAC__uint8 crc;
  87103. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  87104. * of the raw frame header bytes, meaning everything before the CRC byte
  87105. * including the sync code.
  87106. */
  87107. } FLAC__FrameHeader;
  87108. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  87109. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  87110. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  87111. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  87112. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  87113. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  87114. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  87115. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  87116. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  87117. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  87118. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  87119. */
  87120. typedef struct {
  87121. FLAC__uint16 crc;
  87122. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  87123. * 0) of the bytes before the crc, back to and including the frame header
  87124. * sync code.
  87125. */
  87126. } FLAC__FrameFooter;
  87127. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  87128. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  87129. */
  87130. typedef struct {
  87131. FLAC__FrameHeader header;
  87132. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87133. FLAC__FrameFooter footer;
  87134. } FLAC__Frame;
  87135. /*****************************************************************************/
  87136. /*****************************************************************************
  87137. *
  87138. * Meta-data structures
  87139. *
  87140. *****************************************************************************/
  87141. /** An enumeration of the available metadata block types. */
  87142. typedef enum {
  87143. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87144. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87145. FLAC__METADATA_TYPE_PADDING = 1,
  87146. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87147. FLAC__METADATA_TYPE_APPLICATION = 2,
  87148. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87149. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87150. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87151. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87152. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87153. FLAC__METADATA_TYPE_CUESHEET = 5,
  87154. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87155. FLAC__METADATA_TYPE_PICTURE = 6,
  87156. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87157. FLAC__METADATA_TYPE_UNDEFINED = 7
  87158. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87159. } FLAC__MetadataType;
  87160. /** Maps a FLAC__MetadataType to a C string.
  87161. *
  87162. * Using a FLAC__MetadataType as the index to this array will
  87163. * give the string equivalent. The contents should not be modified.
  87164. */
  87165. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87166. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87167. */
  87168. typedef struct {
  87169. unsigned min_blocksize, max_blocksize;
  87170. unsigned min_framesize, max_framesize;
  87171. unsigned sample_rate;
  87172. unsigned channels;
  87173. unsigned bits_per_sample;
  87174. FLAC__uint64 total_samples;
  87175. FLAC__byte md5sum[16];
  87176. } FLAC__StreamMetadata_StreamInfo;
  87177. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87178. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87179. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87180. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87181. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87182. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87183. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87184. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87185. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87186. /** The total stream length of the STREAMINFO block in bytes. */
  87187. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87188. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87189. */
  87190. typedef struct {
  87191. int dummy;
  87192. /**< Conceptually this is an empty struct since we don't store the
  87193. * padding bytes. Empty structs are not allowed by some C compilers,
  87194. * hence the dummy.
  87195. */
  87196. } FLAC__StreamMetadata_Padding;
  87197. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87198. */
  87199. typedef struct {
  87200. FLAC__byte id[4];
  87201. FLAC__byte *data;
  87202. } FLAC__StreamMetadata_Application;
  87203. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87204. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87205. */
  87206. typedef struct {
  87207. FLAC__uint64 sample_number;
  87208. /**< The sample number of the target frame. */
  87209. FLAC__uint64 stream_offset;
  87210. /**< The offset, in bytes, of the target frame with respect to
  87211. * beginning of the first frame. */
  87212. unsigned frame_samples;
  87213. /**< The number of samples in the target frame. */
  87214. } FLAC__StreamMetadata_SeekPoint;
  87215. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87216. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87217. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87218. /** The total stream length of a seek point in bytes. */
  87219. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87220. /** The value used in the \a sample_number field of
  87221. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87222. * point (== 0xffffffffffffffff).
  87223. */
  87224. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87225. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87226. *
  87227. * \note From the format specification:
  87228. * - The seek points must be sorted by ascending sample number.
  87229. * - Each seek point's sample number must be the first sample of the
  87230. * target frame.
  87231. * - Each seek point's sample number must be unique within the table.
  87232. * - Existence of a SEEKTABLE block implies a correct setting of
  87233. * total_samples in the stream_info block.
  87234. * - Behavior is undefined when more than one SEEKTABLE block is
  87235. * present in a stream.
  87236. */
  87237. typedef struct {
  87238. unsigned num_points;
  87239. FLAC__StreamMetadata_SeekPoint *points;
  87240. } FLAC__StreamMetadata_SeekTable;
  87241. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87242. *
  87243. * For convenience, the APIs maintain a trailing NUL character at the end of
  87244. * \a entry which is not counted toward \a length, i.e.
  87245. * \code strlen(entry) == length \endcode
  87246. */
  87247. typedef struct {
  87248. FLAC__uint32 length;
  87249. FLAC__byte *entry;
  87250. } FLAC__StreamMetadata_VorbisComment_Entry;
  87251. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87252. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87253. */
  87254. typedef struct {
  87255. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87256. FLAC__uint32 num_comments;
  87257. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87258. } FLAC__StreamMetadata_VorbisComment;
  87259. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87260. /** FLAC CUESHEET track index structure. (See the
  87261. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87262. * the full description of each field.)
  87263. */
  87264. typedef struct {
  87265. FLAC__uint64 offset;
  87266. /**< Offset in samples, relative to the track offset, of the index
  87267. * point.
  87268. */
  87269. FLAC__byte number;
  87270. /**< The index point number. */
  87271. } FLAC__StreamMetadata_CueSheet_Index;
  87272. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87273. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87274. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87275. /** FLAC CUESHEET track structure. (See the
  87276. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87277. * the full description of each field.)
  87278. */
  87279. typedef struct {
  87280. FLAC__uint64 offset;
  87281. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87282. FLAC__byte number;
  87283. /**< The track number. */
  87284. char isrc[13];
  87285. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87286. unsigned type:1;
  87287. /**< The track type: 0 for audio, 1 for non-audio. */
  87288. unsigned pre_emphasis:1;
  87289. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87290. FLAC__byte num_indices;
  87291. /**< The number of track index points. */
  87292. FLAC__StreamMetadata_CueSheet_Index *indices;
  87293. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87294. } FLAC__StreamMetadata_CueSheet_Track;
  87295. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87296. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87297. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87298. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87299. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87300. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87301. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87302. /** FLAC CUESHEET structure. (See the
  87303. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87304. * for the full description of each field.)
  87305. */
  87306. typedef struct {
  87307. char media_catalog_number[129];
  87308. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87309. * general, the media catalog number may be 0 to 128 bytes long; any
  87310. * unused characters should be right-padded with NUL characters.
  87311. */
  87312. FLAC__uint64 lead_in;
  87313. /**< The number of lead-in samples. */
  87314. FLAC__bool is_cd;
  87315. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87316. unsigned num_tracks;
  87317. /**< The number of tracks. */
  87318. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87319. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87320. } FLAC__StreamMetadata_CueSheet;
  87321. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87322. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87323. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87324. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87325. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87326. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87327. typedef enum {
  87328. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87329. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87330. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87331. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87332. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87333. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87334. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87335. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87336. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87337. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87338. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87339. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87340. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87341. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87342. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87343. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87344. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87345. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87346. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87347. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87348. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87349. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87350. } FLAC__StreamMetadata_Picture_Type;
  87351. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87352. *
  87353. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87354. * will give the string equivalent. The contents should not be
  87355. * modified.
  87356. */
  87357. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87358. /** FLAC PICTURE structure. (See the
  87359. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87360. * for the full description of each field.)
  87361. */
  87362. typedef struct {
  87363. FLAC__StreamMetadata_Picture_Type type;
  87364. /**< The kind of picture stored. */
  87365. char *mime_type;
  87366. /**< Picture data's MIME type, in ASCII printable characters
  87367. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87368. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87369. * MIME type of '-->' is also allowed, in which case the picture
  87370. * data should be a complete URL. In file storage, the MIME type is
  87371. * stored as a 32-bit length followed by the ASCII string with no NUL
  87372. * terminator, but is converted to a plain C string in this structure
  87373. * for convenience.
  87374. */
  87375. FLAC__byte *description;
  87376. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87377. * the description is stored as a 32-bit length followed by the UTF-8
  87378. * string with no NUL terminator, but is converted to a plain C string
  87379. * in this structure for convenience.
  87380. */
  87381. FLAC__uint32 width;
  87382. /**< Picture's width in pixels. */
  87383. FLAC__uint32 height;
  87384. /**< Picture's height in pixels. */
  87385. FLAC__uint32 depth;
  87386. /**< Picture's color depth in bits-per-pixel. */
  87387. FLAC__uint32 colors;
  87388. /**< For indexed palettes (like GIF), picture's number of colors (the
  87389. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87390. */
  87391. FLAC__uint32 data_length;
  87392. /**< Length of binary picture data in bytes. */
  87393. FLAC__byte *data;
  87394. /**< Binary picture data. */
  87395. } FLAC__StreamMetadata_Picture;
  87396. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87397. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87398. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87399. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87400. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87401. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87402. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87403. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87404. /** Structure that is used when a metadata block of unknown type is loaded.
  87405. * The contents are opaque. The structure is used only internally to
  87406. * correctly handle unknown metadata.
  87407. */
  87408. typedef struct {
  87409. FLAC__byte *data;
  87410. } FLAC__StreamMetadata_Unknown;
  87411. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87412. */
  87413. typedef struct {
  87414. FLAC__MetadataType type;
  87415. /**< The type of the metadata block; used determine which member of the
  87416. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87417. * then \a data.unknown must be used. */
  87418. FLAC__bool is_last;
  87419. /**< \c true if this metadata block is the last, else \a false */
  87420. unsigned length;
  87421. /**< Length, in bytes, of the block data as it appears in the stream. */
  87422. union {
  87423. FLAC__StreamMetadata_StreamInfo stream_info;
  87424. FLAC__StreamMetadata_Padding padding;
  87425. FLAC__StreamMetadata_Application application;
  87426. FLAC__StreamMetadata_SeekTable seek_table;
  87427. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87428. FLAC__StreamMetadata_CueSheet cue_sheet;
  87429. FLAC__StreamMetadata_Picture picture;
  87430. FLAC__StreamMetadata_Unknown unknown;
  87431. } data;
  87432. /**< Polymorphic block data; use the \a type value to determine which
  87433. * to use. */
  87434. } FLAC__StreamMetadata;
  87435. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87436. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87437. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87438. /** The total stream length of a metadata block header in bytes. */
  87439. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87440. /*****************************************************************************/
  87441. /*****************************************************************************
  87442. *
  87443. * Utility functions
  87444. *
  87445. *****************************************************************************/
  87446. /** Tests that a sample rate is valid for FLAC.
  87447. *
  87448. * \param sample_rate The sample rate to test for compliance.
  87449. * \retval FLAC__bool
  87450. * \c true if the given sample rate conforms to the specification, else
  87451. * \c false.
  87452. */
  87453. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87454. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87455. * for valid sample rates are slightly more complex since the rate has to
  87456. * be expressible completely in the frame header.
  87457. *
  87458. * \param sample_rate The sample rate to test for compliance.
  87459. * \retval FLAC__bool
  87460. * \c true if the given sample rate conforms to the specification for the
  87461. * subset, else \c false.
  87462. */
  87463. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87464. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87465. * comment specification.
  87466. *
  87467. * Vorbis comment names must be composed only of characters from
  87468. * [0x20-0x3C,0x3E-0x7D].
  87469. *
  87470. * \param name A NUL-terminated string to be checked.
  87471. * \assert
  87472. * \code name != NULL \endcode
  87473. * \retval FLAC__bool
  87474. * \c false if entry name is illegal, else \c true.
  87475. */
  87476. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87477. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87478. * comment specification.
  87479. *
  87480. * Vorbis comment values must be valid UTF-8 sequences.
  87481. *
  87482. * \param value A string to be checked.
  87483. * \param length A the length of \a value in bytes. May be
  87484. * \c (unsigned)(-1) to indicate that \a value is a plain
  87485. * UTF-8 NUL-terminated string.
  87486. * \assert
  87487. * \code value != NULL \endcode
  87488. * \retval FLAC__bool
  87489. * \c false if entry name is illegal, else \c true.
  87490. */
  87491. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87492. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87493. * comment specification.
  87494. *
  87495. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87496. * 'value' must be legal according to
  87497. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87498. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87499. *
  87500. * \param entry An entry to be checked.
  87501. * \param length The length of \a entry in bytes.
  87502. * \assert
  87503. * \code value != NULL \endcode
  87504. * \retval FLAC__bool
  87505. * \c false if entry name is illegal, else \c true.
  87506. */
  87507. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87508. /** Check a seek table to see if it conforms to the FLAC specification.
  87509. * See the format specification for limits on the contents of the
  87510. * seek table.
  87511. *
  87512. * \param seek_table A pointer to a seek table to be checked.
  87513. * \assert
  87514. * \code seek_table != NULL \endcode
  87515. * \retval FLAC__bool
  87516. * \c false if seek table is illegal, else \c true.
  87517. */
  87518. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87519. /** Sort a seek table's seek points according to the format specification.
  87520. * This includes a "unique-ification" step to remove duplicates, i.e.
  87521. * seek points with identical \a sample_number values. Duplicate seek
  87522. * points are converted into placeholder points and sorted to the end of
  87523. * the table.
  87524. *
  87525. * \param seek_table A pointer to a seek table to be sorted.
  87526. * \assert
  87527. * \code seek_table != NULL \endcode
  87528. * \retval unsigned
  87529. * The number of duplicate seek points converted into placeholders.
  87530. */
  87531. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87532. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87533. * See the format specification for limits on the contents of the
  87534. * cue sheet.
  87535. *
  87536. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87537. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87538. * stringent requirements for a CD-DA (audio) disc.
  87539. * \param violation Address of a pointer to a string. If there is a
  87540. * violation, a pointer to a string explanation of the
  87541. * violation will be returned here. \a violation may be
  87542. * \c NULL if you don't need the returned string. Do not
  87543. * free the returned string; it will always point to static
  87544. * data.
  87545. * \assert
  87546. * \code cue_sheet != NULL \endcode
  87547. * \retval FLAC__bool
  87548. * \c false if cue sheet is illegal, else \c true.
  87549. */
  87550. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87551. /** Check picture data to see if it conforms to the FLAC specification.
  87552. * See the format specification for limits on the contents of the
  87553. * PICTURE block.
  87554. *
  87555. * \param picture A pointer to existing picture data to be checked.
  87556. * \param violation Address of a pointer to a string. If there is a
  87557. * violation, a pointer to a string explanation of the
  87558. * violation will be returned here. \a violation may be
  87559. * \c NULL if you don't need the returned string. Do not
  87560. * free the returned string; it will always point to static
  87561. * data.
  87562. * \assert
  87563. * \code picture != NULL \endcode
  87564. * \retval FLAC__bool
  87565. * \c false if picture data is illegal, else \c true.
  87566. */
  87567. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87568. /* \} */
  87569. #ifdef __cplusplus
  87570. }
  87571. #endif
  87572. #endif
  87573. /*** End of inlined file: format.h ***/
  87574. /*** Start of inlined file: metadata.h ***/
  87575. #ifndef FLAC__METADATA_H
  87576. #define FLAC__METADATA_H
  87577. #include <sys/types.h> /* for off_t */
  87578. /* --------------------------------------------------------------------
  87579. (For an example of how all these routines are used, see the source
  87580. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87581. metaflac in src/metaflac/)
  87582. ------------------------------------------------------------------*/
  87583. /** \file include/FLAC/metadata.h
  87584. *
  87585. * \brief
  87586. * This module provides functions for creating and manipulating FLAC
  87587. * metadata blocks in memory, and three progressively more powerful
  87588. * interfaces for traversing and editing metadata in FLAC files.
  87589. *
  87590. * See the detailed documentation for each interface in the
  87591. * \link flac_metadata metadata \endlink module.
  87592. */
  87593. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87594. * \ingroup flac
  87595. *
  87596. * \brief
  87597. * This module provides functions for creating and manipulating FLAC
  87598. * metadata blocks in memory, and three progressively more powerful
  87599. * interfaces for traversing and editing metadata in native FLAC files.
  87600. * Note that currently only the Chain interface (level 2) supports Ogg
  87601. * FLAC files, and it is read-only i.e. no writing back changed
  87602. * metadata to file.
  87603. *
  87604. * There are three metadata interfaces of increasing complexity:
  87605. *
  87606. * Level 0:
  87607. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87608. * PICTURE blocks.
  87609. *
  87610. * Level 1:
  87611. * Read-write access to all metadata blocks. This level is write-
  87612. * efficient in most cases (more on this below), and uses less memory
  87613. * than level 2.
  87614. *
  87615. * Level 2:
  87616. * Read-write access to all metadata blocks. This level is write-
  87617. * efficient in all cases, but uses more memory since all metadata for
  87618. * the whole file is read into memory and manipulated before writing
  87619. * out again.
  87620. *
  87621. * What do we mean by efficient? Since FLAC metadata appears at the
  87622. * beginning of the file, when writing metadata back to a FLAC file
  87623. * it is possible to grow or shrink the metadata such that the entire
  87624. * file must be rewritten. However, if the size remains the same during
  87625. * changes or PADDING blocks are utilized, only the metadata needs to be
  87626. * overwritten, which is much faster.
  87627. *
  87628. * Efficient means the whole file is rewritten at most one time, and only
  87629. * when necessary. Level 1 is not efficient only in the case that you
  87630. * cause more than one metadata block to grow or shrink beyond what can
  87631. * be accomodated by padding. In this case you should probably use level
  87632. * 2, which allows you to edit all the metadata for a file in memory and
  87633. * write it out all at once.
  87634. *
  87635. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87636. * front of the file.
  87637. *
  87638. * All levels access files via their filenames. In addition, level 2
  87639. * has additional alternative read and write functions that take an I/O
  87640. * handle and callbacks, for situations where access by filename is not
  87641. * possible.
  87642. *
  87643. * In addition to the three interfaces, this module defines functions for
  87644. * creating and manipulating various metadata objects in memory. As we see
  87645. * from the Format module, FLAC metadata blocks in memory are very primitive
  87646. * structures for storing information in an efficient way. Reading
  87647. * information from the structures is easy but creating or modifying them
  87648. * directly is more complex. The metadata object routines here facilitate
  87649. * this by taking care of the consistency and memory management drudgery.
  87650. *
  87651. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87652. * metadata however, you will not probably not need these.
  87653. *
  87654. * From a dependency standpoint, none of the encoders or decoders require
  87655. * the metadata module. This is so that embedded users can strip out the
  87656. * metadata module from libFLAC to reduce the size and complexity.
  87657. */
  87658. #ifdef __cplusplus
  87659. extern "C" {
  87660. #endif
  87661. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87662. * \ingroup flac_metadata
  87663. *
  87664. * \brief
  87665. * The level 0 interface consists of individual routines to read the
  87666. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87667. * only a filename.
  87668. *
  87669. * They try to skip any ID3v2 tag at the head of the file.
  87670. *
  87671. * \{
  87672. */
  87673. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87674. * will try to skip any ID3v2 tag at the head of the file.
  87675. *
  87676. * \param filename The path to the FLAC file to read.
  87677. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87678. * FLAC__StreamMetadata is a simple structure with no
  87679. * memory allocation involved, you pass the address of
  87680. * an existing structure. It need not be initialized.
  87681. * \assert
  87682. * \code filename != NULL \endcode
  87683. * \code streaminfo != NULL \endcode
  87684. * \retval FLAC__bool
  87685. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87686. * \c false if there was a memory allocation error, a file decoder error,
  87687. * or the file contained no STREAMINFO block. (A memory allocation error
  87688. * is possible because this function must set up a file decoder.)
  87689. */
  87690. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87691. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87692. * function will try to skip any ID3v2 tag at the head of the file.
  87693. *
  87694. * \param filename The path to the FLAC file to read.
  87695. * \param tags The address where the returned pointer will be
  87696. * stored. The \a tags object must be deleted by
  87697. * the caller using FLAC__metadata_object_delete().
  87698. * \assert
  87699. * \code filename != NULL \endcode
  87700. * \code tags != NULL \endcode
  87701. * \retval FLAC__bool
  87702. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87703. * and \a *tags will be set to the address of the metadata structure.
  87704. * Returns \c false if there was a memory allocation error, a file
  87705. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87706. * \a *tags will be set to \c NULL.
  87707. */
  87708. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87709. /** Read the CUESHEET metadata block of the given FLAC file. This
  87710. * function will try to skip any ID3v2 tag at the head of the file.
  87711. *
  87712. * \param filename The path to the FLAC file to read.
  87713. * \param cuesheet The address where the returned pointer will be
  87714. * stored. The \a cuesheet object must be deleted by
  87715. * the caller using FLAC__metadata_object_delete().
  87716. * \assert
  87717. * \code filename != NULL \endcode
  87718. * \code cuesheet != NULL \endcode
  87719. * \retval FLAC__bool
  87720. * \c true if a valid CUESHEET block was read from \a filename,
  87721. * and \a *cuesheet will be set to the address of the metadata
  87722. * structure. Returns \c false if there was a memory allocation
  87723. * error, a file decoder error, or the file contained no CUESHEET
  87724. * block, and \a *cuesheet will be set to \c NULL.
  87725. */
  87726. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87727. /** Read a PICTURE metadata block of the given FLAC file. This
  87728. * function will try to skip any ID3v2 tag at the head of the file.
  87729. * Since there can be more than one PICTURE block in a file, this
  87730. * function takes a number of parameters that act as constraints to
  87731. * the search. The PICTURE block with the largest area matching all
  87732. * the constraints will be returned, or \a *picture will be set to
  87733. * \c NULL if there was no such block.
  87734. *
  87735. * \param filename The path to the FLAC file to read.
  87736. * \param picture The address where the returned pointer will be
  87737. * stored. The \a picture object must be deleted by
  87738. * the caller using FLAC__metadata_object_delete().
  87739. * \param type The desired picture type. Use \c -1 to mean
  87740. * "any type".
  87741. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87742. * string will be matched exactly. Use \c NULL to
  87743. * mean "any MIME type".
  87744. * \param description The desired description. The string will be
  87745. * matched exactly. Use \c NULL to mean "any
  87746. * description".
  87747. * \param max_width The maximum width in pixels desired. Use
  87748. * \c (unsigned)(-1) to mean "any width".
  87749. * \param max_height The maximum height in pixels desired. Use
  87750. * \c (unsigned)(-1) to mean "any height".
  87751. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87752. * Use \c (unsigned)(-1) to mean "any depth".
  87753. * \param max_colors The maximum number of colors desired. Use
  87754. * \c (unsigned)(-1) to mean "any number of colors".
  87755. * \assert
  87756. * \code filename != NULL \endcode
  87757. * \code picture != NULL \endcode
  87758. * \retval FLAC__bool
  87759. * \c true if a valid PICTURE block was read from \a filename,
  87760. * and \a *picture will be set to the address of the metadata
  87761. * structure. Returns \c false if there was a memory allocation
  87762. * error, a file decoder error, or the file contained no PICTURE
  87763. * block, and \a *picture will be set to \c NULL.
  87764. */
  87765. 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);
  87766. /* \} */
  87767. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87768. * \ingroup flac_metadata
  87769. *
  87770. * \brief
  87771. * The level 1 interface provides read-write access to FLAC file metadata and
  87772. * operates directly on the FLAC file.
  87773. *
  87774. * The general usage of this interface is:
  87775. *
  87776. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87777. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87778. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87779. * see if the file is writable, or only read access is allowed.
  87780. * - Use FLAC__metadata_simple_iterator_next() and
  87781. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87782. * This is does not read the actual blocks themselves.
  87783. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87784. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87785. * forward from the front of the file.
  87786. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87787. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87788. * the current iterator position. The returned object is yours to modify
  87789. * and free.
  87790. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87791. * back. You must have write permission to the original file. Make sure to
  87792. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87793. * below.
  87794. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87795. * Use the object creation functions from
  87796. * \link flac_metadata_object here \endlink to generate new objects.
  87797. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87798. * currently referred to by the iterator, or replace it with padding.
  87799. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87800. * finished.
  87801. *
  87802. * \note
  87803. * The FLAC file remains open the whole time between
  87804. * FLAC__metadata_simple_iterator_init() and
  87805. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87806. * the file during this time.
  87807. *
  87808. * \note
  87809. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87810. * FLAC__StreamMetadata objects. These are managed automatically.
  87811. *
  87812. * \note
  87813. * If any of the modification functions
  87814. * (FLAC__metadata_simple_iterator_set_block(),
  87815. * FLAC__metadata_simple_iterator_delete_block(),
  87816. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87817. * you should delete the iterator as it may no longer be valid.
  87818. *
  87819. * \{
  87820. */
  87821. struct FLAC__Metadata_SimpleIterator;
  87822. /** The opaque structure definition for the level 1 iterator type.
  87823. * See the
  87824. * \link flac_metadata_level1 metadata level 1 module \endlink
  87825. * for a detailed description.
  87826. */
  87827. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87828. /** Status type for FLAC__Metadata_SimpleIterator.
  87829. *
  87830. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87831. */
  87832. typedef enum {
  87833. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87834. /**< The iterator is in the normal OK state */
  87835. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87836. /**< The data passed into a function violated the function's usage criteria */
  87837. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87838. /**< The iterator could not open the target file */
  87839. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87840. /**< The iterator could not find the FLAC signature at the start of the file */
  87841. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87842. /**< The iterator tried to write to a file that was not writable */
  87843. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87844. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87845. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87846. /**< The iterator encountered an error while reading the FLAC file */
  87847. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87848. /**< The iterator encountered an error while seeking in the FLAC file */
  87849. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87850. /**< The iterator encountered an error while writing the FLAC file */
  87851. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87852. /**< The iterator encountered an error renaming the FLAC file */
  87853. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87854. /**< The iterator encountered an error removing the temporary file */
  87855. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87856. /**< Memory allocation failed */
  87857. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87858. /**< The caller violated an assertion or an unexpected error occurred */
  87859. } FLAC__Metadata_SimpleIteratorStatus;
  87860. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87861. *
  87862. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87863. * will give the string equivalent. The contents should not be modified.
  87864. */
  87865. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87866. /** Create a new iterator instance.
  87867. *
  87868. * \retval FLAC__Metadata_SimpleIterator*
  87869. * \c NULL if there was an error allocating memory, else the new instance.
  87870. */
  87871. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87872. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87873. *
  87874. * \param iterator A pointer to an existing iterator.
  87875. * \assert
  87876. * \code iterator != NULL \endcode
  87877. */
  87878. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87879. /** Get the current status of the iterator. Call this after a function
  87880. * returns \c false to get the reason for the error. Also resets the status
  87881. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87882. *
  87883. * \param iterator A pointer to an existing iterator.
  87884. * \assert
  87885. * \code iterator != NULL \endcode
  87886. * \retval FLAC__Metadata_SimpleIteratorStatus
  87887. * The current status of the iterator.
  87888. */
  87889. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87890. /** Initialize the iterator to point to the first metadata block in the
  87891. * given FLAC file.
  87892. *
  87893. * \param iterator A pointer to an existing iterator.
  87894. * \param filename The path to the FLAC file.
  87895. * \param read_only If \c true, the FLAC file will be opened
  87896. * in read-only mode; if \c false, the FLAC
  87897. * file will be opened for edit even if no
  87898. * edits are performed.
  87899. * \param preserve_file_stats If \c true, the owner and modification
  87900. * time will be preserved even if the FLAC
  87901. * file is written to.
  87902. * \assert
  87903. * \code iterator != NULL \endcode
  87904. * \code filename != NULL \endcode
  87905. * \retval FLAC__bool
  87906. * \c false if a memory allocation error occurs, the file can't be
  87907. * opened, or another error occurs, else \c true.
  87908. */
  87909. 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);
  87910. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87911. * FLAC__metadata_simple_iterator_set_block() and
  87912. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87913. *
  87914. * \param iterator A pointer to an existing iterator.
  87915. * \assert
  87916. * \code iterator != NULL \endcode
  87917. * \retval FLAC__bool
  87918. * See above.
  87919. */
  87920. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87921. /** Moves the iterator forward one metadata block, returning \c false if
  87922. * already at the end.
  87923. *
  87924. * \param iterator A pointer to an existing initialized iterator.
  87925. * \assert
  87926. * \code iterator != NULL \endcode
  87927. * \a iterator has been successfully initialized with
  87928. * FLAC__metadata_simple_iterator_init()
  87929. * \retval FLAC__bool
  87930. * \c false if already at the last metadata block of the chain, else
  87931. * \c true.
  87932. */
  87933. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87934. /** Moves the iterator backward one metadata block, returning \c false if
  87935. * already at the beginning.
  87936. *
  87937. * \param iterator A pointer to an existing initialized iterator.
  87938. * \assert
  87939. * \code iterator != NULL \endcode
  87940. * \a iterator has been successfully initialized with
  87941. * FLAC__metadata_simple_iterator_init()
  87942. * \retval FLAC__bool
  87943. * \c false if already at the first metadata block of the chain, else
  87944. * \c true.
  87945. */
  87946. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87947. /** Returns a flag telling if the current metadata block is the last.
  87948. *
  87949. * \param iterator A pointer to an existing initialized iterator.
  87950. * \assert
  87951. * \code iterator != NULL \endcode
  87952. * \a iterator has been successfully initialized with
  87953. * FLAC__metadata_simple_iterator_init()
  87954. * \retval FLAC__bool
  87955. * \c true if the current metadata block is the last in the file,
  87956. * else \c false.
  87957. */
  87958. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87959. /** Get the offset of the metadata block at the current position. This
  87960. * avoids reading the actual block data which can save time for large
  87961. * blocks.
  87962. *
  87963. * \param iterator A pointer to an existing initialized iterator.
  87964. * \assert
  87965. * \code iterator != NULL \endcode
  87966. * \a iterator has been successfully initialized with
  87967. * FLAC__metadata_simple_iterator_init()
  87968. * \retval off_t
  87969. * The offset of the metadata block at the current iterator position.
  87970. * This is the byte offset relative to the beginning of the file of
  87971. * the current metadata block's header.
  87972. */
  87973. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87974. /** Get the type of the metadata block at the current position. This
  87975. * avoids reading the actual block data which can save time for large
  87976. * blocks.
  87977. *
  87978. * \param iterator A pointer to an existing initialized iterator.
  87979. * \assert
  87980. * \code iterator != NULL \endcode
  87981. * \a iterator has been successfully initialized with
  87982. * FLAC__metadata_simple_iterator_init()
  87983. * \retval FLAC__MetadataType
  87984. * The type of the metadata block at the current iterator position.
  87985. */
  87986. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87987. /** Get the length of the metadata block at the current position. This
  87988. * avoids reading the actual block data which can save time for large
  87989. * blocks.
  87990. *
  87991. * \param iterator A pointer to an existing initialized iterator.
  87992. * \assert
  87993. * \code iterator != NULL \endcode
  87994. * \a iterator has been successfully initialized with
  87995. * FLAC__metadata_simple_iterator_init()
  87996. * \retval unsigned
  87997. * The length of the metadata block at the current iterator position.
  87998. * The is same length as that in the
  87999. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  88000. * i.e. the length of the metadata body that follows the header.
  88001. */
  88002. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  88003. /** Get the application ID of the \c APPLICATION block at the current
  88004. * position. This avoids reading the actual block data which can save
  88005. * time for large blocks.
  88006. *
  88007. * \param iterator A pointer to an existing initialized iterator.
  88008. * \param id A pointer to a buffer of at least \c 4 bytes where
  88009. * the ID will be stored.
  88010. * \assert
  88011. * \code iterator != NULL \endcode
  88012. * \code id != NULL \endcode
  88013. * \a iterator has been successfully initialized with
  88014. * FLAC__metadata_simple_iterator_init()
  88015. * \retval FLAC__bool
  88016. * \c true if the ID was successfully read, else \c false, in which
  88017. * case you should check FLAC__metadata_simple_iterator_status() to
  88018. * find out why. If the status is
  88019. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  88020. * current metadata block is not an \c APPLICATION block. Otherwise
  88021. * if the status is
  88022. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  88023. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  88024. * occurred and the iterator can no longer be used.
  88025. */
  88026. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  88027. /** Get the metadata block at the current position. You can modify the
  88028. * block but must use FLAC__metadata_simple_iterator_set_block() to
  88029. * write it back to the FLAC file.
  88030. *
  88031. * You must call FLAC__metadata_object_delete() on the returned object
  88032. * when you are finished with it.
  88033. *
  88034. * \param iterator A pointer to an existing initialized iterator.
  88035. * \assert
  88036. * \code iterator != NULL \endcode
  88037. * \a iterator has been successfully initialized with
  88038. * FLAC__metadata_simple_iterator_init()
  88039. * \retval FLAC__StreamMetadata*
  88040. * The current metadata block, or \c NULL if there was a memory
  88041. * allocation error.
  88042. */
  88043. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  88044. /** Write a block back to the FLAC file. This function tries to be
  88045. * as efficient as possible; how the block is actually written is
  88046. * shown by the following:
  88047. *
  88048. * Existing block is a STREAMINFO block and the new block is a
  88049. * STREAMINFO block: the new block is written in place. Make sure
  88050. * you know what you're doing when changing the values of a
  88051. * STREAMINFO block.
  88052. *
  88053. * Existing block is a STREAMINFO block and the new block is a
  88054. * not a STREAMINFO block: this is an error since the first block
  88055. * must be a STREAMINFO block. Returns \c false without altering the
  88056. * file.
  88057. *
  88058. * Existing block is not a STREAMINFO block and the new block is a
  88059. * STREAMINFO block: this is an error since there may be only one
  88060. * STREAMINFO block. Returns \c false without altering the file.
  88061. *
  88062. * Existing block and new block are the same length: the existing
  88063. * block will be replaced by the new block, written in place.
  88064. *
  88065. * Existing block is longer than new block: if use_padding is \c true,
  88066. * the existing block will be overwritten in place with the new
  88067. * block followed by a PADDING block, if possible, to make the total
  88068. * size the same as the existing block. Remember that a padding
  88069. * block requires at least four bytes so if the difference in size
  88070. * between the new block and existing block is less than that, the
  88071. * entire file will have to be rewritten, using the new block's
  88072. * exact size. If use_padding is \c false, the entire file will be
  88073. * rewritten, replacing the existing block by the new block.
  88074. *
  88075. * Existing block is shorter than new block: if use_padding is \c true,
  88076. * the function will try and expand the new block into the following
  88077. * PADDING block, if it exists and doing so won't shrink the PADDING
  88078. * block to less than 4 bytes. If there is no following PADDING
  88079. * block, or it will shrink to less than 4 bytes, or use_padding is
  88080. * \c false, the entire file is rewritten, replacing the existing block
  88081. * with the new block. Note that in this case any following PADDING
  88082. * block is preserved as is.
  88083. *
  88084. * After writing the block, the iterator will remain in the same
  88085. * place, i.e. pointing to the new block.
  88086. *
  88087. * \param iterator A pointer to an existing initialized iterator.
  88088. * \param block The block to set.
  88089. * \param use_padding See above.
  88090. * \assert
  88091. * \code iterator != NULL \endcode
  88092. * \a iterator has been successfully initialized with
  88093. * FLAC__metadata_simple_iterator_init()
  88094. * \code block != NULL \endcode
  88095. * \retval FLAC__bool
  88096. * \c true if successful, else \c false.
  88097. */
  88098. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88099. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  88100. * except that instead of writing over an existing block, it appends
  88101. * a block after the existing block. \a use_padding is again used to
  88102. * tell the function to try an expand into following padding in an
  88103. * attempt to avoid rewriting the entire file.
  88104. *
  88105. * This function will fail and return \c false if given a STREAMINFO
  88106. * block.
  88107. *
  88108. * After writing the block, the iterator will be pointing to the
  88109. * new block.
  88110. *
  88111. * \param iterator A pointer to an existing initialized iterator.
  88112. * \param block The block to set.
  88113. * \param use_padding See above.
  88114. * \assert
  88115. * \code iterator != NULL \endcode
  88116. * \a iterator has been successfully initialized with
  88117. * FLAC__metadata_simple_iterator_init()
  88118. * \code block != NULL \endcode
  88119. * \retval FLAC__bool
  88120. * \c true if successful, else \c false.
  88121. */
  88122. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88123. /** Deletes the block at the current position. This will cause the
  88124. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  88125. * in which case the block will be replaced by an equal-sized PADDING
  88126. * block. The iterator will be left pointing to the block before the
  88127. * one just deleted.
  88128. *
  88129. * You may not delete the STREAMINFO block.
  88130. *
  88131. * \param iterator A pointer to an existing initialized iterator.
  88132. * \param use_padding See above.
  88133. * \assert
  88134. * \code iterator != NULL \endcode
  88135. * \a iterator has been successfully initialized with
  88136. * FLAC__metadata_simple_iterator_init()
  88137. * \retval FLAC__bool
  88138. * \c true if successful, else \c false.
  88139. */
  88140. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88141. /* \} */
  88142. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88143. * \ingroup flac_metadata
  88144. *
  88145. * \brief
  88146. * The level 2 interface provides read-write access to FLAC file metadata;
  88147. * all metadata is read into memory, operated on in memory, and then written
  88148. * to file, which is more efficient than level 1 when editing multiple blocks.
  88149. *
  88150. * Currently Ogg FLAC is supported for read only, via
  88151. * FLAC__metadata_chain_read_ogg() but a subsequent
  88152. * FLAC__metadata_chain_write() will fail.
  88153. *
  88154. * The general usage of this interface is:
  88155. *
  88156. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88157. * linked list of FLAC metadata blocks.
  88158. * - Read all metadata into the the chain from a FLAC file using
  88159. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88160. * check the status.
  88161. * - Optionally, consolidate the padding using
  88162. * FLAC__metadata_chain_merge_padding() or
  88163. * FLAC__metadata_chain_sort_padding().
  88164. * - Create a new iterator using FLAC__metadata_iterator_new()
  88165. * - Initialize the iterator to point to the first element in the chain
  88166. * using FLAC__metadata_iterator_init()
  88167. * - Traverse the chain using FLAC__metadata_iterator_next and
  88168. * FLAC__metadata_iterator_prev().
  88169. * - Get a block for reading or modification using
  88170. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88171. * inside the chain is returned, so the block is yours to modify.
  88172. * Changes will be reflected in the FLAC file when you write the
  88173. * chain. You can also add and delete blocks (see functions below).
  88174. * - When done, write out the chain using FLAC__metadata_chain_write().
  88175. * Make sure to read the whole comment to the function below.
  88176. * - Delete the chain using FLAC__metadata_chain_delete().
  88177. *
  88178. * \note
  88179. * Even though the FLAC file is not open while the chain is being
  88180. * manipulated, you must not alter the file externally during
  88181. * this time. The chain assumes the FLAC file will not change
  88182. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88183. * and FLAC__metadata_chain_write().
  88184. *
  88185. * \note
  88186. * Do not modify the is_last, length, or type fields of returned
  88187. * FLAC__StreamMetadata objects. These are managed automatically.
  88188. *
  88189. * \note
  88190. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88191. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88192. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88193. * become owned by the chain and they will be deleted when the chain is
  88194. * deleted.
  88195. *
  88196. * \{
  88197. */
  88198. struct FLAC__Metadata_Chain;
  88199. /** The opaque structure definition for the level 2 chain type.
  88200. */
  88201. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88202. struct FLAC__Metadata_Iterator;
  88203. /** The opaque structure definition for the level 2 iterator type.
  88204. */
  88205. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88206. typedef enum {
  88207. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88208. /**< The chain is in the normal OK state */
  88209. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88210. /**< The data passed into a function violated the function's usage criteria */
  88211. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88212. /**< The chain could not open the target file */
  88213. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88214. /**< The chain could not find the FLAC signature at the start of the file */
  88215. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88216. /**< The chain tried to write to a file that was not writable */
  88217. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88218. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88219. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88220. /**< The chain encountered an error while reading the FLAC file */
  88221. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88222. /**< The chain encountered an error while seeking in the FLAC file */
  88223. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88224. /**< The chain encountered an error while writing the FLAC file */
  88225. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88226. /**< The chain encountered an error renaming the FLAC file */
  88227. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88228. /**< The chain encountered an error removing the temporary file */
  88229. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88230. /**< Memory allocation failed */
  88231. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88232. /**< The caller violated an assertion or an unexpected error occurred */
  88233. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88234. /**< One or more of the required callbacks was NULL */
  88235. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88236. /**< FLAC__metadata_chain_write() was called on a chain read by
  88237. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88238. * or
  88239. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88240. * was called on a chain read by
  88241. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88242. * Matching read/write methods must always be used. */
  88243. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88244. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88245. * chain write requires a tempfile; use
  88246. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88247. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88248. * called when the chain write does not require a tempfile; use
  88249. * FLAC__metadata_chain_write_with_callbacks() instead.
  88250. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88251. * before writing via callbacks. */
  88252. } FLAC__Metadata_ChainStatus;
  88253. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88254. *
  88255. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88256. * will give the string equivalent. The contents should not be modified.
  88257. */
  88258. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88259. /*********** FLAC__Metadata_Chain ***********/
  88260. /** Create a new chain instance.
  88261. *
  88262. * \retval FLAC__Metadata_Chain*
  88263. * \c NULL if there was an error allocating memory, else the new instance.
  88264. */
  88265. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88266. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88267. *
  88268. * \param chain A pointer to an existing chain.
  88269. * \assert
  88270. * \code chain != NULL \endcode
  88271. */
  88272. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88273. /** Get the current status of the chain. Call this after a function
  88274. * returns \c false to get the reason for the error. Also resets the
  88275. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88276. *
  88277. * \param chain A pointer to an existing chain.
  88278. * \assert
  88279. * \code chain != NULL \endcode
  88280. * \retval FLAC__Metadata_ChainStatus
  88281. * The current status of the chain.
  88282. */
  88283. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88284. /** Read all metadata from a FLAC file into the chain.
  88285. *
  88286. * \param chain A pointer to an existing chain.
  88287. * \param filename The path to the FLAC file to read.
  88288. * \assert
  88289. * \code chain != NULL \endcode
  88290. * \code filename != NULL \endcode
  88291. * \retval FLAC__bool
  88292. * \c true if a valid list of metadata blocks was read from
  88293. * \a filename, else \c false. On failure, check the status with
  88294. * FLAC__metadata_chain_status().
  88295. */
  88296. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88297. /** Read all metadata from an Ogg FLAC file into the chain.
  88298. *
  88299. * \note Ogg FLAC metadata data writing is not supported yet and
  88300. * FLAC__metadata_chain_write() will fail.
  88301. *
  88302. * \param chain A pointer to an existing chain.
  88303. * \param filename The path to the Ogg FLAC file to read.
  88304. * \assert
  88305. * \code chain != NULL \endcode
  88306. * \code filename != NULL \endcode
  88307. * \retval FLAC__bool
  88308. * \c true if a valid list of metadata blocks was read from
  88309. * \a filename, else \c false. On failure, check the status with
  88310. * FLAC__metadata_chain_status().
  88311. */
  88312. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88313. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88314. *
  88315. * The \a handle need only be open for reading, but must be seekable.
  88316. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88317. * for Windows).
  88318. *
  88319. * \param chain A pointer to an existing chain.
  88320. * \param handle The I/O handle of the FLAC stream to read. The
  88321. * handle will NOT be closed after the metadata is read;
  88322. * that is the duty of the caller.
  88323. * \param callbacks
  88324. * A set of callbacks to use for I/O. The mandatory
  88325. * callbacks are \a read, \a seek, and \a tell.
  88326. * \assert
  88327. * \code chain != NULL \endcode
  88328. * \retval FLAC__bool
  88329. * \c true if a valid list of metadata blocks was read from
  88330. * \a handle, else \c false. On failure, check the status with
  88331. * FLAC__metadata_chain_status().
  88332. */
  88333. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88334. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88335. *
  88336. * The \a handle need only be open for reading, but must be seekable.
  88337. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88338. * for Windows).
  88339. *
  88340. * \note Ogg FLAC metadata data writing is not supported yet and
  88341. * FLAC__metadata_chain_write() will fail.
  88342. *
  88343. * \param chain A pointer to an existing chain.
  88344. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88345. * handle will NOT be closed after the metadata is read;
  88346. * that is the duty of the caller.
  88347. * \param callbacks
  88348. * A set of callbacks to use for I/O. The mandatory
  88349. * callbacks are \a read, \a seek, and \a tell.
  88350. * \assert
  88351. * \code chain != NULL \endcode
  88352. * \retval FLAC__bool
  88353. * \c true if a valid list of metadata blocks was read from
  88354. * \a handle, else \c false. On failure, check the status with
  88355. * FLAC__metadata_chain_status().
  88356. */
  88357. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88358. /** Checks if writing the given chain would require the use of a
  88359. * temporary file, or if it could be written in place.
  88360. *
  88361. * Under certain conditions, padding can be utilized so that writing
  88362. * edited metadata back to the FLAC file does not require rewriting the
  88363. * entire file. If rewriting is required, then a temporary workfile is
  88364. * required. When writing metadata using callbacks, you must check
  88365. * this function to know whether to call
  88366. * FLAC__metadata_chain_write_with_callbacks() or
  88367. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88368. * writing with FLAC__metadata_chain_write(), the temporary file is
  88369. * handled internally.
  88370. *
  88371. * \param chain A pointer to an existing chain.
  88372. * \param use_padding
  88373. * Whether or not padding will be allowed to be used
  88374. * during the write. The value of \a use_padding given
  88375. * here must match the value later passed to
  88376. * FLAC__metadata_chain_write_with_callbacks() or
  88377. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88378. * \assert
  88379. * \code chain != NULL \endcode
  88380. * \retval FLAC__bool
  88381. * \c true if writing the current chain would require a tempfile, or
  88382. * \c false if metadata can be written in place.
  88383. */
  88384. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88385. /** Write all metadata out to the FLAC file. This function tries to be as
  88386. * efficient as possible; how the metadata is actually written is shown by
  88387. * the following:
  88388. *
  88389. * If the current chain is the same size as the existing metadata, the new
  88390. * data is written in place.
  88391. *
  88392. * If the current chain is longer than the existing metadata, and
  88393. * \a use_padding is \c true, and the last block is a PADDING block of
  88394. * sufficient length, the function will truncate the final padding block
  88395. * so that the overall size of the metadata is the same as the existing
  88396. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88397. * the above conditions are met, the entire FLAC file must be rewritten.
  88398. * If you want to use padding this way it is a good idea to call
  88399. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88400. * amount of padding to work with, unless you need to preserve ordering
  88401. * of the PADDING blocks for some reason.
  88402. *
  88403. * If the current chain is shorter than the existing metadata, and
  88404. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88405. * is extended to make the overall size the same as the existing data. If
  88406. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88407. * PADDING block is added to the end of the new data to make it the same
  88408. * size as the existing data (if possible, see the note to
  88409. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88410. * and the new data is written in place. If none of the above apply or
  88411. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88412. *
  88413. * If \a preserve_file_stats is \c true, the owner and modification time will
  88414. * be preserved even if the FLAC file is written.
  88415. *
  88416. * For this write function to be used, the chain must have been read with
  88417. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88418. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88419. *
  88420. * \param chain A pointer to an existing chain.
  88421. * \param use_padding See above.
  88422. * \param preserve_file_stats See above.
  88423. * \assert
  88424. * \code chain != NULL \endcode
  88425. * \retval FLAC__bool
  88426. * \c true if the write succeeded, else \c false. On failure,
  88427. * check the status with FLAC__metadata_chain_status().
  88428. */
  88429. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88430. /** Write all metadata out to a FLAC stream via callbacks.
  88431. *
  88432. * (See FLAC__metadata_chain_write() for the details on how padding is
  88433. * used to write metadata in place if possible.)
  88434. *
  88435. * The \a handle must be open for updating and be seekable. The
  88436. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88437. * for Windows).
  88438. *
  88439. * For this write function to be used, the chain must have been read with
  88440. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88441. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88442. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88443. * \c false.
  88444. *
  88445. * \param chain A pointer to an existing chain.
  88446. * \param use_padding See FLAC__metadata_chain_write()
  88447. * \param handle The I/O handle of the FLAC stream to write. The
  88448. * handle will NOT be closed after the metadata is
  88449. * written; that is the duty of the caller.
  88450. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88451. * callbacks are \a write and \a seek.
  88452. * \assert
  88453. * \code chain != NULL \endcode
  88454. * \retval FLAC__bool
  88455. * \c true if the write succeeded, else \c false. On failure,
  88456. * check the status with FLAC__metadata_chain_status().
  88457. */
  88458. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88459. /** Write all metadata out to a FLAC stream via callbacks.
  88460. *
  88461. * (See FLAC__metadata_chain_write() for the details on how padding is
  88462. * used to write metadata in place if possible.)
  88463. *
  88464. * This version of the write-with-callbacks function must be used when
  88465. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88466. * this function, you must supply an I/O handle corresponding to the
  88467. * FLAC file to edit, and a temporary handle to which the new FLAC
  88468. * file will be written. It is the caller's job to move this temporary
  88469. * FLAC file on top of the original FLAC file to complete the metadata
  88470. * edit.
  88471. *
  88472. * The \a handle must be open for reading and be seekable. The
  88473. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88474. * for Windows).
  88475. *
  88476. * The \a temp_handle must be open for writing. The
  88477. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88478. * for Windows). It should be an empty stream, or at least positioned
  88479. * at the start-of-file (in which case it is the caller's duty to
  88480. * truncate it on return).
  88481. *
  88482. * For this write function to be used, the chain must have been read with
  88483. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88484. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88485. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88486. * \c true.
  88487. *
  88488. * \param chain A pointer to an existing chain.
  88489. * \param use_padding See FLAC__metadata_chain_write()
  88490. * \param handle The I/O handle of the original FLAC stream to read.
  88491. * The handle will NOT be closed after the metadata is
  88492. * written; that is the duty of the caller.
  88493. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88494. * The mandatory callbacks are \a read, \a seek, and
  88495. * \a eof.
  88496. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88497. * handle will NOT be closed after the metadata is
  88498. * written; that is the duty of the caller.
  88499. * \param temp_callbacks
  88500. * A set of callbacks to use for I/O on temp_handle.
  88501. * The only mandatory callback is \a write.
  88502. * \assert
  88503. * \code chain != NULL \endcode
  88504. * \retval FLAC__bool
  88505. * \c true if the write succeeded, else \c false. On failure,
  88506. * check the status with FLAC__metadata_chain_status().
  88507. */
  88508. 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);
  88509. /** Merge adjacent PADDING blocks into a single block.
  88510. *
  88511. * \note This function does not write to the FLAC file, it only
  88512. * modifies the chain.
  88513. *
  88514. * \warning Any iterator on the current chain will become invalid after this
  88515. * call. You should delete the iterator and get a new one.
  88516. *
  88517. * \param chain A pointer to an existing chain.
  88518. * \assert
  88519. * \code chain != NULL \endcode
  88520. */
  88521. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88522. /** This function will move all PADDING blocks to the end on the metadata,
  88523. * then merge them into a single block.
  88524. *
  88525. * \note This function does not write to the FLAC file, it only
  88526. * modifies the chain.
  88527. *
  88528. * \warning Any iterator on the current chain will become invalid after this
  88529. * call. You should delete the iterator and get a new one.
  88530. *
  88531. * \param chain A pointer to an existing chain.
  88532. * \assert
  88533. * \code chain != NULL \endcode
  88534. */
  88535. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88536. /*********** FLAC__Metadata_Iterator ***********/
  88537. /** Create a new iterator instance.
  88538. *
  88539. * \retval FLAC__Metadata_Iterator*
  88540. * \c NULL if there was an error allocating memory, else the new instance.
  88541. */
  88542. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88543. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88544. *
  88545. * \param iterator A pointer to an existing iterator.
  88546. * \assert
  88547. * \code iterator != NULL \endcode
  88548. */
  88549. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88550. /** Initialize the iterator to point to the first metadata block in the
  88551. * given chain.
  88552. *
  88553. * \param iterator A pointer to an existing iterator.
  88554. * \param chain A pointer to an existing and initialized (read) chain.
  88555. * \assert
  88556. * \code iterator != NULL \endcode
  88557. * \code chain != NULL \endcode
  88558. */
  88559. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88560. /** Moves the iterator forward one metadata block, returning \c false if
  88561. * already at the end.
  88562. *
  88563. * \param iterator A pointer to an existing initialized iterator.
  88564. * \assert
  88565. * \code iterator != NULL \endcode
  88566. * \a iterator has been successfully initialized with
  88567. * FLAC__metadata_iterator_init()
  88568. * \retval FLAC__bool
  88569. * \c false if already at the last metadata block of the chain, else
  88570. * \c true.
  88571. */
  88572. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88573. /** Moves the iterator backward one metadata block, returning \c false if
  88574. * already at the beginning.
  88575. *
  88576. * \param iterator A pointer to an existing initialized iterator.
  88577. * \assert
  88578. * \code iterator != NULL \endcode
  88579. * \a iterator has been successfully initialized with
  88580. * FLAC__metadata_iterator_init()
  88581. * \retval FLAC__bool
  88582. * \c false if already at the first metadata block of the chain, else
  88583. * \c true.
  88584. */
  88585. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88586. /** Get the type of the metadata block at the current position.
  88587. *
  88588. * \param iterator A pointer to an existing initialized iterator.
  88589. * \assert
  88590. * \code iterator != NULL \endcode
  88591. * \a iterator has been successfully initialized with
  88592. * FLAC__metadata_iterator_init()
  88593. * \retval FLAC__MetadataType
  88594. * The type of the metadata block at the current iterator position.
  88595. */
  88596. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88597. /** Get the metadata block at the current position. You can modify
  88598. * the block in place but must write the chain before the changes
  88599. * are reflected to the FLAC file. You do not need to call
  88600. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88601. * the pointer returned by FLAC__metadata_iterator_get_block()
  88602. * points directly into the chain.
  88603. *
  88604. * \warning
  88605. * Do not call FLAC__metadata_object_delete() on the returned object;
  88606. * to delete a block use FLAC__metadata_iterator_delete_block().
  88607. *
  88608. * \param iterator A pointer to an existing initialized iterator.
  88609. * \assert
  88610. * \code iterator != NULL \endcode
  88611. * \a iterator has been successfully initialized with
  88612. * FLAC__metadata_iterator_init()
  88613. * \retval FLAC__StreamMetadata*
  88614. * The current metadata block.
  88615. */
  88616. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88617. /** Set the metadata block at the current position, replacing the existing
  88618. * block. The new block passed in becomes owned by the chain and it will be
  88619. * deleted when the chain is deleted.
  88620. *
  88621. * \param iterator A pointer to an existing initialized iterator.
  88622. * \param block A pointer to a metadata block.
  88623. * \assert
  88624. * \code iterator != NULL \endcode
  88625. * \a iterator has been successfully initialized with
  88626. * FLAC__metadata_iterator_init()
  88627. * \code block != NULL \endcode
  88628. * \retval FLAC__bool
  88629. * \c false if the conditions in the above description are not met, or
  88630. * a memory allocation error occurs, otherwise \c true.
  88631. */
  88632. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88633. /** Removes the current block from the chain. If \a replace_with_padding is
  88634. * \c true, the block will instead be replaced with a padding block of equal
  88635. * size. You can not delete the STREAMINFO block. The iterator will be
  88636. * left pointing to the block before the one just "deleted", even if
  88637. * \a replace_with_padding is \c true.
  88638. *
  88639. * \param iterator A pointer to an existing initialized iterator.
  88640. * \param replace_with_padding See above.
  88641. * \assert
  88642. * \code iterator != NULL \endcode
  88643. * \a iterator has been successfully initialized with
  88644. * FLAC__metadata_iterator_init()
  88645. * \retval FLAC__bool
  88646. * \c false if the conditions in the above description are not met,
  88647. * otherwise \c true.
  88648. */
  88649. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88650. /** Insert a new block before the current block. You cannot insert a block
  88651. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88652. * as there can be only one, the one that already exists at the head when you
  88653. * read in a chain. The chain takes ownership of the new block and it will be
  88654. * deleted when the chain is deleted. The iterator will be left pointing to
  88655. * the new block.
  88656. *
  88657. * \param iterator A pointer to an existing initialized iterator.
  88658. * \param block A pointer to a metadata block to insert.
  88659. * \assert
  88660. * \code iterator != NULL \endcode
  88661. * \a iterator has been successfully initialized with
  88662. * FLAC__metadata_iterator_init()
  88663. * \retval FLAC__bool
  88664. * \c false if the conditions in the above description are not met, or
  88665. * a memory allocation error occurs, otherwise \c true.
  88666. */
  88667. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88668. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88669. * block as there can be only one, the one that already exists at the head when
  88670. * you read in a chain. The chain takes ownership of the new block and it will
  88671. * be deleted when the chain is deleted. The iterator will be left pointing to
  88672. * the new block.
  88673. *
  88674. * \param iterator A pointer to an existing initialized iterator.
  88675. * \param block A pointer to a metadata block to insert.
  88676. * \assert
  88677. * \code iterator != NULL \endcode
  88678. * \a iterator has been successfully initialized with
  88679. * FLAC__metadata_iterator_init()
  88680. * \retval FLAC__bool
  88681. * \c false if the conditions in the above description are not met, or
  88682. * a memory allocation error occurs, otherwise \c true.
  88683. */
  88684. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88685. /* \} */
  88686. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88687. * \ingroup flac_metadata
  88688. *
  88689. * \brief
  88690. * This module contains methods for manipulating FLAC metadata objects.
  88691. *
  88692. * Since many are variable length we have to be careful about the memory
  88693. * management. We decree that all pointers to data in the object are
  88694. * owned by the object and memory-managed by the object.
  88695. *
  88696. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88697. * functions to create all instances. When using the
  88698. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88699. * \a copy to \c true to have the function make it's own copy of the data, or
  88700. * to \c false to give the object ownership of your data. In the latter case
  88701. * your pointer must be freeable by free() and will be free()d when the object
  88702. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88703. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88704. * the length argument is 0 and the \a copy argument is \c false.
  88705. *
  88706. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88707. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88708. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88709. * case of a memory allocation error.
  88710. *
  88711. * We don't have the convenience of C++ here, so note that the library relies
  88712. * on you to keep the types straight. In other words, if you pass, for
  88713. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88714. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88715. * failure.
  88716. *
  88717. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88718. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88719. * toward the length or stored in the stream, but it can make working with plain
  88720. * comments (those that don't contain embedded-NULs in the value) easier.
  88721. * Entries passed into these functions have trailing NULs added if missing, and
  88722. * returned entries are guaranteed to have a trailing NUL.
  88723. *
  88724. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88725. * comment entry/name/value will first validate that it complies with the Vorbis
  88726. * comment specification and return false if it does not.
  88727. *
  88728. * There is no need to recalculate the length field on metadata blocks you
  88729. * have modified. They will be calculated automatically before they are
  88730. * written back to a file.
  88731. *
  88732. * \{
  88733. */
  88734. /** Create a new metadata object instance of the given type.
  88735. *
  88736. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88737. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88738. * the vendor string set (but zero comments).
  88739. *
  88740. * Do not pass in a value greater than or equal to
  88741. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88742. * doing.
  88743. *
  88744. * \param type Type of object to create
  88745. * \retval FLAC__StreamMetadata*
  88746. * \c NULL if there was an error allocating memory or the type code is
  88747. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88748. */
  88749. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88750. /** Create a copy of an existing metadata object.
  88751. *
  88752. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88753. * object is also copied. The caller takes ownership of the new block and
  88754. * is responsible for freeing it with FLAC__metadata_object_delete().
  88755. *
  88756. * \param object Pointer to object to copy.
  88757. * \assert
  88758. * \code object != NULL \endcode
  88759. * \retval FLAC__StreamMetadata*
  88760. * \c NULL if there was an error allocating memory, else the new instance.
  88761. */
  88762. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88763. /** Free a metadata object. Deletes the object pointed to by \a object.
  88764. *
  88765. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88766. * object is also deleted.
  88767. *
  88768. * \param object A pointer to an existing object.
  88769. * \assert
  88770. * \code object != NULL \endcode
  88771. */
  88772. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88773. /** Compares two metadata objects.
  88774. *
  88775. * The compare is "deep", i.e. dynamically allocated data within the
  88776. * object is also compared.
  88777. *
  88778. * \param block1 A pointer to an existing object.
  88779. * \param block2 A pointer to an existing object.
  88780. * \assert
  88781. * \code block1 != NULL \endcode
  88782. * \code block2 != NULL \endcode
  88783. * \retval FLAC__bool
  88784. * \c true if objects are identical, else \c false.
  88785. */
  88786. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88787. /** Sets the application data of an APPLICATION block.
  88788. *
  88789. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88790. * takes ownership of the pointer. The existing data will be freed if this
  88791. * function is successful, otherwise the original data will remain if \a copy
  88792. * is \c true and malloc() fails.
  88793. *
  88794. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88795. *
  88796. * \param object A pointer to an existing APPLICATION object.
  88797. * \param data A pointer to the data to set.
  88798. * \param length The length of \a data in bytes.
  88799. * \param copy See above.
  88800. * \assert
  88801. * \code object != NULL \endcode
  88802. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88803. * \code (data != NULL && length > 0) ||
  88804. * (data == NULL && length == 0 && copy == false) \endcode
  88805. * \retval FLAC__bool
  88806. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88807. */
  88808. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88809. /** Resize the seekpoint array.
  88810. *
  88811. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88812. * points will be added to the end.
  88813. *
  88814. * \param object A pointer to an existing SEEKTABLE object.
  88815. * \param new_num_points The desired length of the array; may be \c 0.
  88816. * \assert
  88817. * \code object != NULL \endcode
  88818. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88819. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88820. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88821. * \retval FLAC__bool
  88822. * \c false if memory allocation error, else \c true.
  88823. */
  88824. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88825. /** Set a seekpoint in a seektable.
  88826. *
  88827. * \param object A pointer to an existing SEEKTABLE object.
  88828. * \param point_num Index into seekpoint array to set.
  88829. * \param point The point to set.
  88830. * \assert
  88831. * \code object != NULL \endcode
  88832. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88833. * \code object->data.seek_table.num_points > point_num \endcode
  88834. */
  88835. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88836. /** Insert a seekpoint into a seektable.
  88837. *
  88838. * \param object A pointer to an existing SEEKTABLE object.
  88839. * \param point_num Index into seekpoint array to set.
  88840. * \param point The point to set.
  88841. * \assert
  88842. * \code object != NULL \endcode
  88843. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88844. * \code object->data.seek_table.num_points >= point_num \endcode
  88845. * \retval FLAC__bool
  88846. * \c false if memory allocation error, else \c true.
  88847. */
  88848. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88849. /** Delete a seekpoint from a seektable.
  88850. *
  88851. * \param object A pointer to an existing SEEKTABLE object.
  88852. * \param point_num Index into seekpoint array to set.
  88853. * \assert
  88854. * \code object != NULL \endcode
  88855. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88856. * \code object->data.seek_table.num_points > point_num \endcode
  88857. * \retval FLAC__bool
  88858. * \c false if memory allocation error, else \c true.
  88859. */
  88860. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88861. /** Check a seektable to see if it conforms to the FLAC specification.
  88862. * See the format specification for limits on the contents of the
  88863. * seektable.
  88864. *
  88865. * \param object A pointer to an existing SEEKTABLE object.
  88866. * \assert
  88867. * \code object != NULL \endcode
  88868. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88869. * \retval FLAC__bool
  88870. * \c false if seek table is illegal, else \c true.
  88871. */
  88872. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88873. /** Append a number of placeholder points to the end of a seek table.
  88874. *
  88875. * \note
  88876. * As with the other ..._seektable_template_... functions, you should
  88877. * call FLAC__metadata_object_seektable_template_sort() when finished
  88878. * to make the seek table legal.
  88879. *
  88880. * \param object A pointer to an existing SEEKTABLE object.
  88881. * \param num The number of placeholder points to append.
  88882. * \assert
  88883. * \code object != NULL \endcode
  88884. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88885. * \retval FLAC__bool
  88886. * \c false if memory allocation fails, else \c true.
  88887. */
  88888. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88889. /** Append a specific seek point template to the end of a seek table.
  88890. *
  88891. * \note
  88892. * As with the other ..._seektable_template_... functions, you should
  88893. * call FLAC__metadata_object_seektable_template_sort() when finished
  88894. * to make the seek table legal.
  88895. *
  88896. * \param object A pointer to an existing SEEKTABLE object.
  88897. * \param sample_number The sample number of the seek point template.
  88898. * \assert
  88899. * \code object != NULL \endcode
  88900. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88901. * \retval FLAC__bool
  88902. * \c false if memory allocation fails, else \c true.
  88903. */
  88904. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88905. /** Append specific seek point templates to the end of a seek table.
  88906. *
  88907. * \note
  88908. * As with the other ..._seektable_template_... functions, you should
  88909. * call FLAC__metadata_object_seektable_template_sort() when finished
  88910. * to make the seek table legal.
  88911. *
  88912. * \param object A pointer to an existing SEEKTABLE object.
  88913. * \param sample_numbers An array of sample numbers for the seek points.
  88914. * \param num The number of seek point templates to append.
  88915. * \assert
  88916. * \code object != NULL \endcode
  88917. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88918. * \retval FLAC__bool
  88919. * \c false if memory allocation fails, else \c true.
  88920. */
  88921. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88922. /** Append a set of evenly-spaced seek point templates to the end of a
  88923. * seek table.
  88924. *
  88925. * \note
  88926. * As with the other ..._seektable_template_... functions, you should
  88927. * call FLAC__metadata_object_seektable_template_sort() when finished
  88928. * to make the seek table legal.
  88929. *
  88930. * \param object A pointer to an existing SEEKTABLE object.
  88931. * \param num The number of placeholder points to append.
  88932. * \param total_samples The total number of samples to be encoded;
  88933. * the seekpoints will be spaced approximately
  88934. * \a total_samples / \a num samples apart.
  88935. * \assert
  88936. * \code object != NULL \endcode
  88937. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88938. * \code total_samples > 0 \endcode
  88939. * \retval FLAC__bool
  88940. * \c false if memory allocation fails, else \c true.
  88941. */
  88942. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88943. /** Append a set of evenly-spaced seek point templates to the end of a
  88944. * seek table.
  88945. *
  88946. * \note
  88947. * As with the other ..._seektable_template_... functions, you should
  88948. * call FLAC__metadata_object_seektable_template_sort() when finished
  88949. * to make the seek table legal.
  88950. *
  88951. * \param object A pointer to an existing SEEKTABLE object.
  88952. * \param samples The number of samples apart to space the placeholder
  88953. * points. The first point will be at sample \c 0, the
  88954. * second at sample \a samples, then 2*\a samples, and
  88955. * so on. As long as \a samples and \a total_samples
  88956. * are greater than \c 0, there will always be at least
  88957. * one seekpoint at sample \c 0.
  88958. * \param total_samples The total number of samples to be encoded;
  88959. * the seekpoints will be spaced
  88960. * \a samples samples apart.
  88961. * \assert
  88962. * \code object != NULL \endcode
  88963. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88964. * \code samples > 0 \endcode
  88965. * \code total_samples > 0 \endcode
  88966. * \retval FLAC__bool
  88967. * \c false if memory allocation fails, else \c true.
  88968. */
  88969. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88970. /** Sort a seek table's seek points according to the format specification,
  88971. * removing duplicates.
  88972. *
  88973. * \param object A pointer to a seek table to be sorted.
  88974. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88975. * If \c true, duplicates are deleted and the seek table is
  88976. * shrunk appropriately; the number of placeholder points
  88977. * present in the seek table will be the same after the call
  88978. * as before.
  88979. * \assert
  88980. * \code object != NULL \endcode
  88981. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88982. * \retval FLAC__bool
  88983. * \c false if realloc() fails, else \c true.
  88984. */
  88985. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88986. /** Sets the vendor string in a VORBIS_COMMENT block.
  88987. *
  88988. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88989. * one already.
  88990. *
  88991. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88992. * takes ownership of the \c entry.entry pointer.
  88993. *
  88994. * \note If this function returns \c false, the caller still owns the
  88995. * pointer.
  88996. *
  88997. * \param object A pointer to an existing VORBIS_COMMENT object.
  88998. * \param entry The entry to set the vendor string to.
  88999. * \param copy See above.
  89000. * \assert
  89001. * \code object != NULL \endcode
  89002. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89003. * \code (entry.entry != NULL && entry.length > 0) ||
  89004. * (entry.entry == NULL && entry.length == 0) \endcode
  89005. * \retval FLAC__bool
  89006. * \c false if memory allocation fails or \a entry does not comply with the
  89007. * Vorbis comment specification, else \c true.
  89008. */
  89009. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89010. /** Resize the comment array.
  89011. *
  89012. * If the size shrinks, elements will truncated; if it grows, new empty
  89013. * fields will be added to the end.
  89014. *
  89015. * \param object A pointer to an existing VORBIS_COMMENT object.
  89016. * \param new_num_comments The desired length of the array; may be \c 0.
  89017. * \assert
  89018. * \code object != NULL \endcode
  89019. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89020. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  89021. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  89022. * \retval FLAC__bool
  89023. * \c false if memory allocation fails, else \c true.
  89024. */
  89025. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  89026. /** Sets a comment in a VORBIS_COMMENT block.
  89027. *
  89028. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89029. * one already.
  89030. *
  89031. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89032. * takes ownership of the \c entry.entry pointer.
  89033. *
  89034. * \note If this function returns \c false, the caller still owns the
  89035. * pointer.
  89036. *
  89037. * \param object A pointer to an existing VORBIS_COMMENT object.
  89038. * \param comment_num Index into comment array to set.
  89039. * \param entry The entry to set the comment to.
  89040. * \param copy See above.
  89041. * \assert
  89042. * \code object != NULL \endcode
  89043. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89044. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  89045. * \code (entry.entry != NULL && entry.length > 0) ||
  89046. * (entry.entry == NULL && entry.length == 0) \endcode
  89047. * \retval FLAC__bool
  89048. * \c false if memory allocation fails or \a entry does not comply with the
  89049. * Vorbis comment specification, else \c true.
  89050. */
  89051. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89052. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  89053. *
  89054. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89055. * one already.
  89056. *
  89057. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89058. * takes ownership of the \c entry.entry pointer.
  89059. *
  89060. * \note If this function returns \c false, the caller still owns the
  89061. * pointer.
  89062. *
  89063. * \param object A pointer to an existing VORBIS_COMMENT object.
  89064. * \param comment_num The index at which to insert the comment. The comments
  89065. * at and after \a comment_num move right one position.
  89066. * To append a comment to the end, set \a comment_num to
  89067. * \c object->data.vorbis_comment.num_comments .
  89068. * \param entry The comment to insert.
  89069. * \param copy See above.
  89070. * \assert
  89071. * \code object != NULL \endcode
  89072. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89073. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  89074. * \code (entry.entry != NULL && entry.length > 0) ||
  89075. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89076. * \retval FLAC__bool
  89077. * \c false if memory allocation fails or \a entry does not comply with the
  89078. * Vorbis comment specification, else \c true.
  89079. */
  89080. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89081. /** Appends a comment to a VORBIS_COMMENT block.
  89082. *
  89083. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89084. * one already.
  89085. *
  89086. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89087. * takes ownership of the \c entry.entry pointer.
  89088. *
  89089. * \note If this function returns \c false, the caller still owns the
  89090. * pointer.
  89091. *
  89092. * \param object A pointer to an existing VORBIS_COMMENT object.
  89093. * \param entry The comment to insert.
  89094. * \param copy See above.
  89095. * \assert
  89096. * \code object != NULL \endcode
  89097. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89098. * \code (entry.entry != NULL && entry.length > 0) ||
  89099. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89100. * \retval FLAC__bool
  89101. * \c false if memory allocation fails or \a entry does not comply with the
  89102. * Vorbis comment specification, else \c true.
  89103. */
  89104. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89105. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  89106. *
  89107. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89108. * one already.
  89109. *
  89110. * Depending on the the value of \a all, either all or just the first comment
  89111. * whose field name(s) match the given entry's name will be replaced by the
  89112. * given entry. If no comments match, \a entry will simply be appended.
  89113. *
  89114. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89115. * takes ownership of the \c entry.entry pointer.
  89116. *
  89117. * \note If this function returns \c false, the caller still owns the
  89118. * pointer.
  89119. *
  89120. * \param object A pointer to an existing VORBIS_COMMENT object.
  89121. * \param entry The comment to insert.
  89122. * \param all If \c true, all comments whose field name matches
  89123. * \a entry's field name will be removed, and \a entry will
  89124. * be inserted at the position of the first matching
  89125. * comment. If \c false, only the first comment whose
  89126. * field name matches \a entry's field name will be
  89127. * replaced with \a entry.
  89128. * \param copy See above.
  89129. * \assert
  89130. * \code object != NULL \endcode
  89131. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89132. * \code (entry.entry != NULL && entry.length > 0) ||
  89133. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89134. * \retval FLAC__bool
  89135. * \c false if memory allocation fails or \a entry does not comply with the
  89136. * Vorbis comment specification, else \c true.
  89137. */
  89138. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89139. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89140. *
  89141. * \param object A pointer to an existing VORBIS_COMMENT object.
  89142. * \param comment_num The index of the comment to delete.
  89143. * \assert
  89144. * \code object != NULL \endcode
  89145. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89146. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89147. * \retval FLAC__bool
  89148. * \c false if realloc() fails, else \c true.
  89149. */
  89150. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89151. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89152. *
  89153. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89154. * memory and shall be owned by the caller. For convenience the entry will
  89155. * have a terminating NUL.
  89156. *
  89157. * \param entry A pointer to a Vorbis comment entry. The entry's
  89158. * \c entry pointer should not point to allocated
  89159. * memory as it will be overwritten.
  89160. * \param field_name The field name in ASCII, \c NUL terminated.
  89161. * \param field_value The field value in UTF-8, \c NUL terminated.
  89162. * \assert
  89163. * \code entry != NULL \endcode
  89164. * \code field_name != NULL \endcode
  89165. * \code field_value != NULL \endcode
  89166. * \retval FLAC__bool
  89167. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89168. * not comply with the Vorbis comment specification, else \c true.
  89169. */
  89170. 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);
  89171. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89172. *
  89173. * The returned pointers to name and value will be allocated by malloc()
  89174. * and shall be owned by the caller.
  89175. *
  89176. * \param entry An existing Vorbis comment entry.
  89177. * \param field_name The address of where the returned pointer to the
  89178. * field name will be stored.
  89179. * \param field_value The address of where the returned pointer to the
  89180. * field value will be stored.
  89181. * \assert
  89182. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89183. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89184. * \code field_name != NULL \endcode
  89185. * \code field_value != NULL \endcode
  89186. * \retval FLAC__bool
  89187. * \c false if memory allocation fails or \a entry does not comply with the
  89188. * Vorbis comment specification, else \c true.
  89189. */
  89190. 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);
  89191. /** Check if the given Vorbis comment entry's field name matches the given
  89192. * field name.
  89193. *
  89194. * \param entry An existing Vorbis comment entry.
  89195. * \param field_name The field name to check.
  89196. * \param field_name_length The length of \a field_name, not including the
  89197. * terminating \c NUL.
  89198. * \assert
  89199. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89200. * \retval FLAC__bool
  89201. * \c true if the field names match, else \c false
  89202. */
  89203. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89204. /** Find a Vorbis comment with the given field name.
  89205. *
  89206. * The search begins at entry number \a offset; use an offset of 0 to
  89207. * search from the beginning of the comment array.
  89208. *
  89209. * \param object A pointer to an existing VORBIS_COMMENT object.
  89210. * \param offset The offset into the comment array from where to start
  89211. * the search.
  89212. * \param field_name The field name of the comment to find.
  89213. * \assert
  89214. * \code object != NULL \endcode
  89215. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89216. * \code field_name != NULL \endcode
  89217. * \retval int
  89218. * The offset in the comment array of the first comment whose field
  89219. * name matches \a field_name, or \c -1 if no match was found.
  89220. */
  89221. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89222. /** Remove first Vorbis comment matching the given field name.
  89223. *
  89224. * \param object A pointer to an existing VORBIS_COMMENT object.
  89225. * \param field_name The field name of comment to delete.
  89226. * \assert
  89227. * \code object != NULL \endcode
  89228. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89229. * \retval int
  89230. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89231. * \c 1 for one matching entry deleted.
  89232. */
  89233. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89234. /** Remove all Vorbis comments matching the given field name.
  89235. *
  89236. * \param object A pointer to an existing VORBIS_COMMENT object.
  89237. * \param field_name The field name of comments to delete.
  89238. * \assert
  89239. * \code object != NULL \endcode
  89240. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89241. * \retval int
  89242. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89243. * else the number of matching entries deleted.
  89244. */
  89245. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89246. /** Create a new CUESHEET track instance.
  89247. *
  89248. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89249. *
  89250. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89251. * \c NULL if there was an error allocating memory, else the new instance.
  89252. */
  89253. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89254. /** Create a copy of an existing CUESHEET track object.
  89255. *
  89256. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89257. * object is also copied. The caller takes ownership of the new object and
  89258. * is responsible for freeing it with
  89259. * FLAC__metadata_object_cuesheet_track_delete().
  89260. *
  89261. * \param object Pointer to object to copy.
  89262. * \assert
  89263. * \code object != NULL \endcode
  89264. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89265. * \c NULL if there was an error allocating memory, else the new instance.
  89266. */
  89267. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89268. /** Delete a CUESHEET track object
  89269. *
  89270. * \param object A pointer to an existing CUESHEET track object.
  89271. * \assert
  89272. * \code object != NULL \endcode
  89273. */
  89274. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89275. /** Resize a track's index point array.
  89276. *
  89277. * If the size shrinks, elements will truncated; if it grows, new blank
  89278. * indices will be added to the end.
  89279. *
  89280. * \param object A pointer to an existing CUESHEET object.
  89281. * \param track_num The index of the track to modify. NOTE: this is not
  89282. * necessarily the same as the track's \a number field.
  89283. * \param new_num_indices The desired length of the array; may be \c 0.
  89284. * \assert
  89285. * \code object != NULL \endcode
  89286. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89287. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89288. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89289. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89290. * \retval FLAC__bool
  89291. * \c false if memory allocation error, else \c true.
  89292. */
  89293. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89294. /** Insert an index point in a CUESHEET track at the given index.
  89295. *
  89296. * \param object A pointer to an existing CUESHEET object.
  89297. * \param track_num The index of the track to modify. NOTE: this is not
  89298. * necessarily the same as the track's \a number field.
  89299. * \param index_num The index into the track's index array at which to
  89300. * insert the index point. NOTE: this is not necessarily
  89301. * the same as the index point's \a number field. The
  89302. * indices at and after \a index_num move right one
  89303. * position. To append an index point to the end, set
  89304. * \a index_num to
  89305. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89306. * \param index The index point to insert.
  89307. * \assert
  89308. * \code object != NULL \endcode
  89309. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89310. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89311. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89312. * \retval FLAC__bool
  89313. * \c false if realloc() fails, else \c true.
  89314. */
  89315. 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);
  89316. /** Insert a blank index point in a CUESHEET track at the given index.
  89317. *
  89318. * A blank index point is one in which all field values are zero.
  89319. *
  89320. * \param object A pointer to an existing CUESHEET object.
  89321. * \param track_num The index of the track to modify. NOTE: this is not
  89322. * necessarily the same as the track's \a number field.
  89323. * \param index_num The index into the track's index array at which to
  89324. * insert the index point. NOTE: this is not necessarily
  89325. * the same as the index point's \a number field. The
  89326. * indices at and after \a index_num move right one
  89327. * position. To append an index point to the end, set
  89328. * \a index_num to
  89329. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89330. * \assert
  89331. * \code object != NULL \endcode
  89332. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89333. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89334. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89335. * \retval FLAC__bool
  89336. * \c false if realloc() fails, else \c true.
  89337. */
  89338. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89339. /** Delete an index point in a CUESHEET track at the given index.
  89340. *
  89341. * \param object A pointer to an existing CUESHEET object.
  89342. * \param track_num The index into the track array of the track to
  89343. * modify. NOTE: this is not necessarily the same
  89344. * as the track's \a number field.
  89345. * \param index_num The index into the track's index array of the index
  89346. * to delete. NOTE: this is not necessarily the same
  89347. * as the index's \a number field.
  89348. * \assert
  89349. * \code object != NULL \endcode
  89350. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89351. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89352. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89353. * \retval FLAC__bool
  89354. * \c false if realloc() fails, else \c true.
  89355. */
  89356. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89357. /** Resize the track array.
  89358. *
  89359. * If the size shrinks, elements will truncated; if it grows, new blank
  89360. * tracks will be added to the end.
  89361. *
  89362. * \param object A pointer to an existing CUESHEET object.
  89363. * \param new_num_tracks The desired length of the array; may be \c 0.
  89364. * \assert
  89365. * \code object != NULL \endcode
  89366. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89367. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89368. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89369. * \retval FLAC__bool
  89370. * \c false if memory allocation error, else \c true.
  89371. */
  89372. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89373. /** Sets a track in a CUESHEET block.
  89374. *
  89375. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89376. * takes ownership of the \a track pointer.
  89377. *
  89378. * \param object A pointer to an existing CUESHEET object.
  89379. * \param track_num Index into track array to set. NOTE: this is not
  89380. * necessarily the same as the track's \a number field.
  89381. * \param track The track to set the track to. You may safely pass in
  89382. * a const pointer if \a copy is \c true.
  89383. * \param copy See above.
  89384. * \assert
  89385. * \code object != NULL \endcode
  89386. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89387. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89388. * \code (track->indices != NULL && track->num_indices > 0) ||
  89389. * (track->indices == NULL && track->num_indices == 0)
  89390. * \retval FLAC__bool
  89391. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89392. */
  89393. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89394. /** Insert a track in a CUESHEET block at the given index.
  89395. *
  89396. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89397. * takes ownership of the \a track pointer.
  89398. *
  89399. * \param object A pointer to an existing CUESHEET object.
  89400. * \param track_num The index at which to insert the track. NOTE: this
  89401. * is not necessarily the same as the track's \a number
  89402. * field. The tracks at and after \a track_num move right
  89403. * one position. To append a track to the end, set
  89404. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89405. * \param track The track to insert. You may safely pass in a const
  89406. * pointer if \a copy is \c true.
  89407. * \param copy See above.
  89408. * \assert
  89409. * \code object != NULL \endcode
  89410. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89411. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89412. * \retval FLAC__bool
  89413. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89414. */
  89415. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89416. /** Insert a blank track in a CUESHEET block at the given index.
  89417. *
  89418. * A blank track is one in which all field values are zero.
  89419. *
  89420. * \param object A pointer to an existing CUESHEET object.
  89421. * \param track_num The index at which to insert the track. NOTE: this
  89422. * is not necessarily the same as the track's \a number
  89423. * field. The tracks at and after \a track_num move right
  89424. * one position. To append a track to the end, set
  89425. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89426. * \assert
  89427. * \code object != NULL \endcode
  89428. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89429. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89430. * \retval FLAC__bool
  89431. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89432. */
  89433. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89434. /** Delete a track in a CUESHEET block at the given index.
  89435. *
  89436. * \param object A pointer to an existing CUESHEET object.
  89437. * \param track_num The index into the track array of the track to
  89438. * delete. NOTE: this is not necessarily the same
  89439. * as the track's \a number field.
  89440. * \assert
  89441. * \code object != NULL \endcode
  89442. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89443. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89444. * \retval FLAC__bool
  89445. * \c false if realloc() fails, else \c true.
  89446. */
  89447. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89448. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89449. * See the format specification for limits on the contents of the
  89450. * cue sheet.
  89451. *
  89452. * \param object A pointer to an existing CUESHEET object.
  89453. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89454. * stringent requirements for a CD-DA (audio) disc.
  89455. * \param violation Address of a pointer to a string. If there is a
  89456. * violation, a pointer to a string explanation of the
  89457. * violation will be returned here. \a violation may be
  89458. * \c NULL if you don't need the returned string. Do not
  89459. * free the returned string; it will always point to static
  89460. * data.
  89461. * \assert
  89462. * \code object != NULL \endcode
  89463. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89464. * \retval FLAC__bool
  89465. * \c false if cue sheet is illegal, else \c true.
  89466. */
  89467. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89468. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89469. * assumes the cue sheet corresponds to a CD; the result is undefined
  89470. * if the cuesheet's is_cd bit is not set.
  89471. *
  89472. * \param object A pointer to an existing CUESHEET object.
  89473. * \assert
  89474. * \code object != NULL \endcode
  89475. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89476. * \retval FLAC__uint32
  89477. * The unsigned integer representation of the CDDB/freedb ID
  89478. */
  89479. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89480. /** Sets the MIME type of a PICTURE block.
  89481. *
  89482. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89483. * takes ownership of the pointer. The existing string will be freed if this
  89484. * function is successful, otherwise the original string will remain if \a copy
  89485. * is \c true and malloc() fails.
  89486. *
  89487. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89488. *
  89489. * \param object A pointer to an existing PICTURE object.
  89490. * \param mime_type A pointer to the MIME type string. The string must be
  89491. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89492. * is done.
  89493. * \param copy See above.
  89494. * \assert
  89495. * \code object != NULL \endcode
  89496. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89497. * \code (mime_type != NULL) \endcode
  89498. * \retval FLAC__bool
  89499. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89500. */
  89501. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89502. /** Sets the description of a PICTURE block.
  89503. *
  89504. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89505. * takes ownership of the pointer. The existing string will be freed if this
  89506. * function is successful, otherwise the original string will remain if \a copy
  89507. * is \c true and malloc() fails.
  89508. *
  89509. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89510. *
  89511. * \param object A pointer to an existing PICTURE object.
  89512. * \param description A pointer to the description string. The string must be
  89513. * valid UTF-8, NUL-terminated. No validation is done.
  89514. * \param copy See above.
  89515. * \assert
  89516. * \code object != NULL \endcode
  89517. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89518. * \code (description != NULL) \endcode
  89519. * \retval FLAC__bool
  89520. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89521. */
  89522. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89523. /** Sets the picture data of a PICTURE block.
  89524. *
  89525. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89526. * takes ownership of the pointer. Also sets the \a data_length field of the
  89527. * metadata object to what is passed in as the \a length parameter. The
  89528. * existing data will be freed if this function is successful, otherwise the
  89529. * original data and data_length will remain if \a copy is \c true and
  89530. * malloc() fails.
  89531. *
  89532. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89533. *
  89534. * \param object A pointer to an existing PICTURE object.
  89535. * \param data A pointer to the data to set.
  89536. * \param length The length of \a data in bytes.
  89537. * \param copy See above.
  89538. * \assert
  89539. * \code object != NULL \endcode
  89540. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89541. * \code (data != NULL && length > 0) ||
  89542. * (data == NULL && length == 0 && copy == false) \endcode
  89543. * \retval FLAC__bool
  89544. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89545. */
  89546. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89547. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89548. * See the format specification for limits on the contents of the
  89549. * PICTURE block.
  89550. *
  89551. * \param object A pointer to existing PICTURE block to be checked.
  89552. * \param violation Address of a pointer to a string. If there is a
  89553. * violation, a pointer to a string explanation of the
  89554. * violation will be returned here. \a violation may be
  89555. * \c NULL if you don't need the returned string. Do not
  89556. * free the returned string; it will always point to static
  89557. * data.
  89558. * \assert
  89559. * \code object != NULL \endcode
  89560. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89561. * \retval FLAC__bool
  89562. * \c false if PICTURE block is illegal, else \c true.
  89563. */
  89564. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89565. /* \} */
  89566. #ifdef __cplusplus
  89567. }
  89568. #endif
  89569. #endif
  89570. /*** End of inlined file: metadata.h ***/
  89571. /*** Start of inlined file: stream_decoder.h ***/
  89572. #ifndef FLAC__STREAM_DECODER_H
  89573. #define FLAC__STREAM_DECODER_H
  89574. #include <stdio.h> /* for FILE */
  89575. #ifdef __cplusplus
  89576. extern "C" {
  89577. #endif
  89578. /** \file include/FLAC/stream_decoder.h
  89579. *
  89580. * \brief
  89581. * This module contains the functions which implement the stream
  89582. * decoder.
  89583. *
  89584. * See the detailed documentation in the
  89585. * \link flac_stream_decoder stream decoder \endlink module.
  89586. */
  89587. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89588. * \ingroup flac
  89589. *
  89590. * \brief
  89591. * This module describes the decoder layers provided by libFLAC.
  89592. *
  89593. * The stream decoder can be used to decode complete streams either from
  89594. * the client via callbacks, or directly from a file, depending on how
  89595. * it is initialized. When decoding via callbacks, the client provides
  89596. * callbacks for reading FLAC data and writing decoded samples, and
  89597. * handling metadata and errors. If the client also supplies seek-related
  89598. * callback, the decoder function for sample-accurate seeking within the
  89599. * FLAC input is also available. When decoding from a file, the client
  89600. * needs only supply a filename or open \c FILE* and write/metadata/error
  89601. * callbacks; the rest of the callbacks are supplied internally. For more
  89602. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89603. */
  89604. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89605. * \ingroup flac_decoder
  89606. *
  89607. * \brief
  89608. * This module contains the functions which implement the stream
  89609. * decoder.
  89610. *
  89611. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89612. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89613. *
  89614. * The basic usage of this decoder is as follows:
  89615. * - The program creates an instance of a decoder using
  89616. * FLAC__stream_decoder_new().
  89617. * - The program overrides the default settings using
  89618. * FLAC__stream_decoder_set_*() functions.
  89619. * - The program initializes the instance to validate the settings and
  89620. * prepare for decoding using
  89621. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89622. * or FLAC__stream_decoder_init_file() for native FLAC,
  89623. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89624. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89625. * - The program calls the FLAC__stream_decoder_process_*() functions
  89626. * to decode data, which subsequently calls the callbacks.
  89627. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89628. * which flushes the input and output and resets the decoder to the
  89629. * uninitialized state.
  89630. * - The instance may be used again or deleted with
  89631. * FLAC__stream_decoder_delete().
  89632. *
  89633. * In more detail, the program will create a new instance by calling
  89634. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89635. * functions to override the default decoder options, and call
  89636. * one of the FLAC__stream_decoder_init_*() functions.
  89637. *
  89638. * There are three initialization functions for native FLAC, one for
  89639. * setting up the decoder to decode FLAC data from the client via
  89640. * callbacks, and two for decoding directly from a FLAC file.
  89641. *
  89642. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89643. * You must also supply several callbacks for handling I/O. Some (like
  89644. * seeking) are optional, depending on the capabilities of the input.
  89645. *
  89646. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89647. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89648. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89649. * the other callbacks internally.
  89650. *
  89651. * There are three similarly-named init functions for decoding from Ogg
  89652. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89653. * library has been built with Ogg support.
  89654. *
  89655. * Once the decoder is initialized, your program will call one of several
  89656. * functions to start the decoding process:
  89657. *
  89658. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89659. * most one metadata block or audio frame and return, calling either the
  89660. * metadata callback or write callback, respectively, once. If the decoder
  89661. * loses sync it will return with only the error callback being called.
  89662. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89663. * to process the stream from the current location and stop upon reaching
  89664. * the first audio frame. The client will get one metadata, write, or error
  89665. * callback per metadata block, audio frame, or sync error, respectively.
  89666. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89667. * to process the stream from the current location until the read callback
  89668. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89669. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89670. * write, or error callback per metadata block, audio frame, or sync error,
  89671. * respectively.
  89672. *
  89673. * When the decoder has finished decoding (normally or through an abort),
  89674. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89675. * ensures the decoder is in the correct state and frees memory. Then the
  89676. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89677. * again to decode another stream.
  89678. *
  89679. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89680. * At any point after the stream decoder has been initialized, the client can
  89681. * call this function to seek to an exact sample within the stream.
  89682. * Subsequently, the first time the write callback is called it will be
  89683. * passed a (possibly partial) block starting at that sample.
  89684. *
  89685. * If the client cannot seek via the callback interface provided, but still
  89686. * has another way of seeking, it can flush the decoder using
  89687. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89688. * through the read callback.
  89689. *
  89690. * The stream decoder also provides MD5 signature checking. If this is
  89691. * turned on before initialization, FLAC__stream_decoder_finish() will
  89692. * report when the decoded MD5 signature does not match the one stored
  89693. * in the STREAMINFO block. MD5 checking is automatically turned off
  89694. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89695. * in the STREAMINFO block or when a seek is attempted.
  89696. *
  89697. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89698. * attention. By default, the decoder only calls the metadata_callback for
  89699. * the STREAMINFO block. These functions allow you to tell the decoder
  89700. * explicitly which blocks to parse and return via the metadata_callback
  89701. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89702. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89703. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89704. * which blocks to return. Remember that metadata blocks can potentially
  89705. * be big (for example, cover art) so filtering out the ones you don't
  89706. * use can reduce the memory requirements of the decoder. Also note the
  89707. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89708. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89709. * filtering APPLICATION blocks based on the application ID.
  89710. *
  89711. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89712. * they still can legally be filtered from the metadata_callback.
  89713. *
  89714. * \note
  89715. * The "set" functions may only be called when the decoder is in the
  89716. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89717. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89718. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89719. * return \c true, otherwise \c false.
  89720. *
  89721. * \note
  89722. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89723. * defaults, including the callbacks.
  89724. *
  89725. * \{
  89726. */
  89727. /** State values for a FLAC__StreamDecoder
  89728. *
  89729. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89730. */
  89731. typedef enum {
  89732. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89733. /**< The decoder is ready to search for metadata. */
  89734. FLAC__STREAM_DECODER_READ_METADATA,
  89735. /**< The decoder is ready to or is in the process of reading metadata. */
  89736. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89737. /**< The decoder is ready to or is in the process of searching for the
  89738. * frame sync code.
  89739. */
  89740. FLAC__STREAM_DECODER_READ_FRAME,
  89741. /**< The decoder is ready to or is in the process of reading a frame. */
  89742. FLAC__STREAM_DECODER_END_OF_STREAM,
  89743. /**< The decoder has reached the end of the stream. */
  89744. FLAC__STREAM_DECODER_OGG_ERROR,
  89745. /**< An error occurred in the underlying Ogg layer. */
  89746. FLAC__STREAM_DECODER_SEEK_ERROR,
  89747. /**< An error occurred while seeking. The decoder must be flushed
  89748. * with FLAC__stream_decoder_flush() or reset with
  89749. * FLAC__stream_decoder_reset() before decoding can continue.
  89750. */
  89751. FLAC__STREAM_DECODER_ABORTED,
  89752. /**< The decoder was aborted by the read callback. */
  89753. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89754. /**< An error occurred allocating memory. The decoder is in an invalid
  89755. * state and can no longer be used.
  89756. */
  89757. FLAC__STREAM_DECODER_UNINITIALIZED
  89758. /**< The decoder is in the uninitialized state; one of the
  89759. * FLAC__stream_decoder_init_*() functions must be called before samples
  89760. * can be processed.
  89761. */
  89762. } FLAC__StreamDecoderState;
  89763. /** Maps a FLAC__StreamDecoderState to a C string.
  89764. *
  89765. * Using a FLAC__StreamDecoderState as the index to this array
  89766. * will give the string equivalent. The contents should not be modified.
  89767. */
  89768. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89769. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89770. */
  89771. typedef enum {
  89772. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89773. /**< Initialization was successful. */
  89774. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89775. /**< The library was not compiled with support for the given container
  89776. * format.
  89777. */
  89778. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89779. /**< A required callback was not supplied. */
  89780. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89781. /**< An error occurred allocating memory. */
  89782. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89783. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89784. * FLAC__stream_decoder_init_ogg_file(). */
  89785. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89786. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89787. * already initialized, usually because
  89788. * FLAC__stream_decoder_finish() was not called.
  89789. */
  89790. } FLAC__StreamDecoderInitStatus;
  89791. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89792. *
  89793. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89794. * will give the string equivalent. The contents should not be modified.
  89795. */
  89796. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89797. /** Return values for the FLAC__StreamDecoder read callback.
  89798. */
  89799. typedef enum {
  89800. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89801. /**< The read was OK and decoding can continue. */
  89802. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89803. /**< The read was attempted while at the end of the stream. Note that
  89804. * the client must only return this value when the read callback was
  89805. * called when already at the end of the stream. Otherwise, if the read
  89806. * itself moves to the end of the stream, the client should still return
  89807. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89808. * the next read callback it should return
  89809. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89810. * of \c 0.
  89811. */
  89812. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89813. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89814. } FLAC__StreamDecoderReadStatus;
  89815. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89816. *
  89817. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89818. * will give the string equivalent. The contents should not be modified.
  89819. */
  89820. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89821. /** Return values for the FLAC__StreamDecoder seek callback.
  89822. */
  89823. typedef enum {
  89824. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89825. /**< The seek was OK and decoding can continue. */
  89826. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89827. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89828. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89829. /**< Client does not support seeking. */
  89830. } FLAC__StreamDecoderSeekStatus;
  89831. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89832. *
  89833. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89834. * will give the string equivalent. The contents should not be modified.
  89835. */
  89836. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89837. /** Return values for the FLAC__StreamDecoder tell callback.
  89838. */
  89839. typedef enum {
  89840. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89841. /**< The tell was OK and decoding can continue. */
  89842. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89843. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89844. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89845. /**< Client does not support telling the position. */
  89846. } FLAC__StreamDecoderTellStatus;
  89847. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89848. *
  89849. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89850. * will give the string equivalent. The contents should not be modified.
  89851. */
  89852. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89853. /** Return values for the FLAC__StreamDecoder length callback.
  89854. */
  89855. typedef enum {
  89856. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89857. /**< The length call was OK and decoding can continue. */
  89858. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89859. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89860. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89861. /**< Client does not support reporting the length. */
  89862. } FLAC__StreamDecoderLengthStatus;
  89863. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89864. *
  89865. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89866. * will give the string equivalent. The contents should not be modified.
  89867. */
  89868. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89869. /** Return values for the FLAC__StreamDecoder write callback.
  89870. */
  89871. typedef enum {
  89872. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89873. /**< The write was OK and decoding can continue. */
  89874. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89875. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89876. } FLAC__StreamDecoderWriteStatus;
  89877. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89878. *
  89879. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89880. * will give the string equivalent. The contents should not be modified.
  89881. */
  89882. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89883. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89884. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89885. * all. The rest could be caused by bad sync (false synchronization on
  89886. * data that is not the start of a frame) or corrupted data. The error
  89887. * itself is the decoder's best guess at what happened assuming a correct
  89888. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89889. * could be caused by a correct sync on the start of a frame, but some
  89890. * data in the frame header was corrupted. Or it could be the result of
  89891. * syncing on a point the stream that looked like the starting of a frame
  89892. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89893. * could be because the decoder encountered a valid frame made by a future
  89894. * version of the encoder which it cannot parse, or because of a false
  89895. * sync making it appear as though an encountered frame was generated by
  89896. * a future encoder.
  89897. */
  89898. typedef enum {
  89899. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89900. /**< An error in the stream caused the decoder to lose synchronization. */
  89901. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89902. /**< The decoder encountered a corrupted frame header. */
  89903. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89904. /**< The frame's data did not match the CRC in the footer. */
  89905. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89906. /**< The decoder encountered reserved fields in use in the stream. */
  89907. } FLAC__StreamDecoderErrorStatus;
  89908. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89909. *
  89910. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89911. * will give the string equivalent. The contents should not be modified.
  89912. */
  89913. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89914. /***********************************************************************
  89915. *
  89916. * class FLAC__StreamDecoder
  89917. *
  89918. ***********************************************************************/
  89919. struct FLAC__StreamDecoderProtected;
  89920. struct FLAC__StreamDecoderPrivate;
  89921. /** The opaque structure definition for the stream decoder type.
  89922. * See the \link flac_stream_decoder stream decoder module \endlink
  89923. * for a detailed description.
  89924. */
  89925. typedef struct {
  89926. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89927. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89928. } FLAC__StreamDecoder;
  89929. /** Signature for the read callback.
  89930. *
  89931. * A function pointer matching this signature must be passed to
  89932. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89933. * called when the decoder needs more input data. The address of the
  89934. * buffer to be filled is supplied, along with the number of bytes the
  89935. * buffer can hold. The callback may choose to supply less data and
  89936. * modify the byte count but must be careful not to overflow the buffer.
  89937. * The callback then returns a status code chosen from
  89938. * FLAC__StreamDecoderReadStatus.
  89939. *
  89940. * Here is an example of a read callback for stdio streams:
  89941. * \code
  89942. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89943. * {
  89944. * FILE *file = ((MyClientData*)client_data)->file;
  89945. * if(*bytes > 0) {
  89946. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89947. * if(ferror(file))
  89948. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89949. * else if(*bytes == 0)
  89950. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89951. * else
  89952. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89953. * }
  89954. * else
  89955. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89956. * }
  89957. * \endcode
  89958. *
  89959. * \note In general, FLAC__StreamDecoder functions which change the
  89960. * state should not be called on the \a decoder while in the callback.
  89961. *
  89962. * \param decoder The decoder instance calling the callback.
  89963. * \param buffer A pointer to a location for the callee to store
  89964. * data to be decoded.
  89965. * \param bytes A pointer to the size of the buffer. On entry
  89966. * to the callback, it contains the maximum number
  89967. * of bytes that may be stored in \a buffer. The
  89968. * callee must set it to the actual number of bytes
  89969. * stored (0 in case of error or end-of-stream) before
  89970. * returning.
  89971. * \param client_data The callee's client data set through
  89972. * FLAC__stream_decoder_init_*().
  89973. * \retval FLAC__StreamDecoderReadStatus
  89974. * The callee's return status. Note that the callback should return
  89975. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89976. * zero bytes were read and there is no more data to be read.
  89977. */
  89978. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89979. /** Signature for the seek callback.
  89980. *
  89981. * A function pointer matching this signature may be passed to
  89982. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89983. * called when the decoder needs to seek the input stream. The decoder
  89984. * will pass the absolute byte offset to seek to, 0 meaning the
  89985. * beginning of the stream.
  89986. *
  89987. * Here is an example of a seek callback for stdio streams:
  89988. * \code
  89989. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89990. * {
  89991. * FILE *file = ((MyClientData*)client_data)->file;
  89992. * if(file == stdin)
  89993. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89994. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89995. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89996. * else
  89997. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89998. * }
  89999. * \endcode
  90000. *
  90001. * \note In general, FLAC__StreamDecoder functions which change the
  90002. * state should not be called on the \a decoder while in the callback.
  90003. *
  90004. * \param decoder The decoder instance calling the callback.
  90005. * \param absolute_byte_offset The offset from the beginning of the stream
  90006. * to seek to.
  90007. * \param client_data The callee's client data set through
  90008. * FLAC__stream_decoder_init_*().
  90009. * \retval FLAC__StreamDecoderSeekStatus
  90010. * The callee's return status.
  90011. */
  90012. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90013. /** Signature for the tell callback.
  90014. *
  90015. * A function pointer matching this signature may be passed to
  90016. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90017. * called when the decoder wants to know the current position of the
  90018. * stream. The callback should return the byte offset from the
  90019. * beginning of the stream.
  90020. *
  90021. * Here is an example of a tell callback for stdio streams:
  90022. * \code
  90023. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90024. * {
  90025. * FILE *file = ((MyClientData*)client_data)->file;
  90026. * off_t pos;
  90027. * if(file == stdin)
  90028. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  90029. * else if((pos = ftello(file)) < 0)
  90030. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  90031. * else {
  90032. * *absolute_byte_offset = (FLAC__uint64)pos;
  90033. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  90034. * }
  90035. * }
  90036. * \endcode
  90037. *
  90038. * \note In general, FLAC__StreamDecoder functions which change the
  90039. * state should not be called on the \a decoder while in the callback.
  90040. *
  90041. * \param decoder The decoder instance calling the callback.
  90042. * \param absolute_byte_offset A pointer to storage for the current offset
  90043. * from the beginning of the stream.
  90044. * \param client_data The callee's client data set through
  90045. * FLAC__stream_decoder_init_*().
  90046. * \retval FLAC__StreamDecoderTellStatus
  90047. * The callee's return status.
  90048. */
  90049. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90050. /** Signature for the length callback.
  90051. *
  90052. * A function pointer matching this signature may be passed to
  90053. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90054. * called when the decoder wants to know the total length of the stream
  90055. * in bytes.
  90056. *
  90057. * Here is an example of a length callback for stdio streams:
  90058. * \code
  90059. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  90060. * {
  90061. * FILE *file = ((MyClientData*)client_data)->file;
  90062. * struct stat filestats;
  90063. *
  90064. * if(file == stdin)
  90065. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  90066. * else if(fstat(fileno(file), &filestats) != 0)
  90067. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  90068. * else {
  90069. * *stream_length = (FLAC__uint64)filestats.st_size;
  90070. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  90071. * }
  90072. * }
  90073. * \endcode
  90074. *
  90075. * \note In general, FLAC__StreamDecoder functions which change the
  90076. * state should not be called on the \a decoder while in the callback.
  90077. *
  90078. * \param decoder The decoder instance calling the callback.
  90079. * \param stream_length A pointer to storage for the length of the stream
  90080. * in bytes.
  90081. * \param client_data The callee's client data set through
  90082. * FLAC__stream_decoder_init_*().
  90083. * \retval FLAC__StreamDecoderLengthStatus
  90084. * The callee's return status.
  90085. */
  90086. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  90087. /** Signature for the EOF callback.
  90088. *
  90089. * A function pointer matching this signature may be passed to
  90090. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90091. * called when the decoder needs to know if the end of the stream has
  90092. * been reached.
  90093. *
  90094. * Here is an example of a EOF callback for stdio streams:
  90095. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  90096. * \code
  90097. * {
  90098. * FILE *file = ((MyClientData*)client_data)->file;
  90099. * return feof(file)? true : false;
  90100. * }
  90101. * \endcode
  90102. *
  90103. * \note In general, FLAC__StreamDecoder functions which change the
  90104. * state should not be called on the \a decoder while in the callback.
  90105. *
  90106. * \param decoder The decoder instance calling the callback.
  90107. * \param client_data The callee's client data set through
  90108. * FLAC__stream_decoder_init_*().
  90109. * \retval FLAC__bool
  90110. * \c true if the currently at the end of the stream, else \c false.
  90111. */
  90112. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  90113. /** Signature for the write callback.
  90114. *
  90115. * A function pointer matching this signature must be passed to one of
  90116. * the FLAC__stream_decoder_init_*() functions.
  90117. * The supplied function will be called when the decoder has decoded a
  90118. * single audio frame. The decoder will pass the frame metadata as well
  90119. * as an array of pointers (one for each channel) pointing to the
  90120. * decoded audio.
  90121. *
  90122. * \note In general, FLAC__StreamDecoder functions which change the
  90123. * state should not be called on the \a decoder while in the callback.
  90124. *
  90125. * \param decoder The decoder instance calling the callback.
  90126. * \param frame The description of the decoded frame. See
  90127. * FLAC__Frame.
  90128. * \param buffer An array of pointers to decoded channels of data.
  90129. * Each pointer will point to an array of signed
  90130. * samples of length \a frame->header.blocksize.
  90131. * Channels will be ordered according to the FLAC
  90132. * specification; see the documentation for the
  90133. * <A HREF="../format.html#frame_header">frame header</A>.
  90134. * \param client_data The callee's client data set through
  90135. * FLAC__stream_decoder_init_*().
  90136. * \retval FLAC__StreamDecoderWriteStatus
  90137. * The callee's return status.
  90138. */
  90139. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90140. /** Signature for the metadata callback.
  90141. *
  90142. * A function pointer matching this signature must be passed to one of
  90143. * the FLAC__stream_decoder_init_*() functions.
  90144. * The supplied function will be called when the decoder has decoded a
  90145. * metadata block. In a valid FLAC file there will always be one
  90146. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90147. * These will be supplied by the decoder in the same order as they
  90148. * appear in the stream and always before the first audio frame (i.e.
  90149. * write callback). The metadata block that is passed in must not be
  90150. * modified, and it doesn't live beyond the callback, so you should make
  90151. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90152. * elsewhere. Since metadata blocks can potentially be large, by
  90153. * default the decoder only calls the metadata callback for the
  90154. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90155. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90156. *
  90157. * \note In general, FLAC__StreamDecoder functions which change the
  90158. * state should not be called on the \a decoder while in the callback.
  90159. *
  90160. * \param decoder The decoder instance calling the callback.
  90161. * \param metadata The decoded metadata block.
  90162. * \param client_data The callee's client data set through
  90163. * FLAC__stream_decoder_init_*().
  90164. */
  90165. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90166. /** Signature for the error callback.
  90167. *
  90168. * A function pointer matching this signature must be passed to one of
  90169. * the FLAC__stream_decoder_init_*() functions.
  90170. * The supplied function will be called whenever an error occurs during
  90171. * decoding.
  90172. *
  90173. * \note In general, FLAC__StreamDecoder functions which change the
  90174. * state should not be called on the \a decoder while in the callback.
  90175. *
  90176. * \param decoder The decoder instance calling the callback.
  90177. * \param status The error encountered by the decoder.
  90178. * \param client_data The callee's client data set through
  90179. * FLAC__stream_decoder_init_*().
  90180. */
  90181. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90182. /***********************************************************************
  90183. *
  90184. * Class constructor/destructor
  90185. *
  90186. ***********************************************************************/
  90187. /** Create a new stream decoder instance. The instance is created with
  90188. * default settings; see the individual FLAC__stream_decoder_set_*()
  90189. * functions for each setting's default.
  90190. *
  90191. * \retval FLAC__StreamDecoder*
  90192. * \c NULL if there was an error allocating memory, else the new instance.
  90193. */
  90194. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90195. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90196. *
  90197. * \param decoder A pointer to an existing decoder.
  90198. * \assert
  90199. * \code decoder != NULL \endcode
  90200. */
  90201. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90202. /***********************************************************************
  90203. *
  90204. * Public class method prototypes
  90205. *
  90206. ***********************************************************************/
  90207. /** Set the serial number for the FLAC stream within the Ogg container.
  90208. * The default behavior is to use the serial number of the first Ogg
  90209. * page. Setting a serial number here will explicitly specify which
  90210. * stream is to be decoded.
  90211. *
  90212. * \note
  90213. * This does not need to be set for native FLAC decoding.
  90214. *
  90215. * \default \c use serial number of first page
  90216. * \param decoder A decoder instance to set.
  90217. * \param serial_number See above.
  90218. * \assert
  90219. * \code decoder != NULL \endcode
  90220. * \retval FLAC__bool
  90221. * \c false if the decoder is already initialized, else \c true.
  90222. */
  90223. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90224. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90225. * compute the MD5 signature of the unencoded audio data while decoding
  90226. * and compare it to the signature from the STREAMINFO block, if it
  90227. * exists, during FLAC__stream_decoder_finish().
  90228. *
  90229. * MD5 signature checking will be turned off (until the next
  90230. * FLAC__stream_decoder_reset()) if there is no signature in the
  90231. * STREAMINFO block or when a seek is attempted.
  90232. *
  90233. * Clients that do not use the MD5 check should leave this off to speed
  90234. * up decoding.
  90235. *
  90236. * \default \c false
  90237. * \param decoder A decoder instance to set.
  90238. * \param value Flag value (see above).
  90239. * \assert
  90240. * \code decoder != NULL \endcode
  90241. * \retval FLAC__bool
  90242. * \c false if the decoder is already initialized, else \c true.
  90243. */
  90244. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90245. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90246. *
  90247. * \default By default, only the \c STREAMINFO block is returned via the
  90248. * metadata callback.
  90249. * \param decoder A decoder instance to set.
  90250. * \param type See above.
  90251. * \assert
  90252. * \code decoder != NULL \endcode
  90253. * \a type is valid
  90254. * \retval FLAC__bool
  90255. * \c false if the decoder is already initialized, else \c true.
  90256. */
  90257. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90258. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90259. * given \a id.
  90260. *
  90261. * \default By default, only the \c STREAMINFO block is returned via the
  90262. * metadata callback.
  90263. * \param decoder A decoder instance to set.
  90264. * \param id See above.
  90265. * \assert
  90266. * \code decoder != NULL \endcode
  90267. * \code id != NULL \endcode
  90268. * \retval FLAC__bool
  90269. * \c false if the decoder is already initialized, else \c true.
  90270. */
  90271. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90272. /** Direct the decoder to pass on all metadata blocks of any type.
  90273. *
  90274. * \default By default, only the \c STREAMINFO block is returned via the
  90275. * metadata callback.
  90276. * \param decoder A decoder instance to set.
  90277. * \assert
  90278. * \code decoder != NULL \endcode
  90279. * \retval FLAC__bool
  90280. * \c false if the decoder is already initialized, else \c true.
  90281. */
  90282. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90283. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90284. *
  90285. * \default By default, only the \c STREAMINFO block is returned via the
  90286. * metadata callback.
  90287. * \param decoder A decoder instance to set.
  90288. * \param type See above.
  90289. * \assert
  90290. * \code decoder != NULL \endcode
  90291. * \a type is valid
  90292. * \retval FLAC__bool
  90293. * \c false if the decoder is already initialized, else \c true.
  90294. */
  90295. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90296. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90297. * the given \a id.
  90298. *
  90299. * \default By default, only the \c STREAMINFO block is returned via the
  90300. * metadata callback.
  90301. * \param decoder A decoder instance to set.
  90302. * \param id See above.
  90303. * \assert
  90304. * \code decoder != NULL \endcode
  90305. * \code id != NULL \endcode
  90306. * \retval FLAC__bool
  90307. * \c false if the decoder is already initialized, else \c true.
  90308. */
  90309. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90310. /** Direct the decoder to filter out all metadata blocks of any type.
  90311. *
  90312. * \default By default, only the \c STREAMINFO block is returned via the
  90313. * metadata callback.
  90314. * \param decoder A decoder instance to set.
  90315. * \assert
  90316. * \code decoder != NULL \endcode
  90317. * \retval FLAC__bool
  90318. * \c false if the decoder is already initialized, else \c true.
  90319. */
  90320. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90321. /** Get the current decoder state.
  90322. *
  90323. * \param decoder A decoder instance to query.
  90324. * \assert
  90325. * \code decoder != NULL \endcode
  90326. * \retval FLAC__StreamDecoderState
  90327. * The current decoder state.
  90328. */
  90329. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90330. /** Get the current decoder state as a C string.
  90331. *
  90332. * \param decoder A decoder instance to query.
  90333. * \assert
  90334. * \code decoder != NULL \endcode
  90335. * \retval const char *
  90336. * The decoder state as a C string. Do not modify the contents.
  90337. */
  90338. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90339. /** Get the "MD5 signature checking" flag.
  90340. * This is the value of the setting, not whether or not the decoder is
  90341. * currently checking the MD5 (remember, it can be turned off automatically
  90342. * by a seek). When the decoder is reset the flag will be restored to the
  90343. * value returned by this function.
  90344. *
  90345. * \param decoder A decoder instance to query.
  90346. * \assert
  90347. * \code decoder != NULL \endcode
  90348. * \retval FLAC__bool
  90349. * See above.
  90350. */
  90351. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90352. /** Get the total number of samples in the stream being decoded.
  90353. * Will only be valid after decoding has started and will contain the
  90354. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90355. *
  90356. * \param decoder A decoder instance to query.
  90357. * \assert
  90358. * \code decoder != NULL \endcode
  90359. * \retval unsigned
  90360. * See above.
  90361. */
  90362. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90363. /** Get the current number of channels in the stream being decoded.
  90364. * Will only be valid after decoding has started and will contain the
  90365. * value from the most recently decoded frame header.
  90366. *
  90367. * \param decoder A decoder instance to query.
  90368. * \assert
  90369. * \code decoder != NULL \endcode
  90370. * \retval unsigned
  90371. * See above.
  90372. */
  90373. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90374. /** Get the current channel assignment in the stream being decoded.
  90375. * Will only be valid after decoding has started and will contain the
  90376. * value from the most recently decoded frame header.
  90377. *
  90378. * \param decoder A decoder instance to query.
  90379. * \assert
  90380. * \code decoder != NULL \endcode
  90381. * \retval FLAC__ChannelAssignment
  90382. * See above.
  90383. */
  90384. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90385. /** Get the current sample resolution in the stream being decoded.
  90386. * Will only be valid after decoding has started and will contain the
  90387. * value from the most recently decoded frame header.
  90388. *
  90389. * \param decoder A decoder instance to query.
  90390. * \assert
  90391. * \code decoder != NULL \endcode
  90392. * \retval unsigned
  90393. * See above.
  90394. */
  90395. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90396. /** Get the current sample rate in Hz of the stream being decoded.
  90397. * Will only be valid after decoding has started and will contain the
  90398. * value from the most recently decoded frame header.
  90399. *
  90400. * \param decoder A decoder instance to query.
  90401. * \assert
  90402. * \code decoder != NULL \endcode
  90403. * \retval unsigned
  90404. * See above.
  90405. */
  90406. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90407. /** Get the current blocksize of the stream being decoded.
  90408. * Will only be valid after decoding has started and will contain the
  90409. * value from the most recently decoded frame header.
  90410. *
  90411. * \param decoder A decoder instance to query.
  90412. * \assert
  90413. * \code decoder != NULL \endcode
  90414. * \retval unsigned
  90415. * See above.
  90416. */
  90417. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90418. /** Returns the decoder's current read position within the stream.
  90419. * The position is the byte offset from the start of the stream.
  90420. * Bytes before this position have been fully decoded. Note that
  90421. * there may still be undecoded bytes in the decoder's read FIFO.
  90422. * The returned position is correct even after a seek.
  90423. *
  90424. * \warning This function currently only works for native FLAC,
  90425. * not Ogg FLAC streams.
  90426. *
  90427. * \param decoder A decoder instance to query.
  90428. * \param position Address at which to return the desired position.
  90429. * \assert
  90430. * \code decoder != NULL \endcode
  90431. * \code position != NULL \endcode
  90432. * \retval FLAC__bool
  90433. * \c true if successful, \c false if the stream is not native FLAC,
  90434. * or there was an error from the 'tell' callback or it returned
  90435. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90436. */
  90437. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90438. /** Initialize the decoder instance to decode native FLAC streams.
  90439. *
  90440. * This flavor of initialization sets up the decoder to decode from a
  90441. * native FLAC stream. I/O is performed via callbacks to the client.
  90442. * For decoding from a plain file via filename or open FILE*,
  90443. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90444. * provide a simpler interface.
  90445. *
  90446. * This function should be called after FLAC__stream_decoder_new() and
  90447. * FLAC__stream_decoder_set_*() but before any of the
  90448. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90449. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90450. * if initialization succeeded.
  90451. *
  90452. * \param decoder An uninitialized decoder instance.
  90453. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90454. * pointer must not be \c NULL.
  90455. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90456. * pointer may be \c NULL if seeking is not
  90457. * supported. If \a seek_callback is not \c NULL then a
  90458. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90459. * Alternatively, a dummy seek callback that just
  90460. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90461. * may also be supplied, all though this is slightly
  90462. * less efficient for the decoder.
  90463. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90464. * pointer may be \c NULL if not supported by the client. If
  90465. * \a seek_callback is not \c NULL then a
  90466. * \a tell_callback must also be supplied.
  90467. * Alternatively, a dummy tell callback that just
  90468. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90469. * may also be supplied, all though this is slightly
  90470. * less efficient for the decoder.
  90471. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90472. * pointer may be \c NULL if not supported by the client. If
  90473. * \a seek_callback is not \c NULL then a
  90474. * \a length_callback must also be supplied.
  90475. * Alternatively, a dummy length callback that just
  90476. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90477. * may also be supplied, all though this is slightly
  90478. * less efficient for the decoder.
  90479. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90480. * pointer may be \c NULL if not supported by the client. If
  90481. * \a seek_callback is not \c NULL then a
  90482. * \a eof_callback must also be supplied.
  90483. * Alternatively, a dummy length callback that just
  90484. * returns \c false
  90485. * may also be supplied, all though this is slightly
  90486. * less efficient for the decoder.
  90487. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90488. * pointer must not be \c NULL.
  90489. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90490. * pointer may be \c NULL if the callback is not
  90491. * desired.
  90492. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90493. * pointer must not be \c NULL.
  90494. * \param client_data This value will be supplied to callbacks in their
  90495. * \a client_data argument.
  90496. * \assert
  90497. * \code decoder != NULL \endcode
  90498. * \retval FLAC__StreamDecoderInitStatus
  90499. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90500. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90501. */
  90502. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90503. FLAC__StreamDecoder *decoder,
  90504. FLAC__StreamDecoderReadCallback read_callback,
  90505. FLAC__StreamDecoderSeekCallback seek_callback,
  90506. FLAC__StreamDecoderTellCallback tell_callback,
  90507. FLAC__StreamDecoderLengthCallback length_callback,
  90508. FLAC__StreamDecoderEofCallback eof_callback,
  90509. FLAC__StreamDecoderWriteCallback write_callback,
  90510. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90511. FLAC__StreamDecoderErrorCallback error_callback,
  90512. void *client_data
  90513. );
  90514. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90515. *
  90516. * This flavor of initialization sets up the decoder to decode from a
  90517. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90518. * client. For decoding from a plain file via filename or open FILE*,
  90519. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90520. * provide a simpler interface.
  90521. *
  90522. * This function should be called after FLAC__stream_decoder_new() and
  90523. * FLAC__stream_decoder_set_*() but before any of the
  90524. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90525. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90526. * if initialization succeeded.
  90527. *
  90528. * \note Support for Ogg FLAC in the library is optional. If this
  90529. * library has been built without support for Ogg FLAC, this function
  90530. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90531. *
  90532. * \param decoder An uninitialized decoder instance.
  90533. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90534. * pointer must not be \c NULL.
  90535. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90536. * pointer may be \c NULL if seeking is not
  90537. * supported. If \a seek_callback is not \c NULL then a
  90538. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90539. * Alternatively, a dummy seek callback that just
  90540. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90541. * may also be supplied, all though this is slightly
  90542. * less efficient for the decoder.
  90543. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90544. * pointer may be \c NULL if not supported by the client. If
  90545. * \a seek_callback is not \c NULL then a
  90546. * \a tell_callback must also be supplied.
  90547. * Alternatively, a dummy tell callback that just
  90548. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90549. * may also be supplied, all though this is slightly
  90550. * less efficient for the decoder.
  90551. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90552. * pointer may be \c NULL if not supported by the client. If
  90553. * \a seek_callback is not \c NULL then a
  90554. * \a length_callback must also be supplied.
  90555. * Alternatively, a dummy length callback that just
  90556. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90557. * may also be supplied, all though this is slightly
  90558. * less efficient for the decoder.
  90559. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90560. * pointer may be \c NULL if not supported by the client. If
  90561. * \a seek_callback is not \c NULL then a
  90562. * \a eof_callback must also be supplied.
  90563. * Alternatively, a dummy length callback that just
  90564. * returns \c false
  90565. * may also be supplied, all though this is slightly
  90566. * less efficient for the decoder.
  90567. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90568. * pointer must not be \c NULL.
  90569. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90570. * pointer may be \c NULL if the callback is not
  90571. * desired.
  90572. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90573. * pointer must not be \c NULL.
  90574. * \param client_data This value will be supplied to callbacks in their
  90575. * \a client_data argument.
  90576. * \assert
  90577. * \code decoder != NULL \endcode
  90578. * \retval FLAC__StreamDecoderInitStatus
  90579. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90580. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90581. */
  90582. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90583. FLAC__StreamDecoder *decoder,
  90584. FLAC__StreamDecoderReadCallback read_callback,
  90585. FLAC__StreamDecoderSeekCallback seek_callback,
  90586. FLAC__StreamDecoderTellCallback tell_callback,
  90587. FLAC__StreamDecoderLengthCallback length_callback,
  90588. FLAC__StreamDecoderEofCallback eof_callback,
  90589. FLAC__StreamDecoderWriteCallback write_callback,
  90590. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90591. FLAC__StreamDecoderErrorCallback error_callback,
  90592. void *client_data
  90593. );
  90594. /** Initialize the decoder instance to decode native FLAC files.
  90595. *
  90596. * This flavor of initialization sets up the decoder to decode from a
  90597. * plain native FLAC file. For non-stdio streams, you must use
  90598. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90599. *
  90600. * This function should be called after FLAC__stream_decoder_new() and
  90601. * FLAC__stream_decoder_set_*() but before any of the
  90602. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90603. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90604. * if initialization succeeded.
  90605. *
  90606. * \param decoder An uninitialized decoder instance.
  90607. * \param file An open FLAC file. The file should have been
  90608. * opened with mode \c "rb" and rewound. The file
  90609. * becomes owned by the decoder and should not be
  90610. * manipulated by the client while decoding.
  90611. * Unless \a file is \c stdin, it will be closed
  90612. * when FLAC__stream_decoder_finish() is called.
  90613. * Note however that seeking will not work when
  90614. * decoding from \c stdout since it is not seekable.
  90615. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90616. * pointer must not be \c NULL.
  90617. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90618. * pointer may be \c NULL if the callback is not
  90619. * desired.
  90620. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90621. * pointer must not be \c NULL.
  90622. * \param client_data This value will be supplied to callbacks in their
  90623. * \a client_data argument.
  90624. * \assert
  90625. * \code decoder != NULL \endcode
  90626. * \code file != NULL \endcode
  90627. * \retval FLAC__StreamDecoderInitStatus
  90628. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90629. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90630. */
  90631. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90632. FLAC__StreamDecoder *decoder,
  90633. FILE *file,
  90634. FLAC__StreamDecoderWriteCallback write_callback,
  90635. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90636. FLAC__StreamDecoderErrorCallback error_callback,
  90637. void *client_data
  90638. );
  90639. /** Initialize the decoder instance to decode Ogg FLAC files.
  90640. *
  90641. * This flavor of initialization sets up the decoder to decode from a
  90642. * plain Ogg FLAC file. For non-stdio streams, you must use
  90643. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90644. *
  90645. * This function should be called after FLAC__stream_decoder_new() and
  90646. * FLAC__stream_decoder_set_*() but before any of the
  90647. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90648. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90649. * if initialization succeeded.
  90650. *
  90651. * \note Support for Ogg FLAC in the library is optional. If this
  90652. * library has been built without support for Ogg FLAC, this function
  90653. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90654. *
  90655. * \param decoder An uninitialized decoder instance.
  90656. * \param file An open FLAC file. The file should have been
  90657. * opened with mode \c "rb" and rewound. The file
  90658. * becomes owned by the decoder and should not be
  90659. * manipulated by the client while decoding.
  90660. * Unless \a file is \c stdin, it will be closed
  90661. * when FLAC__stream_decoder_finish() is called.
  90662. * Note however that seeking will not work when
  90663. * decoding from \c stdout since it is not seekable.
  90664. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90665. * pointer must not be \c NULL.
  90666. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90667. * pointer may be \c NULL if the callback is not
  90668. * desired.
  90669. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90670. * pointer must not be \c NULL.
  90671. * \param client_data This value will be supplied to callbacks in their
  90672. * \a client_data argument.
  90673. * \assert
  90674. * \code decoder != NULL \endcode
  90675. * \code file != NULL \endcode
  90676. * \retval FLAC__StreamDecoderInitStatus
  90677. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90678. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90679. */
  90680. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90681. FLAC__StreamDecoder *decoder,
  90682. FILE *file,
  90683. FLAC__StreamDecoderWriteCallback write_callback,
  90684. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90685. FLAC__StreamDecoderErrorCallback error_callback,
  90686. void *client_data
  90687. );
  90688. /** Initialize the decoder instance to decode native FLAC files.
  90689. *
  90690. * This flavor of initialization sets up the decoder to decode from a plain
  90691. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90692. * example, with Unicode filenames on Windows), you must use
  90693. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90694. * and provide callbacks for the I/O.
  90695. *
  90696. * This function should be called after FLAC__stream_decoder_new() and
  90697. * FLAC__stream_decoder_set_*() but before any of the
  90698. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90699. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90700. * if initialization succeeded.
  90701. *
  90702. * \param decoder An uninitialized decoder instance.
  90703. * \param filename The name of the file to decode from. The file will
  90704. * be opened with fopen(). Use \c NULL to decode from
  90705. * \c stdin. Note that \c stdin is not seekable.
  90706. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90707. * pointer must not be \c NULL.
  90708. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90709. * pointer may be \c NULL if the callback is not
  90710. * desired.
  90711. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90712. * pointer must not be \c NULL.
  90713. * \param client_data This value will be supplied to callbacks in their
  90714. * \a client_data argument.
  90715. * \assert
  90716. * \code decoder != NULL \endcode
  90717. * \retval FLAC__StreamDecoderInitStatus
  90718. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90719. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90720. */
  90721. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90722. FLAC__StreamDecoder *decoder,
  90723. const char *filename,
  90724. FLAC__StreamDecoderWriteCallback write_callback,
  90725. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90726. FLAC__StreamDecoderErrorCallback error_callback,
  90727. void *client_data
  90728. );
  90729. /** Initialize the decoder instance to decode Ogg FLAC files.
  90730. *
  90731. * This flavor of initialization sets up the decoder to decode from a plain
  90732. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90733. * example, with Unicode filenames on Windows), you must use
  90734. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90735. * and provide callbacks for the I/O.
  90736. *
  90737. * This function should be called after FLAC__stream_decoder_new() and
  90738. * FLAC__stream_decoder_set_*() but before any of the
  90739. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90740. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90741. * if initialization succeeded.
  90742. *
  90743. * \note Support for Ogg FLAC in the library is optional. If this
  90744. * library has been built without support for Ogg FLAC, this function
  90745. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90746. *
  90747. * \param decoder An uninitialized decoder instance.
  90748. * \param filename The name of the file to decode from. The file will
  90749. * be opened with fopen(). Use \c NULL to decode from
  90750. * \c stdin. Note that \c stdin is not seekable.
  90751. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90752. * pointer must not be \c NULL.
  90753. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90754. * pointer may be \c NULL if the callback is not
  90755. * desired.
  90756. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90757. * pointer must not be \c NULL.
  90758. * \param client_data This value will be supplied to callbacks in their
  90759. * \a client_data argument.
  90760. * \assert
  90761. * \code decoder != NULL \endcode
  90762. * \retval FLAC__StreamDecoderInitStatus
  90763. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90764. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90765. */
  90766. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90767. FLAC__StreamDecoder *decoder,
  90768. const char *filename,
  90769. FLAC__StreamDecoderWriteCallback write_callback,
  90770. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90771. FLAC__StreamDecoderErrorCallback error_callback,
  90772. void *client_data
  90773. );
  90774. /** Finish the decoding process.
  90775. * Flushes the decoding buffer, releases resources, resets the decoder
  90776. * settings to their defaults, and returns the decoder state to
  90777. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90778. *
  90779. * In the event of a prematurely-terminated decode, it is not strictly
  90780. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90781. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90782. * with a FLAC__stream_decoder_finish().
  90783. *
  90784. * \param decoder An uninitialized decoder instance.
  90785. * \assert
  90786. * \code decoder != NULL \endcode
  90787. * \retval FLAC__bool
  90788. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90789. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90790. * signature does not match the one computed by the decoder; else
  90791. * \c true.
  90792. */
  90793. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90794. /** Flush the stream input.
  90795. * The decoder's input buffer will be cleared and the state set to
  90796. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90797. * off MD5 checking.
  90798. *
  90799. * \param decoder A decoder instance.
  90800. * \assert
  90801. * \code decoder != NULL \endcode
  90802. * \retval FLAC__bool
  90803. * \c true if successful, else \c false if a memory allocation
  90804. * error occurs (in which case the state will be set to
  90805. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90806. */
  90807. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90808. /** Reset the decoding process.
  90809. * The decoder's input buffer will be cleared and the state set to
  90810. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90811. * FLAC__stream_decoder_finish() except that the settings are
  90812. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90813. * before decoding again. MD5 checking will be restored to its original
  90814. * setting.
  90815. *
  90816. * If the decoder is seekable, or was initialized with
  90817. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90818. * the decoder will also attempt to seek to the beginning of the file.
  90819. * If this rewind fails, this function will return \c false. It follows
  90820. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90821. * \c stdin.
  90822. *
  90823. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90824. * and is not seekable (i.e. no seek callback was provided or the seek
  90825. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90826. * is the duty of the client to start feeding data from the beginning of
  90827. * the stream on the next FLAC__stream_decoder_process() or
  90828. * FLAC__stream_decoder_process_interleaved() call.
  90829. *
  90830. * \param decoder A decoder instance.
  90831. * \assert
  90832. * \code decoder != NULL \endcode
  90833. * \retval FLAC__bool
  90834. * \c true if successful, else \c false if a memory allocation occurs
  90835. * (in which case the state will be set to
  90836. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90837. * occurs (the state will be unchanged).
  90838. */
  90839. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90840. /** Decode one metadata block or audio frame.
  90841. * This version instructs the decoder to decode a either a single metadata
  90842. * block or a single frame and stop, unless the callbacks return a fatal
  90843. * error or the read callback returns
  90844. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90845. *
  90846. * As the decoder needs more input it will call the read callback.
  90847. * Depending on what was decoded, the metadata or write callback will be
  90848. * called with the decoded metadata block or audio frame.
  90849. *
  90850. * Unless there is a fatal read error or end of stream, this function
  90851. * will return once one whole frame is decoded. In other words, if the
  90852. * stream is not synchronized or points to a corrupt frame header, the
  90853. * decoder will continue to try and resync until it gets to a valid
  90854. * frame, then decode one frame, then return. If the decoder points to
  90855. * a frame whose frame CRC in the frame footer does not match the
  90856. * computed frame CRC, this function will issue a
  90857. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90858. * error callback, and return, having decoded one complete, although
  90859. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90860. * correct length to the write callback.)
  90861. *
  90862. * \param decoder An initialized decoder instance.
  90863. * \assert
  90864. * \code decoder != NULL \endcode
  90865. * \retval FLAC__bool
  90866. * \c false if any fatal read, write, or memory allocation error
  90867. * occurred (meaning decoding must stop), else \c true; for more
  90868. * information about the decoder, check the decoder state with
  90869. * FLAC__stream_decoder_get_state().
  90870. */
  90871. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90872. /** Decode until the end of the metadata.
  90873. * This version instructs the decoder to decode from the current position
  90874. * and continue until all the metadata has been read, or until the
  90875. * callbacks return a fatal error or the read callback returns
  90876. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90877. *
  90878. * As the decoder needs more input it will call the read callback.
  90879. * As each metadata block is decoded, the metadata callback will be called
  90880. * with the decoded metadata.
  90881. *
  90882. * \param decoder An initialized decoder instance.
  90883. * \assert
  90884. * \code decoder != NULL \endcode
  90885. * \retval FLAC__bool
  90886. * \c false if any fatal read, write, or memory allocation error
  90887. * occurred (meaning decoding must stop), else \c true; for more
  90888. * information about the decoder, check the decoder state with
  90889. * FLAC__stream_decoder_get_state().
  90890. */
  90891. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90892. /** Decode until the end of the stream.
  90893. * This version instructs the decoder to decode from the current position
  90894. * and continue until the end of stream (the read callback returns
  90895. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90896. * callbacks return a fatal error.
  90897. *
  90898. * As the decoder needs more input it will call the read callback.
  90899. * As each metadata block and frame is decoded, the metadata or write
  90900. * callback will be called with the decoded metadata or frame.
  90901. *
  90902. * \param decoder An initialized decoder instance.
  90903. * \assert
  90904. * \code decoder != NULL \endcode
  90905. * \retval FLAC__bool
  90906. * \c false if any fatal read, write, or memory allocation error
  90907. * occurred (meaning decoding must stop), else \c true; for more
  90908. * information about the decoder, check the decoder state with
  90909. * FLAC__stream_decoder_get_state().
  90910. */
  90911. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90912. /** Skip one audio frame.
  90913. * This version instructs the decoder to 'skip' a single frame and stop,
  90914. * unless the callbacks return a fatal error or the read callback returns
  90915. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90916. *
  90917. * The decoding flow is the same as what occurs when
  90918. * FLAC__stream_decoder_process_single() is called to process an audio
  90919. * frame, except that this function does not decode the parsed data into
  90920. * PCM or call the write callback. The integrity of the frame is still
  90921. * checked the same way as in the other process functions.
  90922. *
  90923. * This function will return once one whole frame is skipped, in the
  90924. * same way that FLAC__stream_decoder_process_single() will return once
  90925. * one whole frame is decoded.
  90926. *
  90927. * This function can be used in more quickly determining FLAC frame
  90928. * boundaries when decoding of the actual data is not needed, for
  90929. * example when an application is separating a FLAC stream into frames
  90930. * for editing or storing in a container. To do this, the application
  90931. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90932. * to the next frame, then use
  90933. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90934. * boundary.
  90935. *
  90936. * This function should only be called when the stream has advanced
  90937. * past all the metadata, otherwise it will return \c false.
  90938. *
  90939. * \param decoder An initialized decoder instance not in a metadata
  90940. * state.
  90941. * \assert
  90942. * \code decoder != NULL \endcode
  90943. * \retval FLAC__bool
  90944. * \c false if any fatal read, write, or memory allocation error
  90945. * occurred (meaning decoding must stop), or if the decoder
  90946. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90947. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90948. * information about the decoder, check the decoder state with
  90949. * FLAC__stream_decoder_get_state().
  90950. */
  90951. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90952. /** Flush the input and seek to an absolute sample.
  90953. * Decoding will resume at the given sample. Note that because of
  90954. * this, the next write callback may contain a partial block. The
  90955. * client must support seeking the input or this function will fail
  90956. * and return \c false. Furthermore, if the decoder state is
  90957. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90958. * with FLAC__stream_decoder_flush() or reset with
  90959. * FLAC__stream_decoder_reset() before decoding can continue.
  90960. *
  90961. * \param decoder A decoder instance.
  90962. * \param sample The target sample number to seek to.
  90963. * \assert
  90964. * \code decoder != NULL \endcode
  90965. * \retval FLAC__bool
  90966. * \c true if successful, else \c false.
  90967. */
  90968. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90969. /* \} */
  90970. #ifdef __cplusplus
  90971. }
  90972. #endif
  90973. #endif
  90974. /*** End of inlined file: stream_decoder.h ***/
  90975. /*** Start of inlined file: stream_encoder.h ***/
  90976. #ifndef FLAC__STREAM_ENCODER_H
  90977. #define FLAC__STREAM_ENCODER_H
  90978. #include <stdio.h> /* for FILE */
  90979. #ifdef __cplusplus
  90980. extern "C" {
  90981. #endif
  90982. /** \file include/FLAC/stream_encoder.h
  90983. *
  90984. * \brief
  90985. * This module contains the functions which implement the stream
  90986. * encoder.
  90987. *
  90988. * See the detailed documentation in the
  90989. * \link flac_stream_encoder stream encoder \endlink module.
  90990. */
  90991. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90992. * \ingroup flac
  90993. *
  90994. * \brief
  90995. * This module describes the encoder layers provided by libFLAC.
  90996. *
  90997. * The stream encoder can be used to encode complete streams either to the
  90998. * client via callbacks, or directly to a file, depending on how it is
  90999. * initialized. When encoding via callbacks, the client provides a write
  91000. * callback which will be called whenever FLAC data is ready to be written.
  91001. * If the client also supplies a seek callback, the encoder will also
  91002. * automatically handle the writing back of metadata discovered while
  91003. * encoding, like stream info, seek points offsets, etc. When encoding to
  91004. * a file, the client needs only supply a filename or open \c FILE* and an
  91005. * optional progress callback for periodic notification of progress; the
  91006. * write and seek callbacks are supplied internally. For more info see the
  91007. * \link flac_stream_encoder stream encoder \endlink module.
  91008. */
  91009. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  91010. * \ingroup flac_encoder
  91011. *
  91012. * \brief
  91013. * This module contains the functions which implement the stream
  91014. * encoder.
  91015. *
  91016. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  91017. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  91018. *
  91019. * The basic usage of this encoder is as follows:
  91020. * - The program creates an instance of an encoder using
  91021. * FLAC__stream_encoder_new().
  91022. * - The program overrides the default settings using
  91023. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  91024. * functions should be called:
  91025. * - FLAC__stream_encoder_set_channels()
  91026. * - FLAC__stream_encoder_set_bits_per_sample()
  91027. * - FLAC__stream_encoder_set_sample_rate()
  91028. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  91029. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  91030. * - If the application wants to control the compression level or set its own
  91031. * metadata, then the following should also be called:
  91032. * - FLAC__stream_encoder_set_compression_level()
  91033. * - FLAC__stream_encoder_set_verify()
  91034. * - FLAC__stream_encoder_set_metadata()
  91035. * - The rest of the set functions should only be called if the client needs
  91036. * exact control over how the audio is compressed; thorough understanding
  91037. * of the FLAC format is necessary to achieve good results.
  91038. * - The program initializes the instance to validate the settings and
  91039. * prepare for encoding using
  91040. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  91041. * or FLAC__stream_encoder_init_file() for native FLAC
  91042. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  91043. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  91044. * - The program calls FLAC__stream_encoder_process() or
  91045. * FLAC__stream_encoder_process_interleaved() to encode data, which
  91046. * subsequently calls the callbacks when there is encoder data ready
  91047. * to be written.
  91048. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  91049. * which causes the encoder to encode any data still in its input pipe,
  91050. * update the metadata with the final encoding statistics if output
  91051. * seeking is possible, and finally reset the encoder to the
  91052. * uninitialized state.
  91053. * - The instance may be used again or deleted with
  91054. * FLAC__stream_encoder_delete().
  91055. *
  91056. * In more detail, the stream encoder functions similarly to the
  91057. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  91058. * callbacks and more options. Typically the client will create a new
  91059. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  91060. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  91061. * calling one of the FLAC__stream_encoder_init_*() functions.
  91062. *
  91063. * Unlike the decoders, the stream encoder has many options that can
  91064. * affect the speed and compression ratio. When setting these parameters
  91065. * you should have some basic knowledge of the format (see the
  91066. * <A HREF="../documentation.html#format">user-level documentation</A>
  91067. * or the <A HREF="../format.html">formal description</A>). The
  91068. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  91069. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  91070. * functions will do this, so make sure to pay attention to the state
  91071. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  91072. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  91073. * before FLAC__stream_encoder_init_*() will take on the defaults from
  91074. * the constructor.
  91075. *
  91076. * There are three initialization functions for native FLAC, one for
  91077. * setting up the encoder to encode FLAC data to the client via
  91078. * callbacks, and two for encoding directly to a file.
  91079. *
  91080. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  91081. * You must also supply a write callback which will be called anytime
  91082. * there is raw encoded data to write. If the client can seek the output
  91083. * it is best to also supply seek and tell callbacks, as this allows the
  91084. * encoder to go back after encoding is finished to write back
  91085. * information that was collected while encoding, like seek point offsets,
  91086. * frame sizes, etc.
  91087. *
  91088. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  91089. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  91090. * filename or open \c FILE*; the encoder will handle all the callbacks
  91091. * internally. You may also supply a progress callback for periodic
  91092. * notification of the encoding progress.
  91093. *
  91094. * There are three similarly-named init functions for encoding to Ogg
  91095. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  91096. * library has been built with Ogg support.
  91097. *
  91098. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  91099. * call the write callback several times, once with the \c fLaC signature,
  91100. * and once for each encoded metadata block. Note that for Ogg FLAC
  91101. * encoding you will usually get at least twice the number of callbacks than
  91102. * with native FLAC, one for the Ogg page header and one for the page body.
  91103. *
  91104. * After initializing the instance, the client may feed audio data to the
  91105. * encoder in one of two ways:
  91106. *
  91107. * - Channel separate, through FLAC__stream_encoder_process() - The client
  91108. * will pass an array of pointers to buffers, one for each channel, to
  91109. * the encoder, each of the same length. The samples need not be
  91110. * block-aligned, but each channel should have the same number of samples.
  91111. * - Channel interleaved, through
  91112. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  91113. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  91114. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91115. * Again, the samples need not be block-aligned but they must be
  91116. * sample-aligned, i.e. the first value should be channel0_sample0 and
  91117. * the last value channelN_sampleM.
  91118. *
  91119. * Note that for either process call, each sample in the buffers should be a
  91120. * signed integer, right-justified to the resolution set by
  91121. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  91122. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  91123. *
  91124. * When the client is finished encoding data, it calls
  91125. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  91126. * data still in its input pipe, and call the metadata callback with the
  91127. * final encoding statistics. Then the instance may be deleted with
  91128. * FLAC__stream_encoder_delete() or initialized again to encode another
  91129. * stream.
  91130. *
  91131. * For programs that write their own metadata, but that do not know the
  91132. * actual metadata until after encoding, it is advantageous to instruct
  91133. * the encoder to write a PADDING block of the correct size, so that
  91134. * instead of rewriting the whole stream after encoding, the program can
  91135. * just overwrite the PADDING block. If only the maximum size of the
  91136. * metadata is known, the program can write a slightly larger padding
  91137. * block, then split it after encoding.
  91138. *
  91139. * Make sure you understand how lengths are calculated. All FLAC metadata
  91140. * blocks have a 4 byte header which contains the type and length. This
  91141. * length does not include the 4 bytes of the header. See the format page
  91142. * for the specification of metadata blocks and their lengths.
  91143. *
  91144. * \note
  91145. * If you are writing the FLAC data to a file via callbacks, make sure it
  91146. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91147. * after the first encoding pass, the encoder will try to seek back to the
  91148. * beginning of the stream, to the STREAMINFO block, to write some data
  91149. * there. (If using FLAC__stream_encoder_init*_file() or
  91150. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91151. *
  91152. * \note
  91153. * The "set" functions may only be called when the encoder is in the
  91154. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91155. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91156. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91157. * return \c true, otherwise \c false.
  91158. *
  91159. * \note
  91160. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91161. * defaults.
  91162. *
  91163. * \{
  91164. */
  91165. /** State values for a FLAC__StreamEncoder.
  91166. *
  91167. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91168. *
  91169. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91170. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91171. * must be deleted with FLAC__stream_encoder_delete().
  91172. */
  91173. typedef enum {
  91174. FLAC__STREAM_ENCODER_OK = 0,
  91175. /**< The encoder is in the normal OK state and samples can be processed. */
  91176. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91177. /**< The encoder is in the uninitialized state; one of the
  91178. * FLAC__stream_encoder_init_*() functions must be called before samples
  91179. * can be processed.
  91180. */
  91181. FLAC__STREAM_ENCODER_OGG_ERROR,
  91182. /**< An error occurred in the underlying Ogg layer. */
  91183. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91184. /**< An error occurred in the underlying verify stream decoder;
  91185. * check FLAC__stream_encoder_get_verify_decoder_state().
  91186. */
  91187. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91188. /**< The verify decoder detected a mismatch between the original
  91189. * audio signal and the decoded audio signal.
  91190. */
  91191. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91192. /**< One of the callbacks returned a fatal error. */
  91193. FLAC__STREAM_ENCODER_IO_ERROR,
  91194. /**< An I/O error occurred while opening/reading/writing a file.
  91195. * Check \c errno.
  91196. */
  91197. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91198. /**< An error occurred while writing the stream; usually, the
  91199. * write_callback returned an error.
  91200. */
  91201. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91202. /**< Memory allocation failed. */
  91203. } FLAC__StreamEncoderState;
  91204. /** Maps a FLAC__StreamEncoderState to a C string.
  91205. *
  91206. * Using a FLAC__StreamEncoderState as the index to this array
  91207. * will give the string equivalent. The contents should not be modified.
  91208. */
  91209. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91210. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91211. */
  91212. typedef enum {
  91213. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91214. /**< Initialization was successful. */
  91215. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91216. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91217. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91218. /**< The library was not compiled with support for the given container
  91219. * format.
  91220. */
  91221. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91222. /**< A required callback was not supplied. */
  91223. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91224. /**< The encoder has an invalid setting for number of channels. */
  91225. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91226. /**< The encoder has an invalid setting for bits-per-sample.
  91227. * FLAC supports 4-32 bps but the reference encoder currently supports
  91228. * only up to 24 bps.
  91229. */
  91230. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91231. /**< The encoder has an invalid setting for the input sample rate. */
  91232. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91233. /**< The encoder has an invalid setting for the block size. */
  91234. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91235. /**< The encoder has an invalid setting for the maximum LPC order. */
  91236. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91237. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91238. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91239. /**< The specified block size is less than the maximum LPC order. */
  91240. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91241. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91242. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91243. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91244. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91245. * - One of the metadata blocks contains an undefined type
  91246. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91247. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91248. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91249. */
  91250. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91251. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91252. * already initialized, usually because
  91253. * FLAC__stream_encoder_finish() was not called.
  91254. */
  91255. } FLAC__StreamEncoderInitStatus;
  91256. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91257. *
  91258. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91259. * will give the string equivalent. The contents should not be modified.
  91260. */
  91261. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91262. /** Return values for the FLAC__StreamEncoder read callback.
  91263. */
  91264. typedef enum {
  91265. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91266. /**< The read was OK and decoding can continue. */
  91267. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91268. /**< The read was attempted at the end of the stream. */
  91269. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91270. /**< An unrecoverable error occurred. */
  91271. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91272. /**< Client does not support reading back from the output. */
  91273. } FLAC__StreamEncoderReadStatus;
  91274. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91275. *
  91276. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91277. * will give the string equivalent. The contents should not be modified.
  91278. */
  91279. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91280. /** Return values for the FLAC__StreamEncoder write callback.
  91281. */
  91282. typedef enum {
  91283. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91284. /**< The write was OK and encoding can continue. */
  91285. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91286. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91287. } FLAC__StreamEncoderWriteStatus;
  91288. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91289. *
  91290. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91291. * will give the string equivalent. The contents should not be modified.
  91292. */
  91293. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91294. /** Return values for the FLAC__StreamEncoder seek callback.
  91295. */
  91296. typedef enum {
  91297. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91298. /**< The seek was OK and encoding can continue. */
  91299. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91300. /**< An unrecoverable error occurred. */
  91301. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91302. /**< Client does not support seeking. */
  91303. } FLAC__StreamEncoderSeekStatus;
  91304. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91305. *
  91306. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91307. * will give the string equivalent. The contents should not be modified.
  91308. */
  91309. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91310. /** Return values for the FLAC__StreamEncoder tell callback.
  91311. */
  91312. typedef enum {
  91313. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91314. /**< The tell was OK and encoding can continue. */
  91315. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91316. /**< An unrecoverable error occurred. */
  91317. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91318. /**< Client does not support seeking. */
  91319. } FLAC__StreamEncoderTellStatus;
  91320. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91321. *
  91322. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91323. * will give the string equivalent. The contents should not be modified.
  91324. */
  91325. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91326. /***********************************************************************
  91327. *
  91328. * class FLAC__StreamEncoder
  91329. *
  91330. ***********************************************************************/
  91331. struct FLAC__StreamEncoderProtected;
  91332. struct FLAC__StreamEncoderPrivate;
  91333. /** The opaque structure definition for the stream encoder type.
  91334. * See the \link flac_stream_encoder stream encoder module \endlink
  91335. * for a detailed description.
  91336. */
  91337. typedef struct {
  91338. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91339. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91340. } FLAC__StreamEncoder;
  91341. /** Signature for the read callback.
  91342. *
  91343. * A function pointer matching this signature must be passed to
  91344. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91345. * The supplied function will be called when the encoder needs to read back
  91346. * encoded data. This happens during the metadata callback, when the encoder
  91347. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91348. * while encoding. The address of the buffer to be filled is supplied, along
  91349. * with the number of bytes the buffer can hold. The callback may choose to
  91350. * supply less data and modify the byte count but must be careful not to
  91351. * overflow the buffer. The callback then returns a status code chosen from
  91352. * FLAC__StreamEncoderReadStatus.
  91353. *
  91354. * Here is an example of a read callback for stdio streams:
  91355. * \code
  91356. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91357. * {
  91358. * FILE *file = ((MyClientData*)client_data)->file;
  91359. * if(*bytes > 0) {
  91360. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91361. * if(ferror(file))
  91362. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91363. * else if(*bytes == 0)
  91364. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91365. * else
  91366. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91367. * }
  91368. * else
  91369. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91370. * }
  91371. * \endcode
  91372. *
  91373. * \note In general, FLAC__StreamEncoder functions which change the
  91374. * state should not be called on the \a encoder while in the callback.
  91375. *
  91376. * \param encoder The encoder instance calling the callback.
  91377. * \param buffer A pointer to a location for the callee to store
  91378. * data to be encoded.
  91379. * \param bytes A pointer to the size of the buffer. On entry
  91380. * to the callback, it contains the maximum number
  91381. * of bytes that may be stored in \a buffer. The
  91382. * callee must set it to the actual number of bytes
  91383. * stored (0 in case of error or end-of-stream) before
  91384. * returning.
  91385. * \param client_data The callee's client data set through
  91386. * FLAC__stream_encoder_set_client_data().
  91387. * \retval FLAC__StreamEncoderReadStatus
  91388. * The callee's return status.
  91389. */
  91390. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91391. /** Signature for the write callback.
  91392. *
  91393. * A function pointer matching this signature must be passed to
  91394. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91395. * by the encoder anytime there is raw encoded data ready to write. It may
  91396. * include metadata mixed with encoded audio frames and the data is not
  91397. * guaranteed to be aligned on frame or metadata block boundaries.
  91398. *
  91399. * The only duty of the callback is to write out the \a bytes worth of data
  91400. * in \a buffer to the current position in the output stream. The arguments
  91401. * \a samples and \a current_frame are purely informational. If \a samples
  91402. * is greater than \c 0, then \a current_frame will hold the current frame
  91403. * number that is being written; otherwise it indicates that the write
  91404. * callback is being called to write metadata.
  91405. *
  91406. * \note
  91407. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91408. * write callback will be called twice when writing each audio
  91409. * frame; once for the page header, and once for the page body.
  91410. * When writing the page header, the \a samples argument to the
  91411. * write callback will be \c 0.
  91412. *
  91413. * \note In general, FLAC__StreamEncoder functions which change the
  91414. * state should not be called on the \a encoder while in the callback.
  91415. *
  91416. * \param encoder The encoder instance calling the callback.
  91417. * \param buffer An array of encoded data of length \a bytes.
  91418. * \param bytes The byte length of \a buffer.
  91419. * \param samples The number of samples encoded by \a buffer.
  91420. * \c 0 has a special meaning; see above.
  91421. * \param current_frame The number of the current frame being encoded.
  91422. * \param client_data The callee's client data set through
  91423. * FLAC__stream_encoder_init_*().
  91424. * \retval FLAC__StreamEncoderWriteStatus
  91425. * The callee's return status.
  91426. */
  91427. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91428. /** Signature for the seek callback.
  91429. *
  91430. * A function pointer matching this signature may be passed to
  91431. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91432. * when the encoder needs to seek the output stream. The encoder will pass
  91433. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91434. *
  91435. * Here is an example of a seek callback for stdio streams:
  91436. * \code
  91437. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91438. * {
  91439. * FILE *file = ((MyClientData*)client_data)->file;
  91440. * if(file == stdin)
  91441. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91442. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91443. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91444. * else
  91445. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91446. * }
  91447. * \endcode
  91448. *
  91449. * \note In general, FLAC__StreamEncoder functions which change the
  91450. * state should not be called on the \a encoder while in the callback.
  91451. *
  91452. * \param encoder The encoder instance calling the callback.
  91453. * \param absolute_byte_offset The offset from the beginning of the stream
  91454. * to seek to.
  91455. * \param client_data The callee's client data set through
  91456. * FLAC__stream_encoder_init_*().
  91457. * \retval FLAC__StreamEncoderSeekStatus
  91458. * The callee's return status.
  91459. */
  91460. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91461. /** Signature for the tell callback.
  91462. *
  91463. * A function pointer matching this signature may be passed to
  91464. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91465. * when the encoder needs to know the current position of the output stream.
  91466. *
  91467. * \warning
  91468. * The callback must return the true current byte offset of the output to
  91469. * which the encoder is writing. If you are buffering the output, make
  91470. * sure and take this into account. If you are writing directly to a
  91471. * FILE* from your write callback, ftell() is sufficient. If you are
  91472. * writing directly to a file descriptor from your write callback, you
  91473. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91474. * these points to rewrite metadata after encoding.
  91475. *
  91476. * Here is an example of a tell callback for stdio streams:
  91477. * \code
  91478. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91479. * {
  91480. * FILE *file = ((MyClientData*)client_data)->file;
  91481. * off_t pos;
  91482. * if(file == stdin)
  91483. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91484. * else if((pos = ftello(file)) < 0)
  91485. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91486. * else {
  91487. * *absolute_byte_offset = (FLAC__uint64)pos;
  91488. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91489. * }
  91490. * }
  91491. * \endcode
  91492. *
  91493. * \note In general, FLAC__StreamEncoder functions which change the
  91494. * state should not be called on the \a encoder while in the callback.
  91495. *
  91496. * \param encoder The encoder instance calling the callback.
  91497. * \param absolute_byte_offset The address at which to store the current
  91498. * position of the output.
  91499. * \param client_data The callee's client data set through
  91500. * FLAC__stream_encoder_init_*().
  91501. * \retval FLAC__StreamEncoderTellStatus
  91502. * The callee's return status.
  91503. */
  91504. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91505. /** Signature for the metadata callback.
  91506. *
  91507. * A function pointer matching this signature may be passed to
  91508. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91509. * once at the end of encoding with the populated STREAMINFO structure. This
  91510. * is so the client can seek back to the beginning of the file and write the
  91511. * STREAMINFO block with the correct statistics after encoding (like
  91512. * minimum/maximum frame size and total samples).
  91513. *
  91514. * \note In general, FLAC__StreamEncoder functions which change the
  91515. * state should not be called on the \a encoder while in the callback.
  91516. *
  91517. * \param encoder The encoder instance calling the callback.
  91518. * \param metadata The final populated STREAMINFO block.
  91519. * \param client_data The callee's client data set through
  91520. * FLAC__stream_encoder_init_*().
  91521. */
  91522. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91523. /** Signature for the progress callback.
  91524. *
  91525. * A function pointer matching this signature may be passed to
  91526. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91527. * The supplied function will be called when the encoder has finished
  91528. * writing a frame. The \c total_frames_estimate argument to the
  91529. * callback will be based on the value from
  91530. * FLAC__stream_encoder_set_total_samples_estimate().
  91531. *
  91532. * \note In general, FLAC__StreamEncoder functions which change the
  91533. * state should not be called on the \a encoder while in the callback.
  91534. *
  91535. * \param encoder The encoder instance calling the callback.
  91536. * \param bytes_written Bytes written so far.
  91537. * \param samples_written Samples written so far.
  91538. * \param frames_written Frames written so far.
  91539. * \param total_frames_estimate The estimate of the total number of
  91540. * frames to be written.
  91541. * \param client_data The callee's client data set through
  91542. * FLAC__stream_encoder_init_*().
  91543. */
  91544. 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);
  91545. /***********************************************************************
  91546. *
  91547. * Class constructor/destructor
  91548. *
  91549. ***********************************************************************/
  91550. /** Create a new stream encoder instance. The instance is created with
  91551. * default settings; see the individual FLAC__stream_encoder_set_*()
  91552. * functions for each setting's default.
  91553. *
  91554. * \retval FLAC__StreamEncoder*
  91555. * \c NULL if there was an error allocating memory, else the new instance.
  91556. */
  91557. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91558. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91559. *
  91560. * \param encoder A pointer to an existing encoder.
  91561. * \assert
  91562. * \code encoder != NULL \endcode
  91563. */
  91564. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91565. /***********************************************************************
  91566. *
  91567. * Public class method prototypes
  91568. *
  91569. ***********************************************************************/
  91570. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91571. *
  91572. * \note
  91573. * This does not need to be set for native FLAC encoding.
  91574. *
  91575. * \note
  91576. * It is recommended to set a serial number explicitly as the default of '0'
  91577. * may collide with other streams.
  91578. *
  91579. * \default \c 0
  91580. * \param encoder An encoder instance to set.
  91581. * \param serial_number See above.
  91582. * \assert
  91583. * \code encoder != NULL \endcode
  91584. * \retval FLAC__bool
  91585. * \c false if the encoder is already initialized, else \c true.
  91586. */
  91587. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91588. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91589. * encoded output by feeding it through an internal decoder and comparing
  91590. * the original signal against the decoded signal. If a mismatch occurs,
  91591. * the process call will return \c false. Note that this will slow the
  91592. * encoding process by the extra time required for decoding and comparison.
  91593. *
  91594. * \default \c false
  91595. * \param encoder An encoder instance to set.
  91596. * \param value Flag value (see above).
  91597. * \assert
  91598. * \code encoder != NULL \endcode
  91599. * \retval FLAC__bool
  91600. * \c false if the encoder is already initialized, else \c true.
  91601. */
  91602. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91603. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91604. * the encoder will comply with the Subset and will check the
  91605. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91606. * comply. If \c false, the settings may take advantage of the full
  91607. * range that the format allows.
  91608. *
  91609. * Make sure you know what it entails before setting this to \c false.
  91610. *
  91611. * \default \c true
  91612. * \param encoder An encoder instance to set.
  91613. * \param value Flag value (see above).
  91614. * \assert
  91615. * \code encoder != NULL \endcode
  91616. * \retval FLAC__bool
  91617. * \c false if the encoder is already initialized, else \c true.
  91618. */
  91619. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91620. /** Set the number of channels to be encoded.
  91621. *
  91622. * \default \c 2
  91623. * \param encoder An encoder instance to set.
  91624. * \param value See above.
  91625. * \assert
  91626. * \code encoder != NULL \endcode
  91627. * \retval FLAC__bool
  91628. * \c false if the encoder is already initialized, else \c true.
  91629. */
  91630. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91631. /** Set the sample resolution of the input to be encoded.
  91632. *
  91633. * \warning
  91634. * Do not feed the encoder data that is wider than the value you
  91635. * set here or you will generate an invalid stream.
  91636. *
  91637. * \default \c 16
  91638. * \param encoder An encoder instance to set.
  91639. * \param value See above.
  91640. * \assert
  91641. * \code encoder != NULL \endcode
  91642. * \retval FLAC__bool
  91643. * \c false if the encoder is already initialized, else \c true.
  91644. */
  91645. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91646. /** Set the sample rate (in Hz) of the input to be encoded.
  91647. *
  91648. * \default \c 44100
  91649. * \param encoder An encoder instance to set.
  91650. * \param value See above.
  91651. * \assert
  91652. * \code encoder != NULL \endcode
  91653. * \retval FLAC__bool
  91654. * \c false if the encoder is already initialized, else \c true.
  91655. */
  91656. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91657. /** Set the compression level
  91658. *
  91659. * The compression level is roughly proportional to the amount of effort
  91660. * the encoder expends to compress the file. A higher level usually
  91661. * means more computation but higher compression. The default level is
  91662. * suitable for most applications.
  91663. *
  91664. * Currently the levels range from \c 0 (fastest, least compression) to
  91665. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91666. * treated as \c 8.
  91667. *
  91668. * This function automatically calls the following other \c _set_
  91669. * functions with appropriate values, so the client does not need to
  91670. * unless it specifically wants to override them:
  91671. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91672. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91673. * - FLAC__stream_encoder_set_apodization()
  91674. * - FLAC__stream_encoder_set_max_lpc_order()
  91675. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91676. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91677. * - FLAC__stream_encoder_set_do_escape_coding()
  91678. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91679. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91680. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91681. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91682. *
  91683. * The actual values set for each level are:
  91684. * <table>
  91685. * <tr>
  91686. * <td><b>level</b><td>
  91687. * <td>do mid-side stereo<td>
  91688. * <td>loose mid-side stereo<td>
  91689. * <td>apodization<td>
  91690. * <td>max lpc order<td>
  91691. * <td>qlp coeff precision<td>
  91692. * <td>qlp coeff prec search<td>
  91693. * <td>escape coding<td>
  91694. * <td>exhaustive model search<td>
  91695. * <td>min residual partition order<td>
  91696. * <td>max residual partition order<td>
  91697. * <td>rice parameter search dist<td>
  91698. * </tr>
  91699. * <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>
  91700. * <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>
  91701. * <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>
  91702. * <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>
  91703. * <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>
  91704. * <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>
  91705. * <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>
  91706. * <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>
  91707. * <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>
  91708. * </table>
  91709. *
  91710. * \default \c 5
  91711. * \param encoder An encoder instance to set.
  91712. * \param value See above.
  91713. * \assert
  91714. * \code encoder != NULL \endcode
  91715. * \retval FLAC__bool
  91716. * \c false if the encoder is already initialized, else \c true.
  91717. */
  91718. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91719. /** Set the blocksize to use while encoding.
  91720. *
  91721. * The number of samples to use per frame. Use \c 0 to let the encoder
  91722. * estimate a blocksize; this is usually best.
  91723. *
  91724. * \default \c 0
  91725. * \param encoder An encoder instance to set.
  91726. * \param value See above.
  91727. * \assert
  91728. * \code encoder != NULL \endcode
  91729. * \retval FLAC__bool
  91730. * \c false if the encoder is already initialized, else \c true.
  91731. */
  91732. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91733. /** Set to \c true to enable mid-side encoding on stereo input. The
  91734. * number of channels must be 2 for this to have any effect. Set to
  91735. * \c false to use only independent channel coding.
  91736. *
  91737. * \default \c false
  91738. * \param encoder An encoder instance to set.
  91739. * \param value Flag value (see above).
  91740. * \assert
  91741. * \code encoder != NULL \endcode
  91742. * \retval FLAC__bool
  91743. * \c false if the encoder is already initialized, else \c true.
  91744. */
  91745. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91746. /** Set to \c true to enable adaptive switching between mid-side and
  91747. * left-right encoding on stereo input. Set to \c false to use
  91748. * exhaustive searching. Setting this to \c true requires
  91749. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91750. * \c true in order to have any effect.
  91751. *
  91752. * \default \c false
  91753. * \param encoder An encoder instance to set.
  91754. * \param value Flag value (see above).
  91755. * \assert
  91756. * \code encoder != NULL \endcode
  91757. * \retval FLAC__bool
  91758. * \c false if the encoder is already initialized, else \c true.
  91759. */
  91760. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91761. /** Sets the apodization function(s) the encoder will use when windowing
  91762. * audio data for LPC analysis.
  91763. *
  91764. * The \a specification is a plain ASCII string which specifies exactly
  91765. * which functions to use. There may be more than one (up to 32),
  91766. * separated by \c ';' characters. Some functions take one or more
  91767. * comma-separated arguments in parentheses.
  91768. *
  91769. * The available functions are \c bartlett, \c bartlett_hann,
  91770. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91771. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91772. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91773. *
  91774. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91775. * (0<STDDEV<=0.5).
  91776. *
  91777. * For \c tukey(P), P specifies the fraction of the window that is
  91778. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91779. * corresponds to \c hann.
  91780. *
  91781. * Example specifications are \c "blackman" or
  91782. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91783. *
  91784. * Any function that is specified erroneously is silently dropped. Up
  91785. * to 32 functions are kept, the rest are dropped. If the specification
  91786. * is empty the encoder defaults to \c "tukey(0.5)".
  91787. *
  91788. * When more than one function is specified, then for every subframe the
  91789. * encoder will try each of them separately and choose the window that
  91790. * results in the smallest compressed subframe.
  91791. *
  91792. * Note that each function specified causes the encoder to occupy a
  91793. * floating point array in which to store the window.
  91794. *
  91795. * \default \c "tukey(0.5)"
  91796. * \param encoder An encoder instance to set.
  91797. * \param specification See above.
  91798. * \assert
  91799. * \code encoder != NULL \endcode
  91800. * \code specification != NULL \endcode
  91801. * \retval FLAC__bool
  91802. * \c false if the encoder is already initialized, else \c true.
  91803. */
  91804. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91805. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91806. *
  91807. * \default \c 0
  91808. * \param encoder An encoder instance to set.
  91809. * \param value See above.
  91810. * \assert
  91811. * \code encoder != NULL \endcode
  91812. * \retval FLAC__bool
  91813. * \c false if the encoder is already initialized, else \c true.
  91814. */
  91815. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91816. /** Set the precision, in bits, of the quantized linear predictor
  91817. * coefficients, or \c 0 to let the encoder select it based on the
  91818. * blocksize.
  91819. *
  91820. * \note
  91821. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91822. * be less than 32.
  91823. *
  91824. * \default \c 0
  91825. * \param encoder An encoder instance to set.
  91826. * \param value See above.
  91827. * \assert
  91828. * \code encoder != NULL \endcode
  91829. * \retval FLAC__bool
  91830. * \c false if the encoder is already initialized, else \c true.
  91831. */
  91832. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91833. /** Set to \c false to use only the specified quantized linear predictor
  91834. * coefficient precision, or \c true to search neighboring precision
  91835. * values and use the best one.
  91836. *
  91837. * \default \c false
  91838. * \param encoder An encoder instance to set.
  91839. * \param value See above.
  91840. * \assert
  91841. * \code encoder != NULL \endcode
  91842. * \retval FLAC__bool
  91843. * \c false if the encoder is already initialized, else \c true.
  91844. */
  91845. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91846. /** Deprecated. Setting this value has no effect.
  91847. *
  91848. * \default \c false
  91849. * \param encoder An encoder instance to set.
  91850. * \param value See above.
  91851. * \assert
  91852. * \code encoder != NULL \endcode
  91853. * \retval FLAC__bool
  91854. * \c false if the encoder is already initialized, else \c true.
  91855. */
  91856. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91857. /** Set to \c false to let the encoder estimate the best model order
  91858. * based on the residual signal energy, or \c true to force the
  91859. * encoder to evaluate all order models and select the best.
  91860. *
  91861. * \default \c false
  91862. * \param encoder An encoder instance to set.
  91863. * \param value See above.
  91864. * \assert
  91865. * \code encoder != NULL \endcode
  91866. * \retval FLAC__bool
  91867. * \c false if the encoder is already initialized, else \c true.
  91868. */
  91869. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91870. /** Set the minimum partition order to search when coding the residual.
  91871. * This is used in tandem with
  91872. * FLAC__stream_encoder_set_max_residual_partition_order().
  91873. *
  91874. * The partition order determines the context size in the residual.
  91875. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91876. *
  91877. * Set both min and max values to \c 0 to force a single context,
  91878. * whose Rice parameter is based on the residual signal variance.
  91879. * Otherwise, set a min and max order, and the encoder will search
  91880. * all orders, using the mean of each context for its Rice parameter,
  91881. * and use the best.
  91882. *
  91883. * \default \c 0
  91884. * \param encoder An encoder instance to set.
  91885. * \param value See above.
  91886. * \assert
  91887. * \code encoder != NULL \endcode
  91888. * \retval FLAC__bool
  91889. * \c false if the encoder is already initialized, else \c true.
  91890. */
  91891. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91892. /** Set the maximum partition order to search when coding the residual.
  91893. * This is used in tandem with
  91894. * FLAC__stream_encoder_set_min_residual_partition_order().
  91895. *
  91896. * The partition order determines the context size in the residual.
  91897. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91898. *
  91899. * Set both min and max values to \c 0 to force a single context,
  91900. * whose Rice parameter is based on the residual signal variance.
  91901. * Otherwise, set a min and max order, and the encoder will search
  91902. * all orders, using the mean of each context for its Rice parameter,
  91903. * and use the best.
  91904. *
  91905. * \default \c 0
  91906. * \param encoder An encoder instance to set.
  91907. * \param value See above.
  91908. * \assert
  91909. * \code encoder != NULL \endcode
  91910. * \retval FLAC__bool
  91911. * \c false if the encoder is already initialized, else \c true.
  91912. */
  91913. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91914. /** Deprecated. Setting this value has no effect.
  91915. *
  91916. * \default \c 0
  91917. * \param encoder An encoder instance to set.
  91918. * \param value See above.
  91919. * \assert
  91920. * \code encoder != NULL \endcode
  91921. * \retval FLAC__bool
  91922. * \c false if the encoder is already initialized, else \c true.
  91923. */
  91924. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91925. /** Set an estimate of the total samples that will be encoded.
  91926. * This is merely an estimate and may be set to \c 0 if unknown.
  91927. * This value will be written to the STREAMINFO block before encoding,
  91928. * and can remove the need for the caller to rewrite the value later
  91929. * if the value is known before encoding.
  91930. *
  91931. * \default \c 0
  91932. * \param encoder An encoder instance to set.
  91933. * \param value See above.
  91934. * \assert
  91935. * \code encoder != NULL \endcode
  91936. * \retval FLAC__bool
  91937. * \c false if the encoder is already initialized, else \c true.
  91938. */
  91939. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91940. /** Set the metadata blocks to be emitted to the stream before encoding.
  91941. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91942. * array of pointers to metadata blocks. The array is non-const since
  91943. * the encoder may need to change the \a is_last flag inside them, and
  91944. * in some cases update seek point offsets. Otherwise, the encoder will
  91945. * not modify or free the blocks. It is up to the caller to free the
  91946. * metadata blocks after encoding finishes.
  91947. *
  91948. * \note
  91949. * The encoder stores only copies of the pointers in the \a metadata array;
  91950. * the metadata blocks themselves must survive at least until after
  91951. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91952. *
  91953. * \note
  91954. * The STREAMINFO block is always written and no STREAMINFO block may
  91955. * occur in the supplied array.
  91956. *
  91957. * \note
  91958. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91959. * in the \a metadata array, but the client has specified that it does not
  91960. * support seeking, then the SEEKTABLE will be written verbatim. However
  91961. * by itself this is not very useful as the client will not know the stream
  91962. * offsets for the seekpoints ahead of time. In order to get a proper
  91963. * seektable the client must support seeking. See next note.
  91964. *
  91965. * \note
  91966. * SEEKTABLE blocks are handled specially. Since you will not know
  91967. * the values for the seek point stream offsets, you should pass in
  91968. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91969. * required sample numbers (or placeholder points), with \c 0 for the
  91970. * \a frame_samples and \a stream_offset fields for each point. If the
  91971. * client has specified that it supports seeking by providing a seek
  91972. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91973. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91974. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91975. * then while it is encoding the encoder will fill the stream offsets in
  91976. * for you and when encoding is finished, it will seek back and write the
  91977. * real values into the SEEKTABLE block in the stream. There are helper
  91978. * routines for manipulating seektable template blocks; see metadata.h:
  91979. * FLAC__metadata_object_seektable_template_*(). If the client does
  91980. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91981. * will slow down or remove the ability to seek in the FLAC stream.
  91982. *
  91983. * \note
  91984. * The encoder instance \b will modify the first \c SEEKTABLE block
  91985. * as it transforms the template to a valid seektable while encoding,
  91986. * but it is still up to the caller to free all metadata blocks after
  91987. * encoding.
  91988. *
  91989. * \note
  91990. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91991. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91992. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91993. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91994. * block is present in the \a metadata array, libFLAC will write an
  91995. * empty one, containing only the vendor string.
  91996. *
  91997. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91998. * the second metadata block of the stream. The encoder already supplies
  91999. * the STREAMINFO block automatically. If \a metadata does not contain a
  92000. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  92001. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  92002. * first, the init function will reorder \a metadata by moving the
  92003. * VORBIS_COMMENT block to the front; the relative ordering of the other
  92004. * blocks will remain as they were.
  92005. *
  92006. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  92007. * stream to \c 65535. If \a num_blocks exceeds this the function will
  92008. * return \c false.
  92009. *
  92010. * \default \c NULL, 0
  92011. * \param encoder An encoder instance to set.
  92012. * \param metadata See above.
  92013. * \param num_blocks See above.
  92014. * \assert
  92015. * \code encoder != NULL \endcode
  92016. * \retval FLAC__bool
  92017. * \c false if the encoder is already initialized, else \c true.
  92018. * \c false if the encoder is already initialized, or if
  92019. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  92020. */
  92021. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  92022. /** Get the current encoder state.
  92023. *
  92024. * \param encoder An encoder instance to query.
  92025. * \assert
  92026. * \code encoder != NULL \endcode
  92027. * \retval FLAC__StreamEncoderState
  92028. * The current encoder state.
  92029. */
  92030. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  92031. /** Get the state of the verify stream decoder.
  92032. * Useful when the stream encoder state is
  92033. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  92034. *
  92035. * \param encoder An encoder instance to query.
  92036. * \assert
  92037. * \code encoder != NULL \endcode
  92038. * \retval FLAC__StreamDecoderState
  92039. * The verify stream decoder state.
  92040. */
  92041. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  92042. /** Get the current encoder state as a C string.
  92043. * This version automatically resolves
  92044. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  92045. * verify decoder's state.
  92046. *
  92047. * \param encoder A encoder instance to query.
  92048. * \assert
  92049. * \code encoder != NULL \endcode
  92050. * \retval const char *
  92051. * The encoder state as a C string. Do not modify the contents.
  92052. */
  92053. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  92054. /** Get relevant values about the nature of a verify decoder error.
  92055. * Useful when the stream encoder state is
  92056. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  92057. * be addresses in which the stats will be returned, or NULL if value
  92058. * is not desired.
  92059. *
  92060. * \param encoder An encoder instance to query.
  92061. * \param absolute_sample The absolute sample number of the mismatch.
  92062. * \param frame_number The number of the frame in which the mismatch occurred.
  92063. * \param channel The channel in which the mismatch occurred.
  92064. * \param sample The number of the sample (relative to the frame) in
  92065. * which the mismatch occurred.
  92066. * \param expected The expected value for the sample in question.
  92067. * \param got The actual value returned by the decoder.
  92068. * \assert
  92069. * \code encoder != NULL \endcode
  92070. */
  92071. 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);
  92072. /** Get the "verify" flag.
  92073. *
  92074. * \param encoder An encoder instance to query.
  92075. * \assert
  92076. * \code encoder != NULL \endcode
  92077. * \retval FLAC__bool
  92078. * See FLAC__stream_encoder_set_verify().
  92079. */
  92080. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  92081. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  92082. *
  92083. * \param encoder An encoder instance to query.
  92084. * \assert
  92085. * \code encoder != NULL \endcode
  92086. * \retval FLAC__bool
  92087. * See FLAC__stream_encoder_set_streamable_subset().
  92088. */
  92089. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  92090. /** Get the number of input channels being processed.
  92091. *
  92092. * \param encoder An encoder instance to query.
  92093. * \assert
  92094. * \code encoder != NULL \endcode
  92095. * \retval unsigned
  92096. * See FLAC__stream_encoder_set_channels().
  92097. */
  92098. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  92099. /** Get the input sample resolution setting.
  92100. *
  92101. * \param encoder An encoder instance to query.
  92102. * \assert
  92103. * \code encoder != NULL \endcode
  92104. * \retval unsigned
  92105. * See FLAC__stream_encoder_set_bits_per_sample().
  92106. */
  92107. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  92108. /** Get the input sample rate setting.
  92109. *
  92110. * \param encoder An encoder instance to query.
  92111. * \assert
  92112. * \code encoder != NULL \endcode
  92113. * \retval unsigned
  92114. * See FLAC__stream_encoder_set_sample_rate().
  92115. */
  92116. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  92117. /** Get the blocksize setting.
  92118. *
  92119. * \param encoder An encoder instance to query.
  92120. * \assert
  92121. * \code encoder != NULL \endcode
  92122. * \retval unsigned
  92123. * See FLAC__stream_encoder_set_blocksize().
  92124. */
  92125. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  92126. /** Get the "mid/side stereo coding" flag.
  92127. *
  92128. * \param encoder An encoder instance to query.
  92129. * \assert
  92130. * \code encoder != NULL \endcode
  92131. * \retval FLAC__bool
  92132. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92133. */
  92134. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92135. /** Get the "adaptive mid/side switching" flag.
  92136. *
  92137. * \param encoder An encoder instance to query.
  92138. * \assert
  92139. * \code encoder != NULL \endcode
  92140. * \retval FLAC__bool
  92141. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92142. */
  92143. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92144. /** Get the maximum LPC order setting.
  92145. *
  92146. * \param encoder An encoder instance to query.
  92147. * \assert
  92148. * \code encoder != NULL \endcode
  92149. * \retval unsigned
  92150. * See FLAC__stream_encoder_set_max_lpc_order().
  92151. */
  92152. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92153. /** Get the quantized linear predictor coefficient precision setting.
  92154. *
  92155. * \param encoder An encoder instance to query.
  92156. * \assert
  92157. * \code encoder != NULL \endcode
  92158. * \retval unsigned
  92159. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92160. */
  92161. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92162. /** Get the qlp coefficient precision search flag.
  92163. *
  92164. * \param encoder An encoder instance to query.
  92165. * \assert
  92166. * \code encoder != NULL \endcode
  92167. * \retval FLAC__bool
  92168. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92169. */
  92170. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92171. /** Get the "escape coding" flag.
  92172. *
  92173. * \param encoder An encoder instance to query.
  92174. * \assert
  92175. * \code encoder != NULL \endcode
  92176. * \retval FLAC__bool
  92177. * See FLAC__stream_encoder_set_do_escape_coding().
  92178. */
  92179. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92180. /** Get the exhaustive model search flag.
  92181. *
  92182. * \param encoder An encoder instance to query.
  92183. * \assert
  92184. * \code encoder != NULL \endcode
  92185. * \retval FLAC__bool
  92186. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92187. */
  92188. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92189. /** Get the minimum residual partition order setting.
  92190. *
  92191. * \param encoder An encoder instance to query.
  92192. * \assert
  92193. * \code encoder != NULL \endcode
  92194. * \retval unsigned
  92195. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92196. */
  92197. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92198. /** Get maximum residual partition order setting.
  92199. *
  92200. * \param encoder An encoder instance to query.
  92201. * \assert
  92202. * \code encoder != NULL \endcode
  92203. * \retval unsigned
  92204. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92205. */
  92206. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92207. /** Get the Rice parameter search distance setting.
  92208. *
  92209. * \param encoder An encoder instance to query.
  92210. * \assert
  92211. * \code encoder != NULL \endcode
  92212. * \retval unsigned
  92213. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92214. */
  92215. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92216. /** Get the previously set estimate of the total samples to be encoded.
  92217. * The encoder merely mimics back the value given to
  92218. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92219. * other way of knowing how many samples the client will encode.
  92220. *
  92221. * \param encoder An encoder instance to set.
  92222. * \assert
  92223. * \code encoder != NULL \endcode
  92224. * \retval FLAC__uint64
  92225. * See FLAC__stream_encoder_get_total_samples_estimate().
  92226. */
  92227. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92228. /** Initialize the encoder instance to encode native FLAC streams.
  92229. *
  92230. * This flavor of initialization sets up the encoder to encode to a
  92231. * native FLAC stream. I/O is performed via callbacks to the client.
  92232. * For encoding to a plain file via filename or open \c FILE*,
  92233. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92234. * provide a simpler interface.
  92235. *
  92236. * This function should be called after FLAC__stream_encoder_new() and
  92237. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92238. * or FLAC__stream_encoder_process_interleaved().
  92239. * initialization succeeded.
  92240. *
  92241. * The call to FLAC__stream_encoder_init_stream() currently will also
  92242. * immediately call the write callback several times, once with the \c fLaC
  92243. * signature, and once for each encoded metadata block.
  92244. *
  92245. * \param encoder An uninitialized encoder instance.
  92246. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92247. * pointer must not be \c NULL.
  92248. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92249. * pointer may be \c NULL if seeking is not
  92250. * supported. The encoder uses seeking to go back
  92251. * and write some some stream statistics to the
  92252. * STREAMINFO block; this is recommended but not
  92253. * necessary to create a valid FLAC stream. If
  92254. * \a seek_callback is not \c NULL then a
  92255. * \a tell_callback must also be supplied.
  92256. * Alternatively, a dummy seek callback that just
  92257. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92258. * may also be supplied, all though this is slightly
  92259. * less efficient for the encoder.
  92260. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92261. * pointer may be \c NULL if seeking is not
  92262. * supported. If \a seek_callback is \c NULL then
  92263. * this argument will be ignored. If
  92264. * \a seek_callback is not \c NULL then a
  92265. * \a tell_callback must also be supplied.
  92266. * Alternatively, a dummy tell callback that just
  92267. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92268. * may also be supplied, all though this is slightly
  92269. * less efficient for the encoder.
  92270. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92271. * pointer may be \c NULL if the callback is not
  92272. * desired. If the client provides a seek callback,
  92273. * this function is not necessary as the encoder
  92274. * will automatically seek back and update the
  92275. * STREAMINFO block. It may also be \c NULL if the
  92276. * client does not support seeking, since it will
  92277. * have no way of going back to update the
  92278. * STREAMINFO. However the client can still supply
  92279. * a callback if it would like to know the details
  92280. * from the STREAMINFO.
  92281. * \param client_data This value will be supplied to callbacks in their
  92282. * \a client_data argument.
  92283. * \assert
  92284. * \code encoder != NULL \endcode
  92285. * \retval FLAC__StreamEncoderInitStatus
  92286. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92287. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92288. */
  92289. 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);
  92290. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92291. *
  92292. * This flavor of initialization sets up the encoder to encode to a FLAC
  92293. * stream in an Ogg container. I/O is performed via callbacks to the
  92294. * client. For encoding to a plain file via filename or open \c FILE*,
  92295. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92296. * provide a simpler interface.
  92297. *
  92298. * This function should be called after FLAC__stream_encoder_new() and
  92299. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92300. * or FLAC__stream_encoder_process_interleaved().
  92301. * initialization succeeded.
  92302. *
  92303. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92304. * immediately call the write callback several times to write the metadata
  92305. * packets.
  92306. *
  92307. * \param encoder An uninitialized encoder instance.
  92308. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92309. * pointer must not be \c NULL if \a seek_callback
  92310. * is non-NULL since they are both needed to be
  92311. * able to write data back to the Ogg FLAC stream
  92312. * in the post-encode phase.
  92313. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92314. * pointer must not be \c NULL.
  92315. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92316. * pointer may be \c NULL if seeking is not
  92317. * supported. The encoder uses seeking to go back
  92318. * and write some some stream statistics to the
  92319. * STREAMINFO block; this is recommended but not
  92320. * necessary to create a valid FLAC stream. If
  92321. * \a seek_callback is not \c NULL then a
  92322. * \a tell_callback must also be supplied.
  92323. * Alternatively, a dummy seek callback that just
  92324. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92325. * may also be supplied, all though this is slightly
  92326. * less efficient for the encoder.
  92327. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92328. * pointer may be \c NULL if seeking is not
  92329. * supported. If \a seek_callback is \c NULL then
  92330. * this argument will be ignored. If
  92331. * \a seek_callback is not \c NULL then a
  92332. * \a tell_callback must also be supplied.
  92333. * Alternatively, a dummy tell callback that just
  92334. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92335. * may also be supplied, all though this is slightly
  92336. * less efficient for the encoder.
  92337. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92338. * pointer may be \c NULL if the callback is not
  92339. * desired. If the client provides a seek callback,
  92340. * this function is not necessary as the encoder
  92341. * will automatically seek back and update the
  92342. * STREAMINFO block. It may also be \c NULL if the
  92343. * client does not support seeking, since it will
  92344. * have no way of going back to update the
  92345. * STREAMINFO. However the client can still supply
  92346. * a callback if it would like to know the details
  92347. * from the STREAMINFO.
  92348. * \param client_data This value will be supplied to callbacks in their
  92349. * \a client_data argument.
  92350. * \assert
  92351. * \code encoder != NULL \endcode
  92352. * \retval FLAC__StreamEncoderInitStatus
  92353. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92354. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92355. */
  92356. 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);
  92357. /** Initialize the encoder instance to encode native FLAC files.
  92358. *
  92359. * This flavor of initialization sets up the encoder to encode to a
  92360. * plain native FLAC file. For non-stdio streams, you must use
  92361. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92362. *
  92363. * This function should be called after FLAC__stream_encoder_new() and
  92364. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92365. * or FLAC__stream_encoder_process_interleaved().
  92366. * initialization succeeded.
  92367. *
  92368. * \param encoder An uninitialized encoder instance.
  92369. * \param file An open file. The file should have been opened
  92370. * with mode \c "w+b" and rewound. The file
  92371. * becomes owned by the encoder and should not be
  92372. * manipulated by the client while encoding.
  92373. * Unless \a file is \c stdout, it will be closed
  92374. * when FLAC__stream_encoder_finish() is called.
  92375. * Note however that a proper SEEKTABLE cannot be
  92376. * created when encoding to \c stdout since it is
  92377. * not seekable.
  92378. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92379. * pointer may be \c NULL if the callback is not
  92380. * desired.
  92381. * \param client_data This value will be supplied to callbacks in their
  92382. * \a client_data argument.
  92383. * \assert
  92384. * \code encoder != NULL \endcode
  92385. * \code file != NULL \endcode
  92386. * \retval FLAC__StreamEncoderInitStatus
  92387. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92388. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92389. */
  92390. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92391. /** Initialize the encoder instance to encode Ogg FLAC files.
  92392. *
  92393. * This flavor of initialization sets up the encoder to encode to a
  92394. * plain Ogg FLAC file. For non-stdio streams, you must use
  92395. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92396. *
  92397. * This function should be called after FLAC__stream_encoder_new() and
  92398. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92399. * or FLAC__stream_encoder_process_interleaved().
  92400. * initialization succeeded.
  92401. *
  92402. * \param encoder An uninitialized encoder instance.
  92403. * \param file An open file. The file should have been opened
  92404. * with mode \c "w+b" and rewound. The file
  92405. * becomes owned by the encoder and should not be
  92406. * manipulated by the client while encoding.
  92407. * Unless \a file is \c stdout, it will be closed
  92408. * when FLAC__stream_encoder_finish() is called.
  92409. * Note however that a proper SEEKTABLE cannot be
  92410. * created when encoding to \c stdout since it is
  92411. * not seekable.
  92412. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92413. * pointer may be \c NULL if the callback is not
  92414. * desired.
  92415. * \param client_data This value will be supplied to callbacks in their
  92416. * \a client_data argument.
  92417. * \assert
  92418. * \code encoder != NULL \endcode
  92419. * \code file != NULL \endcode
  92420. * \retval FLAC__StreamEncoderInitStatus
  92421. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92422. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92423. */
  92424. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92425. /** Initialize the encoder instance to encode native FLAC files.
  92426. *
  92427. * This flavor of initialization sets up the encoder to encode to a plain
  92428. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92429. * with Unicode filenames on Windows), you must use
  92430. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92431. * and provide callbacks for the I/O.
  92432. *
  92433. * This function should be called after FLAC__stream_encoder_new() and
  92434. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92435. * or FLAC__stream_encoder_process_interleaved().
  92436. * initialization succeeded.
  92437. *
  92438. * \param encoder An uninitialized encoder instance.
  92439. * \param filename The name of the file to encode to. The file will
  92440. * be opened with fopen(). Use \c NULL to encode to
  92441. * \c stdout. Note however that a proper SEEKTABLE
  92442. * cannot be created when encoding to \c stdout since
  92443. * it is not seekable.
  92444. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92445. * pointer may be \c NULL if the callback is not
  92446. * desired.
  92447. * \param client_data This value will be supplied to callbacks in their
  92448. * \a client_data argument.
  92449. * \assert
  92450. * \code encoder != NULL \endcode
  92451. * \retval FLAC__StreamEncoderInitStatus
  92452. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92453. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92454. */
  92455. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92456. /** Initialize the encoder instance to encode Ogg FLAC files.
  92457. *
  92458. * This flavor of initialization sets up the encoder to encode to a plain
  92459. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92460. * with Unicode filenames on Windows), you must use
  92461. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92462. * and provide callbacks for the I/O.
  92463. *
  92464. * This function should be called after FLAC__stream_encoder_new() and
  92465. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92466. * or FLAC__stream_encoder_process_interleaved().
  92467. * initialization succeeded.
  92468. *
  92469. * \param encoder An uninitialized encoder instance.
  92470. * \param filename The name of the file to encode to. The file will
  92471. * be opened with fopen(). Use \c NULL to encode to
  92472. * \c stdout. Note however that a proper SEEKTABLE
  92473. * cannot be created when encoding to \c stdout since
  92474. * it is not seekable.
  92475. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92476. * pointer may be \c NULL if the callback is not
  92477. * desired.
  92478. * \param client_data This value will be supplied to callbacks in their
  92479. * \a client_data argument.
  92480. * \assert
  92481. * \code encoder != NULL \endcode
  92482. * \retval FLAC__StreamEncoderInitStatus
  92483. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92484. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92485. */
  92486. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92487. /** Finish the encoding process.
  92488. * Flushes the encoding buffer, releases resources, resets the encoder
  92489. * settings to their defaults, and returns the encoder state to
  92490. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92491. * one or more write callbacks before returning, and will generate
  92492. * a metadata callback.
  92493. *
  92494. * Note that in the course of processing the last frame, errors can
  92495. * occur, so the caller should be sure to check the return value to
  92496. * ensure the file was encoded properly.
  92497. *
  92498. * In the event of a prematurely-terminated encode, it is not strictly
  92499. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92500. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92501. * with a FLAC__stream_encoder_finish().
  92502. *
  92503. * \param encoder An uninitialized encoder instance.
  92504. * \assert
  92505. * \code encoder != NULL \endcode
  92506. * \retval FLAC__bool
  92507. * \c false if an error occurred processing the last frame; or if verify
  92508. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92509. * verify mismatch; else \c true. If \c false, caller should check the
  92510. * state with FLAC__stream_encoder_get_state() for more information
  92511. * about the error.
  92512. */
  92513. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92514. /** Submit data for encoding.
  92515. * This version allows you to supply the input data via an array of
  92516. * pointers, each pointer pointing to an array of \a samples samples
  92517. * representing one channel. The samples need not be block-aligned,
  92518. * but each channel should have the same number of samples. Each sample
  92519. * should be a signed integer, right-justified to the resolution set by
  92520. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92521. * resolution is 16 bits per sample, the samples should all be in the
  92522. * range [-32768,32767].
  92523. *
  92524. * For applications where channel order is important, channels must
  92525. * follow the order as described in the
  92526. * <A HREF="../format.html#frame_header">frame header</A>.
  92527. *
  92528. * \param encoder An initialized encoder instance in the OK state.
  92529. * \param buffer An array of pointers to each channel's signal.
  92530. * \param samples The number of samples in one channel.
  92531. * \assert
  92532. * \code encoder != NULL \endcode
  92533. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92534. * \retval FLAC__bool
  92535. * \c true if successful, else \c false; in this case, check the
  92536. * encoder state with FLAC__stream_encoder_get_state() to see what
  92537. * went wrong.
  92538. */
  92539. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92540. /** Submit data for encoding.
  92541. * This version allows you to supply the input data where the channels
  92542. * are interleaved into a single array (i.e. channel0_sample0,
  92543. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92544. * The samples need not be block-aligned but they must be
  92545. * sample-aligned, i.e. the first value should be channel0_sample0
  92546. * and the last value channelN_sampleM. Each sample should be a signed
  92547. * integer, right-justified to the resolution set by
  92548. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92549. * resolution is 16 bits per sample, the samples should all be in the
  92550. * range [-32768,32767].
  92551. *
  92552. * For applications where channel order is important, channels must
  92553. * follow the order as described in the
  92554. * <A HREF="../format.html#frame_header">frame header</A>.
  92555. *
  92556. * \param encoder An initialized encoder instance in the OK state.
  92557. * \param buffer An array of channel-interleaved data (see above).
  92558. * \param samples The number of samples in one channel, the same as for
  92559. * FLAC__stream_encoder_process(). For example, if
  92560. * encoding two channels, \c 1000 \a samples corresponds
  92561. * to a \a buffer of 2000 values.
  92562. * \assert
  92563. * \code encoder != NULL \endcode
  92564. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92565. * \retval FLAC__bool
  92566. * \c true if successful, else \c false; in this case, check the
  92567. * encoder state with FLAC__stream_encoder_get_state() to see what
  92568. * went wrong.
  92569. */
  92570. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92571. /* \} */
  92572. #ifdef __cplusplus
  92573. }
  92574. #endif
  92575. #endif
  92576. /*** End of inlined file: stream_encoder.h ***/
  92577. #ifdef _MSC_VER
  92578. /* OPT: an MSVC built-in would be better */
  92579. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92580. {
  92581. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92582. return (x>>16) | (x<<16);
  92583. }
  92584. #endif
  92585. #if defined(_MSC_VER) && defined(_X86_)
  92586. /* OPT: an MSVC built-in would be better */
  92587. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92588. {
  92589. __asm {
  92590. mov edx, start
  92591. mov ecx, len
  92592. test ecx, ecx
  92593. loop1:
  92594. jz done1
  92595. mov eax, [edx]
  92596. bswap eax
  92597. mov [edx], eax
  92598. add edx, 4
  92599. dec ecx
  92600. jmp short loop1
  92601. done1:
  92602. }
  92603. }
  92604. #endif
  92605. /** \mainpage
  92606. *
  92607. * \section intro Introduction
  92608. *
  92609. * This is the documentation for the FLAC C and C++ APIs. It is
  92610. * highly interconnected; this introduction should give you a top
  92611. * level idea of the structure and how to find the information you
  92612. * need. As a prerequisite you should have at least a basic
  92613. * knowledge of the FLAC format, documented
  92614. * <A HREF="../format.html">here</A>.
  92615. *
  92616. * \section c_api FLAC C API
  92617. *
  92618. * The FLAC C API is the interface to libFLAC, a set of structures
  92619. * describing the components of FLAC streams, and functions for
  92620. * encoding and decoding streams, as well as manipulating FLAC
  92621. * metadata in files. The public include files will be installed
  92622. * in your include area (for example /usr/include/FLAC/...).
  92623. *
  92624. * By writing a little code and linking against libFLAC, it is
  92625. * relatively easy to add FLAC support to another program. The
  92626. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92627. * Complete source code of libFLAC as well as the command-line
  92628. * encoder and plugins is available and is a useful source of
  92629. * examples.
  92630. *
  92631. * Aside from encoders and decoders, libFLAC provides a powerful
  92632. * metadata interface for manipulating metadata in FLAC files. It
  92633. * allows the user to add, delete, and modify FLAC metadata blocks
  92634. * and it can automatically take advantage of PADDING blocks to avoid
  92635. * rewriting the entire FLAC file when changing the size of the
  92636. * metadata.
  92637. *
  92638. * libFLAC usually only requires the standard C library and C math
  92639. * library. In particular, threading is not used so there is no
  92640. * dependency on a thread library. However, libFLAC does not use
  92641. * global variables and should be thread-safe.
  92642. *
  92643. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92644. * However the metadata editing interfaces currently have limited
  92645. * read-only support for Ogg FLAC files.
  92646. *
  92647. * \section cpp_api FLAC C++ API
  92648. *
  92649. * The FLAC C++ API is a set of classes that encapsulate the
  92650. * structures and functions in libFLAC. They provide slightly more
  92651. * functionality with respect to metadata but are otherwise
  92652. * equivalent. For the most part, they share the same usage as
  92653. * their counterparts in libFLAC, and the FLAC C API documentation
  92654. * can be used as a supplement. The public include files
  92655. * for the C++ API will be installed in your include area (for
  92656. * example /usr/include/FLAC++/...).
  92657. *
  92658. * libFLAC++ is also licensed under
  92659. * <A HREF="../license.html">Xiph's BSD license</A>.
  92660. *
  92661. * \section getting_started Getting Started
  92662. *
  92663. * A good starting point for learning the API is to browse through
  92664. * the <A HREF="modules.html">modules</A>. Modules are logical
  92665. * groupings of related functions or classes, which correspond roughly
  92666. * to header files or sections of header files. Each module includes a
  92667. * detailed description of the general usage of its functions or
  92668. * classes.
  92669. *
  92670. * From there you can go on to look at the documentation of
  92671. * individual functions. You can see different views of the individual
  92672. * functions through the links in top bar across this page.
  92673. *
  92674. * If you prefer a more hands-on approach, you can jump right to some
  92675. * <A HREF="../documentation_example_code.html">example code</A>.
  92676. *
  92677. * \section porting_guide Porting Guide
  92678. *
  92679. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92680. * has been introduced which gives detailed instructions on how to
  92681. * port your code to newer versions of FLAC.
  92682. *
  92683. * \section embedded_developers Embedded Developers
  92684. *
  92685. * libFLAC has grown larger over time as more functionality has been
  92686. * included, but much of it may be unnecessary for a particular embedded
  92687. * implementation. Unused parts may be pruned by some simple editing of
  92688. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92689. * metadata interface are all independent from each other.
  92690. *
  92691. * It is easiest to just describe the dependencies:
  92692. *
  92693. * - All modules depend on the \link flac_format Format \endlink module.
  92694. * - The decoders and encoders depend on the bitbuffer.
  92695. * - The decoder is independent of the encoder. The encoder uses the
  92696. * decoder because of the verify feature, but this can be removed if
  92697. * not needed.
  92698. * - Parts of the metadata interface require the stream decoder (but not
  92699. * the encoder).
  92700. * - Ogg support is selectable through the compile time macro
  92701. * \c FLAC__HAS_OGG.
  92702. *
  92703. * For example, if your application only requires the stream decoder, no
  92704. * encoder, and no metadata interface, you can remove the stream encoder
  92705. * and the metadata interface, which will greatly reduce the size of the
  92706. * library.
  92707. *
  92708. * Also, there are several places in the libFLAC code with comments marked
  92709. * with "OPT:" where a #define can be changed to enable code that might be
  92710. * faster on a specific platform. Experimenting with these can yield faster
  92711. * binaries.
  92712. */
  92713. /** \defgroup porting Porting Guide for New Versions
  92714. *
  92715. * This module describes differences in the library interfaces from
  92716. * version to version. It assists in the porting of code that uses
  92717. * the libraries to newer versions of FLAC.
  92718. *
  92719. * One simple facility for making porting easier that has been added
  92720. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92721. * library's includes (e.g. \c include/FLAC/export.h). The
  92722. * \c #defines mirror the libraries'
  92723. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92724. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92725. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92726. * These can be used to support multiple versions of an API during the
  92727. * transition phase, e.g.
  92728. *
  92729. * \code
  92730. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92731. * legacy code
  92732. * #else
  92733. * new code
  92734. * #endif
  92735. * \endcode
  92736. *
  92737. * The the source will work for multiple versions and the legacy code can
  92738. * easily be removed when the transition is complete.
  92739. *
  92740. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92741. * include/FLAC/export.h), which can be used to determine whether or not
  92742. * the library has been compiled with support for Ogg FLAC. This is
  92743. * simpler than trying to call an Ogg init function and catching the
  92744. * error.
  92745. */
  92746. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92747. * \ingroup porting
  92748. *
  92749. * \brief
  92750. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92751. *
  92752. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92753. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92754. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92755. * decoding layers and three encoding layers have been merged into a
  92756. * single stream decoder and stream encoder. That is, the functionality
  92757. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92758. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92759. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92760. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92761. * is there is now a single API that can be used to encode or decode
  92762. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92763. * on both seekable and non-seekable streams.
  92764. *
  92765. * Instead of creating an encoder or decoder of a certain layer, now the
  92766. * client will always create a FLAC__StreamEncoder or
  92767. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92768. * initialization function. For example, for the decoder,
  92769. * FLAC__stream_decoder_init() has been replaced by
  92770. * FLAC__stream_decoder_init_stream(). This init function takes
  92771. * callbacks for the I/O, and the seeking callbacks are optional. This
  92772. * allows the client to use the same object for seekable and
  92773. * non-seekable streams. For decoding a FLAC file directly, the client
  92774. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92775. * and fewer callbacks; most of the other callbacks are supplied
  92776. * internally. For situations where fopen()ing by filename is not
  92777. * possible (e.g. Unicode filenames on Windows) the client can instead
  92778. * open the file itself and supply the FILE* to
  92779. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92780. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92781. * Since the callbacks and client data are now passed to the init
  92782. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92783. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92784. * rest of the calls to the decoder are the same as before.
  92785. *
  92786. * There are counterpart init functions for Ogg FLAC, e.g.
  92787. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92788. * and callbacks are the same as for native FLAC.
  92789. *
  92790. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92791. * been set up like so:
  92792. *
  92793. * \code
  92794. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92795. * if(decoder == NULL) do_something;
  92796. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92797. * [... other settings ...]
  92798. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92799. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92800. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92801. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92802. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92803. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92804. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92805. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92806. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92807. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92808. * \endcode
  92809. *
  92810. * In FLAC 1.1.3 it is like this:
  92811. *
  92812. * \code
  92813. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92814. * if(decoder == NULL) do_something;
  92815. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92816. * [... other settings ...]
  92817. * if(FLAC__stream_decoder_init_stream(
  92818. * decoder,
  92819. * my_read_callback,
  92820. * my_seek_callback, // or NULL
  92821. * my_tell_callback, // or NULL
  92822. * my_length_callback, // or NULL
  92823. * my_eof_callback, // or NULL
  92824. * my_write_callback,
  92825. * my_metadata_callback, // or NULL
  92826. * my_error_callback,
  92827. * my_client_data
  92828. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92829. * \endcode
  92830. *
  92831. * or you could do;
  92832. *
  92833. * \code
  92834. * [...]
  92835. * FILE *file = fopen("somefile.flac","rb");
  92836. * if(file == NULL) do_somthing;
  92837. * if(FLAC__stream_decoder_init_FILE(
  92838. * decoder,
  92839. * file,
  92840. * my_write_callback,
  92841. * my_metadata_callback, // or NULL
  92842. * my_error_callback,
  92843. * my_client_data
  92844. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92845. * \endcode
  92846. *
  92847. * or just:
  92848. *
  92849. * \code
  92850. * [...]
  92851. * if(FLAC__stream_decoder_init_file(
  92852. * decoder,
  92853. * "somefile.flac",
  92854. * my_write_callback,
  92855. * my_metadata_callback, // or NULL
  92856. * my_error_callback,
  92857. * my_client_data
  92858. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92859. * \endcode
  92860. *
  92861. * Another small change to the decoder is in how it handles unparseable
  92862. * streams. Before, when the decoder found an unparseable stream
  92863. * (reserved for when the decoder encounters a stream from a future
  92864. * encoder that it can't parse), it changed the state to
  92865. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92866. * drops sync and calls the error callback with a new error code
  92867. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92868. * more robust. If your error callback does not discriminate on the the
  92869. * error state, your code does not need to be changed.
  92870. *
  92871. * The encoder now has a new setting:
  92872. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92873. * method used to window the data before LPC analysis. You only need to
  92874. * add a call to this function if the default is not suitable. There
  92875. * are also two new convenience functions that may be useful:
  92876. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92877. * FLAC__metadata_get_cuesheet().
  92878. *
  92879. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92880. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92881. * is now \c size_t instead of \c unsigned.
  92882. */
  92883. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92884. * \ingroup porting
  92885. *
  92886. * \brief
  92887. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92888. *
  92889. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92890. * There was a slight change in the implementation of
  92891. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92892. * of the \a metadata array of pointers so the client no longer needs
  92893. * to maintain it after the call. The objects themselves that are
  92894. * pointed to by the array are still not copied though and must be
  92895. * maintained until the call to FLAC__stream_encoder_finish().
  92896. */
  92897. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92898. * \ingroup porting
  92899. *
  92900. * \brief
  92901. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92902. *
  92903. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92904. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92905. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92906. *
  92907. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92908. * has changed to reflect the conversion of one of the reserved bits
  92909. * into active use. It used to be \c 2 and now is \c 1. However the
  92910. * FLAC frame header length has not changed, so to skip the proper
  92911. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92912. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92913. */
  92914. /** \defgroup flac FLAC C API
  92915. *
  92916. * The FLAC C API is the interface to libFLAC, a set of structures
  92917. * describing the components of FLAC streams, and functions for
  92918. * encoding and decoding streams, as well as manipulating FLAC
  92919. * metadata in files.
  92920. *
  92921. * You should start with the format components as all other modules
  92922. * are dependent on it.
  92923. */
  92924. #endif
  92925. /*** End of inlined file: all.h ***/
  92926. /*** Start of inlined file: bitmath.c ***/
  92927. /*** Start of inlined file: juce_FlacHeader.h ***/
  92928. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92929. // tasks..
  92930. #define VERSION "1.2.1"
  92931. #define FLAC__NO_DLL 1
  92932. #if JUCE_MSVC
  92933. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92934. #endif
  92935. #if JUCE_MAC
  92936. #define FLAC__SYS_DARWIN 1
  92937. #endif
  92938. /*** End of inlined file: juce_FlacHeader.h ***/
  92939. #if JUCE_USE_FLAC
  92940. #if HAVE_CONFIG_H
  92941. # include <config.h>
  92942. #endif
  92943. /*** Start of inlined file: bitmath.h ***/
  92944. #ifndef FLAC__PRIVATE__BITMATH_H
  92945. #define FLAC__PRIVATE__BITMATH_H
  92946. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92947. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92948. unsigned FLAC__bitmath_silog2(int v);
  92949. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92950. #endif
  92951. /*** End of inlined file: bitmath.h ***/
  92952. /* An example of what FLAC__bitmath_ilog2() computes:
  92953. *
  92954. * ilog2( 0) = assertion failure
  92955. * ilog2( 1) = 0
  92956. * ilog2( 2) = 1
  92957. * ilog2( 3) = 1
  92958. * ilog2( 4) = 2
  92959. * ilog2( 5) = 2
  92960. * ilog2( 6) = 2
  92961. * ilog2( 7) = 2
  92962. * ilog2( 8) = 3
  92963. * ilog2( 9) = 3
  92964. * ilog2(10) = 3
  92965. * ilog2(11) = 3
  92966. * ilog2(12) = 3
  92967. * ilog2(13) = 3
  92968. * ilog2(14) = 3
  92969. * ilog2(15) = 3
  92970. * ilog2(16) = 4
  92971. * ilog2(17) = 4
  92972. * ilog2(18) = 4
  92973. */
  92974. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92975. {
  92976. unsigned l = 0;
  92977. FLAC__ASSERT(v > 0);
  92978. while(v >>= 1)
  92979. l++;
  92980. return l;
  92981. }
  92982. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92983. {
  92984. unsigned l = 0;
  92985. FLAC__ASSERT(v > 0);
  92986. while(v >>= 1)
  92987. l++;
  92988. return l;
  92989. }
  92990. /* An example of what FLAC__bitmath_silog2() computes:
  92991. *
  92992. * silog2(-10) = 5
  92993. * silog2(- 9) = 5
  92994. * silog2(- 8) = 4
  92995. * silog2(- 7) = 4
  92996. * silog2(- 6) = 4
  92997. * silog2(- 5) = 4
  92998. * silog2(- 4) = 3
  92999. * silog2(- 3) = 3
  93000. * silog2(- 2) = 2
  93001. * silog2(- 1) = 2
  93002. * silog2( 0) = 0
  93003. * silog2( 1) = 2
  93004. * silog2( 2) = 3
  93005. * silog2( 3) = 3
  93006. * silog2( 4) = 4
  93007. * silog2( 5) = 4
  93008. * silog2( 6) = 4
  93009. * silog2( 7) = 4
  93010. * silog2( 8) = 5
  93011. * silog2( 9) = 5
  93012. * silog2( 10) = 5
  93013. */
  93014. unsigned FLAC__bitmath_silog2(int v)
  93015. {
  93016. while(1) {
  93017. if(v == 0) {
  93018. return 0;
  93019. }
  93020. else if(v > 0) {
  93021. unsigned l = 0;
  93022. while(v) {
  93023. l++;
  93024. v >>= 1;
  93025. }
  93026. return l+1;
  93027. }
  93028. else if(v == -1) {
  93029. return 2;
  93030. }
  93031. else {
  93032. v++;
  93033. v = -v;
  93034. }
  93035. }
  93036. }
  93037. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  93038. {
  93039. while(1) {
  93040. if(v == 0) {
  93041. return 0;
  93042. }
  93043. else if(v > 0) {
  93044. unsigned l = 0;
  93045. while(v) {
  93046. l++;
  93047. v >>= 1;
  93048. }
  93049. return l+1;
  93050. }
  93051. else if(v == -1) {
  93052. return 2;
  93053. }
  93054. else {
  93055. v++;
  93056. v = -v;
  93057. }
  93058. }
  93059. }
  93060. #endif
  93061. /*** End of inlined file: bitmath.c ***/
  93062. /*** Start of inlined file: bitreader.c ***/
  93063. /*** Start of inlined file: juce_FlacHeader.h ***/
  93064. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93065. // tasks..
  93066. #define VERSION "1.2.1"
  93067. #define FLAC__NO_DLL 1
  93068. #if JUCE_MSVC
  93069. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93070. #endif
  93071. #if JUCE_MAC
  93072. #define FLAC__SYS_DARWIN 1
  93073. #endif
  93074. /*** End of inlined file: juce_FlacHeader.h ***/
  93075. #if JUCE_USE_FLAC
  93076. #if HAVE_CONFIG_H
  93077. # include <config.h>
  93078. #endif
  93079. #include <stdlib.h> /* for malloc() */
  93080. #include <string.h> /* for memcpy(), memset() */
  93081. #ifdef _MSC_VER
  93082. #include <winsock.h> /* for ntohl() */
  93083. #elif defined FLAC__SYS_DARWIN
  93084. #include <machine/endian.h> /* for ntohl() */
  93085. #elif defined __MINGW32__
  93086. #include <winsock.h> /* for ntohl() */
  93087. #else
  93088. #include <netinet/in.h> /* for ntohl() */
  93089. #endif
  93090. /*** Start of inlined file: bitreader.h ***/
  93091. #ifndef FLAC__PRIVATE__BITREADER_H
  93092. #define FLAC__PRIVATE__BITREADER_H
  93093. #include <stdio.h> /* for FILE */
  93094. /*** Start of inlined file: cpu.h ***/
  93095. #ifndef FLAC__PRIVATE__CPU_H
  93096. #define FLAC__PRIVATE__CPU_H
  93097. #ifdef HAVE_CONFIG_H
  93098. #include <config.h>
  93099. #endif
  93100. typedef enum {
  93101. FLAC__CPUINFO_TYPE_IA32,
  93102. FLAC__CPUINFO_TYPE_PPC,
  93103. FLAC__CPUINFO_TYPE_UNKNOWN
  93104. } FLAC__CPUInfo_Type;
  93105. typedef struct {
  93106. FLAC__bool cpuid;
  93107. FLAC__bool bswap;
  93108. FLAC__bool cmov;
  93109. FLAC__bool mmx;
  93110. FLAC__bool fxsr;
  93111. FLAC__bool sse;
  93112. FLAC__bool sse2;
  93113. FLAC__bool sse3;
  93114. FLAC__bool ssse3;
  93115. FLAC__bool _3dnow;
  93116. FLAC__bool ext3dnow;
  93117. FLAC__bool extmmx;
  93118. } FLAC__CPUInfo_IA32;
  93119. typedef struct {
  93120. FLAC__bool altivec;
  93121. FLAC__bool ppc64;
  93122. } FLAC__CPUInfo_PPC;
  93123. typedef struct {
  93124. FLAC__bool use_asm;
  93125. FLAC__CPUInfo_Type type;
  93126. union {
  93127. FLAC__CPUInfo_IA32 ia32;
  93128. FLAC__CPUInfo_PPC ppc;
  93129. } data;
  93130. } FLAC__CPUInfo;
  93131. void FLAC__cpu_info(FLAC__CPUInfo *info);
  93132. #ifndef FLAC__NO_ASM
  93133. #ifdef FLAC__CPU_IA32
  93134. #ifdef FLAC__HAS_NASM
  93135. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93136. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93137. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93138. #endif
  93139. #endif
  93140. #endif
  93141. #endif
  93142. /*** End of inlined file: cpu.h ***/
  93143. /*
  93144. * opaque structure definition
  93145. */
  93146. struct FLAC__BitReader;
  93147. typedef struct FLAC__BitReader FLAC__BitReader;
  93148. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93149. /*
  93150. * construction, deletion, initialization, etc functions
  93151. */
  93152. FLAC__BitReader *FLAC__bitreader_new(void);
  93153. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93154. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93155. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93156. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93157. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93158. /*
  93159. * CRC functions
  93160. */
  93161. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93162. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93163. /*
  93164. * info functions
  93165. */
  93166. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93167. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93168. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93169. /*
  93170. * read functions
  93171. */
  93172. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93173. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93174. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93175. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93176. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93177. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93178. 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! */
  93179. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93180. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93181. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93182. #ifndef FLAC__NO_ASM
  93183. # ifdef FLAC__CPU_IA32
  93184. # ifdef FLAC__HAS_NASM
  93185. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93186. # endif
  93187. # endif
  93188. #endif
  93189. #if 0 /* UNUSED */
  93190. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93191. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93192. #endif
  93193. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93194. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93195. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93196. #endif
  93197. /*** End of inlined file: bitreader.h ***/
  93198. /*** Start of inlined file: crc.h ***/
  93199. #ifndef FLAC__PRIVATE__CRC_H
  93200. #define FLAC__PRIVATE__CRC_H
  93201. /* 8 bit CRC generator, MSB shifted first
  93202. ** polynomial = x^8 + x^2 + x^1 + x^0
  93203. ** init = 0
  93204. */
  93205. extern FLAC__byte const FLAC__crc8_table[256];
  93206. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93207. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93208. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93209. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93210. /* 16 bit CRC generator, MSB shifted first
  93211. ** polynomial = x^16 + x^15 + x^2 + x^0
  93212. ** init = 0
  93213. */
  93214. extern unsigned FLAC__crc16_table[256];
  93215. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93216. /* this alternate may be faster on some systems/compilers */
  93217. #if 0
  93218. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93219. #endif
  93220. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93221. #endif
  93222. /*** End of inlined file: crc.h ***/
  93223. /* Things should be fastest when this matches the machine word size */
  93224. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93225. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93226. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93227. typedef FLAC__uint32 brword;
  93228. #define FLAC__BYTES_PER_WORD 4
  93229. #define FLAC__BITS_PER_WORD 32
  93230. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93231. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93232. #if WORDS_BIGENDIAN
  93233. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93234. #else
  93235. #if defined (_MSC_VER) && defined (_X86_)
  93236. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93237. #else
  93238. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93239. #endif
  93240. #endif
  93241. /* counts the # of zero MSBs in a word */
  93242. #define COUNT_ZERO_MSBS(word) ( \
  93243. (word) <= 0xffff ? \
  93244. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93245. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93246. )
  93247. /* this alternate might be slightly faster on some systems/compilers: */
  93248. #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])) )
  93249. /*
  93250. * This should be at least twice as large as the largest number of words
  93251. * required to represent any 'number' (in any encoding) you are going to
  93252. * read. With FLAC this is on the order of maybe a few hundred bits.
  93253. * If the buffer is smaller than that, the decoder won't be able to read
  93254. * in a whole number that is in a variable length encoding (e.g. Rice).
  93255. * But to be practical it should be at least 1K bytes.
  93256. *
  93257. * Increase this number to decrease the number of read callbacks, at the
  93258. * expense of using more memory. Or decrease for the reverse effect,
  93259. * keeping in mind the limit from the first paragraph. The optimal size
  93260. * also depends on the CPU cache size and other factors; some twiddling
  93261. * may be necessary to squeeze out the best performance.
  93262. */
  93263. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93264. static const unsigned char byte_to_unary_table[] = {
  93265. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93266. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93267. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93268. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93269. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93270. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93271. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93272. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93281. };
  93282. #ifdef min
  93283. #undef min
  93284. #endif
  93285. #define min(x,y) ((x)<(y)?(x):(y))
  93286. #ifdef max
  93287. #undef max
  93288. #endif
  93289. #define max(x,y) ((x)>(y)?(x):(y))
  93290. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93291. #ifdef _MSC_VER
  93292. #define FLAC__U64L(x) x
  93293. #else
  93294. #define FLAC__U64L(x) x##LLU
  93295. #endif
  93296. #ifndef FLaC__INLINE
  93297. #define FLaC__INLINE
  93298. #endif
  93299. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93300. struct FLAC__BitReader {
  93301. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93302. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93303. brword *buffer;
  93304. unsigned capacity; /* in words */
  93305. unsigned words; /* # of completed words in buffer */
  93306. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93307. unsigned consumed_words; /* #words ... */
  93308. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93309. unsigned read_crc16; /* the running frame CRC */
  93310. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93311. FLAC__BitReaderReadCallback read_callback;
  93312. void *client_data;
  93313. FLAC__CPUInfo cpu_info;
  93314. };
  93315. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93316. {
  93317. register unsigned crc = br->read_crc16;
  93318. #if FLAC__BYTES_PER_WORD == 4
  93319. switch(br->crc16_align) {
  93320. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93321. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93322. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93323. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93324. }
  93325. #elif FLAC__BYTES_PER_WORD == 8
  93326. switch(br->crc16_align) {
  93327. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93328. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93329. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93330. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93331. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93332. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93333. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93334. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93335. }
  93336. #else
  93337. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93338. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93339. br->read_crc16 = crc;
  93340. #endif
  93341. br->crc16_align = 0;
  93342. }
  93343. /* would be static except it needs to be called by asm routines */
  93344. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93345. {
  93346. unsigned start, end;
  93347. size_t bytes;
  93348. FLAC__byte *target;
  93349. /* first shift the unconsumed buffer data toward the front as much as possible */
  93350. if(br->consumed_words > 0) {
  93351. start = br->consumed_words;
  93352. end = br->words + (br->bytes? 1:0);
  93353. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93354. br->words -= start;
  93355. br->consumed_words = 0;
  93356. }
  93357. /*
  93358. * set the target for reading, taking into account word alignment and endianness
  93359. */
  93360. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93361. if(bytes == 0)
  93362. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93363. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93364. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93365. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93366. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93367. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93368. * ^^-------target, bytes=3
  93369. * on LE machines, have to byteswap the odd tail word so nothing is
  93370. * overwritten:
  93371. */
  93372. #if WORDS_BIGENDIAN
  93373. #else
  93374. if(br->bytes)
  93375. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93376. #endif
  93377. /* now it looks like:
  93378. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93379. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93380. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93381. * ^^-------target, bytes=3
  93382. */
  93383. /* read in the data; note that the callback may return a smaller number of bytes */
  93384. if(!br->read_callback(target, &bytes, br->client_data))
  93385. return false;
  93386. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93387. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93388. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93389. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93390. * now have to byteswap on LE machines:
  93391. */
  93392. #if WORDS_BIGENDIAN
  93393. #else
  93394. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93395. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93396. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93397. start = br->words;
  93398. local_swap32_block_(br->buffer + start, end - start);
  93399. }
  93400. else
  93401. # endif
  93402. for(start = br->words; start < end; start++)
  93403. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93404. #endif
  93405. /* now it looks like:
  93406. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93407. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93408. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93409. * finally we'll update the reader values:
  93410. */
  93411. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93412. br->words = end / FLAC__BYTES_PER_WORD;
  93413. br->bytes = end % FLAC__BYTES_PER_WORD;
  93414. return true;
  93415. }
  93416. /***********************************************************************
  93417. *
  93418. * Class constructor/destructor
  93419. *
  93420. ***********************************************************************/
  93421. FLAC__BitReader *FLAC__bitreader_new(void)
  93422. {
  93423. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93424. /* calloc() implies:
  93425. memset(br, 0, sizeof(FLAC__BitReader));
  93426. br->buffer = 0;
  93427. br->capacity = 0;
  93428. br->words = br->bytes = 0;
  93429. br->consumed_words = br->consumed_bits = 0;
  93430. br->read_callback = 0;
  93431. br->client_data = 0;
  93432. */
  93433. return br;
  93434. }
  93435. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93436. {
  93437. FLAC__ASSERT(0 != br);
  93438. FLAC__bitreader_free(br);
  93439. free(br);
  93440. }
  93441. /***********************************************************************
  93442. *
  93443. * Public class methods
  93444. *
  93445. ***********************************************************************/
  93446. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93447. {
  93448. FLAC__ASSERT(0 != br);
  93449. br->words = br->bytes = 0;
  93450. br->consumed_words = br->consumed_bits = 0;
  93451. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93452. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93453. if(br->buffer == 0)
  93454. return false;
  93455. br->read_callback = rcb;
  93456. br->client_data = cd;
  93457. br->cpu_info = cpu;
  93458. return true;
  93459. }
  93460. void FLAC__bitreader_free(FLAC__BitReader *br)
  93461. {
  93462. FLAC__ASSERT(0 != br);
  93463. if(0 != br->buffer)
  93464. free(br->buffer);
  93465. br->buffer = 0;
  93466. br->capacity = 0;
  93467. br->words = br->bytes = 0;
  93468. br->consumed_words = br->consumed_bits = 0;
  93469. br->read_callback = 0;
  93470. br->client_data = 0;
  93471. }
  93472. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93473. {
  93474. br->words = br->bytes = 0;
  93475. br->consumed_words = br->consumed_bits = 0;
  93476. return true;
  93477. }
  93478. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93479. {
  93480. unsigned i, j;
  93481. if(br == 0) {
  93482. fprintf(out, "bitreader is NULL\n");
  93483. }
  93484. else {
  93485. 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);
  93486. for(i = 0; i < br->words; i++) {
  93487. fprintf(out, "%08X: ", i);
  93488. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93489. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93490. fprintf(out, ".");
  93491. else
  93492. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93493. fprintf(out, "\n");
  93494. }
  93495. if(br->bytes > 0) {
  93496. fprintf(out, "%08X: ", i);
  93497. for(j = 0; j < br->bytes*8; j++)
  93498. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93499. fprintf(out, ".");
  93500. else
  93501. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93502. fprintf(out, "\n");
  93503. }
  93504. }
  93505. }
  93506. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93507. {
  93508. FLAC__ASSERT(0 != br);
  93509. FLAC__ASSERT(0 != br->buffer);
  93510. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93511. br->read_crc16 = (unsigned)seed;
  93512. br->crc16_align = br->consumed_bits;
  93513. }
  93514. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93515. {
  93516. FLAC__ASSERT(0 != br);
  93517. FLAC__ASSERT(0 != br->buffer);
  93518. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93519. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93520. /* CRC any tail bytes in a partially-consumed word */
  93521. if(br->consumed_bits) {
  93522. const brword tail = br->buffer[br->consumed_words];
  93523. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93524. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93525. }
  93526. return br->read_crc16;
  93527. }
  93528. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93529. {
  93530. return ((br->consumed_bits & 7) == 0);
  93531. }
  93532. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93533. {
  93534. return 8 - (br->consumed_bits & 7);
  93535. }
  93536. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93537. {
  93538. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93539. }
  93540. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93541. {
  93542. FLAC__ASSERT(0 != br);
  93543. FLAC__ASSERT(0 != br->buffer);
  93544. FLAC__ASSERT(bits <= 32);
  93545. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93546. FLAC__ASSERT(br->consumed_words <= br->words);
  93547. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93548. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93549. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93550. *val = 0;
  93551. return true;
  93552. }
  93553. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93554. if(!bitreader_read_from_client_(br))
  93555. return false;
  93556. }
  93557. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93558. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93559. if(br->consumed_bits) {
  93560. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93561. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93562. const brword word = br->buffer[br->consumed_words];
  93563. if(bits < n) {
  93564. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93565. br->consumed_bits += bits;
  93566. return true;
  93567. }
  93568. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93569. bits -= n;
  93570. crc16_update_word_(br, word);
  93571. br->consumed_words++;
  93572. br->consumed_bits = 0;
  93573. 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 */
  93574. *val <<= bits;
  93575. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93576. br->consumed_bits = bits;
  93577. }
  93578. return true;
  93579. }
  93580. else {
  93581. const brword word = br->buffer[br->consumed_words];
  93582. if(bits < FLAC__BITS_PER_WORD) {
  93583. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93584. br->consumed_bits = bits;
  93585. return true;
  93586. }
  93587. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93588. *val = word;
  93589. crc16_update_word_(br, word);
  93590. br->consumed_words++;
  93591. return true;
  93592. }
  93593. }
  93594. else {
  93595. /* in this case we're starting our read at a partial tail word;
  93596. * the reader has guaranteed that we have at least 'bits' bits
  93597. * available to read, which makes this case simpler.
  93598. */
  93599. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93600. if(br->consumed_bits) {
  93601. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93602. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93603. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93604. br->consumed_bits += bits;
  93605. return true;
  93606. }
  93607. else {
  93608. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93609. br->consumed_bits += bits;
  93610. return true;
  93611. }
  93612. }
  93613. }
  93614. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93615. {
  93616. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93617. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93618. return false;
  93619. /* sign-extend: */
  93620. *val <<= (32-bits);
  93621. *val >>= (32-bits);
  93622. return true;
  93623. }
  93624. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93625. {
  93626. FLAC__uint32 hi, lo;
  93627. if(bits > 32) {
  93628. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93629. return false;
  93630. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93631. return false;
  93632. *val = hi;
  93633. *val <<= 32;
  93634. *val |= lo;
  93635. }
  93636. else {
  93637. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93638. return false;
  93639. *val = lo;
  93640. }
  93641. return true;
  93642. }
  93643. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93644. {
  93645. FLAC__uint32 x8, x32 = 0;
  93646. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93647. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93648. return false;
  93649. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93650. return false;
  93651. x32 |= (x8 << 8);
  93652. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93653. return false;
  93654. x32 |= (x8 << 16);
  93655. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93656. return false;
  93657. x32 |= (x8 << 24);
  93658. *val = x32;
  93659. return true;
  93660. }
  93661. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93662. {
  93663. /*
  93664. * OPT: a faster implementation is possible but probably not that useful
  93665. * since this is only called a couple of times in the metadata readers.
  93666. */
  93667. FLAC__ASSERT(0 != br);
  93668. FLAC__ASSERT(0 != br->buffer);
  93669. if(bits > 0) {
  93670. const unsigned n = br->consumed_bits & 7;
  93671. unsigned m;
  93672. FLAC__uint32 x;
  93673. if(n != 0) {
  93674. m = min(8-n, bits);
  93675. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93676. return false;
  93677. bits -= m;
  93678. }
  93679. m = bits / 8;
  93680. if(m > 0) {
  93681. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93682. return false;
  93683. bits %= 8;
  93684. }
  93685. if(bits > 0) {
  93686. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93687. return false;
  93688. }
  93689. }
  93690. return true;
  93691. }
  93692. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93693. {
  93694. FLAC__uint32 x;
  93695. FLAC__ASSERT(0 != br);
  93696. FLAC__ASSERT(0 != br->buffer);
  93697. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93698. /* step 1: skip over partial head word to get word aligned */
  93699. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93700. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93701. return false;
  93702. nvals--;
  93703. }
  93704. if(0 == nvals)
  93705. return true;
  93706. /* step 2: skip whole words in chunks */
  93707. while(nvals >= FLAC__BYTES_PER_WORD) {
  93708. if(br->consumed_words < br->words) {
  93709. br->consumed_words++;
  93710. nvals -= FLAC__BYTES_PER_WORD;
  93711. }
  93712. else if(!bitreader_read_from_client_(br))
  93713. return false;
  93714. }
  93715. /* step 3: skip any remainder from partial tail bytes */
  93716. while(nvals) {
  93717. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93718. return false;
  93719. nvals--;
  93720. }
  93721. return true;
  93722. }
  93723. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93724. {
  93725. FLAC__uint32 x;
  93726. FLAC__ASSERT(0 != br);
  93727. FLAC__ASSERT(0 != br->buffer);
  93728. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93729. /* step 1: read from partial head word to get word aligned */
  93730. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93731. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93732. return false;
  93733. *val++ = (FLAC__byte)x;
  93734. nvals--;
  93735. }
  93736. if(0 == nvals)
  93737. return true;
  93738. /* step 2: read whole words in chunks */
  93739. while(nvals >= FLAC__BYTES_PER_WORD) {
  93740. if(br->consumed_words < br->words) {
  93741. const brword word = br->buffer[br->consumed_words++];
  93742. #if FLAC__BYTES_PER_WORD == 4
  93743. val[0] = (FLAC__byte)(word >> 24);
  93744. val[1] = (FLAC__byte)(word >> 16);
  93745. val[2] = (FLAC__byte)(word >> 8);
  93746. val[3] = (FLAC__byte)word;
  93747. #elif FLAC__BYTES_PER_WORD == 8
  93748. val[0] = (FLAC__byte)(word >> 56);
  93749. val[1] = (FLAC__byte)(word >> 48);
  93750. val[2] = (FLAC__byte)(word >> 40);
  93751. val[3] = (FLAC__byte)(word >> 32);
  93752. val[4] = (FLAC__byte)(word >> 24);
  93753. val[5] = (FLAC__byte)(word >> 16);
  93754. val[6] = (FLAC__byte)(word >> 8);
  93755. val[7] = (FLAC__byte)word;
  93756. #else
  93757. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93758. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93759. #endif
  93760. val += FLAC__BYTES_PER_WORD;
  93761. nvals -= FLAC__BYTES_PER_WORD;
  93762. }
  93763. else if(!bitreader_read_from_client_(br))
  93764. return false;
  93765. }
  93766. /* step 3: read any remainder from partial tail bytes */
  93767. while(nvals) {
  93768. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93769. return false;
  93770. *val++ = (FLAC__byte)x;
  93771. nvals--;
  93772. }
  93773. return true;
  93774. }
  93775. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93776. #if 0 /* slow but readable version */
  93777. {
  93778. unsigned bit;
  93779. FLAC__ASSERT(0 != br);
  93780. FLAC__ASSERT(0 != br->buffer);
  93781. *val = 0;
  93782. while(1) {
  93783. if(!FLAC__bitreader_read_bit(br, &bit))
  93784. return false;
  93785. if(bit)
  93786. break;
  93787. else
  93788. *val++;
  93789. }
  93790. return true;
  93791. }
  93792. #else
  93793. {
  93794. unsigned i;
  93795. FLAC__ASSERT(0 != br);
  93796. FLAC__ASSERT(0 != br->buffer);
  93797. *val = 0;
  93798. while(1) {
  93799. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93800. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93801. if(b) {
  93802. i = COUNT_ZERO_MSBS(b);
  93803. *val += i;
  93804. i++;
  93805. br->consumed_bits += i;
  93806. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93807. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93808. br->consumed_words++;
  93809. br->consumed_bits = 0;
  93810. }
  93811. return true;
  93812. }
  93813. else {
  93814. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93815. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93816. br->consumed_words++;
  93817. br->consumed_bits = 0;
  93818. /* didn't find stop bit yet, have to keep going... */
  93819. }
  93820. }
  93821. /* at this point we've eaten up all the whole words; have to try
  93822. * reading through any tail bytes before calling the read callback.
  93823. * this is a repeat of the above logic adjusted for the fact we
  93824. * don't have a whole word. note though if the client is feeding
  93825. * us data a byte at a time (unlikely), br->consumed_bits may not
  93826. * be zero.
  93827. */
  93828. if(br->bytes) {
  93829. const unsigned end = br->bytes * 8;
  93830. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93831. if(b) {
  93832. i = COUNT_ZERO_MSBS(b);
  93833. *val += i;
  93834. i++;
  93835. br->consumed_bits += i;
  93836. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93837. return true;
  93838. }
  93839. else {
  93840. *val += end - br->consumed_bits;
  93841. br->consumed_bits += end;
  93842. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93843. /* didn't find stop bit yet, have to keep going... */
  93844. }
  93845. }
  93846. if(!bitreader_read_from_client_(br))
  93847. return false;
  93848. }
  93849. }
  93850. #endif
  93851. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93852. {
  93853. FLAC__uint32 lsbs = 0, msbs = 0;
  93854. unsigned uval;
  93855. FLAC__ASSERT(0 != br);
  93856. FLAC__ASSERT(0 != br->buffer);
  93857. FLAC__ASSERT(parameter <= 31);
  93858. /* read the unary MSBs and end bit */
  93859. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93860. return false;
  93861. /* read the binary LSBs */
  93862. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93863. return false;
  93864. /* compose the value */
  93865. uval = (msbs << parameter) | lsbs;
  93866. if(uval & 1)
  93867. *val = -((int)(uval >> 1)) - 1;
  93868. else
  93869. *val = (int)(uval >> 1);
  93870. return true;
  93871. }
  93872. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93873. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93874. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93875. /* OPT: possibly faster version for use with MSVC */
  93876. #ifdef _MSC_VER
  93877. {
  93878. unsigned i;
  93879. unsigned uval = 0;
  93880. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93881. /* try and get br->consumed_words and br->consumed_bits into register;
  93882. * must remember to flush them back to *br before calling other
  93883. * bitwriter functions that use them, and before returning */
  93884. register unsigned cwords;
  93885. register unsigned cbits;
  93886. FLAC__ASSERT(0 != br);
  93887. FLAC__ASSERT(0 != br->buffer);
  93888. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93889. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93890. FLAC__ASSERT(parameter < 32);
  93891. /* 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 */
  93892. if(nvals == 0)
  93893. return true;
  93894. cbits = br->consumed_bits;
  93895. cwords = br->consumed_words;
  93896. while(1) {
  93897. /* read unary part */
  93898. while(1) {
  93899. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93900. brword b = br->buffer[cwords] << cbits;
  93901. if(b) {
  93902. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93903. __asm {
  93904. bsr eax, b
  93905. not eax
  93906. and eax, 31
  93907. mov i, eax
  93908. }
  93909. #else
  93910. i = COUNT_ZERO_MSBS(b);
  93911. #endif
  93912. uval += i;
  93913. bits = parameter;
  93914. i++;
  93915. cbits += i;
  93916. if(cbits == FLAC__BITS_PER_WORD) {
  93917. crc16_update_word_(br, br->buffer[cwords]);
  93918. cwords++;
  93919. cbits = 0;
  93920. }
  93921. goto break1;
  93922. }
  93923. else {
  93924. uval += FLAC__BITS_PER_WORD - cbits;
  93925. crc16_update_word_(br, br->buffer[cwords]);
  93926. cwords++;
  93927. cbits = 0;
  93928. /* didn't find stop bit yet, have to keep going... */
  93929. }
  93930. }
  93931. /* at this point we've eaten up all the whole words; have to try
  93932. * reading through any tail bytes before calling the read callback.
  93933. * this is a repeat of the above logic adjusted for the fact we
  93934. * don't have a whole word. note though if the client is feeding
  93935. * us data a byte at a time (unlikely), br->consumed_bits may not
  93936. * be zero.
  93937. */
  93938. if(br->bytes) {
  93939. const unsigned end = br->bytes * 8;
  93940. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93941. if(b) {
  93942. i = COUNT_ZERO_MSBS(b);
  93943. uval += i;
  93944. bits = parameter;
  93945. i++;
  93946. cbits += i;
  93947. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93948. goto break1;
  93949. }
  93950. else {
  93951. uval += end - cbits;
  93952. cbits += end;
  93953. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93954. /* didn't find stop bit yet, have to keep going... */
  93955. }
  93956. }
  93957. /* flush registers and read; bitreader_read_from_client_() does
  93958. * not touch br->consumed_bits at all but we still need to set
  93959. * it in case it fails and we have to return false.
  93960. */
  93961. br->consumed_bits = cbits;
  93962. br->consumed_words = cwords;
  93963. if(!bitreader_read_from_client_(br))
  93964. return false;
  93965. cwords = br->consumed_words;
  93966. }
  93967. break1:
  93968. /* read binary part */
  93969. FLAC__ASSERT(cwords <= br->words);
  93970. if(bits) {
  93971. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93972. /* flush registers and read; bitreader_read_from_client_() does
  93973. * not touch br->consumed_bits at all but we still need to set
  93974. * it in case it fails and we have to return false.
  93975. */
  93976. br->consumed_bits = cbits;
  93977. br->consumed_words = cwords;
  93978. if(!bitreader_read_from_client_(br))
  93979. return false;
  93980. cwords = br->consumed_words;
  93981. }
  93982. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93983. if(cbits) {
  93984. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93985. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93986. const brword word = br->buffer[cwords];
  93987. if(bits < n) {
  93988. uval <<= bits;
  93989. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93990. cbits += bits;
  93991. goto break2;
  93992. }
  93993. uval <<= n;
  93994. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93995. bits -= n;
  93996. crc16_update_word_(br, word);
  93997. cwords++;
  93998. cbits = 0;
  93999. 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 */
  94000. uval <<= bits;
  94001. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  94002. cbits = bits;
  94003. }
  94004. goto break2;
  94005. }
  94006. else {
  94007. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  94008. uval <<= bits;
  94009. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94010. cbits = bits;
  94011. goto break2;
  94012. }
  94013. }
  94014. else {
  94015. /* in this case we're starting our read at a partial tail word;
  94016. * the reader has guaranteed that we have at least 'bits' bits
  94017. * available to read, which makes this case simpler.
  94018. */
  94019. uval <<= bits;
  94020. if(cbits) {
  94021. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94022. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  94023. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  94024. cbits += bits;
  94025. goto break2;
  94026. }
  94027. else {
  94028. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94029. cbits += bits;
  94030. goto break2;
  94031. }
  94032. }
  94033. }
  94034. break2:
  94035. /* compose the value */
  94036. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94037. /* are we done? */
  94038. --nvals;
  94039. if(nvals == 0) {
  94040. br->consumed_bits = cbits;
  94041. br->consumed_words = cwords;
  94042. return true;
  94043. }
  94044. uval = 0;
  94045. ++vals;
  94046. }
  94047. }
  94048. #else
  94049. {
  94050. unsigned i;
  94051. unsigned uval = 0;
  94052. /* try and get br->consumed_words and br->consumed_bits into register;
  94053. * must remember to flush them back to *br before calling other
  94054. * bitwriter functions that use them, and before returning */
  94055. register unsigned cwords;
  94056. register unsigned cbits;
  94057. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  94058. FLAC__ASSERT(0 != br);
  94059. FLAC__ASSERT(0 != br->buffer);
  94060. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94061. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94062. FLAC__ASSERT(parameter < 32);
  94063. /* 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 */
  94064. if(nvals == 0)
  94065. return true;
  94066. cbits = br->consumed_bits;
  94067. cwords = br->consumed_words;
  94068. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94069. while(1) {
  94070. /* read unary part */
  94071. while(1) {
  94072. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94073. brword b = br->buffer[cwords] << cbits;
  94074. if(b) {
  94075. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  94076. asm volatile (
  94077. "bsrl %1, %0;"
  94078. "notl %0;"
  94079. "andl $31, %0;"
  94080. : "=r"(i)
  94081. : "r"(b)
  94082. );
  94083. #else
  94084. i = COUNT_ZERO_MSBS(b);
  94085. #endif
  94086. uval += i;
  94087. cbits += i;
  94088. cbits++; /* skip over stop bit */
  94089. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  94090. crc16_update_word_(br, br->buffer[cwords]);
  94091. cwords++;
  94092. cbits = 0;
  94093. }
  94094. goto break1;
  94095. }
  94096. else {
  94097. uval += FLAC__BITS_PER_WORD - cbits;
  94098. crc16_update_word_(br, br->buffer[cwords]);
  94099. cwords++;
  94100. cbits = 0;
  94101. /* didn't find stop bit yet, have to keep going... */
  94102. }
  94103. }
  94104. /* at this point we've eaten up all the whole words; have to try
  94105. * reading through any tail bytes before calling the read callback.
  94106. * this is a repeat of the above logic adjusted for the fact we
  94107. * don't have a whole word. note though if the client is feeding
  94108. * us data a byte at a time (unlikely), br->consumed_bits may not
  94109. * be zero.
  94110. */
  94111. if(br->bytes) {
  94112. const unsigned end = br->bytes * 8;
  94113. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  94114. if(b) {
  94115. i = COUNT_ZERO_MSBS(b);
  94116. uval += i;
  94117. cbits += i;
  94118. cbits++; /* skip over stop bit */
  94119. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94120. goto break1;
  94121. }
  94122. else {
  94123. uval += end - cbits;
  94124. cbits += end;
  94125. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94126. /* didn't find stop bit yet, have to keep going... */
  94127. }
  94128. }
  94129. /* flush registers and read; bitreader_read_from_client_() does
  94130. * not touch br->consumed_bits at all but we still need to set
  94131. * it in case it fails and we have to return false.
  94132. */
  94133. br->consumed_bits = cbits;
  94134. br->consumed_words = cwords;
  94135. if(!bitreader_read_from_client_(br))
  94136. return false;
  94137. cwords = br->consumed_words;
  94138. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94139. /* + uval to offset our count by the # of unary bits already
  94140. * consumed before the read, because we will add these back
  94141. * in all at once at break1
  94142. */
  94143. }
  94144. break1:
  94145. ucbits -= uval;
  94146. ucbits--; /* account for stop bit */
  94147. /* read binary part */
  94148. FLAC__ASSERT(cwords <= br->words);
  94149. if(parameter) {
  94150. while(ucbits < parameter) {
  94151. /* flush registers and read; bitreader_read_from_client_() does
  94152. * not touch br->consumed_bits at all but we still need to set
  94153. * it in case it fails and we have to return false.
  94154. */
  94155. br->consumed_bits = cbits;
  94156. br->consumed_words = cwords;
  94157. if(!bitreader_read_from_client_(br))
  94158. return false;
  94159. cwords = br->consumed_words;
  94160. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94161. }
  94162. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94163. if(cbits) {
  94164. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94165. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94166. const brword word = br->buffer[cwords];
  94167. if(parameter < n) {
  94168. uval <<= parameter;
  94169. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94170. cbits += parameter;
  94171. }
  94172. else {
  94173. uval <<= n;
  94174. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94175. crc16_update_word_(br, word);
  94176. cwords++;
  94177. cbits = parameter - n;
  94178. 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 */
  94179. uval <<= cbits;
  94180. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94181. }
  94182. }
  94183. }
  94184. else {
  94185. cbits = parameter;
  94186. uval <<= parameter;
  94187. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94188. }
  94189. }
  94190. else {
  94191. /* in this case we're starting our read at a partial tail word;
  94192. * the reader has guaranteed that we have at least 'parameter'
  94193. * bits available to read, which makes this case simpler.
  94194. */
  94195. uval <<= parameter;
  94196. if(cbits) {
  94197. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94198. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94199. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94200. cbits += parameter;
  94201. }
  94202. else {
  94203. cbits = parameter;
  94204. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94205. }
  94206. }
  94207. }
  94208. ucbits -= parameter;
  94209. /* compose the value */
  94210. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94211. /* are we done? */
  94212. --nvals;
  94213. if(nvals == 0) {
  94214. br->consumed_bits = cbits;
  94215. br->consumed_words = cwords;
  94216. return true;
  94217. }
  94218. uval = 0;
  94219. ++vals;
  94220. }
  94221. }
  94222. #endif
  94223. #if 0 /* UNUSED */
  94224. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94225. {
  94226. FLAC__uint32 lsbs = 0, msbs = 0;
  94227. unsigned bit, uval, k;
  94228. FLAC__ASSERT(0 != br);
  94229. FLAC__ASSERT(0 != br->buffer);
  94230. k = FLAC__bitmath_ilog2(parameter);
  94231. /* read the unary MSBs and end bit */
  94232. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94233. return false;
  94234. /* read the binary LSBs */
  94235. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94236. return false;
  94237. if(parameter == 1u<<k) {
  94238. /* compose the value */
  94239. uval = (msbs << k) | lsbs;
  94240. }
  94241. else {
  94242. unsigned d = (1 << (k+1)) - parameter;
  94243. if(lsbs >= d) {
  94244. if(!FLAC__bitreader_read_bit(br, &bit))
  94245. return false;
  94246. lsbs <<= 1;
  94247. lsbs |= bit;
  94248. lsbs -= d;
  94249. }
  94250. /* compose the value */
  94251. uval = msbs * parameter + lsbs;
  94252. }
  94253. /* unfold unsigned to signed */
  94254. if(uval & 1)
  94255. *val = -((int)(uval >> 1)) - 1;
  94256. else
  94257. *val = (int)(uval >> 1);
  94258. return true;
  94259. }
  94260. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94261. {
  94262. FLAC__uint32 lsbs, msbs = 0;
  94263. unsigned bit, k;
  94264. FLAC__ASSERT(0 != br);
  94265. FLAC__ASSERT(0 != br->buffer);
  94266. k = FLAC__bitmath_ilog2(parameter);
  94267. /* read the unary MSBs and end bit */
  94268. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94269. return false;
  94270. /* read the binary LSBs */
  94271. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94272. return false;
  94273. if(parameter == 1u<<k) {
  94274. /* compose the value */
  94275. *val = (msbs << k) | lsbs;
  94276. }
  94277. else {
  94278. unsigned d = (1 << (k+1)) - parameter;
  94279. if(lsbs >= d) {
  94280. if(!FLAC__bitreader_read_bit(br, &bit))
  94281. return false;
  94282. lsbs <<= 1;
  94283. lsbs |= bit;
  94284. lsbs -= d;
  94285. }
  94286. /* compose the value */
  94287. *val = msbs * parameter + lsbs;
  94288. }
  94289. return true;
  94290. }
  94291. #endif /* UNUSED */
  94292. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94293. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94294. {
  94295. FLAC__uint32 v = 0;
  94296. FLAC__uint32 x;
  94297. unsigned i;
  94298. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94299. return false;
  94300. if(raw)
  94301. raw[(*rawlen)++] = (FLAC__byte)x;
  94302. if(!(x & 0x80)) { /* 0xxxxxxx */
  94303. v = x;
  94304. i = 0;
  94305. }
  94306. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94307. v = x & 0x1F;
  94308. i = 1;
  94309. }
  94310. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94311. v = x & 0x0F;
  94312. i = 2;
  94313. }
  94314. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94315. v = x & 0x07;
  94316. i = 3;
  94317. }
  94318. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94319. v = x & 0x03;
  94320. i = 4;
  94321. }
  94322. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94323. v = x & 0x01;
  94324. i = 5;
  94325. }
  94326. else {
  94327. *val = 0xffffffff;
  94328. return true;
  94329. }
  94330. for( ; i; i--) {
  94331. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94332. return false;
  94333. if(raw)
  94334. raw[(*rawlen)++] = (FLAC__byte)x;
  94335. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94336. *val = 0xffffffff;
  94337. return true;
  94338. }
  94339. v <<= 6;
  94340. v |= (x & 0x3F);
  94341. }
  94342. *val = v;
  94343. return true;
  94344. }
  94345. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94346. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94347. {
  94348. FLAC__uint64 v = 0;
  94349. FLAC__uint32 x;
  94350. unsigned i;
  94351. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94352. return false;
  94353. if(raw)
  94354. raw[(*rawlen)++] = (FLAC__byte)x;
  94355. if(!(x & 0x80)) { /* 0xxxxxxx */
  94356. v = x;
  94357. i = 0;
  94358. }
  94359. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94360. v = x & 0x1F;
  94361. i = 1;
  94362. }
  94363. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94364. v = x & 0x0F;
  94365. i = 2;
  94366. }
  94367. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94368. v = x & 0x07;
  94369. i = 3;
  94370. }
  94371. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94372. v = x & 0x03;
  94373. i = 4;
  94374. }
  94375. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94376. v = x & 0x01;
  94377. i = 5;
  94378. }
  94379. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94380. v = 0;
  94381. i = 6;
  94382. }
  94383. else {
  94384. *val = FLAC__U64L(0xffffffffffffffff);
  94385. return true;
  94386. }
  94387. for( ; i; i--) {
  94388. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94389. return false;
  94390. if(raw)
  94391. raw[(*rawlen)++] = (FLAC__byte)x;
  94392. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94393. *val = FLAC__U64L(0xffffffffffffffff);
  94394. return true;
  94395. }
  94396. v <<= 6;
  94397. v |= (x & 0x3F);
  94398. }
  94399. *val = v;
  94400. return true;
  94401. }
  94402. #endif
  94403. /*** End of inlined file: bitreader.c ***/
  94404. /*** Start of inlined file: bitwriter.c ***/
  94405. /*** Start of inlined file: juce_FlacHeader.h ***/
  94406. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94407. // tasks..
  94408. #define VERSION "1.2.1"
  94409. #define FLAC__NO_DLL 1
  94410. #if JUCE_MSVC
  94411. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94412. #endif
  94413. #if JUCE_MAC
  94414. #define FLAC__SYS_DARWIN 1
  94415. #endif
  94416. /*** End of inlined file: juce_FlacHeader.h ***/
  94417. #if JUCE_USE_FLAC
  94418. #if HAVE_CONFIG_H
  94419. # include <config.h>
  94420. #endif
  94421. #include <stdlib.h> /* for malloc() */
  94422. #include <string.h> /* for memcpy(), memset() */
  94423. #ifdef _MSC_VER
  94424. #include <winsock.h> /* for ntohl() */
  94425. #elif defined FLAC__SYS_DARWIN
  94426. #include <machine/endian.h> /* for ntohl() */
  94427. #elif defined __MINGW32__
  94428. #include <winsock.h> /* for ntohl() */
  94429. #else
  94430. #include <netinet/in.h> /* for ntohl() */
  94431. #endif
  94432. #if 0 /* UNUSED */
  94433. #endif
  94434. /*** Start of inlined file: bitwriter.h ***/
  94435. #ifndef FLAC__PRIVATE__BITWRITER_H
  94436. #define FLAC__PRIVATE__BITWRITER_H
  94437. #include <stdio.h> /* for FILE */
  94438. /*
  94439. * opaque structure definition
  94440. */
  94441. struct FLAC__BitWriter;
  94442. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94443. /*
  94444. * construction, deletion, initialization, etc functions
  94445. */
  94446. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94447. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94448. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94449. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94450. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94451. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94452. /*
  94453. * CRC functions
  94454. *
  94455. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94456. */
  94457. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94458. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94459. /*
  94460. * info functions
  94461. */
  94462. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94463. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94464. /*
  94465. * direct buffer access
  94466. *
  94467. * there may be no calls on the bitwriter between get and release.
  94468. * the bitwriter continues to own the returned buffer.
  94469. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94470. */
  94471. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94472. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94473. /*
  94474. * write functions
  94475. */
  94476. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94477. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94478. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94479. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94480. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94481. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94482. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94483. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94484. #if 0 /* UNUSED */
  94485. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94486. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94487. #endif
  94488. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94489. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94490. #if 0 /* UNUSED */
  94491. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94492. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94493. #endif
  94494. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94495. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94496. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94497. #endif
  94498. /*** End of inlined file: bitwriter.h ***/
  94499. /*** Start of inlined file: alloc.h ***/
  94500. #ifndef FLAC__SHARE__ALLOC_H
  94501. #define FLAC__SHARE__ALLOC_H
  94502. #if HAVE_CONFIG_H
  94503. # include <config.h>
  94504. #endif
  94505. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94506. * before #including this file, otherwise SIZE_MAX might not be defined
  94507. */
  94508. #include <limits.h> /* for SIZE_MAX */
  94509. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94510. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94511. #endif
  94512. #include <stdlib.h> /* for size_t, malloc(), etc */
  94513. #ifndef SIZE_MAX
  94514. # ifndef SIZE_T_MAX
  94515. # ifdef _MSC_VER
  94516. # define SIZE_T_MAX UINT_MAX
  94517. # else
  94518. # error
  94519. # endif
  94520. # endif
  94521. # define SIZE_MAX SIZE_T_MAX
  94522. #endif
  94523. #ifndef FLaC__INLINE
  94524. #define FLaC__INLINE
  94525. #endif
  94526. /* avoid malloc()ing 0 bytes, see:
  94527. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94528. */
  94529. static FLaC__INLINE void *safe_malloc_(size_t size)
  94530. {
  94531. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94532. if(!size)
  94533. size++;
  94534. return malloc(size);
  94535. }
  94536. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94537. {
  94538. if(!nmemb || !size)
  94539. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94540. return calloc(nmemb, size);
  94541. }
  94542. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94543. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94544. {
  94545. size2 += size1;
  94546. if(size2 < size1)
  94547. return 0;
  94548. return safe_malloc_(size2);
  94549. }
  94550. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94551. {
  94552. size2 += size1;
  94553. if(size2 < size1)
  94554. return 0;
  94555. size3 += size2;
  94556. if(size3 < size2)
  94557. return 0;
  94558. return safe_malloc_(size3);
  94559. }
  94560. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94561. {
  94562. size2 += size1;
  94563. if(size2 < size1)
  94564. return 0;
  94565. size3 += size2;
  94566. if(size3 < size2)
  94567. return 0;
  94568. size4 += size3;
  94569. if(size4 < size3)
  94570. return 0;
  94571. return safe_malloc_(size4);
  94572. }
  94573. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94574. #if 0
  94575. needs support for cases where sizeof(size_t) != 4
  94576. {
  94577. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94578. if(sizeof(size_t) == 4) {
  94579. if ((double)size1 * (double)size2 < 4294967296.0)
  94580. return malloc(size1*size2);
  94581. }
  94582. return 0;
  94583. }
  94584. #else
  94585. /* better? */
  94586. {
  94587. if(!size1 || !size2)
  94588. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94589. if(size1 > SIZE_MAX / size2)
  94590. return 0;
  94591. return malloc(size1*size2);
  94592. }
  94593. #endif
  94594. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94595. {
  94596. if(!size1 || !size2 || !size3)
  94597. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94598. if(size1 > SIZE_MAX / size2)
  94599. return 0;
  94600. size1 *= size2;
  94601. if(size1 > SIZE_MAX / size3)
  94602. return 0;
  94603. return malloc(size1*size3);
  94604. }
  94605. /* size1*size2 + size3 */
  94606. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94607. {
  94608. if(!size1 || !size2)
  94609. return safe_malloc_(size3);
  94610. if(size1 > SIZE_MAX / size2)
  94611. return 0;
  94612. return safe_malloc_add_2op_(size1*size2, size3);
  94613. }
  94614. /* size1 * (size2 + size3) */
  94615. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94616. {
  94617. if(!size1 || (!size2 && !size3))
  94618. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94619. size2 += size3;
  94620. if(size2 < size3)
  94621. return 0;
  94622. return safe_malloc_mul_2op_(size1, size2);
  94623. }
  94624. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94625. {
  94626. size2 += size1;
  94627. if(size2 < size1)
  94628. return 0;
  94629. return realloc(ptr, size2);
  94630. }
  94631. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94632. {
  94633. size2 += size1;
  94634. if(size2 < size1)
  94635. return 0;
  94636. size3 += size2;
  94637. if(size3 < size2)
  94638. return 0;
  94639. return realloc(ptr, size3);
  94640. }
  94641. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94642. {
  94643. size2 += size1;
  94644. if(size2 < size1)
  94645. return 0;
  94646. size3 += size2;
  94647. if(size3 < size2)
  94648. return 0;
  94649. size4 += size3;
  94650. if(size4 < size3)
  94651. return 0;
  94652. return realloc(ptr, size4);
  94653. }
  94654. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94655. {
  94656. if(!size1 || !size2)
  94657. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94658. if(size1 > SIZE_MAX / size2)
  94659. return 0;
  94660. return realloc(ptr, size1*size2);
  94661. }
  94662. /* size1 * (size2 + size3) */
  94663. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94664. {
  94665. if(!size1 || (!size2 && !size3))
  94666. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94667. size2 += size3;
  94668. if(size2 < size3)
  94669. return 0;
  94670. return safe_realloc_mul_2op_(ptr, size1, size2);
  94671. }
  94672. #endif
  94673. /*** End of inlined file: alloc.h ***/
  94674. /* Things should be fastest when this matches the machine word size */
  94675. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94676. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94677. typedef FLAC__uint32 bwword;
  94678. #define FLAC__BYTES_PER_WORD 4
  94679. #define FLAC__BITS_PER_WORD 32
  94680. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94681. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94682. #if WORDS_BIGENDIAN
  94683. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94684. #else
  94685. #ifdef _MSC_VER
  94686. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94687. #else
  94688. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94689. #endif
  94690. #endif
  94691. /*
  94692. * The default capacity here doesn't matter too much. The buffer always grows
  94693. * to hold whatever is written to it. Usually the encoder will stop adding at
  94694. * a frame or metadata block, then write that out and clear the buffer for the
  94695. * next one.
  94696. */
  94697. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94698. /* When growing, increment 4K at a time */
  94699. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94700. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94701. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94702. #ifdef min
  94703. #undef min
  94704. #endif
  94705. #define min(x,y) ((x)<(y)?(x):(y))
  94706. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94707. #ifdef _MSC_VER
  94708. #define FLAC__U64L(x) x
  94709. #else
  94710. #define FLAC__U64L(x) x##LLU
  94711. #endif
  94712. #ifndef FLaC__INLINE
  94713. #define FLaC__INLINE
  94714. #endif
  94715. struct FLAC__BitWriter {
  94716. bwword *buffer;
  94717. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94718. unsigned capacity; /* capacity of buffer in words */
  94719. unsigned words; /* # of complete words in buffer */
  94720. unsigned bits; /* # of used bits in accum */
  94721. };
  94722. /* * WATCHOUT: The current implementation only grows the buffer. */
  94723. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94724. {
  94725. unsigned new_capacity;
  94726. bwword *new_buffer;
  94727. FLAC__ASSERT(0 != bw);
  94728. FLAC__ASSERT(0 != bw->buffer);
  94729. /* calculate total words needed to store 'bits_to_add' additional bits */
  94730. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94731. /* it's possible (due to pessimism in the growth estimation that
  94732. * leads to this call) that we don't actually need to grow
  94733. */
  94734. if(bw->capacity >= new_capacity)
  94735. return true;
  94736. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94737. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94738. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94739. /* make sure we got everything right */
  94740. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94741. FLAC__ASSERT(new_capacity > bw->capacity);
  94742. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94743. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94744. if(new_buffer == 0)
  94745. return false;
  94746. bw->buffer = new_buffer;
  94747. bw->capacity = new_capacity;
  94748. return true;
  94749. }
  94750. /***********************************************************************
  94751. *
  94752. * Class constructor/destructor
  94753. *
  94754. ***********************************************************************/
  94755. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94756. {
  94757. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94758. /* note that calloc() sets all members to 0 for us */
  94759. return bw;
  94760. }
  94761. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94762. {
  94763. FLAC__ASSERT(0 != bw);
  94764. FLAC__bitwriter_free(bw);
  94765. free(bw);
  94766. }
  94767. /***********************************************************************
  94768. *
  94769. * Public class methods
  94770. *
  94771. ***********************************************************************/
  94772. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94773. {
  94774. FLAC__ASSERT(0 != bw);
  94775. bw->words = bw->bits = 0;
  94776. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94777. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94778. if(bw->buffer == 0)
  94779. return false;
  94780. return true;
  94781. }
  94782. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94783. {
  94784. FLAC__ASSERT(0 != bw);
  94785. if(0 != bw->buffer)
  94786. free(bw->buffer);
  94787. bw->buffer = 0;
  94788. bw->capacity = 0;
  94789. bw->words = bw->bits = 0;
  94790. }
  94791. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94792. {
  94793. bw->words = bw->bits = 0;
  94794. }
  94795. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94796. {
  94797. unsigned i, j;
  94798. if(bw == 0) {
  94799. fprintf(out, "bitwriter is NULL\n");
  94800. }
  94801. else {
  94802. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94803. for(i = 0; i < bw->words; i++) {
  94804. fprintf(out, "%08X: ", i);
  94805. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94806. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94807. fprintf(out, "\n");
  94808. }
  94809. if(bw->bits > 0) {
  94810. fprintf(out, "%08X: ", i);
  94811. for(j = 0; j < bw->bits; j++)
  94812. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94813. fprintf(out, "\n");
  94814. }
  94815. }
  94816. }
  94817. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94818. {
  94819. const FLAC__byte *buffer;
  94820. size_t bytes;
  94821. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94822. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94823. return false;
  94824. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94825. FLAC__bitwriter_release_buffer(bw);
  94826. return true;
  94827. }
  94828. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94829. {
  94830. const FLAC__byte *buffer;
  94831. size_t bytes;
  94832. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94833. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94834. return false;
  94835. *crc = FLAC__crc8(buffer, bytes);
  94836. FLAC__bitwriter_release_buffer(bw);
  94837. return true;
  94838. }
  94839. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94840. {
  94841. return ((bw->bits & 7) == 0);
  94842. }
  94843. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94844. {
  94845. return FLAC__TOTAL_BITS(bw);
  94846. }
  94847. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94848. {
  94849. FLAC__ASSERT((bw->bits & 7) == 0);
  94850. /* double protection */
  94851. if(bw->bits & 7)
  94852. return false;
  94853. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94854. if(bw->bits) {
  94855. FLAC__ASSERT(bw->words <= bw->capacity);
  94856. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94857. return false;
  94858. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94859. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94860. }
  94861. /* now we can just return what we have */
  94862. *buffer = (FLAC__byte*)bw->buffer;
  94863. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94864. return true;
  94865. }
  94866. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94867. {
  94868. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94869. * get-mode' flag could be added everywhere and then cleared here
  94870. */
  94871. (void)bw;
  94872. }
  94873. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94874. {
  94875. unsigned n;
  94876. FLAC__ASSERT(0 != bw);
  94877. FLAC__ASSERT(0 != bw->buffer);
  94878. if(bits == 0)
  94879. return true;
  94880. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94881. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94882. return false;
  94883. /* first part gets to word alignment */
  94884. if(bw->bits) {
  94885. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94886. bw->accum <<= n;
  94887. bits -= n;
  94888. bw->bits += n;
  94889. if(bw->bits == FLAC__BITS_PER_WORD) {
  94890. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94891. bw->bits = 0;
  94892. }
  94893. else
  94894. return true;
  94895. }
  94896. /* do whole words */
  94897. while(bits >= FLAC__BITS_PER_WORD) {
  94898. bw->buffer[bw->words++] = 0;
  94899. bits -= FLAC__BITS_PER_WORD;
  94900. }
  94901. /* do any leftovers */
  94902. if(bits > 0) {
  94903. bw->accum = 0;
  94904. bw->bits = bits;
  94905. }
  94906. return true;
  94907. }
  94908. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94909. {
  94910. register unsigned left;
  94911. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94912. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94913. FLAC__ASSERT(0 != bw);
  94914. FLAC__ASSERT(0 != bw->buffer);
  94915. FLAC__ASSERT(bits <= 32);
  94916. if(bits == 0)
  94917. return true;
  94918. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94919. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94920. return false;
  94921. left = FLAC__BITS_PER_WORD - bw->bits;
  94922. if(bits < left) {
  94923. bw->accum <<= bits;
  94924. bw->accum |= val;
  94925. bw->bits += bits;
  94926. }
  94927. 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 */
  94928. bw->accum <<= left;
  94929. bw->accum |= val >> (bw->bits = bits - left);
  94930. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94931. bw->accum = val;
  94932. }
  94933. else {
  94934. bw->accum = val;
  94935. bw->bits = 0;
  94936. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94937. }
  94938. return true;
  94939. }
  94940. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94941. {
  94942. /* zero-out unused bits */
  94943. if(bits < 32)
  94944. val &= (~(0xffffffff << bits));
  94945. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94946. }
  94947. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94948. {
  94949. /* this could be a little faster but it's not used for much */
  94950. if(bits > 32) {
  94951. return
  94952. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94953. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94954. }
  94955. else
  94956. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94957. }
  94958. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94959. {
  94960. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94961. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94962. return false;
  94963. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94964. return false;
  94965. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94966. return false;
  94967. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94968. return false;
  94969. return true;
  94970. }
  94971. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94972. {
  94973. unsigned i;
  94974. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94975. for(i = 0; i < nvals; i++) {
  94976. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94977. return false;
  94978. }
  94979. return true;
  94980. }
  94981. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94982. {
  94983. if(val < 32)
  94984. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94985. else
  94986. return
  94987. FLAC__bitwriter_write_zeroes(bw, val) &&
  94988. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94989. }
  94990. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94991. {
  94992. FLAC__uint32 uval;
  94993. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94994. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94995. uval = (val<<1) ^ (val>>31);
  94996. return 1 + parameter + (uval >> parameter);
  94997. }
  94998. #if 0 /* UNUSED */
  94999. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  95000. {
  95001. unsigned bits, msbs, uval;
  95002. unsigned k;
  95003. FLAC__ASSERT(parameter > 0);
  95004. /* fold signed to unsigned */
  95005. if(val < 0)
  95006. uval = (unsigned)(((-(++val)) << 1) + 1);
  95007. else
  95008. uval = (unsigned)(val << 1);
  95009. k = FLAC__bitmath_ilog2(parameter);
  95010. if(parameter == 1u<<k) {
  95011. FLAC__ASSERT(k <= 30);
  95012. msbs = uval >> k;
  95013. bits = 1 + k + msbs;
  95014. }
  95015. else {
  95016. unsigned q, r, d;
  95017. d = (1 << (k+1)) - parameter;
  95018. q = uval / parameter;
  95019. r = uval - (q * parameter);
  95020. bits = 1 + q + k;
  95021. if(r >= d)
  95022. bits++;
  95023. }
  95024. return bits;
  95025. }
  95026. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  95027. {
  95028. unsigned bits, msbs;
  95029. unsigned k;
  95030. FLAC__ASSERT(parameter > 0);
  95031. k = FLAC__bitmath_ilog2(parameter);
  95032. if(parameter == 1u<<k) {
  95033. FLAC__ASSERT(k <= 30);
  95034. msbs = uval >> k;
  95035. bits = 1 + k + msbs;
  95036. }
  95037. else {
  95038. unsigned q, r, d;
  95039. d = (1 << (k+1)) - parameter;
  95040. q = uval / parameter;
  95041. r = uval - (q * parameter);
  95042. bits = 1 + q + k;
  95043. if(r >= d)
  95044. bits++;
  95045. }
  95046. return bits;
  95047. }
  95048. #endif /* UNUSED */
  95049. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  95050. {
  95051. unsigned total_bits, interesting_bits, msbs;
  95052. FLAC__uint32 uval, pattern;
  95053. FLAC__ASSERT(0 != bw);
  95054. FLAC__ASSERT(0 != bw->buffer);
  95055. FLAC__ASSERT(parameter < 8*sizeof(uval));
  95056. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95057. uval = (val<<1) ^ (val>>31);
  95058. msbs = uval >> parameter;
  95059. interesting_bits = 1 + parameter;
  95060. total_bits = interesting_bits + msbs;
  95061. pattern = 1 << parameter; /* the unary end bit */
  95062. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  95063. if(total_bits <= 32)
  95064. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  95065. else
  95066. return
  95067. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  95068. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  95069. }
  95070. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  95071. {
  95072. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  95073. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  95074. FLAC__uint32 uval;
  95075. unsigned left;
  95076. const unsigned lsbits = 1 + parameter;
  95077. unsigned msbits;
  95078. FLAC__ASSERT(0 != bw);
  95079. FLAC__ASSERT(0 != bw->buffer);
  95080. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  95081. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  95082. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  95083. while(nvals) {
  95084. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95085. uval = (*vals<<1) ^ (*vals>>31);
  95086. msbits = uval >> parameter;
  95087. #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) */
  95088. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95089. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95090. bw->bits = bw->bits + msbits + lsbits;
  95091. uval |= mask1; /* set stop bit */
  95092. uval &= mask2; /* mask off unused top bits */
  95093. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  95094. bw->accum <<= msbits;
  95095. bw->accum <<= lsbits;
  95096. bw->accum |= uval;
  95097. if(bw->bits == FLAC__BITS_PER_WORD) {
  95098. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95099. bw->bits = 0;
  95100. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  95101. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  95102. FLAC__ASSERT(bw->capacity == bw->words);
  95103. return false;
  95104. }
  95105. }
  95106. }
  95107. else {
  95108. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  95109. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95110. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95111. bw->bits = bw->bits + msbits + lsbits;
  95112. uval |= mask1; /* set stop bit */
  95113. uval &= mask2; /* mask off unused top bits */
  95114. bw->accum <<= msbits + lsbits;
  95115. bw->accum |= uval;
  95116. }
  95117. else {
  95118. #endif
  95119. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  95120. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  95121. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  95122. return false;
  95123. if(msbits) {
  95124. /* first part gets to word alignment */
  95125. if(bw->bits) {
  95126. left = FLAC__BITS_PER_WORD - bw->bits;
  95127. if(msbits < left) {
  95128. bw->accum <<= msbits;
  95129. bw->bits += msbits;
  95130. goto break1;
  95131. }
  95132. else {
  95133. bw->accum <<= left;
  95134. msbits -= left;
  95135. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95136. bw->bits = 0;
  95137. }
  95138. }
  95139. /* do whole words */
  95140. while(msbits >= FLAC__BITS_PER_WORD) {
  95141. bw->buffer[bw->words++] = 0;
  95142. msbits -= FLAC__BITS_PER_WORD;
  95143. }
  95144. /* do any leftovers */
  95145. if(msbits > 0) {
  95146. bw->accum = 0;
  95147. bw->bits = msbits;
  95148. }
  95149. }
  95150. break1:
  95151. uval |= mask1; /* set stop bit */
  95152. uval &= mask2; /* mask off unused top bits */
  95153. left = FLAC__BITS_PER_WORD - bw->bits;
  95154. if(lsbits < left) {
  95155. bw->accum <<= lsbits;
  95156. bw->accum |= uval;
  95157. bw->bits += lsbits;
  95158. }
  95159. else {
  95160. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95161. * be > lsbits (because of previous assertions) so it would have
  95162. * triggered the (lsbits<left) case above.
  95163. */
  95164. FLAC__ASSERT(bw->bits);
  95165. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95166. bw->accum <<= left;
  95167. bw->accum |= uval >> (bw->bits = lsbits - left);
  95168. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95169. bw->accum = uval;
  95170. }
  95171. #if 1
  95172. }
  95173. #endif
  95174. vals++;
  95175. nvals--;
  95176. }
  95177. return true;
  95178. }
  95179. #if 0 /* UNUSED */
  95180. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95181. {
  95182. unsigned total_bits, msbs, uval;
  95183. unsigned k;
  95184. FLAC__ASSERT(0 != bw);
  95185. FLAC__ASSERT(0 != bw->buffer);
  95186. FLAC__ASSERT(parameter > 0);
  95187. /* fold signed to unsigned */
  95188. if(val < 0)
  95189. uval = (unsigned)(((-(++val)) << 1) + 1);
  95190. else
  95191. uval = (unsigned)(val << 1);
  95192. k = FLAC__bitmath_ilog2(parameter);
  95193. if(parameter == 1u<<k) {
  95194. unsigned pattern;
  95195. FLAC__ASSERT(k <= 30);
  95196. msbs = uval >> k;
  95197. total_bits = 1 + k + msbs;
  95198. pattern = 1 << k; /* the unary end bit */
  95199. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95200. if(total_bits <= 32) {
  95201. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95202. return false;
  95203. }
  95204. else {
  95205. /* write the unary MSBs */
  95206. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95207. return false;
  95208. /* write the unary end bit and binary LSBs */
  95209. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95210. return false;
  95211. }
  95212. }
  95213. else {
  95214. unsigned q, r, d;
  95215. d = (1 << (k+1)) - parameter;
  95216. q = uval / parameter;
  95217. r = uval - (q * parameter);
  95218. /* write the unary MSBs */
  95219. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95220. return false;
  95221. /* write the unary end bit */
  95222. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95223. return false;
  95224. /* write the binary LSBs */
  95225. if(r >= d) {
  95226. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95227. return false;
  95228. }
  95229. else {
  95230. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95231. return false;
  95232. }
  95233. }
  95234. return true;
  95235. }
  95236. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95237. {
  95238. unsigned total_bits, msbs;
  95239. unsigned k;
  95240. FLAC__ASSERT(0 != bw);
  95241. FLAC__ASSERT(0 != bw->buffer);
  95242. FLAC__ASSERT(parameter > 0);
  95243. k = FLAC__bitmath_ilog2(parameter);
  95244. if(parameter == 1u<<k) {
  95245. unsigned pattern;
  95246. FLAC__ASSERT(k <= 30);
  95247. msbs = uval >> k;
  95248. total_bits = 1 + k + msbs;
  95249. pattern = 1 << k; /* the unary end bit */
  95250. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95251. if(total_bits <= 32) {
  95252. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95253. return false;
  95254. }
  95255. else {
  95256. /* write the unary MSBs */
  95257. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95258. return false;
  95259. /* write the unary end bit and binary LSBs */
  95260. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95261. return false;
  95262. }
  95263. }
  95264. else {
  95265. unsigned q, r, d;
  95266. d = (1 << (k+1)) - parameter;
  95267. q = uval / parameter;
  95268. r = uval - (q * parameter);
  95269. /* write the unary MSBs */
  95270. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95271. return false;
  95272. /* write the unary end bit */
  95273. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95274. return false;
  95275. /* write the binary LSBs */
  95276. if(r >= d) {
  95277. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95278. return false;
  95279. }
  95280. else {
  95281. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95282. return false;
  95283. }
  95284. }
  95285. return true;
  95286. }
  95287. #endif /* UNUSED */
  95288. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95289. {
  95290. FLAC__bool ok = 1;
  95291. FLAC__ASSERT(0 != bw);
  95292. FLAC__ASSERT(0 != bw->buffer);
  95293. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95294. if(val < 0x80) {
  95295. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95296. }
  95297. else if(val < 0x800) {
  95298. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95299. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95300. }
  95301. else if(val < 0x10000) {
  95302. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95303. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95304. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95305. }
  95306. else if(val < 0x200000) {
  95307. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95308. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95309. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95310. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95311. }
  95312. else if(val < 0x4000000) {
  95313. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95314. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95315. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95316. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95317. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95318. }
  95319. else {
  95320. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95321. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95322. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95323. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95324. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95325. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95326. }
  95327. return ok;
  95328. }
  95329. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95330. {
  95331. FLAC__bool ok = 1;
  95332. FLAC__ASSERT(0 != bw);
  95333. FLAC__ASSERT(0 != bw->buffer);
  95334. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95335. if(val < 0x80) {
  95336. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95337. }
  95338. else if(val < 0x800) {
  95339. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95340. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95341. }
  95342. else if(val < 0x10000) {
  95343. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95344. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95345. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95346. }
  95347. else if(val < 0x200000) {
  95348. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95349. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95350. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95351. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95352. }
  95353. else if(val < 0x4000000) {
  95354. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95355. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95356. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95357. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95358. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95359. }
  95360. else if(val < 0x80000000) {
  95361. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95362. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95363. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95364. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95365. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95366. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95367. }
  95368. else {
  95369. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95370. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95371. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95372. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95373. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95374. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95375. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95376. }
  95377. return ok;
  95378. }
  95379. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95380. {
  95381. /* 0-pad to byte boundary */
  95382. if(bw->bits & 7u)
  95383. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95384. else
  95385. return true;
  95386. }
  95387. #endif
  95388. /*** End of inlined file: bitwriter.c ***/
  95389. /*** Start of inlined file: cpu.c ***/
  95390. /*** Start of inlined file: juce_FlacHeader.h ***/
  95391. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95392. // tasks..
  95393. #define VERSION "1.2.1"
  95394. #define FLAC__NO_DLL 1
  95395. #if JUCE_MSVC
  95396. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95397. #endif
  95398. #if JUCE_MAC
  95399. #define FLAC__SYS_DARWIN 1
  95400. #endif
  95401. /*** End of inlined file: juce_FlacHeader.h ***/
  95402. #if JUCE_USE_FLAC
  95403. #if HAVE_CONFIG_H
  95404. # include <config.h>
  95405. #endif
  95406. #include <stdlib.h>
  95407. #include <stdio.h>
  95408. #if defined FLAC__CPU_IA32
  95409. # include <signal.h>
  95410. #elif defined FLAC__CPU_PPC
  95411. # if !defined FLAC__NO_ASM
  95412. # if defined FLAC__SYS_DARWIN
  95413. # include <sys/sysctl.h>
  95414. # include <mach/mach.h>
  95415. # include <mach/mach_host.h>
  95416. # include <mach/host_info.h>
  95417. # include <mach/machine.h>
  95418. # ifndef CPU_SUBTYPE_POWERPC_970
  95419. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95420. # endif
  95421. # else /* FLAC__SYS_DARWIN */
  95422. # include <signal.h>
  95423. # include <setjmp.h>
  95424. static sigjmp_buf jmpbuf;
  95425. static volatile sig_atomic_t canjump = 0;
  95426. static void sigill_handler (int sig)
  95427. {
  95428. if (!canjump) {
  95429. signal (sig, SIG_DFL);
  95430. raise (sig);
  95431. }
  95432. canjump = 0;
  95433. siglongjmp (jmpbuf, 1);
  95434. }
  95435. # endif /* FLAC__SYS_DARWIN */
  95436. # endif /* FLAC__NO_ASM */
  95437. #endif /* FLAC__CPU_PPC */
  95438. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95439. #include <sys/param.h>
  95440. #include <sys/sysctl.h>
  95441. #include <machine/cpu.h>
  95442. #endif
  95443. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95444. #include <sys/types.h>
  95445. #include <sys/sysctl.h>
  95446. #endif
  95447. #if defined(__APPLE__)
  95448. /* how to get sysctlbyname()? */
  95449. #endif
  95450. /* these are flags in EDX of CPUID AX=00000001 */
  95451. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95452. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95453. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95454. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95455. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95456. /* these are flags in ECX of CPUID AX=00000001 */
  95457. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95458. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95459. /* these are flags in EDX of CPUID AX=80000001 */
  95460. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95461. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95462. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95463. /*
  95464. * Extra stuff needed for detection of OS support for SSE on IA-32
  95465. */
  95466. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95467. # if defined(__linux__)
  95468. /*
  95469. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95470. * modify the return address to jump over the offending SSE instruction
  95471. * and also the operation following it that indicates the instruction
  95472. * executed successfully. In this way we use no global variables and
  95473. * stay thread-safe.
  95474. *
  95475. * 3 + 3 + 6:
  95476. * 3 bytes for "xorps xmm0,xmm0"
  95477. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95478. * 6 bytes extra in case our estimate is wrong
  95479. * 12 bytes puts us in the NOP "landing zone"
  95480. */
  95481. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95482. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95483. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95484. {
  95485. (void)signal;
  95486. sc.eip += 3 + 3 + 6;
  95487. }
  95488. # else
  95489. # include <sys/ucontext.h>
  95490. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95491. {
  95492. (void)signal, (void)si;
  95493. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95494. }
  95495. # endif
  95496. # elif defined(_MSC_VER)
  95497. # include <windows.h>
  95498. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95499. # ifdef USE_TRY_CATCH_FLAVOR
  95500. # else
  95501. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95502. {
  95503. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95504. ep->ContextRecord->Eip += 3 + 3 + 6;
  95505. return EXCEPTION_CONTINUE_EXECUTION;
  95506. }
  95507. return EXCEPTION_CONTINUE_SEARCH;
  95508. }
  95509. # endif
  95510. # endif
  95511. #endif
  95512. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95513. {
  95514. /*
  95515. * IA32-specific
  95516. */
  95517. #ifdef FLAC__CPU_IA32
  95518. info->type = FLAC__CPUINFO_TYPE_IA32;
  95519. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95520. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95521. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95522. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95523. info->data.ia32.cmov = false;
  95524. info->data.ia32.mmx = false;
  95525. info->data.ia32.fxsr = false;
  95526. info->data.ia32.sse = false;
  95527. info->data.ia32.sse2 = false;
  95528. info->data.ia32.sse3 = false;
  95529. info->data.ia32.ssse3 = false;
  95530. info->data.ia32._3dnow = false;
  95531. info->data.ia32.ext3dnow = false;
  95532. info->data.ia32.extmmx = false;
  95533. if(info->data.ia32.cpuid) {
  95534. /* http://www.sandpile.org/ia32/cpuid.htm */
  95535. FLAC__uint32 flags_edx, flags_ecx;
  95536. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95537. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95538. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95539. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95540. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95541. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95542. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95543. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95544. #ifdef FLAC__USE_3DNOW
  95545. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95546. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95547. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95548. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95549. #else
  95550. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95551. #endif
  95552. #ifdef DEBUG
  95553. fprintf(stderr, "CPU info (IA-32):\n");
  95554. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95555. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95556. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95557. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95558. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95559. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95560. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95561. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95562. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95563. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95564. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95565. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95566. #endif
  95567. /*
  95568. * now have to check for OS support of SSE/SSE2
  95569. */
  95570. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95571. #if defined FLAC__NO_SSE_OS
  95572. /* assume user knows better than us; turn it off */
  95573. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95574. #elif defined FLAC__SSE_OS
  95575. /* assume user knows better than us; leave as detected above */
  95576. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95577. int sse = 0;
  95578. size_t len;
  95579. /* at least one of these must work: */
  95580. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95581. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95582. if(!sse)
  95583. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95584. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95585. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95586. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95587. size_t len = sizeof(val);
  95588. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95589. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95590. else { /* double-check SSE2 */
  95591. mib[1] = CPU_SSE2;
  95592. len = sizeof(val);
  95593. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95594. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95595. }
  95596. # else
  95597. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95598. # endif
  95599. #elif defined(__linux__)
  95600. int sse = 0;
  95601. struct sigaction sigill_save;
  95602. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95603. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95604. #else
  95605. struct sigaction sigill_sse;
  95606. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95607. __sigemptyset(&sigill_sse.sa_mask);
  95608. 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 */
  95609. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95610. #endif
  95611. {
  95612. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95613. /* see sigill_handler_sse_os() for an explanation of the following: */
  95614. asm volatile (
  95615. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95616. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95617. "incl %0\n\t" /* SIGILL handler will jump over this */
  95618. /* landing zone */
  95619. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95620. "nop\n\t"
  95621. "nop\n\t"
  95622. "nop\n\t"
  95623. "nop\n\t"
  95624. "nop\n\t"
  95625. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95626. "nop\n\t"
  95627. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95628. : "=r"(sse)
  95629. : "r"(sse)
  95630. );
  95631. sigaction(SIGILL, &sigill_save, NULL);
  95632. }
  95633. if(!sse)
  95634. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95635. #elif defined(_MSC_VER)
  95636. # ifdef USE_TRY_CATCH_FLAVOR
  95637. _try {
  95638. __asm {
  95639. # if _MSC_VER <= 1200
  95640. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95641. _emit 0x0F
  95642. _emit 0x57
  95643. _emit 0xC0
  95644. # else
  95645. xorps xmm0,xmm0
  95646. # endif
  95647. }
  95648. }
  95649. _except(EXCEPTION_EXECUTE_HANDLER) {
  95650. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95651. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95652. }
  95653. # else
  95654. int sse = 0;
  95655. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95656. /* see GCC version above for explanation */
  95657. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95658. /* http://www.codeproject.com/cpp/gccasm.asp */
  95659. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95660. __asm {
  95661. # if _MSC_VER <= 1200
  95662. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95663. _emit 0x0F
  95664. _emit 0x57
  95665. _emit 0xC0
  95666. # else
  95667. xorps xmm0,xmm0
  95668. # endif
  95669. inc sse
  95670. nop
  95671. nop
  95672. nop
  95673. nop
  95674. nop
  95675. nop
  95676. nop
  95677. nop
  95678. nop
  95679. }
  95680. SetUnhandledExceptionFilter(save);
  95681. if(!sse)
  95682. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95683. # endif
  95684. #else
  95685. /* no way to test, disable to be safe */
  95686. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95687. #endif
  95688. #ifdef DEBUG
  95689. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95690. #endif
  95691. }
  95692. }
  95693. #else
  95694. info->use_asm = false;
  95695. #endif
  95696. /*
  95697. * PPC-specific
  95698. */
  95699. #elif defined FLAC__CPU_PPC
  95700. info->type = FLAC__CPUINFO_TYPE_PPC;
  95701. # if !defined FLAC__NO_ASM
  95702. info->use_asm = true;
  95703. # ifdef FLAC__USE_ALTIVEC
  95704. # if defined FLAC__SYS_DARWIN
  95705. {
  95706. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95707. size_t len = sizeof(val);
  95708. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95709. }
  95710. {
  95711. host_basic_info_data_t hostInfo;
  95712. mach_msg_type_number_t infoCount;
  95713. infoCount = HOST_BASIC_INFO_COUNT;
  95714. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95715. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95716. }
  95717. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95718. {
  95719. /* no Darwin, do it the brute-force way */
  95720. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95721. info->data.ppc.altivec = 0;
  95722. info->data.ppc.ppc64 = 0;
  95723. signal (SIGILL, sigill_handler);
  95724. canjump = 0;
  95725. if (!sigsetjmp (jmpbuf, 1)) {
  95726. canjump = 1;
  95727. asm volatile (
  95728. "mtspr 256, %0\n\t"
  95729. "vand %%v0, %%v0, %%v0"
  95730. :
  95731. : "r" (-1)
  95732. );
  95733. info->data.ppc.altivec = 1;
  95734. }
  95735. canjump = 0;
  95736. if (!sigsetjmp (jmpbuf, 1)) {
  95737. int x = 0;
  95738. canjump = 1;
  95739. /* PPC64 hardware implements the cntlzd instruction */
  95740. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95741. info->data.ppc.ppc64 = 1;
  95742. }
  95743. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95744. }
  95745. # endif
  95746. # else /* !FLAC__USE_ALTIVEC */
  95747. info->data.ppc.altivec = 0;
  95748. info->data.ppc.ppc64 = 0;
  95749. # endif
  95750. # else
  95751. info->use_asm = false;
  95752. # endif
  95753. /*
  95754. * unknown CPI
  95755. */
  95756. #else
  95757. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95758. info->use_asm = false;
  95759. #endif
  95760. }
  95761. #endif
  95762. /*** End of inlined file: cpu.c ***/
  95763. /*** Start of inlined file: crc.c ***/
  95764. /*** Start of inlined file: juce_FlacHeader.h ***/
  95765. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95766. // tasks..
  95767. #define VERSION "1.2.1"
  95768. #define FLAC__NO_DLL 1
  95769. #if JUCE_MSVC
  95770. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95771. #endif
  95772. #if JUCE_MAC
  95773. #define FLAC__SYS_DARWIN 1
  95774. #endif
  95775. /*** End of inlined file: juce_FlacHeader.h ***/
  95776. #if JUCE_USE_FLAC
  95777. #if HAVE_CONFIG_H
  95778. # include <config.h>
  95779. #endif
  95780. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95781. FLAC__byte const FLAC__crc8_table[256] = {
  95782. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95783. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95784. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95785. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95786. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95787. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95788. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95789. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95790. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95791. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95792. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95793. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95794. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95795. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95796. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95797. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95798. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95799. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95800. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95801. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95802. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95803. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95804. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95805. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95806. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95807. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95808. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95809. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95810. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95811. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95812. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95813. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95814. };
  95815. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95816. unsigned FLAC__crc16_table[256] = {
  95817. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95818. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95819. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95820. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95821. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95822. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95823. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95824. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95825. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95826. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95827. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95828. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95829. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95830. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95831. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95832. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95833. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95834. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95835. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95836. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95837. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95838. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95839. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95840. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95841. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95842. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95843. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95844. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95845. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95846. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95847. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95848. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95849. };
  95850. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95851. {
  95852. *crc = FLAC__crc8_table[*crc ^ data];
  95853. }
  95854. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95855. {
  95856. while(len--)
  95857. *crc = FLAC__crc8_table[*crc ^ *data++];
  95858. }
  95859. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95860. {
  95861. FLAC__uint8 crc = 0;
  95862. while(len--)
  95863. crc = FLAC__crc8_table[crc ^ *data++];
  95864. return crc;
  95865. }
  95866. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95867. {
  95868. unsigned crc = 0;
  95869. while(len--)
  95870. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95871. return crc;
  95872. }
  95873. #endif
  95874. /*** End of inlined file: crc.c ***/
  95875. /*** Start of inlined file: fixed.c ***/
  95876. /*** Start of inlined file: juce_FlacHeader.h ***/
  95877. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95878. // tasks..
  95879. #define VERSION "1.2.1"
  95880. #define FLAC__NO_DLL 1
  95881. #if JUCE_MSVC
  95882. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95883. #endif
  95884. #if JUCE_MAC
  95885. #define FLAC__SYS_DARWIN 1
  95886. #endif
  95887. /*** End of inlined file: juce_FlacHeader.h ***/
  95888. #if JUCE_USE_FLAC
  95889. #if HAVE_CONFIG_H
  95890. # include <config.h>
  95891. #endif
  95892. #include <math.h>
  95893. #include <string.h>
  95894. /*** Start of inlined file: fixed.h ***/
  95895. #ifndef FLAC__PRIVATE__FIXED_H
  95896. #define FLAC__PRIVATE__FIXED_H
  95897. #ifdef HAVE_CONFIG_H
  95898. #include <config.h>
  95899. #endif
  95900. /*** Start of inlined file: float.h ***/
  95901. #ifndef FLAC__PRIVATE__FLOAT_H
  95902. #define FLAC__PRIVATE__FLOAT_H
  95903. #ifdef HAVE_CONFIG_H
  95904. #include <config.h>
  95905. #endif
  95906. /*
  95907. * These typedefs make it easier to ensure that integer versions of
  95908. * the library really only contain integer operations. All the code
  95909. * in libFLAC should use FLAC__float and FLAC__double in place of
  95910. * float and double, and be protected by checks of the macro
  95911. * FLAC__INTEGER_ONLY_LIBRARY.
  95912. *
  95913. * FLAC__real is the basic floating point type used in LPC analysis.
  95914. */
  95915. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95916. typedef double FLAC__double;
  95917. typedef float FLAC__float;
  95918. /*
  95919. * WATCHOUT: changing FLAC__real will change the signatures of many
  95920. * functions that have assembly language equivalents and break them.
  95921. */
  95922. typedef float FLAC__real;
  95923. #else
  95924. /*
  95925. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95926. * for the integer part and lower 16 bits for the fractional part.
  95927. */
  95928. typedef FLAC__int32 FLAC__fixedpoint;
  95929. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95930. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95931. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95932. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95933. extern const FLAC__fixedpoint FLAC__FP_E;
  95934. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95935. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95936. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95937. /*
  95938. * FLAC__fixedpoint_log2()
  95939. * --------------------------------------------------------------------
  95940. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95941. * algorithm by Knuth for x >= 1.0
  95942. *
  95943. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95944. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95945. *
  95946. * 'precision' roughly limits the number of iterations that are done;
  95947. * use (unsigned)(-1) for maximum precision.
  95948. *
  95949. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95950. * function will punt and return 0.
  95951. *
  95952. * The return value will also have 'fracbits' fractional bits.
  95953. */
  95954. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95955. #endif
  95956. #endif
  95957. /*** End of inlined file: float.h ***/
  95958. /*** Start of inlined file: format.h ***/
  95959. #ifndef FLAC__PRIVATE__FORMAT_H
  95960. #define FLAC__PRIVATE__FORMAT_H
  95961. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95962. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95963. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95964. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95965. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95966. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95967. #endif
  95968. /*** End of inlined file: format.h ***/
  95969. /*
  95970. * FLAC__fixed_compute_best_predictor()
  95971. * --------------------------------------------------------------------
  95972. * Compute the best fixed predictor and the expected bits-per-sample
  95973. * of the residual signal for each order. The _wide() version uses
  95974. * 64-bit integers which is statistically necessary when bits-per-
  95975. * sample + log2(blocksize) > 30
  95976. *
  95977. * IN data[0,data_len-1]
  95978. * IN data_len
  95979. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95980. */
  95981. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95982. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95983. # ifndef FLAC__NO_ASM
  95984. # ifdef FLAC__CPU_IA32
  95985. # ifdef FLAC__HAS_NASM
  95986. 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]);
  95987. # endif
  95988. # endif
  95989. # endif
  95990. 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]);
  95991. #else
  95992. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95993. 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]);
  95994. #endif
  95995. /*
  95996. * FLAC__fixed_compute_residual()
  95997. * --------------------------------------------------------------------
  95998. * Compute the residual signal obtained from sutracting the predicted
  95999. * signal from the original.
  96000. *
  96001. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96002. * IN data_len length of original signal
  96003. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96004. * OUT residual[0,data_len-1] residual signal
  96005. */
  96006. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  96007. /*
  96008. * FLAC__fixed_restore_signal()
  96009. * --------------------------------------------------------------------
  96010. * Restore the original signal by summing the residual and the
  96011. * predictor.
  96012. *
  96013. * IN residual[0,data_len-1] residual signal
  96014. * IN data_len length of original signal
  96015. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96016. * *** IMPORTANT: the caller must pass in the historical samples:
  96017. * IN data[-order,-1] previously-reconstructed historical samples
  96018. * OUT data[0,data_len-1] original signal
  96019. */
  96020. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  96021. #endif
  96022. /*** End of inlined file: fixed.h ***/
  96023. #ifndef M_LN2
  96024. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96025. #define M_LN2 0.69314718055994530942
  96026. #endif
  96027. #ifdef min
  96028. #undef min
  96029. #endif
  96030. #define min(x,y) ((x) < (y)? (x) : (y))
  96031. #ifdef local_abs
  96032. #undef local_abs
  96033. #endif
  96034. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  96035. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96036. /* rbps stands for residual bits per sample
  96037. *
  96038. * (ln(2) * err)
  96039. * rbps = log (-----------)
  96040. * 2 ( n )
  96041. */
  96042. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  96043. {
  96044. FLAC__uint32 rbps;
  96045. unsigned bits; /* the number of bits required to represent a number */
  96046. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96047. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96048. FLAC__ASSERT(err > 0);
  96049. FLAC__ASSERT(n > 0);
  96050. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96051. if(err <= n)
  96052. return 0;
  96053. /*
  96054. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96055. * These allow us later to know we won't lose too much precision in the
  96056. * fixed-point division (err<<fracbits)/n.
  96057. */
  96058. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  96059. err <<= fracbits;
  96060. err /= n;
  96061. /* err now holds err/n with fracbits fractional bits */
  96062. /*
  96063. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96064. * our purposes.
  96065. */
  96066. FLAC__ASSERT(err > 0);
  96067. bits = FLAC__bitmath_ilog2(err)+1;
  96068. if(bits > 16) {
  96069. err >>= (bits-16);
  96070. fracbits -= (bits-16);
  96071. }
  96072. rbps = (FLAC__uint32)err;
  96073. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96074. rbps *= FLAC__FP_LN2;
  96075. fracbits += 16;
  96076. FLAC__ASSERT(fracbits >= 0);
  96077. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96078. {
  96079. const int f = fracbits & 3;
  96080. if(f) {
  96081. rbps >>= f;
  96082. fracbits -= f;
  96083. }
  96084. }
  96085. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96086. if(rbps == 0)
  96087. return 0;
  96088. /*
  96089. * The return value must have 16 fractional bits. Since the whole part
  96090. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96091. * must be >= -3, these assertion allows us to be able to shift rbps
  96092. * left if necessary to get 16 fracbits without losing any bits of the
  96093. * whole part of rbps.
  96094. *
  96095. * There is a slight chance due to accumulated error that the whole part
  96096. * will require 6 bits, so we use 6 in the assertion. Really though as
  96097. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96098. */
  96099. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96100. FLAC__ASSERT(fracbits >= -3);
  96101. /* now shift the decimal point into place */
  96102. if(fracbits < 16)
  96103. return rbps << (16-fracbits);
  96104. else if(fracbits > 16)
  96105. return rbps >> (fracbits-16);
  96106. else
  96107. return rbps;
  96108. }
  96109. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  96110. {
  96111. FLAC__uint32 rbps;
  96112. unsigned bits; /* the number of bits required to represent a number */
  96113. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96114. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96115. FLAC__ASSERT(err > 0);
  96116. FLAC__ASSERT(n > 0);
  96117. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96118. if(err <= n)
  96119. return 0;
  96120. /*
  96121. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96122. * These allow us later to know we won't lose too much precision in the
  96123. * fixed-point division (err<<fracbits)/n.
  96124. */
  96125. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  96126. err <<= fracbits;
  96127. err /= n;
  96128. /* err now holds err/n with fracbits fractional bits */
  96129. /*
  96130. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96131. * our purposes.
  96132. */
  96133. FLAC__ASSERT(err > 0);
  96134. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96135. if(bits > 16) {
  96136. err >>= (bits-16);
  96137. fracbits -= (bits-16);
  96138. }
  96139. rbps = (FLAC__uint32)err;
  96140. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96141. rbps *= FLAC__FP_LN2;
  96142. fracbits += 16;
  96143. FLAC__ASSERT(fracbits >= 0);
  96144. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96145. {
  96146. const int f = fracbits & 3;
  96147. if(f) {
  96148. rbps >>= f;
  96149. fracbits -= f;
  96150. }
  96151. }
  96152. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96153. if(rbps == 0)
  96154. return 0;
  96155. /*
  96156. * The return value must have 16 fractional bits. Since the whole part
  96157. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96158. * must be >= -3, these assertion allows us to be able to shift rbps
  96159. * left if necessary to get 16 fracbits without losing any bits of the
  96160. * whole part of rbps.
  96161. *
  96162. * There is a slight chance due to accumulated error that the whole part
  96163. * will require 6 bits, so we use 6 in the assertion. Really though as
  96164. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96165. */
  96166. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96167. FLAC__ASSERT(fracbits >= -3);
  96168. /* now shift the decimal point into place */
  96169. if(fracbits < 16)
  96170. return rbps << (16-fracbits);
  96171. else if(fracbits > 16)
  96172. return rbps >> (fracbits-16);
  96173. else
  96174. return rbps;
  96175. }
  96176. #endif
  96177. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96178. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96179. #else
  96180. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96181. #endif
  96182. {
  96183. FLAC__int32 last_error_0 = data[-1];
  96184. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96185. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96186. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96187. FLAC__int32 error, save;
  96188. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96189. unsigned i, order;
  96190. for(i = 0; i < data_len; i++) {
  96191. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96192. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96193. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96194. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96195. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96196. }
  96197. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96198. order = 0;
  96199. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96200. order = 1;
  96201. else if(total_error_2 < min(total_error_3, total_error_4))
  96202. order = 2;
  96203. else if(total_error_3 < total_error_4)
  96204. order = 3;
  96205. else
  96206. order = 4;
  96207. /* Estimate the expected number of bits per residual signal sample. */
  96208. /* 'total_error*' is linearly related to the variance of the residual */
  96209. /* signal, so we use it directly to compute E(|x|) */
  96210. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96211. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96212. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96213. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96214. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96215. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96216. 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);
  96217. 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);
  96218. 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);
  96219. 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);
  96220. 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);
  96221. #else
  96222. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96223. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96224. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96225. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96226. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96227. #endif
  96228. return order;
  96229. }
  96230. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96231. 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])
  96232. #else
  96233. 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])
  96234. #endif
  96235. {
  96236. FLAC__int32 last_error_0 = data[-1];
  96237. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96238. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96239. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96240. FLAC__int32 error, save;
  96241. /* total_error_* are 64-bits to avoid overflow when encoding
  96242. * erratic signals when the bits-per-sample and blocksize are
  96243. * large.
  96244. */
  96245. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96246. unsigned i, order;
  96247. for(i = 0; i < data_len; i++) {
  96248. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96249. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96250. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96251. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96252. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96253. }
  96254. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96255. order = 0;
  96256. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96257. order = 1;
  96258. else if(total_error_2 < min(total_error_3, total_error_4))
  96259. order = 2;
  96260. else if(total_error_3 < total_error_4)
  96261. order = 3;
  96262. else
  96263. order = 4;
  96264. /* Estimate the expected number of bits per residual signal sample. */
  96265. /* 'total_error*' is linearly related to the variance of the residual */
  96266. /* signal, so we use it directly to compute E(|x|) */
  96267. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96268. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96269. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96270. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96271. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96272. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96273. #if defined _MSC_VER || defined __MINGW32__
  96274. /* with MSVC you have to spoon feed it the casting */
  96275. 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);
  96276. 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);
  96277. 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);
  96278. 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);
  96279. 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);
  96280. #else
  96281. 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);
  96282. 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);
  96283. 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);
  96284. 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);
  96285. 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);
  96286. #endif
  96287. #else
  96288. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96289. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96290. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96291. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96292. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96293. #endif
  96294. return order;
  96295. }
  96296. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96297. {
  96298. const int idata_len = (int)data_len;
  96299. int i;
  96300. switch(order) {
  96301. case 0:
  96302. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96303. memcpy(residual, data, sizeof(residual[0])*data_len);
  96304. break;
  96305. case 1:
  96306. for(i = 0; i < idata_len; i++)
  96307. residual[i] = data[i] - data[i-1];
  96308. break;
  96309. case 2:
  96310. for(i = 0; i < idata_len; i++)
  96311. #if 1 /* OPT: may be faster with some compilers on some systems */
  96312. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96313. #else
  96314. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96315. #endif
  96316. break;
  96317. case 3:
  96318. for(i = 0; i < idata_len; i++)
  96319. #if 1 /* OPT: may be faster with some compilers on some systems */
  96320. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96321. #else
  96322. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96323. #endif
  96324. break;
  96325. case 4:
  96326. for(i = 0; i < idata_len; i++)
  96327. #if 1 /* OPT: may be faster with some compilers on some systems */
  96328. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96329. #else
  96330. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96331. #endif
  96332. break;
  96333. default:
  96334. FLAC__ASSERT(0);
  96335. }
  96336. }
  96337. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96338. {
  96339. int i, idata_len = (int)data_len;
  96340. switch(order) {
  96341. case 0:
  96342. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96343. memcpy(data, residual, sizeof(residual[0])*data_len);
  96344. break;
  96345. case 1:
  96346. for(i = 0; i < idata_len; i++)
  96347. data[i] = residual[i] + data[i-1];
  96348. break;
  96349. case 2:
  96350. for(i = 0; i < idata_len; i++)
  96351. #if 1 /* OPT: may be faster with some compilers on some systems */
  96352. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96353. #else
  96354. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96355. #endif
  96356. break;
  96357. case 3:
  96358. for(i = 0; i < idata_len; i++)
  96359. #if 1 /* OPT: may be faster with some compilers on some systems */
  96360. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96361. #else
  96362. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96363. #endif
  96364. break;
  96365. case 4:
  96366. for(i = 0; i < idata_len; i++)
  96367. #if 1 /* OPT: may be faster with some compilers on some systems */
  96368. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96369. #else
  96370. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96371. #endif
  96372. break;
  96373. default:
  96374. FLAC__ASSERT(0);
  96375. }
  96376. }
  96377. #endif
  96378. /*** End of inlined file: fixed.c ***/
  96379. /*** Start of inlined file: float.c ***/
  96380. /*** Start of inlined file: juce_FlacHeader.h ***/
  96381. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96382. // tasks..
  96383. #define VERSION "1.2.1"
  96384. #define FLAC__NO_DLL 1
  96385. #if JUCE_MSVC
  96386. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96387. #endif
  96388. #if JUCE_MAC
  96389. #define FLAC__SYS_DARWIN 1
  96390. #endif
  96391. /*** End of inlined file: juce_FlacHeader.h ***/
  96392. #if JUCE_USE_FLAC
  96393. #if HAVE_CONFIG_H
  96394. # include <config.h>
  96395. #endif
  96396. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96397. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96398. #ifdef _MSC_VER
  96399. #define FLAC__U64L(x) x
  96400. #else
  96401. #define FLAC__U64L(x) x##LLU
  96402. #endif
  96403. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96404. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96405. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96406. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96407. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96408. /* Lookup tables for Knuth's logarithm algorithm */
  96409. #define LOG2_LOOKUP_PRECISION 16
  96410. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96411. {
  96412. /*
  96413. * 0 fraction bits
  96414. */
  96415. /* undefined */ 0x00000000,
  96416. /* lg(2/1) = */ 0x00000001,
  96417. /* lg(4/3) = */ 0x00000000,
  96418. /* lg(8/7) = */ 0x00000000,
  96419. /* lg(16/15) = */ 0x00000000,
  96420. /* lg(32/31) = */ 0x00000000,
  96421. /* lg(64/63) = */ 0x00000000,
  96422. /* lg(128/127) = */ 0x00000000,
  96423. /* lg(256/255) = */ 0x00000000,
  96424. /* lg(512/511) = */ 0x00000000,
  96425. /* lg(1024/1023) = */ 0x00000000,
  96426. /* lg(2048/2047) = */ 0x00000000,
  96427. /* lg(4096/4095) = */ 0x00000000,
  96428. /* lg(8192/8191) = */ 0x00000000,
  96429. /* lg(16384/16383) = */ 0x00000000,
  96430. /* lg(32768/32767) = */ 0x00000000
  96431. },
  96432. {
  96433. /*
  96434. * 4 fraction bits
  96435. */
  96436. /* undefined */ 0x00000000,
  96437. /* lg(2/1) = */ 0x00000010,
  96438. /* lg(4/3) = */ 0x00000007,
  96439. /* lg(8/7) = */ 0x00000003,
  96440. /* lg(16/15) = */ 0x00000001,
  96441. /* lg(32/31) = */ 0x00000001,
  96442. /* lg(64/63) = */ 0x00000000,
  96443. /* lg(128/127) = */ 0x00000000,
  96444. /* lg(256/255) = */ 0x00000000,
  96445. /* lg(512/511) = */ 0x00000000,
  96446. /* lg(1024/1023) = */ 0x00000000,
  96447. /* lg(2048/2047) = */ 0x00000000,
  96448. /* lg(4096/4095) = */ 0x00000000,
  96449. /* lg(8192/8191) = */ 0x00000000,
  96450. /* lg(16384/16383) = */ 0x00000000,
  96451. /* lg(32768/32767) = */ 0x00000000
  96452. },
  96453. {
  96454. /*
  96455. * 8 fraction bits
  96456. */
  96457. /* undefined */ 0x00000000,
  96458. /* lg(2/1) = */ 0x00000100,
  96459. /* lg(4/3) = */ 0x0000006a,
  96460. /* lg(8/7) = */ 0x00000031,
  96461. /* lg(16/15) = */ 0x00000018,
  96462. /* lg(32/31) = */ 0x0000000c,
  96463. /* lg(64/63) = */ 0x00000006,
  96464. /* lg(128/127) = */ 0x00000003,
  96465. /* lg(256/255) = */ 0x00000001,
  96466. /* lg(512/511) = */ 0x00000001,
  96467. /* lg(1024/1023) = */ 0x00000000,
  96468. /* lg(2048/2047) = */ 0x00000000,
  96469. /* lg(4096/4095) = */ 0x00000000,
  96470. /* lg(8192/8191) = */ 0x00000000,
  96471. /* lg(16384/16383) = */ 0x00000000,
  96472. /* lg(32768/32767) = */ 0x00000000
  96473. },
  96474. {
  96475. /*
  96476. * 12 fraction bits
  96477. */
  96478. /* undefined */ 0x00000000,
  96479. /* lg(2/1) = */ 0x00001000,
  96480. /* lg(4/3) = */ 0x000006a4,
  96481. /* lg(8/7) = */ 0x00000315,
  96482. /* lg(16/15) = */ 0x0000017d,
  96483. /* lg(32/31) = */ 0x000000bc,
  96484. /* lg(64/63) = */ 0x0000005d,
  96485. /* lg(128/127) = */ 0x0000002e,
  96486. /* lg(256/255) = */ 0x00000017,
  96487. /* lg(512/511) = */ 0x0000000c,
  96488. /* lg(1024/1023) = */ 0x00000006,
  96489. /* lg(2048/2047) = */ 0x00000003,
  96490. /* lg(4096/4095) = */ 0x00000001,
  96491. /* lg(8192/8191) = */ 0x00000001,
  96492. /* lg(16384/16383) = */ 0x00000000,
  96493. /* lg(32768/32767) = */ 0x00000000
  96494. },
  96495. {
  96496. /*
  96497. * 16 fraction bits
  96498. */
  96499. /* undefined */ 0x00000000,
  96500. /* lg(2/1) = */ 0x00010000,
  96501. /* lg(4/3) = */ 0x00006a40,
  96502. /* lg(8/7) = */ 0x00003151,
  96503. /* lg(16/15) = */ 0x000017d6,
  96504. /* lg(32/31) = */ 0x00000bba,
  96505. /* lg(64/63) = */ 0x000005d1,
  96506. /* lg(128/127) = */ 0x000002e6,
  96507. /* lg(256/255) = */ 0x00000172,
  96508. /* lg(512/511) = */ 0x000000b9,
  96509. /* lg(1024/1023) = */ 0x0000005c,
  96510. /* lg(2048/2047) = */ 0x0000002e,
  96511. /* lg(4096/4095) = */ 0x00000017,
  96512. /* lg(8192/8191) = */ 0x0000000c,
  96513. /* lg(16384/16383) = */ 0x00000006,
  96514. /* lg(32768/32767) = */ 0x00000003
  96515. },
  96516. {
  96517. /*
  96518. * 20 fraction bits
  96519. */
  96520. /* undefined */ 0x00000000,
  96521. /* lg(2/1) = */ 0x00100000,
  96522. /* lg(4/3) = */ 0x0006a3fe,
  96523. /* lg(8/7) = */ 0x00031513,
  96524. /* lg(16/15) = */ 0x00017d60,
  96525. /* lg(32/31) = */ 0x0000bb9d,
  96526. /* lg(64/63) = */ 0x00005d10,
  96527. /* lg(128/127) = */ 0x00002e59,
  96528. /* lg(256/255) = */ 0x00001721,
  96529. /* lg(512/511) = */ 0x00000b8e,
  96530. /* lg(1024/1023) = */ 0x000005c6,
  96531. /* lg(2048/2047) = */ 0x000002e3,
  96532. /* lg(4096/4095) = */ 0x00000171,
  96533. /* lg(8192/8191) = */ 0x000000b9,
  96534. /* lg(16384/16383) = */ 0x0000005c,
  96535. /* lg(32768/32767) = */ 0x0000002e
  96536. },
  96537. {
  96538. /*
  96539. * 24 fraction bits
  96540. */
  96541. /* undefined */ 0x00000000,
  96542. /* lg(2/1) = */ 0x01000000,
  96543. /* lg(4/3) = */ 0x006a3fe6,
  96544. /* lg(8/7) = */ 0x00315130,
  96545. /* lg(16/15) = */ 0x0017d605,
  96546. /* lg(32/31) = */ 0x000bb9ca,
  96547. /* lg(64/63) = */ 0x0005d0fc,
  96548. /* lg(128/127) = */ 0x0002e58f,
  96549. /* lg(256/255) = */ 0x0001720e,
  96550. /* lg(512/511) = */ 0x0000b8d8,
  96551. /* lg(1024/1023) = */ 0x00005c61,
  96552. /* lg(2048/2047) = */ 0x00002e2d,
  96553. /* lg(4096/4095) = */ 0x00001716,
  96554. /* lg(8192/8191) = */ 0x00000b8b,
  96555. /* lg(16384/16383) = */ 0x000005c5,
  96556. /* lg(32768/32767) = */ 0x000002e3
  96557. },
  96558. {
  96559. /*
  96560. * 28 fraction bits
  96561. */
  96562. /* undefined */ 0x00000000,
  96563. /* lg(2/1) = */ 0x10000000,
  96564. /* lg(4/3) = */ 0x06a3fe5c,
  96565. /* lg(8/7) = */ 0x03151301,
  96566. /* lg(16/15) = */ 0x017d6049,
  96567. /* lg(32/31) = */ 0x00bb9ca6,
  96568. /* lg(64/63) = */ 0x005d0fba,
  96569. /* lg(128/127) = */ 0x002e58f7,
  96570. /* lg(256/255) = */ 0x001720da,
  96571. /* lg(512/511) = */ 0x000b8d87,
  96572. /* lg(1024/1023) = */ 0x0005c60b,
  96573. /* lg(2048/2047) = */ 0x0002e2d7,
  96574. /* lg(4096/4095) = */ 0x00017160,
  96575. /* lg(8192/8191) = */ 0x0000b8ad,
  96576. /* lg(16384/16383) = */ 0x00005c56,
  96577. /* lg(32768/32767) = */ 0x00002e2b
  96578. }
  96579. };
  96580. #if 0
  96581. static const FLAC__uint64 log2_lookup_wide[] = {
  96582. {
  96583. /*
  96584. * 32 fraction bits
  96585. */
  96586. /* undefined */ 0x00000000,
  96587. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96588. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96589. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96590. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96591. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96592. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96593. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96594. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96595. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96596. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96597. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96598. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96599. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96600. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96601. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96602. },
  96603. {
  96604. /*
  96605. * 48 fraction bits
  96606. */
  96607. /* undefined */ 0x00000000,
  96608. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96609. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96610. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96611. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96612. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96613. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96614. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96615. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96616. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96617. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96618. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96619. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96620. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96621. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96622. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96623. }
  96624. };
  96625. #endif
  96626. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96627. {
  96628. const FLAC__uint32 ONE = (1u << fracbits);
  96629. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96630. FLAC__ASSERT(fracbits < 32);
  96631. FLAC__ASSERT((fracbits & 0x3) == 0);
  96632. if(x < ONE)
  96633. return 0;
  96634. if(precision > LOG2_LOOKUP_PRECISION)
  96635. precision = LOG2_LOOKUP_PRECISION;
  96636. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96637. {
  96638. FLAC__uint32 y = 0;
  96639. FLAC__uint32 z = x >> 1, k = 1;
  96640. while (x > ONE && k < precision) {
  96641. if (x - z >= ONE) {
  96642. x -= z;
  96643. z = x >> k;
  96644. y += table[k];
  96645. }
  96646. else {
  96647. z >>= 1;
  96648. k++;
  96649. }
  96650. }
  96651. return y;
  96652. }
  96653. }
  96654. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96655. #endif
  96656. /*** End of inlined file: float.c ***/
  96657. /*** Start of inlined file: format.c ***/
  96658. /*** Start of inlined file: juce_FlacHeader.h ***/
  96659. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96660. // tasks..
  96661. #define VERSION "1.2.1"
  96662. #define FLAC__NO_DLL 1
  96663. #if JUCE_MSVC
  96664. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96665. #endif
  96666. #if JUCE_MAC
  96667. #define FLAC__SYS_DARWIN 1
  96668. #endif
  96669. /*** End of inlined file: juce_FlacHeader.h ***/
  96670. #if JUCE_USE_FLAC
  96671. #if HAVE_CONFIG_H
  96672. # include <config.h>
  96673. #endif
  96674. #include <stdio.h>
  96675. #include <stdlib.h> /* for qsort() */
  96676. #include <string.h> /* for memset() */
  96677. #ifndef FLaC__INLINE
  96678. #define FLaC__INLINE
  96679. #endif
  96680. #ifdef min
  96681. #undef min
  96682. #endif
  96683. #define min(a,b) ((a)<(b)?(a):(b))
  96684. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96685. #ifdef _MSC_VER
  96686. #define FLAC__U64L(x) x
  96687. #else
  96688. #define FLAC__U64L(x) x##LLU
  96689. #endif
  96690. /* VERSION should come from configure */
  96691. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96692. ;
  96693. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96694. /* yet one more hack because of MSVC6: */
  96695. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96696. #else
  96697. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96698. #endif
  96699. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96700. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96701. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96702. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96703. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96704. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96705. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96706. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96707. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96708. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96709. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96710. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96711. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96712. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96713. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96714. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96715. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96716. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96717. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96718. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96719. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96720. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96721. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96722. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96723. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96724. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96725. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96726. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96727. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96728. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96729. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96730. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96731. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96732. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96733. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96734. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96735. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96736. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96737. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96738. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96739. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96740. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96741. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96742. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96743. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96744. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96745. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96746. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96747. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96748. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96749. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96750. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96751. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96752. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96753. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96754. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96755. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96756. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96757. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96758. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96759. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96760. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96761. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96762. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96763. "PARTITIONED_RICE",
  96764. "PARTITIONED_RICE2"
  96765. };
  96766. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96767. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96768. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96769. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96770. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96771. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96772. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96773. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96774. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96775. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96776. "CONSTANT",
  96777. "VERBATIM",
  96778. "FIXED",
  96779. "LPC"
  96780. };
  96781. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96782. "INDEPENDENT",
  96783. "LEFT_SIDE",
  96784. "RIGHT_SIDE",
  96785. "MID_SIDE"
  96786. };
  96787. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96788. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96789. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96790. };
  96791. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96792. "STREAMINFO",
  96793. "PADDING",
  96794. "APPLICATION",
  96795. "SEEKTABLE",
  96796. "VORBIS_COMMENT",
  96797. "CUESHEET",
  96798. "PICTURE"
  96799. };
  96800. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96801. "Other",
  96802. "32x32 pixels 'file icon' (PNG only)",
  96803. "Other file icon",
  96804. "Cover (front)",
  96805. "Cover (back)",
  96806. "Leaflet page",
  96807. "Media (e.g. label side of CD)",
  96808. "Lead artist/lead performer/soloist",
  96809. "Artist/performer",
  96810. "Conductor",
  96811. "Band/Orchestra",
  96812. "Composer",
  96813. "Lyricist/text writer",
  96814. "Recording Location",
  96815. "During recording",
  96816. "During performance",
  96817. "Movie/video screen capture",
  96818. "A bright coloured fish",
  96819. "Illustration",
  96820. "Band/artist logotype",
  96821. "Publisher/Studio logotype"
  96822. };
  96823. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96824. {
  96825. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96826. return false;
  96827. }
  96828. else
  96829. return true;
  96830. }
  96831. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96832. {
  96833. if(
  96834. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96835. (
  96836. sample_rate >= (1u << 16) &&
  96837. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96838. )
  96839. ) {
  96840. return false;
  96841. }
  96842. else
  96843. return true;
  96844. }
  96845. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96846. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96847. {
  96848. unsigned i;
  96849. FLAC__uint64 prev_sample_number = 0;
  96850. FLAC__bool got_prev = false;
  96851. FLAC__ASSERT(0 != seek_table);
  96852. for(i = 0; i < seek_table->num_points; i++) {
  96853. if(got_prev) {
  96854. if(
  96855. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96856. seek_table->points[i].sample_number <= prev_sample_number
  96857. )
  96858. return false;
  96859. }
  96860. prev_sample_number = seek_table->points[i].sample_number;
  96861. got_prev = true;
  96862. }
  96863. return true;
  96864. }
  96865. /* used as the sort predicate for qsort() */
  96866. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96867. {
  96868. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96869. if(l->sample_number == r->sample_number)
  96870. return 0;
  96871. else if(l->sample_number < r->sample_number)
  96872. return -1;
  96873. else
  96874. return 1;
  96875. }
  96876. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96877. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96878. {
  96879. unsigned i, j;
  96880. FLAC__bool first;
  96881. FLAC__ASSERT(0 != seek_table);
  96882. /* sort the seekpoints */
  96883. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96884. /* uniquify the seekpoints */
  96885. first = true;
  96886. for(i = j = 0; i < seek_table->num_points; i++) {
  96887. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96888. if(!first) {
  96889. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96890. continue;
  96891. }
  96892. }
  96893. first = false;
  96894. seek_table->points[j++] = seek_table->points[i];
  96895. }
  96896. for(i = j; i < seek_table->num_points; i++) {
  96897. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96898. seek_table->points[i].stream_offset = 0;
  96899. seek_table->points[i].frame_samples = 0;
  96900. }
  96901. return j;
  96902. }
  96903. /*
  96904. * also disallows non-shortest-form encodings, c.f.
  96905. * http://www.unicode.org/versions/corrigendum1.html
  96906. * and a more clear explanation at the end of this section:
  96907. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96908. */
  96909. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96910. {
  96911. FLAC__ASSERT(0 != utf8);
  96912. if ((utf8[0] & 0x80) == 0) {
  96913. return 1;
  96914. }
  96915. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96916. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96917. return 0;
  96918. return 2;
  96919. }
  96920. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96921. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96922. return 0;
  96923. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96924. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96925. return 0;
  96926. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96927. return 0;
  96928. return 3;
  96929. }
  96930. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96931. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96932. return 0;
  96933. return 4;
  96934. }
  96935. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96936. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96937. return 0;
  96938. return 5;
  96939. }
  96940. 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) {
  96941. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96942. return 0;
  96943. return 6;
  96944. }
  96945. else {
  96946. return 0;
  96947. }
  96948. }
  96949. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96950. {
  96951. char c;
  96952. for(c = *name; c; c = *(++name))
  96953. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96954. return false;
  96955. return true;
  96956. }
  96957. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96958. {
  96959. if(length == (unsigned)(-1)) {
  96960. while(*value) {
  96961. unsigned n = utf8len_(value);
  96962. if(n == 0)
  96963. return false;
  96964. value += n;
  96965. }
  96966. }
  96967. else {
  96968. const FLAC__byte *end = value + length;
  96969. while(value < end) {
  96970. unsigned n = utf8len_(value);
  96971. if(n == 0)
  96972. return false;
  96973. value += n;
  96974. }
  96975. if(value != end)
  96976. return false;
  96977. }
  96978. return true;
  96979. }
  96980. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96981. {
  96982. const FLAC__byte *s, *end;
  96983. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96984. if(*s < 0x20 || *s > 0x7D)
  96985. return false;
  96986. }
  96987. if(s == end)
  96988. return false;
  96989. s++; /* skip '=' */
  96990. while(s < end) {
  96991. unsigned n = utf8len_(s);
  96992. if(n == 0)
  96993. return false;
  96994. s += n;
  96995. }
  96996. if(s != end)
  96997. return false;
  96998. return true;
  96999. }
  97000. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97001. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  97002. {
  97003. unsigned i, j;
  97004. if(check_cd_da_subset) {
  97005. if(cue_sheet->lead_in < 2 * 44100) {
  97006. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  97007. return false;
  97008. }
  97009. if(cue_sheet->lead_in % 588 != 0) {
  97010. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  97011. return false;
  97012. }
  97013. }
  97014. if(cue_sheet->num_tracks == 0) {
  97015. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  97016. return false;
  97017. }
  97018. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  97019. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  97020. return false;
  97021. }
  97022. for(i = 0; i < cue_sheet->num_tracks; i++) {
  97023. if(cue_sheet->tracks[i].number == 0) {
  97024. if(violation) *violation = "cue sheet may not have a track number 0";
  97025. return false;
  97026. }
  97027. if(check_cd_da_subset) {
  97028. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  97029. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  97030. return false;
  97031. }
  97032. }
  97033. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  97034. if(violation) {
  97035. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  97036. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  97037. else
  97038. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  97039. }
  97040. return false;
  97041. }
  97042. if(i < cue_sheet->num_tracks - 1) {
  97043. if(cue_sheet->tracks[i].num_indices == 0) {
  97044. if(violation) *violation = "cue sheet track must have at least one index point";
  97045. return false;
  97046. }
  97047. if(cue_sheet->tracks[i].indices[0].number > 1) {
  97048. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  97049. return false;
  97050. }
  97051. }
  97052. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  97053. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  97054. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  97055. return false;
  97056. }
  97057. if(j > 0) {
  97058. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  97059. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  97060. return false;
  97061. }
  97062. }
  97063. }
  97064. }
  97065. return true;
  97066. }
  97067. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97068. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  97069. {
  97070. char *p;
  97071. FLAC__byte *b;
  97072. for(p = picture->mime_type; *p; p++) {
  97073. if(*p < 0x20 || *p > 0x7e) {
  97074. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  97075. return false;
  97076. }
  97077. }
  97078. for(b = picture->description; *b; ) {
  97079. unsigned n = utf8len_(b);
  97080. if(n == 0) {
  97081. if(violation) *violation = "description string must be valid UTF-8";
  97082. return false;
  97083. }
  97084. b += n;
  97085. }
  97086. return true;
  97087. }
  97088. /*
  97089. * These routines are private to libFLAC
  97090. */
  97091. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  97092. {
  97093. return
  97094. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  97095. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  97096. blocksize,
  97097. predictor_order
  97098. );
  97099. }
  97100. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  97101. {
  97102. unsigned max_rice_partition_order = 0;
  97103. while(!(blocksize & 1)) {
  97104. max_rice_partition_order++;
  97105. blocksize >>= 1;
  97106. }
  97107. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  97108. }
  97109. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  97110. {
  97111. unsigned max_rice_partition_order = limit;
  97112. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  97113. max_rice_partition_order--;
  97114. FLAC__ASSERT(
  97115. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  97116. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  97117. );
  97118. return max_rice_partition_order;
  97119. }
  97120. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97121. {
  97122. FLAC__ASSERT(0 != object);
  97123. object->parameters = 0;
  97124. object->raw_bits = 0;
  97125. object->capacity_by_order = 0;
  97126. }
  97127. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97128. {
  97129. FLAC__ASSERT(0 != object);
  97130. if(0 != object->parameters)
  97131. free(object->parameters);
  97132. if(0 != object->raw_bits)
  97133. free(object->raw_bits);
  97134. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97135. }
  97136. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97137. {
  97138. FLAC__ASSERT(0 != object);
  97139. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97140. if(object->capacity_by_order < max_partition_order) {
  97141. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97142. return false;
  97143. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97144. return false;
  97145. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97146. object->capacity_by_order = max_partition_order;
  97147. }
  97148. return true;
  97149. }
  97150. #endif
  97151. /*** End of inlined file: format.c ***/
  97152. /*** Start of inlined file: lpc_flac.c ***/
  97153. /*** Start of inlined file: juce_FlacHeader.h ***/
  97154. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97155. // tasks..
  97156. #define VERSION "1.2.1"
  97157. #define FLAC__NO_DLL 1
  97158. #if JUCE_MSVC
  97159. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97160. #endif
  97161. #if JUCE_MAC
  97162. #define FLAC__SYS_DARWIN 1
  97163. #endif
  97164. /*** End of inlined file: juce_FlacHeader.h ***/
  97165. #if JUCE_USE_FLAC
  97166. #if HAVE_CONFIG_H
  97167. # include <config.h>
  97168. #endif
  97169. #include <math.h>
  97170. /*** Start of inlined file: lpc.h ***/
  97171. #ifndef FLAC__PRIVATE__LPC_H
  97172. #define FLAC__PRIVATE__LPC_H
  97173. #ifdef HAVE_CONFIG_H
  97174. #include <config.h>
  97175. #endif
  97176. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97177. /*
  97178. * FLAC__lpc_window_data()
  97179. * --------------------------------------------------------------------
  97180. * Applies the given window to the data.
  97181. * OPT: asm implementation
  97182. *
  97183. * IN in[0,data_len-1]
  97184. * IN window[0,data_len-1]
  97185. * OUT out[0,lag-1]
  97186. * IN data_len
  97187. */
  97188. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97189. /*
  97190. * FLAC__lpc_compute_autocorrelation()
  97191. * --------------------------------------------------------------------
  97192. * Compute the autocorrelation for lags between 0 and lag-1.
  97193. * Assumes data[] outside of [0,data_len-1] == 0.
  97194. * Asserts that lag > 0.
  97195. *
  97196. * IN data[0,data_len-1]
  97197. * IN data_len
  97198. * IN 0 < lag <= data_len
  97199. * OUT autoc[0,lag-1]
  97200. */
  97201. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97202. #ifndef FLAC__NO_ASM
  97203. # ifdef FLAC__CPU_IA32
  97204. # ifdef FLAC__HAS_NASM
  97205. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97206. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97207. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97208. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97209. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97210. # endif
  97211. # endif
  97212. #endif
  97213. /*
  97214. * FLAC__lpc_compute_lp_coefficients()
  97215. * --------------------------------------------------------------------
  97216. * Computes LP coefficients for orders 1..max_order.
  97217. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97218. * and there is no point in calculating a predictor.
  97219. *
  97220. * IN autoc[0,max_order] autocorrelation values
  97221. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97222. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97223. * *** IMPORTANT:
  97224. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97225. * OUT error[0,max_order-1] error for each order (more
  97226. * specifically, the variance of
  97227. * the error signal times # of
  97228. * samples in the signal)
  97229. *
  97230. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97231. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97232. * in lp_coeff[7][0,7], etc.
  97233. */
  97234. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97235. /*
  97236. * FLAC__lpc_quantize_coefficients()
  97237. * --------------------------------------------------------------------
  97238. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97239. * must be less than 32 (sizeof(FLAC__int32)*8).
  97240. *
  97241. * IN lp_coeff[0,order-1] LP coefficients
  97242. * IN order LP order
  97243. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97244. * desired precision (in bits, including sign
  97245. * bit) of largest coefficient
  97246. * OUT qlp_coeff[0,order-1] quantized coefficients
  97247. * OUT shift # of bits to shift right to get approximated
  97248. * LP coefficients. NOTE: could be negative.
  97249. * RETURN 0 => quantization OK
  97250. * 1 => coefficients require too much shifting for *shift to
  97251. * fit in the LPC subframe header. 'shift' is unset.
  97252. * 2 => coefficients are all zero, which is bad. 'shift' is
  97253. * unset.
  97254. */
  97255. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97256. /*
  97257. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97258. * --------------------------------------------------------------------
  97259. * Compute the residual signal obtained from sutracting the predicted
  97260. * signal from the original.
  97261. *
  97262. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97263. * IN data_len length of original signal
  97264. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97265. * IN order > 0 LP order
  97266. * IN lp_quantization quantization of LP coefficients in bits
  97267. * OUT residual[0,data_len-1] residual signal
  97268. */
  97269. 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[]);
  97270. 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[]);
  97271. #ifndef FLAC__NO_ASM
  97272. # ifdef FLAC__CPU_IA32
  97273. # ifdef FLAC__HAS_NASM
  97274. 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[]);
  97275. 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[]);
  97276. # endif
  97277. # endif
  97278. #endif
  97279. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97280. /*
  97281. * FLAC__lpc_restore_signal()
  97282. * --------------------------------------------------------------------
  97283. * Restore the original signal by summing the residual and the
  97284. * predictor.
  97285. *
  97286. * IN residual[0,data_len-1] residual signal
  97287. * IN data_len length of original signal
  97288. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97289. * IN order > 0 LP order
  97290. * IN lp_quantization quantization of LP coefficients in bits
  97291. * *** IMPORTANT: the caller must pass in the historical samples:
  97292. * IN data[-order,-1] previously-reconstructed historical samples
  97293. * OUT data[0,data_len-1] original signal
  97294. */
  97295. 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[]);
  97296. 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[]);
  97297. #ifndef FLAC__NO_ASM
  97298. # ifdef FLAC__CPU_IA32
  97299. # ifdef FLAC__HAS_NASM
  97300. 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[]);
  97301. 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[]);
  97302. # endif /* FLAC__HAS_NASM */
  97303. # elif defined FLAC__CPU_PPC
  97304. 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[]);
  97305. 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[]);
  97306. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97307. #endif /* FLAC__NO_ASM */
  97308. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97309. /*
  97310. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97311. * --------------------------------------------------------------------
  97312. * Compute the expected number of bits per residual signal sample
  97313. * based on the LP error (which is related to the residual variance).
  97314. *
  97315. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97316. * IN total_samples > 0 # of samples in residual signal
  97317. * RETURN expected bits per sample
  97318. */
  97319. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97320. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97321. /*
  97322. * FLAC__lpc_compute_best_order()
  97323. * --------------------------------------------------------------------
  97324. * Compute the best order from the array of signal errors returned
  97325. * during coefficient computation.
  97326. *
  97327. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97328. * IN max_order > 0 max LP order
  97329. * IN total_samples > 0 # of samples in residual signal
  97330. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97331. * (includes warmup sample size and quantized LP coefficient)
  97332. * RETURN [1,max_order] best order
  97333. */
  97334. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97335. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97336. #endif
  97337. /*** End of inlined file: lpc.h ***/
  97338. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97339. #include <stdio.h>
  97340. #endif
  97341. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97342. #ifndef M_LN2
  97343. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97344. #define M_LN2 0.69314718055994530942
  97345. #endif
  97346. /* OPT: #undef'ing this may improve the speed on some architectures */
  97347. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97348. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97349. {
  97350. unsigned i;
  97351. for(i = 0; i < data_len; i++)
  97352. out[i] = in[i] * window[i];
  97353. }
  97354. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97355. {
  97356. /* a readable, but slower, version */
  97357. #if 0
  97358. FLAC__real d;
  97359. unsigned i;
  97360. FLAC__ASSERT(lag > 0);
  97361. FLAC__ASSERT(lag <= data_len);
  97362. /*
  97363. * Technically we should subtract the mean first like so:
  97364. * for(i = 0; i < data_len; i++)
  97365. * data[i] -= mean;
  97366. * but it appears not to make enough of a difference to matter, and
  97367. * most signals are already closely centered around zero
  97368. */
  97369. while(lag--) {
  97370. for(i = lag, d = 0.0; i < data_len; i++)
  97371. d += data[i] * data[i - lag];
  97372. autoc[lag] = d;
  97373. }
  97374. #endif
  97375. /*
  97376. * this version tends to run faster because of better data locality
  97377. * ('data_len' is usually much larger than 'lag')
  97378. */
  97379. FLAC__real d;
  97380. unsigned sample, coeff;
  97381. const unsigned limit = data_len - lag;
  97382. FLAC__ASSERT(lag > 0);
  97383. FLAC__ASSERT(lag <= data_len);
  97384. for(coeff = 0; coeff < lag; coeff++)
  97385. autoc[coeff] = 0.0;
  97386. for(sample = 0; sample <= limit; sample++) {
  97387. d = data[sample];
  97388. for(coeff = 0; coeff < lag; coeff++)
  97389. autoc[coeff] += d * data[sample+coeff];
  97390. }
  97391. for(; sample < data_len; sample++) {
  97392. d = data[sample];
  97393. for(coeff = 0; coeff < data_len - sample; coeff++)
  97394. autoc[coeff] += d * data[sample+coeff];
  97395. }
  97396. }
  97397. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97398. {
  97399. unsigned i, j;
  97400. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97401. FLAC__ASSERT(0 != max_order);
  97402. FLAC__ASSERT(0 < *max_order);
  97403. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97404. FLAC__ASSERT(autoc[0] != 0.0);
  97405. err = autoc[0];
  97406. for(i = 0; i < *max_order; i++) {
  97407. /* Sum up this iteration's reflection coefficient. */
  97408. r = -autoc[i+1];
  97409. for(j = 0; j < i; j++)
  97410. r -= lpc[j] * autoc[i-j];
  97411. ref[i] = (r/=err);
  97412. /* Update LPC coefficients and total error. */
  97413. lpc[i]=r;
  97414. for(j = 0; j < (i>>1); j++) {
  97415. FLAC__double tmp = lpc[j];
  97416. lpc[j] += r * lpc[i-1-j];
  97417. lpc[i-1-j] += r * tmp;
  97418. }
  97419. if(i & 1)
  97420. lpc[j] += lpc[j] * r;
  97421. err *= (1.0 - r * r);
  97422. /* save this order */
  97423. for(j = 0; j <= i; j++)
  97424. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97425. error[i] = err;
  97426. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97427. if(err == 0.0) {
  97428. *max_order = i+1;
  97429. return;
  97430. }
  97431. }
  97432. }
  97433. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97434. {
  97435. unsigned i;
  97436. FLAC__double cmax;
  97437. FLAC__int32 qmax, qmin;
  97438. FLAC__ASSERT(precision > 0);
  97439. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97440. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97441. precision--;
  97442. qmax = 1 << precision;
  97443. qmin = -qmax;
  97444. qmax--;
  97445. /* calc cmax = max( |lp_coeff[i]| ) */
  97446. cmax = 0.0;
  97447. for(i = 0; i < order; i++) {
  97448. const FLAC__double d = fabs(lp_coeff[i]);
  97449. if(d > cmax)
  97450. cmax = d;
  97451. }
  97452. if(cmax <= 0.0) {
  97453. /* => coefficients are all 0, which means our constant-detect didn't work */
  97454. return 2;
  97455. }
  97456. else {
  97457. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97458. const int min_shiftlimit = -max_shiftlimit - 1;
  97459. int log2cmax;
  97460. (void)frexp(cmax, &log2cmax);
  97461. log2cmax--;
  97462. *shift = (int)precision - log2cmax - 1;
  97463. if(*shift > max_shiftlimit)
  97464. *shift = max_shiftlimit;
  97465. else if(*shift < min_shiftlimit)
  97466. return 1;
  97467. }
  97468. if(*shift >= 0) {
  97469. FLAC__double error = 0.0;
  97470. FLAC__int32 q;
  97471. for(i = 0; i < order; i++) {
  97472. error += lp_coeff[i] * (1 << *shift);
  97473. #if 1 /* unfortunately lround() is C99 */
  97474. if(error >= 0.0)
  97475. q = (FLAC__int32)(error + 0.5);
  97476. else
  97477. q = (FLAC__int32)(error - 0.5);
  97478. #else
  97479. q = lround(error);
  97480. #endif
  97481. #ifdef FLAC__OVERFLOW_DETECT
  97482. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97483. 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]);
  97484. else if(q < qmin)
  97485. 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]);
  97486. #endif
  97487. if(q > qmax)
  97488. q = qmax;
  97489. else if(q < qmin)
  97490. q = qmin;
  97491. error -= q;
  97492. qlp_coeff[i] = q;
  97493. }
  97494. }
  97495. /* negative shift is very rare but due to design flaw, negative shift is
  97496. * a NOP in the decoder, so it must be handled specially by scaling down
  97497. * coeffs
  97498. */
  97499. else {
  97500. const int nshift = -(*shift);
  97501. FLAC__double error = 0.0;
  97502. FLAC__int32 q;
  97503. #ifdef DEBUG
  97504. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97505. #endif
  97506. for(i = 0; i < order; i++) {
  97507. error += lp_coeff[i] / (1 << nshift);
  97508. #if 1 /* unfortunately lround() is C99 */
  97509. if(error >= 0.0)
  97510. q = (FLAC__int32)(error + 0.5);
  97511. else
  97512. q = (FLAC__int32)(error - 0.5);
  97513. #else
  97514. q = lround(error);
  97515. #endif
  97516. #ifdef FLAC__OVERFLOW_DETECT
  97517. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97518. 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]);
  97519. else if(q < qmin)
  97520. 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]);
  97521. #endif
  97522. if(q > qmax)
  97523. q = qmax;
  97524. else if(q < qmin)
  97525. q = qmin;
  97526. error -= q;
  97527. qlp_coeff[i] = q;
  97528. }
  97529. *shift = 0;
  97530. }
  97531. return 0;
  97532. }
  97533. 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[])
  97534. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97535. {
  97536. FLAC__int64 sumo;
  97537. unsigned i, j;
  97538. FLAC__int32 sum;
  97539. const FLAC__int32 *history;
  97540. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97541. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97542. for(i=0;i<order;i++)
  97543. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97544. fprintf(stderr,"\n");
  97545. #endif
  97546. FLAC__ASSERT(order > 0);
  97547. for(i = 0; i < data_len; i++) {
  97548. sumo = 0;
  97549. sum = 0;
  97550. history = data;
  97551. for(j = 0; j < order; j++) {
  97552. sum += qlp_coeff[j] * (*(--history));
  97553. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97554. #if defined _MSC_VER
  97555. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97556. 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);
  97557. #else
  97558. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97559. 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);
  97560. #endif
  97561. }
  97562. *(residual++) = *(data++) - (sum >> lp_quantization);
  97563. }
  97564. /* Here's a slower but clearer version:
  97565. for(i = 0; i < data_len; i++) {
  97566. sum = 0;
  97567. for(j = 0; j < order; j++)
  97568. sum += qlp_coeff[j] * data[i-j-1];
  97569. residual[i] = data[i] - (sum >> lp_quantization);
  97570. }
  97571. */
  97572. }
  97573. #else /* fully unrolled version for normal use */
  97574. {
  97575. int i;
  97576. FLAC__int32 sum;
  97577. FLAC__ASSERT(order > 0);
  97578. FLAC__ASSERT(order <= 32);
  97579. /*
  97580. * We do unique versions up to 12th order since that's the subset limit.
  97581. * Also they are roughly ordered to match frequency of occurrence to
  97582. * minimize branching.
  97583. */
  97584. if(order <= 12) {
  97585. if(order > 8) {
  97586. if(order > 10) {
  97587. if(order == 12) {
  97588. for(i = 0; i < (int)data_len; i++) {
  97589. sum = 0;
  97590. sum += qlp_coeff[11] * data[i-12];
  97591. sum += qlp_coeff[10] * data[i-11];
  97592. sum += qlp_coeff[9] * data[i-10];
  97593. sum += qlp_coeff[8] * data[i-9];
  97594. sum += qlp_coeff[7] * data[i-8];
  97595. sum += qlp_coeff[6] * data[i-7];
  97596. sum += qlp_coeff[5] * data[i-6];
  97597. sum += qlp_coeff[4] * data[i-5];
  97598. sum += qlp_coeff[3] * data[i-4];
  97599. sum += qlp_coeff[2] * data[i-3];
  97600. sum += qlp_coeff[1] * data[i-2];
  97601. sum += qlp_coeff[0] * data[i-1];
  97602. residual[i] = data[i] - (sum >> lp_quantization);
  97603. }
  97604. }
  97605. else { /* order == 11 */
  97606. for(i = 0; i < (int)data_len; i++) {
  97607. sum = 0;
  97608. sum += qlp_coeff[10] * data[i-11];
  97609. sum += qlp_coeff[9] * data[i-10];
  97610. sum += qlp_coeff[8] * data[i-9];
  97611. sum += qlp_coeff[7] * data[i-8];
  97612. sum += qlp_coeff[6] * data[i-7];
  97613. sum += qlp_coeff[5] * data[i-6];
  97614. sum += qlp_coeff[4] * data[i-5];
  97615. sum += qlp_coeff[3] * data[i-4];
  97616. sum += qlp_coeff[2] * data[i-3];
  97617. sum += qlp_coeff[1] * data[i-2];
  97618. sum += qlp_coeff[0] * data[i-1];
  97619. residual[i] = data[i] - (sum >> lp_quantization);
  97620. }
  97621. }
  97622. }
  97623. else {
  97624. if(order == 10) {
  97625. for(i = 0; i < (int)data_len; i++) {
  97626. sum = 0;
  97627. sum += qlp_coeff[9] * data[i-10];
  97628. sum += qlp_coeff[8] * data[i-9];
  97629. sum += qlp_coeff[7] * data[i-8];
  97630. sum += qlp_coeff[6] * data[i-7];
  97631. sum += qlp_coeff[5] * data[i-6];
  97632. sum += qlp_coeff[4] * data[i-5];
  97633. sum += qlp_coeff[3] * data[i-4];
  97634. sum += qlp_coeff[2] * data[i-3];
  97635. sum += qlp_coeff[1] * data[i-2];
  97636. sum += qlp_coeff[0] * data[i-1];
  97637. residual[i] = data[i] - (sum >> lp_quantization);
  97638. }
  97639. }
  97640. else { /* order == 9 */
  97641. for(i = 0; i < (int)data_len; i++) {
  97642. sum = 0;
  97643. sum += qlp_coeff[8] * data[i-9];
  97644. sum += qlp_coeff[7] * data[i-8];
  97645. sum += qlp_coeff[6] * data[i-7];
  97646. sum += qlp_coeff[5] * data[i-6];
  97647. sum += qlp_coeff[4] * data[i-5];
  97648. sum += qlp_coeff[3] * data[i-4];
  97649. sum += qlp_coeff[2] * data[i-3];
  97650. sum += qlp_coeff[1] * data[i-2];
  97651. sum += qlp_coeff[0] * data[i-1];
  97652. residual[i] = data[i] - (sum >> lp_quantization);
  97653. }
  97654. }
  97655. }
  97656. }
  97657. else if(order > 4) {
  97658. if(order > 6) {
  97659. if(order == 8) {
  97660. for(i = 0; i < (int)data_len; i++) {
  97661. sum = 0;
  97662. sum += qlp_coeff[7] * data[i-8];
  97663. sum += qlp_coeff[6] * data[i-7];
  97664. sum += qlp_coeff[5] * data[i-6];
  97665. sum += qlp_coeff[4] * data[i-5];
  97666. sum += qlp_coeff[3] * data[i-4];
  97667. sum += qlp_coeff[2] * data[i-3];
  97668. sum += qlp_coeff[1] * data[i-2];
  97669. sum += qlp_coeff[0] * data[i-1];
  97670. residual[i] = data[i] - (sum >> lp_quantization);
  97671. }
  97672. }
  97673. else { /* order == 7 */
  97674. for(i = 0; i < (int)data_len; i++) {
  97675. sum = 0;
  97676. sum += qlp_coeff[6] * data[i-7];
  97677. sum += qlp_coeff[5] * data[i-6];
  97678. sum += qlp_coeff[4] * data[i-5];
  97679. sum += qlp_coeff[3] * data[i-4];
  97680. sum += qlp_coeff[2] * data[i-3];
  97681. sum += qlp_coeff[1] * data[i-2];
  97682. sum += qlp_coeff[0] * data[i-1];
  97683. residual[i] = data[i] - (sum >> lp_quantization);
  97684. }
  97685. }
  97686. }
  97687. else {
  97688. if(order == 6) {
  97689. for(i = 0; i < (int)data_len; i++) {
  97690. sum = 0;
  97691. sum += qlp_coeff[5] * data[i-6];
  97692. sum += qlp_coeff[4] * data[i-5];
  97693. sum += qlp_coeff[3] * data[i-4];
  97694. sum += qlp_coeff[2] * data[i-3];
  97695. sum += qlp_coeff[1] * data[i-2];
  97696. sum += qlp_coeff[0] * data[i-1];
  97697. residual[i] = data[i] - (sum >> lp_quantization);
  97698. }
  97699. }
  97700. else { /* order == 5 */
  97701. for(i = 0; i < (int)data_len; i++) {
  97702. sum = 0;
  97703. sum += qlp_coeff[4] * data[i-5];
  97704. sum += qlp_coeff[3] * data[i-4];
  97705. sum += qlp_coeff[2] * data[i-3];
  97706. sum += qlp_coeff[1] * data[i-2];
  97707. sum += qlp_coeff[0] * data[i-1];
  97708. residual[i] = data[i] - (sum >> lp_quantization);
  97709. }
  97710. }
  97711. }
  97712. }
  97713. else {
  97714. if(order > 2) {
  97715. if(order == 4) {
  97716. for(i = 0; i < (int)data_len; i++) {
  97717. sum = 0;
  97718. sum += qlp_coeff[3] * data[i-4];
  97719. sum += qlp_coeff[2] * data[i-3];
  97720. sum += qlp_coeff[1] * data[i-2];
  97721. sum += qlp_coeff[0] * data[i-1];
  97722. residual[i] = data[i] - (sum >> lp_quantization);
  97723. }
  97724. }
  97725. else { /* order == 3 */
  97726. for(i = 0; i < (int)data_len; i++) {
  97727. sum = 0;
  97728. sum += qlp_coeff[2] * data[i-3];
  97729. sum += qlp_coeff[1] * data[i-2];
  97730. sum += qlp_coeff[0] * data[i-1];
  97731. residual[i] = data[i] - (sum >> lp_quantization);
  97732. }
  97733. }
  97734. }
  97735. else {
  97736. if(order == 2) {
  97737. for(i = 0; i < (int)data_len; i++) {
  97738. sum = 0;
  97739. sum += qlp_coeff[1] * data[i-2];
  97740. sum += qlp_coeff[0] * data[i-1];
  97741. residual[i] = data[i] - (sum >> lp_quantization);
  97742. }
  97743. }
  97744. else { /* order == 1 */
  97745. for(i = 0; i < (int)data_len; i++)
  97746. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97747. }
  97748. }
  97749. }
  97750. }
  97751. else { /* order > 12 */
  97752. for(i = 0; i < (int)data_len; i++) {
  97753. sum = 0;
  97754. switch(order) {
  97755. case 32: sum += qlp_coeff[31] * data[i-32];
  97756. case 31: sum += qlp_coeff[30] * data[i-31];
  97757. case 30: sum += qlp_coeff[29] * data[i-30];
  97758. case 29: sum += qlp_coeff[28] * data[i-29];
  97759. case 28: sum += qlp_coeff[27] * data[i-28];
  97760. case 27: sum += qlp_coeff[26] * data[i-27];
  97761. case 26: sum += qlp_coeff[25] * data[i-26];
  97762. case 25: sum += qlp_coeff[24] * data[i-25];
  97763. case 24: sum += qlp_coeff[23] * data[i-24];
  97764. case 23: sum += qlp_coeff[22] * data[i-23];
  97765. case 22: sum += qlp_coeff[21] * data[i-22];
  97766. case 21: sum += qlp_coeff[20] * data[i-21];
  97767. case 20: sum += qlp_coeff[19] * data[i-20];
  97768. case 19: sum += qlp_coeff[18] * data[i-19];
  97769. case 18: sum += qlp_coeff[17] * data[i-18];
  97770. case 17: sum += qlp_coeff[16] * data[i-17];
  97771. case 16: sum += qlp_coeff[15] * data[i-16];
  97772. case 15: sum += qlp_coeff[14] * data[i-15];
  97773. case 14: sum += qlp_coeff[13] * data[i-14];
  97774. case 13: sum += qlp_coeff[12] * data[i-13];
  97775. sum += qlp_coeff[11] * data[i-12];
  97776. sum += qlp_coeff[10] * data[i-11];
  97777. sum += qlp_coeff[ 9] * data[i-10];
  97778. sum += qlp_coeff[ 8] * data[i- 9];
  97779. sum += qlp_coeff[ 7] * data[i- 8];
  97780. sum += qlp_coeff[ 6] * data[i- 7];
  97781. sum += qlp_coeff[ 5] * data[i- 6];
  97782. sum += qlp_coeff[ 4] * data[i- 5];
  97783. sum += qlp_coeff[ 3] * data[i- 4];
  97784. sum += qlp_coeff[ 2] * data[i- 3];
  97785. sum += qlp_coeff[ 1] * data[i- 2];
  97786. sum += qlp_coeff[ 0] * data[i- 1];
  97787. }
  97788. residual[i] = data[i] - (sum >> lp_quantization);
  97789. }
  97790. }
  97791. }
  97792. #endif
  97793. 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[])
  97794. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97795. {
  97796. unsigned i, j;
  97797. FLAC__int64 sum;
  97798. const FLAC__int32 *history;
  97799. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97800. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97801. for(i=0;i<order;i++)
  97802. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97803. fprintf(stderr,"\n");
  97804. #endif
  97805. FLAC__ASSERT(order > 0);
  97806. for(i = 0; i < data_len; i++) {
  97807. sum = 0;
  97808. history = data;
  97809. for(j = 0; j < order; j++)
  97810. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97811. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97812. #if defined _MSC_VER
  97813. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97814. #else
  97815. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97816. #endif
  97817. break;
  97818. }
  97819. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97820. #if defined _MSC_VER
  97821. 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));
  97822. #else
  97823. 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)));
  97824. #endif
  97825. break;
  97826. }
  97827. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97828. }
  97829. }
  97830. #else /* fully unrolled version for normal use */
  97831. {
  97832. int i;
  97833. FLAC__int64 sum;
  97834. FLAC__ASSERT(order > 0);
  97835. FLAC__ASSERT(order <= 32);
  97836. /*
  97837. * We do unique versions up to 12th order since that's the subset limit.
  97838. * Also they are roughly ordered to match frequency of occurrence to
  97839. * minimize branching.
  97840. */
  97841. if(order <= 12) {
  97842. if(order > 8) {
  97843. if(order > 10) {
  97844. if(order == 12) {
  97845. for(i = 0; i < (int)data_len; i++) {
  97846. sum = 0;
  97847. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97848. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97849. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97850. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97851. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97852. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97853. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97854. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97855. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97856. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97857. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97858. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97859. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97860. }
  97861. }
  97862. else { /* order == 11 */
  97863. for(i = 0; i < (int)data_len; i++) {
  97864. sum = 0;
  97865. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97866. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97867. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97868. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97869. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97870. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97871. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97872. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97873. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97874. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97875. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97876. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97877. }
  97878. }
  97879. }
  97880. else {
  97881. if(order == 10) {
  97882. for(i = 0; i < (int)data_len; i++) {
  97883. sum = 0;
  97884. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97885. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97886. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97887. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97888. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97889. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97890. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97891. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97892. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97893. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97894. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97895. }
  97896. }
  97897. else { /* order == 9 */
  97898. for(i = 0; i < (int)data_len; i++) {
  97899. sum = 0;
  97900. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97901. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97902. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97903. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97904. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97905. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97906. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97907. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97908. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97909. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97910. }
  97911. }
  97912. }
  97913. }
  97914. else if(order > 4) {
  97915. if(order > 6) {
  97916. if(order == 8) {
  97917. for(i = 0; i < (int)data_len; i++) {
  97918. sum = 0;
  97919. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97920. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97921. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97922. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97923. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97924. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97925. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97926. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97927. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97928. }
  97929. }
  97930. else { /* order == 7 */
  97931. for(i = 0; i < (int)data_len; i++) {
  97932. sum = 0;
  97933. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97934. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97935. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97936. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97937. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97938. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97939. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97940. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97941. }
  97942. }
  97943. }
  97944. else {
  97945. if(order == 6) {
  97946. for(i = 0; i < (int)data_len; i++) {
  97947. sum = 0;
  97948. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97949. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97950. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97951. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97952. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97953. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97954. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97955. }
  97956. }
  97957. else { /* order == 5 */
  97958. for(i = 0; i < (int)data_len; i++) {
  97959. sum = 0;
  97960. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97961. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97962. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97963. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97964. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97965. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97966. }
  97967. }
  97968. }
  97969. }
  97970. else {
  97971. if(order > 2) {
  97972. if(order == 4) {
  97973. for(i = 0; i < (int)data_len; i++) {
  97974. sum = 0;
  97975. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97976. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97977. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97978. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97979. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97980. }
  97981. }
  97982. else { /* order == 3 */
  97983. for(i = 0; i < (int)data_len; i++) {
  97984. sum = 0;
  97985. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97986. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97987. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97988. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97989. }
  97990. }
  97991. }
  97992. else {
  97993. if(order == 2) {
  97994. for(i = 0; i < (int)data_len; i++) {
  97995. sum = 0;
  97996. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97997. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97998. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97999. }
  98000. }
  98001. else { /* order == 1 */
  98002. for(i = 0; i < (int)data_len; i++)
  98003. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98004. }
  98005. }
  98006. }
  98007. }
  98008. else { /* order > 12 */
  98009. for(i = 0; i < (int)data_len; i++) {
  98010. sum = 0;
  98011. switch(order) {
  98012. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98013. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98014. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98015. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98016. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98017. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98018. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98019. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98020. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98021. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98022. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98023. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98024. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98025. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98026. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98027. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98028. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98029. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98030. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98031. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98032. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98033. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98034. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98035. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98036. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98037. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98038. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98039. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98040. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98041. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98042. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98043. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98044. }
  98045. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98046. }
  98047. }
  98048. }
  98049. #endif
  98050. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98051. 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[])
  98052. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98053. {
  98054. FLAC__int64 sumo;
  98055. unsigned i, j;
  98056. FLAC__int32 sum;
  98057. const FLAC__int32 *r = residual, *history;
  98058. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98059. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98060. for(i=0;i<order;i++)
  98061. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98062. fprintf(stderr,"\n");
  98063. #endif
  98064. FLAC__ASSERT(order > 0);
  98065. for(i = 0; i < data_len; i++) {
  98066. sumo = 0;
  98067. sum = 0;
  98068. history = data;
  98069. for(j = 0; j < order; j++) {
  98070. sum += qlp_coeff[j] * (*(--history));
  98071. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  98072. #if defined _MSC_VER
  98073. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  98074. 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);
  98075. #else
  98076. if(sumo > 2147483647ll || sumo < -2147483648ll)
  98077. 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);
  98078. #endif
  98079. }
  98080. *(data++) = *(r++) + (sum >> lp_quantization);
  98081. }
  98082. /* Here's a slower but clearer version:
  98083. for(i = 0; i < data_len; i++) {
  98084. sum = 0;
  98085. for(j = 0; j < order; j++)
  98086. sum += qlp_coeff[j] * data[i-j-1];
  98087. data[i] = residual[i] + (sum >> lp_quantization);
  98088. }
  98089. */
  98090. }
  98091. #else /* fully unrolled version for normal use */
  98092. {
  98093. int i;
  98094. FLAC__int32 sum;
  98095. FLAC__ASSERT(order > 0);
  98096. FLAC__ASSERT(order <= 32);
  98097. /*
  98098. * We do unique versions up to 12th order since that's the subset limit.
  98099. * Also they are roughly ordered to match frequency of occurrence to
  98100. * minimize branching.
  98101. */
  98102. if(order <= 12) {
  98103. if(order > 8) {
  98104. if(order > 10) {
  98105. if(order == 12) {
  98106. for(i = 0; i < (int)data_len; i++) {
  98107. sum = 0;
  98108. sum += qlp_coeff[11] * data[i-12];
  98109. sum += qlp_coeff[10] * data[i-11];
  98110. sum += qlp_coeff[9] * data[i-10];
  98111. sum += qlp_coeff[8] * data[i-9];
  98112. sum += qlp_coeff[7] * data[i-8];
  98113. sum += qlp_coeff[6] * data[i-7];
  98114. sum += qlp_coeff[5] * data[i-6];
  98115. sum += qlp_coeff[4] * data[i-5];
  98116. sum += qlp_coeff[3] * data[i-4];
  98117. sum += qlp_coeff[2] * data[i-3];
  98118. sum += qlp_coeff[1] * data[i-2];
  98119. sum += qlp_coeff[0] * data[i-1];
  98120. data[i] = residual[i] + (sum >> lp_quantization);
  98121. }
  98122. }
  98123. else { /* order == 11 */
  98124. for(i = 0; i < (int)data_len; i++) {
  98125. sum = 0;
  98126. sum += qlp_coeff[10] * data[i-11];
  98127. sum += qlp_coeff[9] * data[i-10];
  98128. sum += qlp_coeff[8] * data[i-9];
  98129. sum += qlp_coeff[7] * data[i-8];
  98130. sum += qlp_coeff[6] * data[i-7];
  98131. sum += qlp_coeff[5] * data[i-6];
  98132. sum += qlp_coeff[4] * data[i-5];
  98133. sum += qlp_coeff[3] * data[i-4];
  98134. sum += qlp_coeff[2] * data[i-3];
  98135. sum += qlp_coeff[1] * data[i-2];
  98136. sum += qlp_coeff[0] * data[i-1];
  98137. data[i] = residual[i] + (sum >> lp_quantization);
  98138. }
  98139. }
  98140. }
  98141. else {
  98142. if(order == 10) {
  98143. for(i = 0; i < (int)data_len; i++) {
  98144. sum = 0;
  98145. sum += qlp_coeff[9] * data[i-10];
  98146. sum += qlp_coeff[8] * data[i-9];
  98147. sum += qlp_coeff[7] * data[i-8];
  98148. sum += qlp_coeff[6] * data[i-7];
  98149. sum += qlp_coeff[5] * data[i-6];
  98150. sum += qlp_coeff[4] * data[i-5];
  98151. sum += qlp_coeff[3] * data[i-4];
  98152. sum += qlp_coeff[2] * data[i-3];
  98153. sum += qlp_coeff[1] * data[i-2];
  98154. sum += qlp_coeff[0] * data[i-1];
  98155. data[i] = residual[i] + (sum >> lp_quantization);
  98156. }
  98157. }
  98158. else { /* order == 9 */
  98159. for(i = 0; i < (int)data_len; i++) {
  98160. sum = 0;
  98161. sum += qlp_coeff[8] * data[i-9];
  98162. sum += qlp_coeff[7] * data[i-8];
  98163. sum += qlp_coeff[6] * data[i-7];
  98164. sum += qlp_coeff[5] * data[i-6];
  98165. sum += qlp_coeff[4] * data[i-5];
  98166. sum += qlp_coeff[3] * data[i-4];
  98167. sum += qlp_coeff[2] * data[i-3];
  98168. sum += qlp_coeff[1] * data[i-2];
  98169. sum += qlp_coeff[0] * data[i-1];
  98170. data[i] = residual[i] + (sum >> lp_quantization);
  98171. }
  98172. }
  98173. }
  98174. }
  98175. else if(order > 4) {
  98176. if(order > 6) {
  98177. if(order == 8) {
  98178. for(i = 0; i < (int)data_len; i++) {
  98179. sum = 0;
  98180. sum += qlp_coeff[7] * data[i-8];
  98181. sum += qlp_coeff[6] * data[i-7];
  98182. sum += qlp_coeff[5] * data[i-6];
  98183. sum += qlp_coeff[4] * data[i-5];
  98184. sum += qlp_coeff[3] * data[i-4];
  98185. sum += qlp_coeff[2] * data[i-3];
  98186. sum += qlp_coeff[1] * data[i-2];
  98187. sum += qlp_coeff[0] * data[i-1];
  98188. data[i] = residual[i] + (sum >> lp_quantization);
  98189. }
  98190. }
  98191. else { /* order == 7 */
  98192. for(i = 0; i < (int)data_len; i++) {
  98193. sum = 0;
  98194. sum += qlp_coeff[6] * data[i-7];
  98195. sum += qlp_coeff[5] * data[i-6];
  98196. sum += qlp_coeff[4] * data[i-5];
  98197. sum += qlp_coeff[3] * data[i-4];
  98198. sum += qlp_coeff[2] * data[i-3];
  98199. sum += qlp_coeff[1] * data[i-2];
  98200. sum += qlp_coeff[0] * data[i-1];
  98201. data[i] = residual[i] + (sum >> lp_quantization);
  98202. }
  98203. }
  98204. }
  98205. else {
  98206. if(order == 6) {
  98207. for(i = 0; i < (int)data_len; i++) {
  98208. sum = 0;
  98209. sum += qlp_coeff[5] * data[i-6];
  98210. sum += qlp_coeff[4] * data[i-5];
  98211. sum += qlp_coeff[3] * data[i-4];
  98212. sum += qlp_coeff[2] * data[i-3];
  98213. sum += qlp_coeff[1] * data[i-2];
  98214. sum += qlp_coeff[0] * data[i-1];
  98215. data[i] = residual[i] + (sum >> lp_quantization);
  98216. }
  98217. }
  98218. else { /* order == 5 */
  98219. for(i = 0; i < (int)data_len; i++) {
  98220. sum = 0;
  98221. sum += qlp_coeff[4] * data[i-5];
  98222. sum += qlp_coeff[3] * data[i-4];
  98223. sum += qlp_coeff[2] * data[i-3];
  98224. sum += qlp_coeff[1] * data[i-2];
  98225. sum += qlp_coeff[0] * data[i-1];
  98226. data[i] = residual[i] + (sum >> lp_quantization);
  98227. }
  98228. }
  98229. }
  98230. }
  98231. else {
  98232. if(order > 2) {
  98233. if(order == 4) {
  98234. for(i = 0; i < (int)data_len; i++) {
  98235. sum = 0;
  98236. sum += qlp_coeff[3] * data[i-4];
  98237. sum += qlp_coeff[2] * data[i-3];
  98238. sum += qlp_coeff[1] * data[i-2];
  98239. sum += qlp_coeff[0] * data[i-1];
  98240. data[i] = residual[i] + (sum >> lp_quantization);
  98241. }
  98242. }
  98243. else { /* order == 3 */
  98244. for(i = 0; i < (int)data_len; i++) {
  98245. sum = 0;
  98246. sum += qlp_coeff[2] * data[i-3];
  98247. sum += qlp_coeff[1] * data[i-2];
  98248. sum += qlp_coeff[0] * data[i-1];
  98249. data[i] = residual[i] + (sum >> lp_quantization);
  98250. }
  98251. }
  98252. }
  98253. else {
  98254. if(order == 2) {
  98255. for(i = 0; i < (int)data_len; i++) {
  98256. sum = 0;
  98257. sum += qlp_coeff[1] * data[i-2];
  98258. sum += qlp_coeff[0] * data[i-1];
  98259. data[i] = residual[i] + (sum >> lp_quantization);
  98260. }
  98261. }
  98262. else { /* order == 1 */
  98263. for(i = 0; i < (int)data_len; i++)
  98264. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98265. }
  98266. }
  98267. }
  98268. }
  98269. else { /* order > 12 */
  98270. for(i = 0; i < (int)data_len; i++) {
  98271. sum = 0;
  98272. switch(order) {
  98273. case 32: sum += qlp_coeff[31] * data[i-32];
  98274. case 31: sum += qlp_coeff[30] * data[i-31];
  98275. case 30: sum += qlp_coeff[29] * data[i-30];
  98276. case 29: sum += qlp_coeff[28] * data[i-29];
  98277. case 28: sum += qlp_coeff[27] * data[i-28];
  98278. case 27: sum += qlp_coeff[26] * data[i-27];
  98279. case 26: sum += qlp_coeff[25] * data[i-26];
  98280. case 25: sum += qlp_coeff[24] * data[i-25];
  98281. case 24: sum += qlp_coeff[23] * data[i-24];
  98282. case 23: sum += qlp_coeff[22] * data[i-23];
  98283. case 22: sum += qlp_coeff[21] * data[i-22];
  98284. case 21: sum += qlp_coeff[20] * data[i-21];
  98285. case 20: sum += qlp_coeff[19] * data[i-20];
  98286. case 19: sum += qlp_coeff[18] * data[i-19];
  98287. case 18: sum += qlp_coeff[17] * data[i-18];
  98288. case 17: sum += qlp_coeff[16] * data[i-17];
  98289. case 16: sum += qlp_coeff[15] * data[i-16];
  98290. case 15: sum += qlp_coeff[14] * data[i-15];
  98291. case 14: sum += qlp_coeff[13] * data[i-14];
  98292. case 13: sum += qlp_coeff[12] * data[i-13];
  98293. sum += qlp_coeff[11] * data[i-12];
  98294. sum += qlp_coeff[10] * data[i-11];
  98295. sum += qlp_coeff[ 9] * data[i-10];
  98296. sum += qlp_coeff[ 8] * data[i- 9];
  98297. sum += qlp_coeff[ 7] * data[i- 8];
  98298. sum += qlp_coeff[ 6] * data[i- 7];
  98299. sum += qlp_coeff[ 5] * data[i- 6];
  98300. sum += qlp_coeff[ 4] * data[i- 5];
  98301. sum += qlp_coeff[ 3] * data[i- 4];
  98302. sum += qlp_coeff[ 2] * data[i- 3];
  98303. sum += qlp_coeff[ 1] * data[i- 2];
  98304. sum += qlp_coeff[ 0] * data[i- 1];
  98305. }
  98306. data[i] = residual[i] + (sum >> lp_quantization);
  98307. }
  98308. }
  98309. }
  98310. #endif
  98311. 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[])
  98312. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98313. {
  98314. unsigned i, j;
  98315. FLAC__int64 sum;
  98316. const FLAC__int32 *r = residual, *history;
  98317. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98318. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98319. for(i=0;i<order;i++)
  98320. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98321. fprintf(stderr,"\n");
  98322. #endif
  98323. FLAC__ASSERT(order > 0);
  98324. for(i = 0; i < data_len; i++) {
  98325. sum = 0;
  98326. history = data;
  98327. for(j = 0; j < order; j++)
  98328. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98329. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98330. #ifdef _MSC_VER
  98331. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98332. #else
  98333. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98334. #endif
  98335. break;
  98336. }
  98337. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98338. #ifdef _MSC_VER
  98339. 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));
  98340. #else
  98341. 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)));
  98342. #endif
  98343. break;
  98344. }
  98345. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98346. }
  98347. }
  98348. #else /* fully unrolled version for normal use */
  98349. {
  98350. int i;
  98351. FLAC__int64 sum;
  98352. FLAC__ASSERT(order > 0);
  98353. FLAC__ASSERT(order <= 32);
  98354. /*
  98355. * We do unique versions up to 12th order since that's the subset limit.
  98356. * Also they are roughly ordered to match frequency of occurrence to
  98357. * minimize branching.
  98358. */
  98359. if(order <= 12) {
  98360. if(order > 8) {
  98361. if(order > 10) {
  98362. if(order == 12) {
  98363. for(i = 0; i < (int)data_len; i++) {
  98364. sum = 0;
  98365. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98366. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98367. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98368. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98369. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98370. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98371. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98372. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98373. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98374. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98375. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98376. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98377. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98378. }
  98379. }
  98380. else { /* order == 11 */
  98381. for(i = 0; i < (int)data_len; i++) {
  98382. sum = 0;
  98383. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98384. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98385. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98386. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98387. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98388. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98389. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98390. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98391. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98392. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98393. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98394. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98395. }
  98396. }
  98397. }
  98398. else {
  98399. if(order == 10) {
  98400. for(i = 0; i < (int)data_len; i++) {
  98401. sum = 0;
  98402. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98403. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98404. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98405. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98406. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98407. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98408. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98409. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98410. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98411. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98412. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98413. }
  98414. }
  98415. else { /* order == 9 */
  98416. for(i = 0; i < (int)data_len; i++) {
  98417. sum = 0;
  98418. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98419. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98420. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98421. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98422. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98423. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98424. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98425. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98426. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98427. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98428. }
  98429. }
  98430. }
  98431. }
  98432. else if(order > 4) {
  98433. if(order > 6) {
  98434. if(order == 8) {
  98435. for(i = 0; i < (int)data_len; i++) {
  98436. sum = 0;
  98437. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98438. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98439. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98440. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98441. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98442. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98443. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98444. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98445. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98446. }
  98447. }
  98448. else { /* order == 7 */
  98449. for(i = 0; i < (int)data_len; i++) {
  98450. sum = 0;
  98451. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98452. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98453. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98454. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98455. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98456. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98457. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98458. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98459. }
  98460. }
  98461. }
  98462. else {
  98463. if(order == 6) {
  98464. for(i = 0; i < (int)data_len; i++) {
  98465. sum = 0;
  98466. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98467. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98468. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98469. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98470. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98471. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98472. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98473. }
  98474. }
  98475. else { /* order == 5 */
  98476. for(i = 0; i < (int)data_len; i++) {
  98477. sum = 0;
  98478. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98479. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98480. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98481. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98482. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98483. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98484. }
  98485. }
  98486. }
  98487. }
  98488. else {
  98489. if(order > 2) {
  98490. if(order == 4) {
  98491. for(i = 0; i < (int)data_len; i++) {
  98492. sum = 0;
  98493. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98494. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98495. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98496. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98497. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98498. }
  98499. }
  98500. else { /* order == 3 */
  98501. for(i = 0; i < (int)data_len; i++) {
  98502. sum = 0;
  98503. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98504. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98505. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98506. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98507. }
  98508. }
  98509. }
  98510. else {
  98511. if(order == 2) {
  98512. for(i = 0; i < (int)data_len; i++) {
  98513. sum = 0;
  98514. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98515. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98516. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98517. }
  98518. }
  98519. else { /* order == 1 */
  98520. for(i = 0; i < (int)data_len; i++)
  98521. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98522. }
  98523. }
  98524. }
  98525. }
  98526. else { /* order > 12 */
  98527. for(i = 0; i < (int)data_len; i++) {
  98528. sum = 0;
  98529. switch(order) {
  98530. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98531. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98532. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98533. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98534. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98535. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98536. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98537. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98538. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98539. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98540. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98541. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98542. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98543. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98544. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98545. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98546. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98547. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98548. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98549. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98550. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98551. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98552. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98553. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98554. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98555. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98556. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98557. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98558. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98559. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98560. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98561. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98562. }
  98563. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98564. }
  98565. }
  98566. }
  98567. #endif
  98568. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98569. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98570. {
  98571. FLAC__double error_scale;
  98572. FLAC__ASSERT(total_samples > 0);
  98573. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98574. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98575. }
  98576. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98577. {
  98578. if(lpc_error > 0.0) {
  98579. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98580. if(bps >= 0.0)
  98581. return bps;
  98582. else
  98583. return 0.0;
  98584. }
  98585. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98586. return 1e32;
  98587. }
  98588. else {
  98589. return 0.0;
  98590. }
  98591. }
  98592. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98593. {
  98594. 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 */
  98595. FLAC__double bits, best_bits, error_scale;
  98596. FLAC__ASSERT(max_order > 0);
  98597. FLAC__ASSERT(total_samples > 0);
  98598. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98599. best_index = 0;
  98600. best_bits = (unsigned)(-1);
  98601. for(index = 0, order = 1; index < max_order; index++, order++) {
  98602. 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);
  98603. if(bits < best_bits) {
  98604. best_index = index;
  98605. best_bits = bits;
  98606. }
  98607. }
  98608. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98609. }
  98610. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98611. #endif
  98612. /*** End of inlined file: lpc_flac.c ***/
  98613. /*** Start of inlined file: md5.c ***/
  98614. /*** Start of inlined file: juce_FlacHeader.h ***/
  98615. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98616. // tasks..
  98617. #define VERSION "1.2.1"
  98618. #define FLAC__NO_DLL 1
  98619. #if JUCE_MSVC
  98620. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98621. #endif
  98622. #if JUCE_MAC
  98623. #define FLAC__SYS_DARWIN 1
  98624. #endif
  98625. /*** End of inlined file: juce_FlacHeader.h ***/
  98626. #if JUCE_USE_FLAC
  98627. #if HAVE_CONFIG_H
  98628. # include <config.h>
  98629. #endif
  98630. #include <stdlib.h> /* for malloc() */
  98631. #include <string.h> /* for memcpy() */
  98632. /*** Start of inlined file: md5.h ***/
  98633. #ifndef FLAC__PRIVATE__MD5_H
  98634. #define FLAC__PRIVATE__MD5_H
  98635. /*
  98636. * This is the header file for the MD5 message-digest algorithm.
  98637. * The algorithm is due to Ron Rivest. This code was
  98638. * written by Colin Plumb in 1993, no copyright is claimed.
  98639. * This code is in the public domain; do with it what you wish.
  98640. *
  98641. * Equivalent code is available from RSA Data Security, Inc.
  98642. * This code has been tested against that, and is equivalent,
  98643. * except that you don't need to include two pages of legalese
  98644. * with every copy.
  98645. *
  98646. * To compute the message digest of a chunk of bytes, declare an
  98647. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98648. * needed on buffers full of bytes, and then call MD5Final, which
  98649. * will fill a supplied 16-byte array with the digest.
  98650. *
  98651. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98652. * header definitions; now uses stuff from dpkg's config.h
  98653. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98654. * Still in the public domain.
  98655. *
  98656. * Josh Coalson: made some changes to integrate with libFLAC.
  98657. * Still in the public domain, with no warranty.
  98658. */
  98659. typedef struct {
  98660. FLAC__uint32 in[16];
  98661. FLAC__uint32 buf[4];
  98662. FLAC__uint32 bytes[2];
  98663. FLAC__byte *internal_buf;
  98664. size_t capacity;
  98665. } FLAC__MD5Context;
  98666. void FLAC__MD5Init(FLAC__MD5Context *context);
  98667. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98668. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98669. #endif
  98670. /*** End of inlined file: md5.h ***/
  98671. #ifndef FLaC__INLINE
  98672. #define FLaC__INLINE
  98673. #endif
  98674. /*
  98675. * This code implements the MD5 message-digest algorithm.
  98676. * The algorithm is due to Ron Rivest. This code was
  98677. * written by Colin Plumb in 1993, no copyright is claimed.
  98678. * This code is in the public domain; do with it what you wish.
  98679. *
  98680. * Equivalent code is available from RSA Data Security, Inc.
  98681. * This code has been tested against that, and is equivalent,
  98682. * except that you don't need to include two pages of legalese
  98683. * with every copy.
  98684. *
  98685. * To compute the message digest of a chunk of bytes, declare an
  98686. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98687. * needed on buffers full of bytes, and then call MD5Final, which
  98688. * will fill a supplied 16-byte array with the digest.
  98689. *
  98690. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98691. * definitions; now uses stuff from dpkg's config.h.
  98692. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98693. * Still in the public domain.
  98694. *
  98695. * Josh Coalson: made some changes to integrate with libFLAC.
  98696. * Still in the public domain.
  98697. */
  98698. /* The four core functions - F1 is optimized somewhat */
  98699. /* #define F1(x, y, z) (x & y | ~x & z) */
  98700. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98701. #define F2(x, y, z) F1(z, x, y)
  98702. #define F3(x, y, z) (x ^ y ^ z)
  98703. #define F4(x, y, z) (y ^ (x | ~z))
  98704. /* This is the central step in the MD5 algorithm. */
  98705. #define MD5STEP(f,w,x,y,z,in,s) \
  98706. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98707. /*
  98708. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98709. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98710. * the data and converts bytes into longwords for this routine.
  98711. */
  98712. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98713. {
  98714. register FLAC__uint32 a, b, c, d;
  98715. a = buf[0];
  98716. b = buf[1];
  98717. c = buf[2];
  98718. d = buf[3];
  98719. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98720. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98721. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98722. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98723. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98724. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98725. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98726. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98727. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98728. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98729. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98730. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98731. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98732. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98733. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98734. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98735. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98736. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98737. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98738. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98739. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98740. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98741. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98742. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98743. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98744. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98745. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98746. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98747. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98748. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98749. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98750. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98751. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98752. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98753. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98754. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98755. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98756. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98757. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98758. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98759. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98760. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98761. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98762. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98763. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98764. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98765. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98766. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98767. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98768. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98769. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98770. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98771. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98772. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98773. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98774. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98775. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98776. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98777. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98778. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98779. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98780. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98781. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98782. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98783. buf[0] += a;
  98784. buf[1] += b;
  98785. buf[2] += c;
  98786. buf[3] += d;
  98787. }
  98788. #if WORDS_BIGENDIAN
  98789. //@@@@@@ OPT: use bswap/intrinsics
  98790. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98791. {
  98792. register FLAC__uint32 x;
  98793. do {
  98794. x = *buf;
  98795. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98796. *buf++ = (x >> 16) | (x << 16);
  98797. } while (--words);
  98798. }
  98799. static void byteSwapX16(FLAC__uint32 *buf)
  98800. {
  98801. register FLAC__uint32 x;
  98802. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98803. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98804. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98805. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98806. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98807. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98808. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98809. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98810. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98811. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98812. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98813. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98814. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98815. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98816. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98817. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98818. }
  98819. #else
  98820. #define byteSwap(buf, words)
  98821. #define byteSwapX16(buf)
  98822. #endif
  98823. /*
  98824. * Update context to reflect the concatenation of another buffer full
  98825. * of bytes.
  98826. */
  98827. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98828. {
  98829. FLAC__uint32 t;
  98830. /* Update byte count */
  98831. t = ctx->bytes[0];
  98832. if ((ctx->bytes[0] = t + len) < t)
  98833. ctx->bytes[1]++; /* Carry from low to high */
  98834. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98835. if (t > len) {
  98836. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98837. return;
  98838. }
  98839. /* First chunk is an odd size */
  98840. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98841. byteSwapX16(ctx->in);
  98842. FLAC__MD5Transform(ctx->buf, ctx->in);
  98843. buf += t;
  98844. len -= t;
  98845. /* Process data in 64-byte chunks */
  98846. while (len >= 64) {
  98847. memcpy(ctx->in, buf, 64);
  98848. byteSwapX16(ctx->in);
  98849. FLAC__MD5Transform(ctx->buf, ctx->in);
  98850. buf += 64;
  98851. len -= 64;
  98852. }
  98853. /* Handle any remaining bytes of data. */
  98854. memcpy(ctx->in, buf, len);
  98855. }
  98856. /*
  98857. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98858. * initialization constants.
  98859. */
  98860. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98861. {
  98862. ctx->buf[0] = 0x67452301;
  98863. ctx->buf[1] = 0xefcdab89;
  98864. ctx->buf[2] = 0x98badcfe;
  98865. ctx->buf[3] = 0x10325476;
  98866. ctx->bytes[0] = 0;
  98867. ctx->bytes[1] = 0;
  98868. ctx->internal_buf = 0;
  98869. ctx->capacity = 0;
  98870. }
  98871. /*
  98872. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98873. * 1 0* (64-bit count of bits processed, MSB-first)
  98874. */
  98875. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98876. {
  98877. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98878. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98879. /* Set the first char of padding to 0x80. There is always room. */
  98880. *p++ = 0x80;
  98881. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98882. count = 56 - 1 - count;
  98883. if (count < 0) { /* Padding forces an extra block */
  98884. memset(p, 0, count + 8);
  98885. byteSwapX16(ctx->in);
  98886. FLAC__MD5Transform(ctx->buf, ctx->in);
  98887. p = (FLAC__byte *)ctx->in;
  98888. count = 56;
  98889. }
  98890. memset(p, 0, count);
  98891. byteSwap(ctx->in, 14);
  98892. /* Append length in bits and transform */
  98893. ctx->in[14] = ctx->bytes[0] << 3;
  98894. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98895. FLAC__MD5Transform(ctx->buf, ctx->in);
  98896. byteSwap(ctx->buf, 4);
  98897. memcpy(digest, ctx->buf, 16);
  98898. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98899. if(0 != ctx->internal_buf) {
  98900. free(ctx->internal_buf);
  98901. ctx->internal_buf = 0;
  98902. ctx->capacity = 0;
  98903. }
  98904. }
  98905. /*
  98906. * Convert the incoming audio signal to a byte stream
  98907. */
  98908. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98909. {
  98910. unsigned channel, sample;
  98911. register FLAC__int32 a_word;
  98912. register FLAC__byte *buf_ = buf;
  98913. #if WORDS_BIGENDIAN
  98914. #else
  98915. if(channels == 2 && bytes_per_sample == 2) {
  98916. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98917. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98918. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98919. *buf1_ = (FLAC__int16)signal[1][sample];
  98920. }
  98921. else if(channels == 1 && bytes_per_sample == 2) {
  98922. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98923. for(sample = 0; sample < samples; sample++)
  98924. *buf1_++ = (FLAC__int16)signal[0][sample];
  98925. }
  98926. else
  98927. #endif
  98928. if(bytes_per_sample == 2) {
  98929. if(channels == 2) {
  98930. for(sample = 0; sample < samples; sample++) {
  98931. a_word = signal[0][sample];
  98932. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98933. *buf_++ = (FLAC__byte)a_word;
  98934. a_word = signal[1][sample];
  98935. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98936. *buf_++ = (FLAC__byte)a_word;
  98937. }
  98938. }
  98939. else if(channels == 1) {
  98940. for(sample = 0; sample < samples; sample++) {
  98941. a_word = signal[0][sample];
  98942. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98943. *buf_++ = (FLAC__byte)a_word;
  98944. }
  98945. }
  98946. else {
  98947. for(sample = 0; sample < samples; sample++) {
  98948. for(channel = 0; channel < channels; channel++) {
  98949. a_word = signal[channel][sample];
  98950. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98951. *buf_++ = (FLAC__byte)a_word;
  98952. }
  98953. }
  98954. }
  98955. }
  98956. else if(bytes_per_sample == 3) {
  98957. if(channels == 2) {
  98958. for(sample = 0; sample < samples; sample++) {
  98959. a_word = signal[0][sample];
  98960. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98961. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98962. *buf_++ = (FLAC__byte)a_word;
  98963. a_word = signal[1][sample];
  98964. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98965. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98966. *buf_++ = (FLAC__byte)a_word;
  98967. }
  98968. }
  98969. else if(channels == 1) {
  98970. for(sample = 0; sample < samples; sample++) {
  98971. a_word = signal[0][sample];
  98972. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98973. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98974. *buf_++ = (FLAC__byte)a_word;
  98975. }
  98976. }
  98977. else {
  98978. for(sample = 0; sample < samples; sample++) {
  98979. for(channel = 0; channel < channels; channel++) {
  98980. a_word = signal[channel][sample];
  98981. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98982. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98983. *buf_++ = (FLAC__byte)a_word;
  98984. }
  98985. }
  98986. }
  98987. }
  98988. else if(bytes_per_sample == 1) {
  98989. if(channels == 2) {
  98990. for(sample = 0; sample < samples; sample++) {
  98991. a_word = signal[0][sample];
  98992. *buf_++ = (FLAC__byte)a_word;
  98993. a_word = signal[1][sample];
  98994. *buf_++ = (FLAC__byte)a_word;
  98995. }
  98996. }
  98997. else if(channels == 1) {
  98998. for(sample = 0; sample < samples; sample++) {
  98999. a_word = signal[0][sample];
  99000. *buf_++ = (FLAC__byte)a_word;
  99001. }
  99002. }
  99003. else {
  99004. for(sample = 0; sample < samples; sample++) {
  99005. for(channel = 0; channel < channels; channel++) {
  99006. a_word = signal[channel][sample];
  99007. *buf_++ = (FLAC__byte)a_word;
  99008. }
  99009. }
  99010. }
  99011. }
  99012. else { /* bytes_per_sample == 4, maybe optimize more later */
  99013. for(sample = 0; sample < samples; sample++) {
  99014. for(channel = 0; channel < channels; channel++) {
  99015. a_word = signal[channel][sample];
  99016. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99017. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99018. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99019. *buf_++ = (FLAC__byte)a_word;
  99020. }
  99021. }
  99022. }
  99023. }
  99024. /*
  99025. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  99026. */
  99027. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  99028. {
  99029. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  99030. /* overflow check */
  99031. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  99032. return false;
  99033. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  99034. return false;
  99035. if(ctx->capacity < bytes_needed) {
  99036. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  99037. if(0 == tmp) {
  99038. free(ctx->internal_buf);
  99039. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  99040. return false;
  99041. }
  99042. ctx->internal_buf = tmp;
  99043. ctx->capacity = bytes_needed;
  99044. }
  99045. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  99046. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  99047. return true;
  99048. }
  99049. #endif
  99050. /*** End of inlined file: md5.c ***/
  99051. /*** Start of inlined file: memory.c ***/
  99052. /*** Start of inlined file: juce_FlacHeader.h ***/
  99053. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99054. // tasks..
  99055. #define VERSION "1.2.1"
  99056. #define FLAC__NO_DLL 1
  99057. #if JUCE_MSVC
  99058. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99059. #endif
  99060. #if JUCE_MAC
  99061. #define FLAC__SYS_DARWIN 1
  99062. #endif
  99063. /*** End of inlined file: juce_FlacHeader.h ***/
  99064. #if JUCE_USE_FLAC
  99065. #if HAVE_CONFIG_H
  99066. # include <config.h>
  99067. #endif
  99068. /*** Start of inlined file: memory.h ***/
  99069. #ifndef FLAC__PRIVATE__MEMORY_H
  99070. #define FLAC__PRIVATE__MEMORY_H
  99071. #ifdef HAVE_CONFIG_H
  99072. #include <config.h>
  99073. #endif
  99074. #include <stdlib.h> /* for size_t */
  99075. /* Returns the unaligned address returned by malloc.
  99076. * Use free() on this address to deallocate.
  99077. */
  99078. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  99079. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  99080. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  99081. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  99082. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  99083. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99084. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  99085. #endif
  99086. #endif
  99087. /*** End of inlined file: memory.h ***/
  99088. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  99089. {
  99090. void *x;
  99091. FLAC__ASSERT(0 != aligned_address);
  99092. #ifdef FLAC__ALIGN_MALLOC_DATA
  99093. /* align on 32-byte (256-bit) boundary */
  99094. x = safe_malloc_add_2op_(bytes, /*+*/31);
  99095. #ifdef SIZEOF_VOIDP
  99096. #if SIZEOF_VOIDP == 4
  99097. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  99098. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99099. #elif SIZEOF_VOIDP == 8
  99100. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99101. #else
  99102. # error Unsupported sizeof(void*)
  99103. #endif
  99104. #else
  99105. /* there's got to be a better way to do this right for all archs */
  99106. if(sizeof(void*) == sizeof(unsigned))
  99107. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99108. else if(sizeof(void*) == sizeof(FLAC__uint64))
  99109. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99110. else
  99111. return 0;
  99112. #endif
  99113. #else
  99114. x = safe_malloc_(bytes);
  99115. *aligned_address = x;
  99116. #endif
  99117. return x;
  99118. }
  99119. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  99120. {
  99121. FLAC__int32 *pu; /* unaligned pointer */
  99122. union { /* union needed to comply with C99 pointer aliasing rules */
  99123. FLAC__int32 *pa; /* aligned pointer */
  99124. void *pv; /* aligned pointer alias */
  99125. } u;
  99126. FLAC__ASSERT(elements > 0);
  99127. FLAC__ASSERT(0 != unaligned_pointer);
  99128. FLAC__ASSERT(0 != aligned_pointer);
  99129. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99130. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  99131. if(0 == pu) {
  99132. return false;
  99133. }
  99134. else {
  99135. if(*unaligned_pointer != 0)
  99136. free(*unaligned_pointer);
  99137. *unaligned_pointer = pu;
  99138. *aligned_pointer = u.pa;
  99139. return true;
  99140. }
  99141. }
  99142. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99143. {
  99144. FLAC__uint32 *pu; /* unaligned pointer */
  99145. union { /* union needed to comply with C99 pointer aliasing rules */
  99146. FLAC__uint32 *pa; /* aligned pointer */
  99147. void *pv; /* aligned pointer alias */
  99148. } u;
  99149. FLAC__ASSERT(elements > 0);
  99150. FLAC__ASSERT(0 != unaligned_pointer);
  99151. FLAC__ASSERT(0 != aligned_pointer);
  99152. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99153. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99154. if(0 == pu) {
  99155. return false;
  99156. }
  99157. else {
  99158. if(*unaligned_pointer != 0)
  99159. free(*unaligned_pointer);
  99160. *unaligned_pointer = pu;
  99161. *aligned_pointer = u.pa;
  99162. return true;
  99163. }
  99164. }
  99165. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99166. {
  99167. FLAC__uint64 *pu; /* unaligned pointer */
  99168. union { /* union needed to comply with C99 pointer aliasing rules */
  99169. FLAC__uint64 *pa; /* aligned pointer */
  99170. void *pv; /* aligned pointer alias */
  99171. } u;
  99172. FLAC__ASSERT(elements > 0);
  99173. FLAC__ASSERT(0 != unaligned_pointer);
  99174. FLAC__ASSERT(0 != aligned_pointer);
  99175. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99176. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99177. if(0 == pu) {
  99178. return false;
  99179. }
  99180. else {
  99181. if(*unaligned_pointer != 0)
  99182. free(*unaligned_pointer);
  99183. *unaligned_pointer = pu;
  99184. *aligned_pointer = u.pa;
  99185. return true;
  99186. }
  99187. }
  99188. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99189. {
  99190. unsigned *pu; /* unaligned pointer */
  99191. union { /* union needed to comply with C99 pointer aliasing rules */
  99192. unsigned *pa; /* aligned pointer */
  99193. void *pv; /* aligned pointer alias */
  99194. } u;
  99195. FLAC__ASSERT(elements > 0);
  99196. FLAC__ASSERT(0 != unaligned_pointer);
  99197. FLAC__ASSERT(0 != aligned_pointer);
  99198. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99199. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99200. if(0 == pu) {
  99201. return false;
  99202. }
  99203. else {
  99204. if(*unaligned_pointer != 0)
  99205. free(*unaligned_pointer);
  99206. *unaligned_pointer = pu;
  99207. *aligned_pointer = u.pa;
  99208. return true;
  99209. }
  99210. }
  99211. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99212. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99213. {
  99214. FLAC__real *pu; /* unaligned pointer */
  99215. union { /* union needed to comply with C99 pointer aliasing rules */
  99216. FLAC__real *pa; /* aligned pointer */
  99217. void *pv; /* aligned pointer alias */
  99218. } u;
  99219. FLAC__ASSERT(elements > 0);
  99220. FLAC__ASSERT(0 != unaligned_pointer);
  99221. FLAC__ASSERT(0 != aligned_pointer);
  99222. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99223. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99224. if(0 == pu) {
  99225. return false;
  99226. }
  99227. else {
  99228. if(*unaligned_pointer != 0)
  99229. free(*unaligned_pointer);
  99230. *unaligned_pointer = pu;
  99231. *aligned_pointer = u.pa;
  99232. return true;
  99233. }
  99234. }
  99235. #endif
  99236. #endif
  99237. /*** End of inlined file: memory.c ***/
  99238. /*** Start of inlined file: stream_decoder.c ***/
  99239. /*** Start of inlined file: juce_FlacHeader.h ***/
  99240. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99241. // tasks..
  99242. #define VERSION "1.2.1"
  99243. #define FLAC__NO_DLL 1
  99244. #if JUCE_MSVC
  99245. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99246. #endif
  99247. #if JUCE_MAC
  99248. #define FLAC__SYS_DARWIN 1
  99249. #endif
  99250. /*** End of inlined file: juce_FlacHeader.h ***/
  99251. #if JUCE_USE_FLAC
  99252. #if HAVE_CONFIG_H
  99253. # include <config.h>
  99254. #endif
  99255. #if defined _MSC_VER || defined __MINGW32__
  99256. #include <io.h> /* for _setmode() */
  99257. #include <fcntl.h> /* for _O_BINARY */
  99258. #endif
  99259. #if defined __CYGWIN__ || defined __EMX__
  99260. #include <io.h> /* for setmode(), O_BINARY */
  99261. #include <fcntl.h> /* for _O_BINARY */
  99262. #endif
  99263. #include <stdio.h>
  99264. #include <stdlib.h> /* for malloc() */
  99265. #include <string.h> /* for memset/memcpy() */
  99266. #include <sys/stat.h> /* for stat() */
  99267. #include <sys/types.h> /* for off_t */
  99268. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99269. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99270. #define fseeko fseek
  99271. #define ftello ftell
  99272. #endif
  99273. #endif
  99274. /*** Start of inlined file: stream_decoder.h ***/
  99275. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99276. #define FLAC__PROTECTED__STREAM_DECODER_H
  99277. #if FLAC__HAS_OGG
  99278. #include "include/private/ogg_decoder_aspect.h"
  99279. #endif
  99280. typedef struct FLAC__StreamDecoderProtected {
  99281. FLAC__StreamDecoderState state;
  99282. unsigned channels;
  99283. FLAC__ChannelAssignment channel_assignment;
  99284. unsigned bits_per_sample;
  99285. unsigned sample_rate; /* in Hz */
  99286. unsigned blocksize; /* in samples (per channel) */
  99287. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99288. #if FLAC__HAS_OGG
  99289. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99290. #endif
  99291. } FLAC__StreamDecoderProtected;
  99292. /*
  99293. * return the number of input bytes consumed
  99294. */
  99295. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99296. #endif
  99297. /*** End of inlined file: stream_decoder.h ***/
  99298. #ifdef max
  99299. #undef max
  99300. #endif
  99301. #define max(a,b) ((a)>(b)?(a):(b))
  99302. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99303. #ifdef _MSC_VER
  99304. #define FLAC__U64L(x) x
  99305. #else
  99306. #define FLAC__U64L(x) x##LLU
  99307. #endif
  99308. /* technically this should be in an "export.c" but this is convenient enough */
  99309. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99310. #if FLAC__HAS_OGG
  99311. 1
  99312. #else
  99313. 0
  99314. #endif
  99315. ;
  99316. /***********************************************************************
  99317. *
  99318. * Private static data
  99319. *
  99320. ***********************************************************************/
  99321. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99322. /***********************************************************************
  99323. *
  99324. * Private class method prototypes
  99325. *
  99326. ***********************************************************************/
  99327. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99328. static FILE *get_binary_stdin_(void);
  99329. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99330. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99331. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99332. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99333. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99334. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99335. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99336. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99337. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99338. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99339. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99340. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99341. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99342. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99343. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99344. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99345. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99346. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99347. 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);
  99348. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99349. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99350. #if FLAC__HAS_OGG
  99351. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99352. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99353. #endif
  99354. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99355. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99356. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99357. #if FLAC__HAS_OGG
  99358. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99359. #endif
  99360. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99361. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99362. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99363. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99364. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99365. /***********************************************************************
  99366. *
  99367. * Private class data
  99368. *
  99369. ***********************************************************************/
  99370. typedef struct FLAC__StreamDecoderPrivate {
  99371. #if FLAC__HAS_OGG
  99372. FLAC__bool is_ogg;
  99373. #endif
  99374. FLAC__StreamDecoderReadCallback read_callback;
  99375. FLAC__StreamDecoderSeekCallback seek_callback;
  99376. FLAC__StreamDecoderTellCallback tell_callback;
  99377. FLAC__StreamDecoderLengthCallback length_callback;
  99378. FLAC__StreamDecoderEofCallback eof_callback;
  99379. FLAC__StreamDecoderWriteCallback write_callback;
  99380. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99381. FLAC__StreamDecoderErrorCallback error_callback;
  99382. /* generic 32-bit datapath: */
  99383. 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[]);
  99384. /* generic 64-bit datapath: */
  99385. 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[]);
  99386. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99387. 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[]);
  99388. /* 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: */
  99389. 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[]);
  99390. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99391. void *client_data;
  99392. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99393. FLAC__BitReader *input;
  99394. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99395. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99396. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99397. unsigned output_capacity, output_channels;
  99398. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99399. FLAC__uint64 samples_decoded;
  99400. FLAC__bool has_stream_info, has_seek_table;
  99401. FLAC__StreamMetadata stream_info;
  99402. FLAC__StreamMetadata seek_table;
  99403. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99404. FLAC__byte *metadata_filter_ids;
  99405. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99406. FLAC__Frame frame;
  99407. FLAC__bool cached; /* true if there is a byte in lookahead */
  99408. FLAC__CPUInfo cpuinfo;
  99409. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99410. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99411. /* unaligned (original) pointers to allocated data */
  99412. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99413. 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 */
  99414. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99415. FLAC__bool is_seeking;
  99416. FLAC__MD5Context md5context;
  99417. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99418. /* (the rest of these are only used for seeking) */
  99419. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99420. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99421. FLAC__uint64 target_sample;
  99422. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99423. #if FLAC__HAS_OGG
  99424. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99425. #endif
  99426. } FLAC__StreamDecoderPrivate;
  99427. /***********************************************************************
  99428. *
  99429. * Public static class data
  99430. *
  99431. ***********************************************************************/
  99432. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99433. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99434. "FLAC__STREAM_DECODER_READ_METADATA",
  99435. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99436. "FLAC__STREAM_DECODER_READ_FRAME",
  99437. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99438. "FLAC__STREAM_DECODER_OGG_ERROR",
  99439. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99440. "FLAC__STREAM_DECODER_ABORTED",
  99441. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99442. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99443. };
  99444. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99445. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99446. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99447. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99448. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99449. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99450. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99451. };
  99452. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99453. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99454. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99455. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99456. };
  99457. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99458. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99459. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99460. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99461. };
  99462. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99463. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99464. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99465. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99466. };
  99467. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99468. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99469. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99470. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99471. };
  99472. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99473. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99474. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99475. };
  99476. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99477. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99478. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99479. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99480. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99481. };
  99482. /***********************************************************************
  99483. *
  99484. * Class constructor/destructor
  99485. *
  99486. ***********************************************************************/
  99487. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99488. {
  99489. FLAC__StreamDecoder *decoder;
  99490. unsigned i;
  99491. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99492. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99493. if(decoder == 0) {
  99494. return 0;
  99495. }
  99496. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99497. if(decoder->protected_ == 0) {
  99498. free(decoder);
  99499. return 0;
  99500. }
  99501. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99502. if(decoder->private_ == 0) {
  99503. free(decoder->protected_);
  99504. free(decoder);
  99505. return 0;
  99506. }
  99507. decoder->private_->input = FLAC__bitreader_new();
  99508. if(decoder->private_->input == 0) {
  99509. free(decoder->private_);
  99510. free(decoder->protected_);
  99511. free(decoder);
  99512. return 0;
  99513. }
  99514. decoder->private_->metadata_filter_ids_capacity = 16;
  99515. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99516. FLAC__bitreader_delete(decoder->private_->input);
  99517. free(decoder->private_);
  99518. free(decoder->protected_);
  99519. free(decoder);
  99520. return 0;
  99521. }
  99522. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99523. decoder->private_->output[i] = 0;
  99524. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99525. }
  99526. decoder->private_->output_capacity = 0;
  99527. decoder->private_->output_channels = 0;
  99528. decoder->private_->has_seek_table = false;
  99529. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99530. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99531. decoder->private_->file = 0;
  99532. set_defaults_dec(decoder);
  99533. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99534. return decoder;
  99535. }
  99536. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99537. {
  99538. unsigned i;
  99539. FLAC__ASSERT(0 != decoder);
  99540. FLAC__ASSERT(0 != decoder->protected_);
  99541. FLAC__ASSERT(0 != decoder->private_);
  99542. FLAC__ASSERT(0 != decoder->private_->input);
  99543. (void)FLAC__stream_decoder_finish(decoder);
  99544. if(0 != decoder->private_->metadata_filter_ids)
  99545. free(decoder->private_->metadata_filter_ids);
  99546. FLAC__bitreader_delete(decoder->private_->input);
  99547. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99548. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99549. free(decoder->private_);
  99550. free(decoder->protected_);
  99551. free(decoder);
  99552. }
  99553. /***********************************************************************
  99554. *
  99555. * Public class methods
  99556. *
  99557. ***********************************************************************/
  99558. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99559. FLAC__StreamDecoder *decoder,
  99560. FLAC__StreamDecoderReadCallback read_callback,
  99561. FLAC__StreamDecoderSeekCallback seek_callback,
  99562. FLAC__StreamDecoderTellCallback tell_callback,
  99563. FLAC__StreamDecoderLengthCallback length_callback,
  99564. FLAC__StreamDecoderEofCallback eof_callback,
  99565. FLAC__StreamDecoderWriteCallback write_callback,
  99566. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99567. FLAC__StreamDecoderErrorCallback error_callback,
  99568. void *client_data,
  99569. FLAC__bool is_ogg
  99570. )
  99571. {
  99572. FLAC__ASSERT(0 != decoder);
  99573. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99574. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99575. #if !FLAC__HAS_OGG
  99576. if(is_ogg)
  99577. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99578. #endif
  99579. if(
  99580. 0 == read_callback ||
  99581. 0 == write_callback ||
  99582. 0 == error_callback ||
  99583. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99584. )
  99585. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99586. #if FLAC__HAS_OGG
  99587. decoder->private_->is_ogg = is_ogg;
  99588. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99589. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99590. #endif
  99591. /*
  99592. * get the CPU info and set the function pointers
  99593. */
  99594. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99595. /* first default to the non-asm routines */
  99596. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99597. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99598. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99599. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99600. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99601. /* now override with asm where appropriate */
  99602. #ifndef FLAC__NO_ASM
  99603. if(decoder->private_->cpuinfo.use_asm) {
  99604. #ifdef FLAC__CPU_IA32
  99605. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99606. #ifdef FLAC__HAS_NASM
  99607. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99608. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99609. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99610. #endif
  99611. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99612. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99613. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99614. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99615. }
  99616. else {
  99617. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99618. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99619. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99620. }
  99621. #endif
  99622. #elif defined FLAC__CPU_PPC
  99623. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99624. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99625. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99626. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99627. }
  99628. #endif
  99629. }
  99630. #endif
  99631. /* from here on, errors are fatal */
  99632. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99633. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99634. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99635. }
  99636. decoder->private_->read_callback = read_callback;
  99637. decoder->private_->seek_callback = seek_callback;
  99638. decoder->private_->tell_callback = tell_callback;
  99639. decoder->private_->length_callback = length_callback;
  99640. decoder->private_->eof_callback = eof_callback;
  99641. decoder->private_->write_callback = write_callback;
  99642. decoder->private_->metadata_callback = metadata_callback;
  99643. decoder->private_->error_callback = error_callback;
  99644. decoder->private_->client_data = client_data;
  99645. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99646. decoder->private_->samples_decoded = 0;
  99647. decoder->private_->has_stream_info = false;
  99648. decoder->private_->cached = false;
  99649. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99650. decoder->private_->is_seeking = false;
  99651. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99652. if(!FLAC__stream_decoder_reset(decoder)) {
  99653. /* above call sets the state for us */
  99654. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99655. }
  99656. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99657. }
  99658. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99659. FLAC__StreamDecoder *decoder,
  99660. FLAC__StreamDecoderReadCallback read_callback,
  99661. FLAC__StreamDecoderSeekCallback seek_callback,
  99662. FLAC__StreamDecoderTellCallback tell_callback,
  99663. FLAC__StreamDecoderLengthCallback length_callback,
  99664. FLAC__StreamDecoderEofCallback eof_callback,
  99665. FLAC__StreamDecoderWriteCallback write_callback,
  99666. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99667. FLAC__StreamDecoderErrorCallback error_callback,
  99668. void *client_data
  99669. )
  99670. {
  99671. return init_stream_internal_dec(
  99672. decoder,
  99673. read_callback,
  99674. seek_callback,
  99675. tell_callback,
  99676. length_callback,
  99677. eof_callback,
  99678. write_callback,
  99679. metadata_callback,
  99680. error_callback,
  99681. client_data,
  99682. /*is_ogg=*/false
  99683. );
  99684. }
  99685. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99686. FLAC__StreamDecoder *decoder,
  99687. FLAC__StreamDecoderReadCallback read_callback,
  99688. FLAC__StreamDecoderSeekCallback seek_callback,
  99689. FLAC__StreamDecoderTellCallback tell_callback,
  99690. FLAC__StreamDecoderLengthCallback length_callback,
  99691. FLAC__StreamDecoderEofCallback eof_callback,
  99692. FLAC__StreamDecoderWriteCallback write_callback,
  99693. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99694. FLAC__StreamDecoderErrorCallback error_callback,
  99695. void *client_data
  99696. )
  99697. {
  99698. return init_stream_internal_dec(
  99699. decoder,
  99700. read_callback,
  99701. seek_callback,
  99702. tell_callback,
  99703. length_callback,
  99704. eof_callback,
  99705. write_callback,
  99706. metadata_callback,
  99707. error_callback,
  99708. client_data,
  99709. /*is_ogg=*/true
  99710. );
  99711. }
  99712. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99713. FLAC__StreamDecoder *decoder,
  99714. FILE *file,
  99715. FLAC__StreamDecoderWriteCallback write_callback,
  99716. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99717. FLAC__StreamDecoderErrorCallback error_callback,
  99718. void *client_data,
  99719. FLAC__bool is_ogg
  99720. )
  99721. {
  99722. FLAC__ASSERT(0 != decoder);
  99723. FLAC__ASSERT(0 != file);
  99724. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99725. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99726. if(0 == write_callback || 0 == error_callback)
  99727. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99728. /*
  99729. * To make sure that our file does not go unclosed after an error, we
  99730. * must assign the FILE pointer before any further error can occur in
  99731. * this routine.
  99732. */
  99733. if(file == stdin)
  99734. file = get_binary_stdin_(); /* just to be safe */
  99735. decoder->private_->file = file;
  99736. return init_stream_internal_dec(
  99737. decoder,
  99738. file_read_callback_dec,
  99739. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99740. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99741. decoder->private_->file == stdin? 0: file_length_callback_,
  99742. file_eof_callback_,
  99743. write_callback,
  99744. metadata_callback,
  99745. error_callback,
  99746. client_data,
  99747. is_ogg
  99748. );
  99749. }
  99750. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99751. FLAC__StreamDecoder *decoder,
  99752. FILE *file,
  99753. FLAC__StreamDecoderWriteCallback write_callback,
  99754. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99755. FLAC__StreamDecoderErrorCallback error_callback,
  99756. void *client_data
  99757. )
  99758. {
  99759. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99760. }
  99761. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99762. FLAC__StreamDecoder *decoder,
  99763. FILE *file,
  99764. FLAC__StreamDecoderWriteCallback write_callback,
  99765. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99766. FLAC__StreamDecoderErrorCallback error_callback,
  99767. void *client_data
  99768. )
  99769. {
  99770. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99771. }
  99772. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99773. FLAC__StreamDecoder *decoder,
  99774. const char *filename,
  99775. FLAC__StreamDecoderWriteCallback write_callback,
  99776. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99777. FLAC__StreamDecoderErrorCallback error_callback,
  99778. void *client_data,
  99779. FLAC__bool is_ogg
  99780. )
  99781. {
  99782. FILE *file;
  99783. FLAC__ASSERT(0 != decoder);
  99784. /*
  99785. * To make sure that our file does not go unclosed after an error, we
  99786. * have to do the same entrance checks here that are later performed
  99787. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99788. */
  99789. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99790. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99791. if(0 == write_callback || 0 == error_callback)
  99792. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99793. file = filename? fopen(filename, "rb") : stdin;
  99794. if(0 == file)
  99795. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99796. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99797. }
  99798. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99799. FLAC__StreamDecoder *decoder,
  99800. const char *filename,
  99801. FLAC__StreamDecoderWriteCallback write_callback,
  99802. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99803. FLAC__StreamDecoderErrorCallback error_callback,
  99804. void *client_data
  99805. )
  99806. {
  99807. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99808. }
  99809. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99810. FLAC__StreamDecoder *decoder,
  99811. const char *filename,
  99812. FLAC__StreamDecoderWriteCallback write_callback,
  99813. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99814. FLAC__StreamDecoderErrorCallback error_callback,
  99815. void *client_data
  99816. )
  99817. {
  99818. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99819. }
  99820. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99821. {
  99822. FLAC__bool md5_failed = false;
  99823. unsigned i;
  99824. FLAC__ASSERT(0 != decoder);
  99825. FLAC__ASSERT(0 != decoder->private_);
  99826. FLAC__ASSERT(0 != decoder->protected_);
  99827. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99828. return true;
  99829. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99830. * always call FLAC__MD5Final()
  99831. */
  99832. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99833. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99834. free(decoder->private_->seek_table.data.seek_table.points);
  99835. decoder->private_->seek_table.data.seek_table.points = 0;
  99836. decoder->private_->has_seek_table = false;
  99837. }
  99838. FLAC__bitreader_free(decoder->private_->input);
  99839. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99840. /* WATCHOUT:
  99841. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99842. * output arrays have a buffer of up to 3 zeroes in front
  99843. * (at negative indices) for alignment purposes; we use 4
  99844. * to keep the data well-aligned.
  99845. */
  99846. if(0 != decoder->private_->output[i]) {
  99847. free(decoder->private_->output[i]-4);
  99848. decoder->private_->output[i] = 0;
  99849. }
  99850. if(0 != decoder->private_->residual_unaligned[i]) {
  99851. free(decoder->private_->residual_unaligned[i]);
  99852. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99853. }
  99854. }
  99855. decoder->private_->output_capacity = 0;
  99856. decoder->private_->output_channels = 0;
  99857. #if FLAC__HAS_OGG
  99858. if(decoder->private_->is_ogg)
  99859. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99860. #endif
  99861. if(0 != decoder->private_->file) {
  99862. if(decoder->private_->file != stdin)
  99863. fclose(decoder->private_->file);
  99864. decoder->private_->file = 0;
  99865. }
  99866. if(decoder->private_->do_md5_checking) {
  99867. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99868. md5_failed = true;
  99869. }
  99870. decoder->private_->is_seeking = false;
  99871. set_defaults_dec(decoder);
  99872. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99873. return !md5_failed;
  99874. }
  99875. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99876. {
  99877. FLAC__ASSERT(0 != decoder);
  99878. FLAC__ASSERT(0 != decoder->private_);
  99879. FLAC__ASSERT(0 != decoder->protected_);
  99880. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99881. return false;
  99882. #if FLAC__HAS_OGG
  99883. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99884. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99885. return true;
  99886. #else
  99887. (void)value;
  99888. return false;
  99889. #endif
  99890. }
  99891. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99892. {
  99893. FLAC__ASSERT(0 != decoder);
  99894. FLAC__ASSERT(0 != decoder->protected_);
  99895. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99896. return false;
  99897. decoder->protected_->md5_checking = value;
  99898. return true;
  99899. }
  99900. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99901. {
  99902. FLAC__ASSERT(0 != decoder);
  99903. FLAC__ASSERT(0 != decoder->private_);
  99904. FLAC__ASSERT(0 != decoder->protected_);
  99905. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99906. /* double protection */
  99907. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99908. return false;
  99909. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99910. return false;
  99911. decoder->private_->metadata_filter[type] = true;
  99912. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99913. decoder->private_->metadata_filter_ids_count = 0;
  99914. return true;
  99915. }
  99916. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99917. {
  99918. FLAC__ASSERT(0 != decoder);
  99919. FLAC__ASSERT(0 != decoder->private_);
  99920. FLAC__ASSERT(0 != decoder->protected_);
  99921. FLAC__ASSERT(0 != id);
  99922. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99923. return false;
  99924. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99925. return true;
  99926. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99927. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99928. 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))) {
  99929. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99930. return false;
  99931. }
  99932. decoder->private_->metadata_filter_ids_capacity *= 2;
  99933. }
  99934. 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));
  99935. decoder->private_->metadata_filter_ids_count++;
  99936. return true;
  99937. }
  99938. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99939. {
  99940. unsigned i;
  99941. FLAC__ASSERT(0 != decoder);
  99942. FLAC__ASSERT(0 != decoder->private_);
  99943. FLAC__ASSERT(0 != decoder->protected_);
  99944. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99945. return false;
  99946. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99947. decoder->private_->metadata_filter[i] = true;
  99948. decoder->private_->metadata_filter_ids_count = 0;
  99949. return true;
  99950. }
  99951. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99952. {
  99953. FLAC__ASSERT(0 != decoder);
  99954. FLAC__ASSERT(0 != decoder->private_);
  99955. FLAC__ASSERT(0 != decoder->protected_);
  99956. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99957. /* double protection */
  99958. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99959. return false;
  99960. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99961. return false;
  99962. decoder->private_->metadata_filter[type] = false;
  99963. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99964. decoder->private_->metadata_filter_ids_count = 0;
  99965. return true;
  99966. }
  99967. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99968. {
  99969. FLAC__ASSERT(0 != decoder);
  99970. FLAC__ASSERT(0 != decoder->private_);
  99971. FLAC__ASSERT(0 != decoder->protected_);
  99972. FLAC__ASSERT(0 != id);
  99973. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99974. return false;
  99975. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99976. return true;
  99977. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99978. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99979. 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))) {
  99980. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99981. return false;
  99982. }
  99983. decoder->private_->metadata_filter_ids_capacity *= 2;
  99984. }
  99985. 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));
  99986. decoder->private_->metadata_filter_ids_count++;
  99987. return true;
  99988. }
  99989. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99990. {
  99991. FLAC__ASSERT(0 != decoder);
  99992. FLAC__ASSERT(0 != decoder->private_);
  99993. FLAC__ASSERT(0 != decoder->protected_);
  99994. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99995. return false;
  99996. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99997. decoder->private_->metadata_filter_ids_count = 0;
  99998. return true;
  99999. }
  100000. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  100001. {
  100002. FLAC__ASSERT(0 != decoder);
  100003. FLAC__ASSERT(0 != decoder->protected_);
  100004. return decoder->protected_->state;
  100005. }
  100006. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  100007. {
  100008. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  100009. }
  100010. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  100011. {
  100012. FLAC__ASSERT(0 != decoder);
  100013. FLAC__ASSERT(0 != decoder->protected_);
  100014. return decoder->protected_->md5_checking;
  100015. }
  100016. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  100017. {
  100018. FLAC__ASSERT(0 != decoder);
  100019. FLAC__ASSERT(0 != decoder->protected_);
  100020. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  100021. }
  100022. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  100023. {
  100024. FLAC__ASSERT(0 != decoder);
  100025. FLAC__ASSERT(0 != decoder->protected_);
  100026. return decoder->protected_->channels;
  100027. }
  100028. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  100029. {
  100030. FLAC__ASSERT(0 != decoder);
  100031. FLAC__ASSERT(0 != decoder->protected_);
  100032. return decoder->protected_->channel_assignment;
  100033. }
  100034. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  100035. {
  100036. FLAC__ASSERT(0 != decoder);
  100037. FLAC__ASSERT(0 != decoder->protected_);
  100038. return decoder->protected_->bits_per_sample;
  100039. }
  100040. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  100041. {
  100042. FLAC__ASSERT(0 != decoder);
  100043. FLAC__ASSERT(0 != decoder->protected_);
  100044. return decoder->protected_->sample_rate;
  100045. }
  100046. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  100047. {
  100048. FLAC__ASSERT(0 != decoder);
  100049. FLAC__ASSERT(0 != decoder->protected_);
  100050. return decoder->protected_->blocksize;
  100051. }
  100052. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  100053. {
  100054. FLAC__ASSERT(0 != decoder);
  100055. FLAC__ASSERT(0 != decoder->private_);
  100056. FLAC__ASSERT(0 != position);
  100057. #if FLAC__HAS_OGG
  100058. if(decoder->private_->is_ogg)
  100059. return false;
  100060. #endif
  100061. if(0 == decoder->private_->tell_callback)
  100062. return false;
  100063. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  100064. return false;
  100065. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  100066. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  100067. return false;
  100068. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  100069. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  100070. return true;
  100071. }
  100072. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  100073. {
  100074. FLAC__ASSERT(0 != decoder);
  100075. FLAC__ASSERT(0 != decoder->private_);
  100076. FLAC__ASSERT(0 != decoder->protected_);
  100077. decoder->private_->samples_decoded = 0;
  100078. decoder->private_->do_md5_checking = false;
  100079. #if FLAC__HAS_OGG
  100080. if(decoder->private_->is_ogg)
  100081. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  100082. #endif
  100083. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  100084. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100085. return false;
  100086. }
  100087. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100088. return true;
  100089. }
  100090. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  100091. {
  100092. FLAC__ASSERT(0 != decoder);
  100093. FLAC__ASSERT(0 != decoder->private_);
  100094. FLAC__ASSERT(0 != decoder->protected_);
  100095. if(!FLAC__stream_decoder_flush(decoder)) {
  100096. /* above call sets the state for us */
  100097. return false;
  100098. }
  100099. #if FLAC__HAS_OGG
  100100. /*@@@ could go in !internal_reset_hack block below */
  100101. if(decoder->private_->is_ogg)
  100102. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  100103. #endif
  100104. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  100105. * (internal_reset_hack) don't try to rewind since we are already at
  100106. * the beginning of the stream and don't want to fail if the input is
  100107. * not seekable.
  100108. */
  100109. if(!decoder->private_->internal_reset_hack) {
  100110. if(decoder->private_->file == stdin)
  100111. return false; /* can't rewind stdin, reset fails */
  100112. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  100113. return false; /* seekable and seek fails, reset fails */
  100114. }
  100115. else
  100116. decoder->private_->internal_reset_hack = false;
  100117. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  100118. decoder->private_->has_stream_info = false;
  100119. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  100120. free(decoder->private_->seek_table.data.seek_table.points);
  100121. decoder->private_->seek_table.data.seek_table.points = 0;
  100122. decoder->private_->has_seek_table = false;
  100123. }
  100124. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  100125. /*
  100126. * This goes in reset() and not flush() because according to the spec, a
  100127. * fixed-blocksize stream must stay that way through the whole stream.
  100128. */
  100129. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  100130. /* We initialize the FLAC__MD5Context even though we may never use it. This
  100131. * is because md5 checking may be turned on to start and then turned off if
  100132. * a seek occurs. So we init the context here and finalize it in
  100133. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100134. * properly.
  100135. */
  100136. FLAC__MD5Init(&decoder->private_->md5context);
  100137. decoder->private_->first_frame_offset = 0;
  100138. decoder->private_->unparseable_frame_count = 0;
  100139. return true;
  100140. }
  100141. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100142. {
  100143. FLAC__bool got_a_frame;
  100144. FLAC__ASSERT(0 != decoder);
  100145. FLAC__ASSERT(0 != decoder->protected_);
  100146. while(1) {
  100147. switch(decoder->protected_->state) {
  100148. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100149. if(!find_metadata_(decoder))
  100150. return false; /* above function sets the status for us */
  100151. break;
  100152. case FLAC__STREAM_DECODER_READ_METADATA:
  100153. if(!read_metadata_(decoder))
  100154. return false; /* above function sets the status for us */
  100155. else
  100156. return true;
  100157. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100158. if(!frame_sync_(decoder))
  100159. return true; /* above function sets the status for us */
  100160. break;
  100161. case FLAC__STREAM_DECODER_READ_FRAME:
  100162. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100163. return false; /* above function sets the status for us */
  100164. if(got_a_frame)
  100165. return true; /* above function sets the status for us */
  100166. break;
  100167. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100168. case FLAC__STREAM_DECODER_ABORTED:
  100169. return true;
  100170. default:
  100171. FLAC__ASSERT(0);
  100172. return false;
  100173. }
  100174. }
  100175. }
  100176. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100177. {
  100178. FLAC__ASSERT(0 != decoder);
  100179. FLAC__ASSERT(0 != decoder->protected_);
  100180. while(1) {
  100181. switch(decoder->protected_->state) {
  100182. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100183. if(!find_metadata_(decoder))
  100184. return false; /* above function sets the status for us */
  100185. break;
  100186. case FLAC__STREAM_DECODER_READ_METADATA:
  100187. if(!read_metadata_(decoder))
  100188. return false; /* above function sets the status for us */
  100189. break;
  100190. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100191. case FLAC__STREAM_DECODER_READ_FRAME:
  100192. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100193. case FLAC__STREAM_DECODER_ABORTED:
  100194. return true;
  100195. default:
  100196. FLAC__ASSERT(0);
  100197. return false;
  100198. }
  100199. }
  100200. }
  100201. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100202. {
  100203. FLAC__bool dummy;
  100204. FLAC__ASSERT(0 != decoder);
  100205. FLAC__ASSERT(0 != decoder->protected_);
  100206. while(1) {
  100207. switch(decoder->protected_->state) {
  100208. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100209. if(!find_metadata_(decoder))
  100210. return false; /* above function sets the status for us */
  100211. break;
  100212. case FLAC__STREAM_DECODER_READ_METADATA:
  100213. if(!read_metadata_(decoder))
  100214. return false; /* above function sets the status for us */
  100215. break;
  100216. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100217. if(!frame_sync_(decoder))
  100218. return true; /* above function sets the status for us */
  100219. break;
  100220. case FLAC__STREAM_DECODER_READ_FRAME:
  100221. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100222. return false; /* above function sets the status for us */
  100223. break;
  100224. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100225. case FLAC__STREAM_DECODER_ABORTED:
  100226. return true;
  100227. default:
  100228. FLAC__ASSERT(0);
  100229. return false;
  100230. }
  100231. }
  100232. }
  100233. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100234. {
  100235. FLAC__bool got_a_frame;
  100236. FLAC__ASSERT(0 != decoder);
  100237. FLAC__ASSERT(0 != decoder->protected_);
  100238. while(1) {
  100239. switch(decoder->protected_->state) {
  100240. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100241. case FLAC__STREAM_DECODER_READ_METADATA:
  100242. return false; /* above function sets the status for us */
  100243. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100244. if(!frame_sync_(decoder))
  100245. return true; /* above function sets the status for us */
  100246. break;
  100247. case FLAC__STREAM_DECODER_READ_FRAME:
  100248. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100249. return false; /* above function sets the status for us */
  100250. if(got_a_frame)
  100251. return true; /* above function sets the status for us */
  100252. break;
  100253. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100254. case FLAC__STREAM_DECODER_ABORTED:
  100255. return true;
  100256. default:
  100257. FLAC__ASSERT(0);
  100258. return false;
  100259. }
  100260. }
  100261. }
  100262. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100263. {
  100264. FLAC__uint64 length;
  100265. FLAC__ASSERT(0 != decoder);
  100266. if(
  100267. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100268. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100269. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100270. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100271. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100272. )
  100273. return false;
  100274. if(0 == decoder->private_->seek_callback)
  100275. return false;
  100276. FLAC__ASSERT(decoder->private_->seek_callback);
  100277. FLAC__ASSERT(decoder->private_->tell_callback);
  100278. FLAC__ASSERT(decoder->private_->length_callback);
  100279. FLAC__ASSERT(decoder->private_->eof_callback);
  100280. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100281. return false;
  100282. decoder->private_->is_seeking = true;
  100283. /* turn off md5 checking if a seek is attempted */
  100284. decoder->private_->do_md5_checking = false;
  100285. /* 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) */
  100286. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100287. decoder->private_->is_seeking = false;
  100288. return false;
  100289. }
  100290. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100291. if(
  100292. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100293. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100294. ) {
  100295. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100296. /* above call sets the state for us */
  100297. decoder->private_->is_seeking = false;
  100298. return false;
  100299. }
  100300. /* check this again in case we didn't know total_samples the first time */
  100301. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100302. decoder->private_->is_seeking = false;
  100303. return false;
  100304. }
  100305. }
  100306. {
  100307. const FLAC__bool ok =
  100308. #if FLAC__HAS_OGG
  100309. decoder->private_->is_ogg?
  100310. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100311. #endif
  100312. seek_to_absolute_sample_(decoder, length, sample)
  100313. ;
  100314. decoder->private_->is_seeking = false;
  100315. return ok;
  100316. }
  100317. }
  100318. /***********************************************************************
  100319. *
  100320. * Protected class methods
  100321. *
  100322. ***********************************************************************/
  100323. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100324. {
  100325. FLAC__ASSERT(0 != decoder);
  100326. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100327. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100328. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100329. }
  100330. /***********************************************************************
  100331. *
  100332. * Private class methods
  100333. *
  100334. ***********************************************************************/
  100335. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100336. {
  100337. #if FLAC__HAS_OGG
  100338. decoder->private_->is_ogg = false;
  100339. #endif
  100340. decoder->private_->read_callback = 0;
  100341. decoder->private_->seek_callback = 0;
  100342. decoder->private_->tell_callback = 0;
  100343. decoder->private_->length_callback = 0;
  100344. decoder->private_->eof_callback = 0;
  100345. decoder->private_->write_callback = 0;
  100346. decoder->private_->metadata_callback = 0;
  100347. decoder->private_->error_callback = 0;
  100348. decoder->private_->client_data = 0;
  100349. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100350. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100351. decoder->private_->metadata_filter_ids_count = 0;
  100352. decoder->protected_->md5_checking = false;
  100353. #if FLAC__HAS_OGG
  100354. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100355. #endif
  100356. }
  100357. /*
  100358. * This will forcibly set stdin to binary mode (for OSes that require it)
  100359. */
  100360. FILE *get_binary_stdin_(void)
  100361. {
  100362. /* if something breaks here it is probably due to the presence or
  100363. * absence of an underscore before the identifiers 'setmode',
  100364. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100365. */
  100366. #if defined _MSC_VER || defined __MINGW32__
  100367. _setmode(_fileno(stdin), _O_BINARY);
  100368. #elif defined __CYGWIN__
  100369. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100370. setmode(_fileno(stdin), _O_BINARY);
  100371. #elif defined __EMX__
  100372. setmode(fileno(stdin), O_BINARY);
  100373. #endif
  100374. return stdin;
  100375. }
  100376. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100377. {
  100378. unsigned i;
  100379. FLAC__int32 *tmp;
  100380. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100381. return true;
  100382. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100383. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100384. if(0 != decoder->private_->output[i]) {
  100385. free(decoder->private_->output[i]-4);
  100386. decoder->private_->output[i] = 0;
  100387. }
  100388. if(0 != decoder->private_->residual_unaligned[i]) {
  100389. free(decoder->private_->residual_unaligned[i]);
  100390. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100391. }
  100392. }
  100393. for(i = 0; i < channels; i++) {
  100394. /* WATCHOUT:
  100395. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100396. * output arrays have a buffer of up to 3 zeroes in front
  100397. * (at negative indices) for alignment purposes; we use 4
  100398. * to keep the data well-aligned.
  100399. */
  100400. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100401. if(tmp == 0) {
  100402. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100403. return false;
  100404. }
  100405. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100406. decoder->private_->output[i] = tmp + 4;
  100407. /* WATCHOUT:
  100408. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100409. */
  100410. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100411. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100412. return false;
  100413. }
  100414. }
  100415. decoder->private_->output_capacity = size;
  100416. decoder->private_->output_channels = channels;
  100417. return true;
  100418. }
  100419. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100420. {
  100421. size_t i;
  100422. FLAC__ASSERT(0 != decoder);
  100423. FLAC__ASSERT(0 != decoder->private_);
  100424. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100425. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100426. return true;
  100427. return false;
  100428. }
  100429. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100430. {
  100431. FLAC__uint32 x;
  100432. unsigned i, id_;
  100433. FLAC__bool first = true;
  100434. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100435. for(i = id_ = 0; i < 4; ) {
  100436. if(decoder->private_->cached) {
  100437. x = (FLAC__uint32)decoder->private_->lookahead;
  100438. decoder->private_->cached = false;
  100439. }
  100440. else {
  100441. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100442. return false; /* read_callback_ sets the state for us */
  100443. }
  100444. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100445. first = true;
  100446. i++;
  100447. id_ = 0;
  100448. continue;
  100449. }
  100450. if(x == ID3V2_TAG_[id_]) {
  100451. id_++;
  100452. i = 0;
  100453. if(id_ == 3) {
  100454. if(!skip_id3v2_tag_(decoder))
  100455. return false; /* skip_id3v2_tag_ sets the state for us */
  100456. }
  100457. continue;
  100458. }
  100459. id_ = 0;
  100460. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100461. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100462. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100463. return false; /* read_callback_ sets the state for us */
  100464. /* 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 */
  100465. /* else we have to check if the second byte is the end of a sync code */
  100466. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100467. decoder->private_->lookahead = (FLAC__byte)x;
  100468. decoder->private_->cached = true;
  100469. }
  100470. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100471. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100472. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100473. return true;
  100474. }
  100475. }
  100476. i = 0;
  100477. if(first) {
  100478. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100479. first = false;
  100480. }
  100481. }
  100482. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100483. return true;
  100484. }
  100485. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100486. {
  100487. FLAC__bool is_last;
  100488. FLAC__uint32 i, x, type, length;
  100489. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100490. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100491. return false; /* read_callback_ sets the state for us */
  100492. is_last = x? true : false;
  100493. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100494. return false; /* read_callback_ sets the state for us */
  100495. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100496. return false; /* read_callback_ sets the state for us */
  100497. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100498. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100499. return false;
  100500. decoder->private_->has_stream_info = true;
  100501. 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))
  100502. decoder->private_->do_md5_checking = false;
  100503. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100504. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100505. }
  100506. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100507. if(!read_metadata_seektable_(decoder, is_last, length))
  100508. return false;
  100509. decoder->private_->has_seek_table = true;
  100510. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100511. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100512. }
  100513. else {
  100514. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100515. unsigned real_length = length;
  100516. FLAC__StreamMetadata block;
  100517. block.is_last = is_last;
  100518. block.type = (FLAC__MetadataType)type;
  100519. block.length = length;
  100520. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100521. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100522. return false; /* read_callback_ sets the state for us */
  100523. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100524. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100525. return false;
  100526. }
  100527. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100528. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100529. skip_it = !skip_it;
  100530. }
  100531. if(skip_it) {
  100532. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100533. return false; /* read_callback_ sets the state for us */
  100534. }
  100535. else {
  100536. switch(type) {
  100537. case FLAC__METADATA_TYPE_PADDING:
  100538. /* skip the padding bytes */
  100539. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100540. return false; /* read_callback_ sets the state for us */
  100541. break;
  100542. case FLAC__METADATA_TYPE_APPLICATION:
  100543. /* remember, we read the ID already */
  100544. if(real_length > 0) {
  100545. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100546. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100547. return false;
  100548. }
  100549. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100550. return false; /* read_callback_ sets the state for us */
  100551. }
  100552. else
  100553. block.data.application.data = 0;
  100554. break;
  100555. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100556. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100557. return false;
  100558. break;
  100559. case FLAC__METADATA_TYPE_CUESHEET:
  100560. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100561. return false;
  100562. break;
  100563. case FLAC__METADATA_TYPE_PICTURE:
  100564. if(!read_metadata_picture_(decoder, &block.data.picture))
  100565. return false;
  100566. break;
  100567. case FLAC__METADATA_TYPE_STREAMINFO:
  100568. case FLAC__METADATA_TYPE_SEEKTABLE:
  100569. FLAC__ASSERT(0);
  100570. break;
  100571. default:
  100572. if(real_length > 0) {
  100573. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100574. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100575. return false;
  100576. }
  100577. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100578. return false; /* read_callback_ sets the state for us */
  100579. }
  100580. else
  100581. block.data.unknown.data = 0;
  100582. break;
  100583. }
  100584. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100585. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100586. /* now we have to free any malloc()ed data in the block */
  100587. switch(type) {
  100588. case FLAC__METADATA_TYPE_PADDING:
  100589. break;
  100590. case FLAC__METADATA_TYPE_APPLICATION:
  100591. if(0 != block.data.application.data)
  100592. free(block.data.application.data);
  100593. break;
  100594. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100595. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100596. free(block.data.vorbis_comment.vendor_string.entry);
  100597. if(block.data.vorbis_comment.num_comments > 0)
  100598. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100599. if(0 != block.data.vorbis_comment.comments[i].entry)
  100600. free(block.data.vorbis_comment.comments[i].entry);
  100601. if(0 != block.data.vorbis_comment.comments)
  100602. free(block.data.vorbis_comment.comments);
  100603. break;
  100604. case FLAC__METADATA_TYPE_CUESHEET:
  100605. if(block.data.cue_sheet.num_tracks > 0)
  100606. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100607. if(0 != block.data.cue_sheet.tracks[i].indices)
  100608. free(block.data.cue_sheet.tracks[i].indices);
  100609. if(0 != block.data.cue_sheet.tracks)
  100610. free(block.data.cue_sheet.tracks);
  100611. break;
  100612. case FLAC__METADATA_TYPE_PICTURE:
  100613. if(0 != block.data.picture.mime_type)
  100614. free(block.data.picture.mime_type);
  100615. if(0 != block.data.picture.description)
  100616. free(block.data.picture.description);
  100617. if(0 != block.data.picture.data)
  100618. free(block.data.picture.data);
  100619. break;
  100620. case FLAC__METADATA_TYPE_STREAMINFO:
  100621. case FLAC__METADATA_TYPE_SEEKTABLE:
  100622. FLAC__ASSERT(0);
  100623. default:
  100624. if(0 != block.data.unknown.data)
  100625. free(block.data.unknown.data);
  100626. break;
  100627. }
  100628. }
  100629. }
  100630. if(is_last) {
  100631. /* if this fails, it's OK, it's just a hint for the seek routine */
  100632. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100633. decoder->private_->first_frame_offset = 0;
  100634. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100635. }
  100636. return true;
  100637. }
  100638. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100639. {
  100640. FLAC__uint32 x;
  100641. unsigned bits, used_bits = 0;
  100642. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100643. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100644. decoder->private_->stream_info.is_last = is_last;
  100645. decoder->private_->stream_info.length = length;
  100646. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100647. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100648. return false; /* read_callback_ sets the state for us */
  100649. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100650. used_bits += bits;
  100651. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100652. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100653. return false; /* read_callback_ sets the state for us */
  100654. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100655. used_bits += bits;
  100656. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100657. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100658. return false; /* read_callback_ sets the state for us */
  100659. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100660. used_bits += bits;
  100661. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100662. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100663. return false; /* read_callback_ sets the state for us */
  100664. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100665. used_bits += bits;
  100666. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100667. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100668. return false; /* read_callback_ sets the state for us */
  100669. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100670. used_bits += bits;
  100671. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100672. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100673. return false; /* read_callback_ sets the state for us */
  100674. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100675. used_bits += bits;
  100676. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100677. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100678. return false; /* read_callback_ sets the state for us */
  100679. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100680. used_bits += bits;
  100681. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100682. 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))
  100683. return false; /* read_callback_ sets the state for us */
  100684. used_bits += bits;
  100685. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100686. return false; /* read_callback_ sets the state for us */
  100687. used_bits += 16*8;
  100688. /* skip the rest of the block */
  100689. FLAC__ASSERT(used_bits % 8 == 0);
  100690. length -= (used_bits / 8);
  100691. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100692. return false; /* read_callback_ sets the state for us */
  100693. return true;
  100694. }
  100695. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100696. {
  100697. FLAC__uint32 i, x;
  100698. FLAC__uint64 xx;
  100699. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100700. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100701. decoder->private_->seek_table.is_last = is_last;
  100702. decoder->private_->seek_table.length = length;
  100703. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100704. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100705. 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)))) {
  100706. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100707. return false;
  100708. }
  100709. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100710. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100711. return false; /* read_callback_ sets the state for us */
  100712. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100713. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100714. return false; /* read_callback_ sets the state for us */
  100715. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100716. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100717. return false; /* read_callback_ sets the state for us */
  100718. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100719. }
  100720. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100721. /* if there is a partial point left, skip over it */
  100722. if(length > 0) {
  100723. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100724. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100725. return false; /* read_callback_ sets the state for us */
  100726. }
  100727. return true;
  100728. }
  100729. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100730. {
  100731. FLAC__uint32 i;
  100732. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100733. /* read vendor string */
  100734. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100735. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100736. return false; /* read_callback_ sets the state for us */
  100737. if(obj->vendor_string.length > 0) {
  100738. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100739. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100740. return false;
  100741. }
  100742. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100743. return false; /* read_callback_ sets the state for us */
  100744. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100745. }
  100746. else
  100747. obj->vendor_string.entry = 0;
  100748. /* read num comments */
  100749. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100750. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100751. return false; /* read_callback_ sets the state for us */
  100752. /* read comments */
  100753. if(obj->num_comments > 0) {
  100754. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100755. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100756. return false;
  100757. }
  100758. for(i = 0; i < obj->num_comments; i++) {
  100759. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100760. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100761. return false; /* read_callback_ sets the state for us */
  100762. if(obj->comments[i].length > 0) {
  100763. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100764. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100765. return false;
  100766. }
  100767. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100768. return false; /* read_callback_ sets the state for us */
  100769. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100770. }
  100771. else
  100772. obj->comments[i].entry = 0;
  100773. }
  100774. }
  100775. else {
  100776. obj->comments = 0;
  100777. }
  100778. return true;
  100779. }
  100780. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100781. {
  100782. FLAC__uint32 i, j, x;
  100783. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100784. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100785. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100786. 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))
  100787. return false; /* read_callback_ sets the state for us */
  100788. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100789. return false; /* read_callback_ sets the state for us */
  100790. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100791. return false; /* read_callback_ sets the state for us */
  100792. obj->is_cd = x? true : false;
  100793. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100794. return false; /* read_callback_ sets the state for us */
  100795. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100796. return false; /* read_callback_ sets the state for us */
  100797. obj->num_tracks = x;
  100798. if(obj->num_tracks > 0) {
  100799. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100800. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100801. return false;
  100802. }
  100803. for(i = 0; i < obj->num_tracks; i++) {
  100804. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100805. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100806. return false; /* read_callback_ sets the state for us */
  100807. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100808. return false; /* read_callback_ sets the state for us */
  100809. track->number = (FLAC__byte)x;
  100810. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100811. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100812. return false; /* read_callback_ sets the state for us */
  100813. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100814. return false; /* read_callback_ sets the state for us */
  100815. track->type = x;
  100816. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100817. return false; /* read_callback_ sets the state for us */
  100818. track->pre_emphasis = x;
  100819. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100820. return false; /* read_callback_ sets the state for us */
  100821. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100822. return false; /* read_callback_ sets the state for us */
  100823. track->num_indices = (FLAC__byte)x;
  100824. if(track->num_indices > 0) {
  100825. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100826. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100827. return false;
  100828. }
  100829. for(j = 0; j < track->num_indices; j++) {
  100830. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100831. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100832. return false; /* read_callback_ sets the state for us */
  100833. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100834. return false; /* read_callback_ sets the state for us */
  100835. index->number = (FLAC__byte)x;
  100836. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100837. return false; /* read_callback_ sets the state for us */
  100838. }
  100839. }
  100840. }
  100841. }
  100842. return true;
  100843. }
  100844. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100845. {
  100846. FLAC__uint32 x;
  100847. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100848. /* read type */
  100849. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100850. return false; /* read_callback_ sets the state for us */
  100851. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100852. /* read MIME type */
  100853. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100854. return false; /* read_callback_ sets the state for us */
  100855. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100856. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100857. return false;
  100858. }
  100859. if(x > 0) {
  100860. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100861. return false; /* read_callback_ sets the state for us */
  100862. }
  100863. obj->mime_type[x] = '\0';
  100864. /* read description */
  100865. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100866. return false; /* read_callback_ sets the state for us */
  100867. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100868. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100869. return false;
  100870. }
  100871. if(x > 0) {
  100872. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100873. return false; /* read_callback_ sets the state for us */
  100874. }
  100875. obj->description[x] = '\0';
  100876. /* read width */
  100877. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100878. return false; /* read_callback_ sets the state for us */
  100879. /* read height */
  100880. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100881. return false; /* read_callback_ sets the state for us */
  100882. /* read depth */
  100883. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100884. return false; /* read_callback_ sets the state for us */
  100885. /* read colors */
  100886. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100887. return false; /* read_callback_ sets the state for us */
  100888. /* read data */
  100889. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100890. return false; /* read_callback_ sets the state for us */
  100891. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100892. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100893. return false;
  100894. }
  100895. if(obj->data_length > 0) {
  100896. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100897. return false; /* read_callback_ sets the state for us */
  100898. }
  100899. return true;
  100900. }
  100901. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100902. {
  100903. FLAC__uint32 x;
  100904. unsigned i, skip;
  100905. /* skip the version and flags bytes */
  100906. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100907. return false; /* read_callback_ sets the state for us */
  100908. /* get the size (in bytes) to skip */
  100909. skip = 0;
  100910. for(i = 0; i < 4; i++) {
  100911. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100912. return false; /* read_callback_ sets the state for us */
  100913. skip <<= 7;
  100914. skip |= (x & 0x7f);
  100915. }
  100916. /* skip the rest of the tag */
  100917. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100918. return false; /* read_callback_ sets the state for us */
  100919. return true;
  100920. }
  100921. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100922. {
  100923. FLAC__uint32 x;
  100924. FLAC__bool first = true;
  100925. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100926. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100927. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100928. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100929. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100930. return true;
  100931. }
  100932. }
  100933. /* make sure we're byte aligned */
  100934. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100935. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100936. return false; /* read_callback_ sets the state for us */
  100937. }
  100938. while(1) {
  100939. if(decoder->private_->cached) {
  100940. x = (FLAC__uint32)decoder->private_->lookahead;
  100941. decoder->private_->cached = false;
  100942. }
  100943. else {
  100944. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100945. return false; /* read_callback_ sets the state for us */
  100946. }
  100947. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100948. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100949. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100950. return false; /* read_callback_ sets the state for us */
  100951. /* 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 */
  100952. /* else we have to check if the second byte is the end of a sync code */
  100953. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100954. decoder->private_->lookahead = (FLAC__byte)x;
  100955. decoder->private_->cached = true;
  100956. }
  100957. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100958. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100959. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100960. return true;
  100961. }
  100962. }
  100963. if(first) {
  100964. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100965. first = false;
  100966. }
  100967. }
  100968. return true;
  100969. }
  100970. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100971. {
  100972. unsigned channel;
  100973. unsigned i;
  100974. FLAC__int32 mid, side;
  100975. unsigned frame_crc; /* the one we calculate from the input stream */
  100976. FLAC__uint32 x;
  100977. *got_a_frame = false;
  100978. /* init the CRC */
  100979. frame_crc = 0;
  100980. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100981. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100982. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100983. if(!read_frame_header_(decoder))
  100984. return false;
  100985. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100986. return true;
  100987. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100988. return false;
  100989. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100990. /*
  100991. * first figure the correct bits-per-sample of the subframe
  100992. */
  100993. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100994. switch(decoder->private_->frame.header.channel_assignment) {
  100995. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100996. /* no adjustment needed */
  100997. break;
  100998. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100999. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101000. if(channel == 1)
  101001. bps++;
  101002. break;
  101003. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101004. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101005. if(channel == 0)
  101006. bps++;
  101007. break;
  101008. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101009. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101010. if(channel == 1)
  101011. bps++;
  101012. break;
  101013. default:
  101014. FLAC__ASSERT(0);
  101015. }
  101016. /*
  101017. * now read it
  101018. */
  101019. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  101020. return false;
  101021. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101022. return true;
  101023. }
  101024. if(!read_zero_padding_(decoder))
  101025. return false;
  101026. 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) */
  101027. return true;
  101028. /*
  101029. * Read the frame CRC-16 from the footer and check
  101030. */
  101031. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  101032. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  101033. return false; /* read_callback_ sets the state for us */
  101034. if(frame_crc == x) {
  101035. if(do_full_decode) {
  101036. /* Undo any special channel coding */
  101037. switch(decoder->private_->frame.header.channel_assignment) {
  101038. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101039. /* do nothing */
  101040. break;
  101041. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101042. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101043. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101044. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  101045. break;
  101046. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101047. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101048. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101049. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  101050. break;
  101051. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101052. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101053. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101054. #if 1
  101055. mid = decoder->private_->output[0][i];
  101056. side = decoder->private_->output[1][i];
  101057. mid <<= 1;
  101058. mid |= (side & 1); /* i.e. if 'side' is odd... */
  101059. decoder->private_->output[0][i] = (mid + side) >> 1;
  101060. decoder->private_->output[1][i] = (mid - side) >> 1;
  101061. #else
  101062. /* OPT: without 'side' temp variable */
  101063. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  101064. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  101065. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  101066. #endif
  101067. }
  101068. break;
  101069. default:
  101070. FLAC__ASSERT(0);
  101071. break;
  101072. }
  101073. }
  101074. }
  101075. else {
  101076. /* Bad frame, emit error and zero the output signal */
  101077. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  101078. if(do_full_decode) {
  101079. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101080. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101081. }
  101082. }
  101083. }
  101084. *got_a_frame = true;
  101085. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  101086. if(decoder->private_->next_fixed_block_size)
  101087. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  101088. /* put the latest values into the public section of the decoder instance */
  101089. decoder->protected_->channels = decoder->private_->frame.header.channels;
  101090. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  101091. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  101092. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  101093. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  101094. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101095. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  101096. /* write it */
  101097. if(do_full_decode) {
  101098. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  101099. return false;
  101100. }
  101101. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101102. return true;
  101103. }
  101104. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  101105. {
  101106. FLAC__uint32 x;
  101107. FLAC__uint64 xx;
  101108. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  101109. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  101110. unsigned raw_header_len;
  101111. FLAC__bool is_unparseable = false;
  101112. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  101113. /* init the raw header with the saved bits from synchronization */
  101114. raw_header[0] = decoder->private_->header_warmup[0];
  101115. raw_header[1] = decoder->private_->header_warmup[1];
  101116. raw_header_len = 2;
  101117. /* check to make sure that reserved bit is 0 */
  101118. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  101119. is_unparseable = true;
  101120. /*
  101121. * Note that along the way as we read the header, we look for a sync
  101122. * code inside. If we find one it would indicate that our original
  101123. * sync was bad since there cannot be a sync code in a valid header.
  101124. *
  101125. * Three kinds of things can go wrong when reading the frame header:
  101126. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  101127. * If we don't find a sync code, it can end up looking like we read
  101128. * a valid but unparseable header, until getting to the frame header
  101129. * CRC. Even then we could get a false positive on the CRC.
  101130. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  101131. * future encoder).
  101132. * 3) We may be on a damaged frame which appears valid but unparseable.
  101133. *
  101134. * For all these reasons, we try and read a complete frame header as
  101135. * long as it seems valid, even if unparseable, up until the frame
  101136. * header CRC.
  101137. */
  101138. /*
  101139. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101140. */
  101141. for(i = 0; i < 2; i++) {
  101142. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101143. return false; /* read_callback_ sets the state for us */
  101144. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101145. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101146. decoder->private_->lookahead = (FLAC__byte)x;
  101147. decoder->private_->cached = true;
  101148. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101149. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101150. return true;
  101151. }
  101152. raw_header[raw_header_len++] = (FLAC__byte)x;
  101153. }
  101154. switch(x = raw_header[2] >> 4) {
  101155. case 0:
  101156. is_unparseable = true;
  101157. break;
  101158. case 1:
  101159. decoder->private_->frame.header.blocksize = 192;
  101160. break;
  101161. case 2:
  101162. case 3:
  101163. case 4:
  101164. case 5:
  101165. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101166. break;
  101167. case 6:
  101168. case 7:
  101169. blocksize_hint = x;
  101170. break;
  101171. case 8:
  101172. case 9:
  101173. case 10:
  101174. case 11:
  101175. case 12:
  101176. case 13:
  101177. case 14:
  101178. case 15:
  101179. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101180. break;
  101181. default:
  101182. FLAC__ASSERT(0);
  101183. break;
  101184. }
  101185. switch(x = raw_header[2] & 0x0f) {
  101186. case 0:
  101187. if(decoder->private_->has_stream_info)
  101188. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101189. else
  101190. is_unparseable = true;
  101191. break;
  101192. case 1:
  101193. decoder->private_->frame.header.sample_rate = 88200;
  101194. break;
  101195. case 2:
  101196. decoder->private_->frame.header.sample_rate = 176400;
  101197. break;
  101198. case 3:
  101199. decoder->private_->frame.header.sample_rate = 192000;
  101200. break;
  101201. case 4:
  101202. decoder->private_->frame.header.sample_rate = 8000;
  101203. break;
  101204. case 5:
  101205. decoder->private_->frame.header.sample_rate = 16000;
  101206. break;
  101207. case 6:
  101208. decoder->private_->frame.header.sample_rate = 22050;
  101209. break;
  101210. case 7:
  101211. decoder->private_->frame.header.sample_rate = 24000;
  101212. break;
  101213. case 8:
  101214. decoder->private_->frame.header.sample_rate = 32000;
  101215. break;
  101216. case 9:
  101217. decoder->private_->frame.header.sample_rate = 44100;
  101218. break;
  101219. case 10:
  101220. decoder->private_->frame.header.sample_rate = 48000;
  101221. break;
  101222. case 11:
  101223. decoder->private_->frame.header.sample_rate = 96000;
  101224. break;
  101225. case 12:
  101226. case 13:
  101227. case 14:
  101228. sample_rate_hint = x;
  101229. break;
  101230. case 15:
  101231. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101232. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101233. return true;
  101234. default:
  101235. FLAC__ASSERT(0);
  101236. }
  101237. x = (unsigned)(raw_header[3] >> 4);
  101238. if(x & 8) {
  101239. decoder->private_->frame.header.channels = 2;
  101240. switch(x & 7) {
  101241. case 0:
  101242. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101243. break;
  101244. case 1:
  101245. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101246. break;
  101247. case 2:
  101248. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101249. break;
  101250. default:
  101251. is_unparseable = true;
  101252. break;
  101253. }
  101254. }
  101255. else {
  101256. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101257. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101258. }
  101259. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101260. case 0:
  101261. if(decoder->private_->has_stream_info)
  101262. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101263. else
  101264. is_unparseable = true;
  101265. break;
  101266. case 1:
  101267. decoder->private_->frame.header.bits_per_sample = 8;
  101268. break;
  101269. case 2:
  101270. decoder->private_->frame.header.bits_per_sample = 12;
  101271. break;
  101272. case 4:
  101273. decoder->private_->frame.header.bits_per_sample = 16;
  101274. break;
  101275. case 5:
  101276. decoder->private_->frame.header.bits_per_sample = 20;
  101277. break;
  101278. case 6:
  101279. decoder->private_->frame.header.bits_per_sample = 24;
  101280. break;
  101281. case 3:
  101282. case 7:
  101283. is_unparseable = true;
  101284. break;
  101285. default:
  101286. FLAC__ASSERT(0);
  101287. break;
  101288. }
  101289. /* check to make sure that reserved bit is 0 */
  101290. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101291. is_unparseable = true;
  101292. /* read the frame's starting sample number (or frame number as the case may be) */
  101293. if(
  101294. raw_header[1] & 0x01 ||
  101295. /*@@@ 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 */
  101296. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101297. ) { /* variable blocksize */
  101298. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101299. return false; /* read_callback_ sets the state for us */
  101300. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101301. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101302. decoder->private_->cached = true;
  101303. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101304. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101305. return true;
  101306. }
  101307. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101308. decoder->private_->frame.header.number.sample_number = xx;
  101309. }
  101310. else { /* fixed blocksize */
  101311. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101312. return false; /* read_callback_ sets the state for us */
  101313. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101314. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101315. decoder->private_->cached = true;
  101316. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101317. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101318. return true;
  101319. }
  101320. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101321. decoder->private_->frame.header.number.frame_number = x;
  101322. }
  101323. if(blocksize_hint) {
  101324. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101325. return false; /* read_callback_ sets the state for us */
  101326. raw_header[raw_header_len++] = (FLAC__byte)x;
  101327. if(blocksize_hint == 7) {
  101328. FLAC__uint32 _x;
  101329. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101330. return false; /* read_callback_ sets the state for us */
  101331. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101332. x = (x << 8) | _x;
  101333. }
  101334. decoder->private_->frame.header.blocksize = x+1;
  101335. }
  101336. if(sample_rate_hint) {
  101337. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101338. return false; /* read_callback_ sets the state for us */
  101339. raw_header[raw_header_len++] = (FLAC__byte)x;
  101340. if(sample_rate_hint != 12) {
  101341. FLAC__uint32 _x;
  101342. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101343. return false; /* read_callback_ sets the state for us */
  101344. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101345. x = (x << 8) | _x;
  101346. }
  101347. if(sample_rate_hint == 12)
  101348. decoder->private_->frame.header.sample_rate = x*1000;
  101349. else if(sample_rate_hint == 13)
  101350. decoder->private_->frame.header.sample_rate = x;
  101351. else
  101352. decoder->private_->frame.header.sample_rate = x*10;
  101353. }
  101354. /* read the CRC-8 byte */
  101355. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101356. return false; /* read_callback_ sets the state for us */
  101357. crc8 = (FLAC__byte)x;
  101358. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101359. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101360. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101361. return true;
  101362. }
  101363. /* calculate the sample number from the frame number if needed */
  101364. decoder->private_->next_fixed_block_size = 0;
  101365. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101366. x = decoder->private_->frame.header.number.frame_number;
  101367. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101368. if(decoder->private_->fixed_block_size)
  101369. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101370. else if(decoder->private_->has_stream_info) {
  101371. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101372. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101373. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101374. }
  101375. else
  101376. is_unparseable = true;
  101377. }
  101378. else if(x == 0) {
  101379. decoder->private_->frame.header.number.sample_number = 0;
  101380. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101381. }
  101382. else {
  101383. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101384. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101385. }
  101386. }
  101387. if(is_unparseable) {
  101388. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101389. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101390. return true;
  101391. }
  101392. return true;
  101393. }
  101394. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101395. {
  101396. FLAC__uint32 x;
  101397. FLAC__bool wasted_bits;
  101398. unsigned i;
  101399. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101400. return false; /* read_callback_ sets the state for us */
  101401. wasted_bits = (x & 1);
  101402. x &= 0xfe;
  101403. if(wasted_bits) {
  101404. unsigned u;
  101405. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101406. return false; /* read_callback_ sets the state for us */
  101407. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101408. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101409. }
  101410. else
  101411. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101412. /*
  101413. * Lots of magic numbers here
  101414. */
  101415. if(x & 0x80) {
  101416. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101417. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101418. return true;
  101419. }
  101420. else if(x == 0) {
  101421. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101422. return false;
  101423. }
  101424. else if(x == 2) {
  101425. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101426. return false;
  101427. }
  101428. else if(x < 16) {
  101429. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101430. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101431. return true;
  101432. }
  101433. else if(x <= 24) {
  101434. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101435. return false;
  101436. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101437. return true;
  101438. }
  101439. else if(x < 64) {
  101440. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101441. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101442. return true;
  101443. }
  101444. else {
  101445. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101446. return false;
  101447. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101448. return true;
  101449. }
  101450. if(wasted_bits && do_full_decode) {
  101451. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101452. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101453. decoder->private_->output[channel][i] <<= x;
  101454. }
  101455. return true;
  101456. }
  101457. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101458. {
  101459. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101460. FLAC__int32 x;
  101461. unsigned i;
  101462. FLAC__int32 *output = decoder->private_->output[channel];
  101463. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101464. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101465. return false; /* read_callback_ sets the state for us */
  101466. subframe->value = x;
  101467. /* decode the subframe */
  101468. if(do_full_decode) {
  101469. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101470. output[i] = x;
  101471. }
  101472. return true;
  101473. }
  101474. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101475. {
  101476. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101477. FLAC__int32 i32;
  101478. FLAC__uint32 u32;
  101479. unsigned u;
  101480. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101481. subframe->residual = decoder->private_->residual[channel];
  101482. subframe->order = order;
  101483. /* read warm-up samples */
  101484. for(u = 0; u < order; u++) {
  101485. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101486. return false; /* read_callback_ sets the state for us */
  101487. subframe->warmup[u] = i32;
  101488. }
  101489. /* read entropy coding method info */
  101490. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101491. return false; /* read_callback_ sets the state for us */
  101492. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101493. switch(subframe->entropy_coding_method.type) {
  101494. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101495. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101496. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101497. return false; /* read_callback_ sets the state for us */
  101498. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101499. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101500. break;
  101501. default:
  101502. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101503. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101504. return true;
  101505. }
  101506. /* read residual */
  101507. switch(subframe->entropy_coding_method.type) {
  101508. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101509. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101510. 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))
  101511. return false;
  101512. break;
  101513. default:
  101514. FLAC__ASSERT(0);
  101515. }
  101516. /* decode the subframe */
  101517. if(do_full_decode) {
  101518. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101519. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101520. }
  101521. return true;
  101522. }
  101523. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101524. {
  101525. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101526. FLAC__int32 i32;
  101527. FLAC__uint32 u32;
  101528. unsigned u;
  101529. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101530. subframe->residual = decoder->private_->residual[channel];
  101531. subframe->order = order;
  101532. /* read warm-up samples */
  101533. for(u = 0; u < order; u++) {
  101534. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101535. return false; /* read_callback_ sets the state for us */
  101536. subframe->warmup[u] = i32;
  101537. }
  101538. /* read qlp coeff precision */
  101539. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101540. return false; /* read_callback_ sets the state for us */
  101541. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101542. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101543. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101544. return true;
  101545. }
  101546. subframe->qlp_coeff_precision = u32+1;
  101547. /* read qlp shift */
  101548. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101549. return false; /* read_callback_ sets the state for us */
  101550. subframe->quantization_level = i32;
  101551. /* read quantized lp coefficiencts */
  101552. for(u = 0; u < order; u++) {
  101553. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101554. return false; /* read_callback_ sets the state for us */
  101555. subframe->qlp_coeff[u] = i32;
  101556. }
  101557. /* read entropy coding method info */
  101558. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101559. return false; /* read_callback_ sets the state for us */
  101560. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101561. switch(subframe->entropy_coding_method.type) {
  101562. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101563. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101564. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101565. return false; /* read_callback_ sets the state for us */
  101566. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101567. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101568. break;
  101569. default:
  101570. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101571. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101572. return true;
  101573. }
  101574. /* read residual */
  101575. switch(subframe->entropy_coding_method.type) {
  101576. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101577. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101578. 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))
  101579. return false;
  101580. break;
  101581. default:
  101582. FLAC__ASSERT(0);
  101583. }
  101584. /* decode the subframe */
  101585. if(do_full_decode) {
  101586. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101587. /*@@@@@@ technically not pessimistic enough, should be more like
  101588. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101589. */
  101590. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101591. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101592. if(order <= 8)
  101593. 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);
  101594. else
  101595. 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);
  101596. }
  101597. else
  101598. 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);
  101599. else
  101600. 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);
  101601. }
  101602. return true;
  101603. }
  101604. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101605. {
  101606. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101607. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101608. unsigned i;
  101609. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101610. subframe->data = residual;
  101611. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101612. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101613. return false; /* read_callback_ sets the state for us */
  101614. residual[i] = x;
  101615. }
  101616. /* decode the subframe */
  101617. if(do_full_decode)
  101618. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101619. return true;
  101620. }
  101621. 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)
  101622. {
  101623. FLAC__uint32 rice_parameter;
  101624. int i;
  101625. unsigned partition, sample, u;
  101626. const unsigned partitions = 1u << partition_order;
  101627. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101628. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101629. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101630. /* sanity checks */
  101631. if(partition_order == 0) {
  101632. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101633. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101634. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101635. return true;
  101636. }
  101637. }
  101638. else {
  101639. if(partition_samples < predictor_order) {
  101640. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101641. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101642. return true;
  101643. }
  101644. }
  101645. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101646. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101647. return false;
  101648. }
  101649. sample = 0;
  101650. for(partition = 0; partition < partitions; partition++) {
  101651. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101652. return false; /* read_callback_ sets the state for us */
  101653. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101654. if(rice_parameter < pesc) {
  101655. partitioned_rice_contents->raw_bits[partition] = 0;
  101656. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101657. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101658. return false; /* read_callback_ sets the state for us */
  101659. sample += u;
  101660. }
  101661. else {
  101662. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101663. return false; /* read_callback_ sets the state for us */
  101664. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101665. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101666. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101667. return false; /* read_callback_ sets the state for us */
  101668. residual[sample] = i;
  101669. }
  101670. }
  101671. }
  101672. return true;
  101673. }
  101674. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101675. {
  101676. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101677. FLAC__uint32 zero = 0;
  101678. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101679. return false; /* read_callback_ sets the state for us */
  101680. if(zero != 0) {
  101681. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101682. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101683. }
  101684. }
  101685. return true;
  101686. }
  101687. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101688. {
  101689. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101690. if(
  101691. #if FLAC__HAS_OGG
  101692. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101693. !decoder->private_->is_ogg &&
  101694. #endif
  101695. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101696. ) {
  101697. *bytes = 0;
  101698. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101699. return false;
  101700. }
  101701. else if(*bytes > 0) {
  101702. /* While seeking, it is possible for our seek to land in the
  101703. * middle of audio data that looks exactly like a frame header
  101704. * from a future version of an encoder. When that happens, our
  101705. * error callback will get an
  101706. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101707. * unparseable_frame_count. But there is a remote possibility
  101708. * that it is properly synced at such a "future-codec frame",
  101709. * so to make sure, we wait to see many "unparseable" errors in
  101710. * a row before bailing out.
  101711. */
  101712. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101713. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101714. return false;
  101715. }
  101716. else {
  101717. const FLAC__StreamDecoderReadStatus status =
  101718. #if FLAC__HAS_OGG
  101719. decoder->private_->is_ogg?
  101720. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101721. #endif
  101722. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101723. ;
  101724. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101725. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101726. return false;
  101727. }
  101728. else if(*bytes == 0) {
  101729. if(
  101730. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101731. (
  101732. #if FLAC__HAS_OGG
  101733. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101734. !decoder->private_->is_ogg &&
  101735. #endif
  101736. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101737. )
  101738. ) {
  101739. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101740. return false;
  101741. }
  101742. else
  101743. return true;
  101744. }
  101745. else
  101746. return true;
  101747. }
  101748. }
  101749. else {
  101750. /* abort to avoid a deadlock */
  101751. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101752. return false;
  101753. }
  101754. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101755. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101756. * and at the same time hit the end of the stream (for example, seeking
  101757. * to a point that is after the beginning of the last Ogg page). There
  101758. * is no way to report an Ogg sync loss through the callbacks (see note
  101759. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101760. * So to keep the decoder from stopping at this point we gate the call
  101761. * to the eof_callback and let the Ogg decoder aspect set the
  101762. * end-of-stream state when it is needed.
  101763. */
  101764. }
  101765. #if FLAC__HAS_OGG
  101766. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101767. {
  101768. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101769. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101770. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101771. /* we don't really have a way to handle lost sync via read
  101772. * callback so we'll let it pass and let the underlying
  101773. * FLAC decoder catch the error
  101774. */
  101775. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101776. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101777. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101778. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101779. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101780. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101781. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101782. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101783. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101784. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101785. default:
  101786. FLAC__ASSERT(0);
  101787. /* double protection */
  101788. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101789. }
  101790. }
  101791. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101792. {
  101793. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101794. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101795. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101796. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101797. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101798. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101799. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101800. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101801. default:
  101802. /* double protection: */
  101803. FLAC__ASSERT(0);
  101804. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101805. }
  101806. }
  101807. #endif
  101808. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101809. {
  101810. if(decoder->private_->is_seeking) {
  101811. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101812. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101813. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101814. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101815. #if FLAC__HAS_OGG
  101816. decoder->private_->got_a_frame = true;
  101817. #endif
  101818. decoder->private_->last_frame = *frame; /* save the frame */
  101819. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101820. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101821. /* kick out of seek mode */
  101822. decoder->private_->is_seeking = false;
  101823. /* shift out the samples before target_sample */
  101824. if(delta > 0) {
  101825. unsigned channel;
  101826. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101827. for(channel = 0; channel < frame->header.channels; channel++)
  101828. newbuffer[channel] = buffer[channel] + delta;
  101829. decoder->private_->last_frame.header.blocksize -= delta;
  101830. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101831. /* write the relevant samples */
  101832. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101833. }
  101834. else {
  101835. /* write the relevant samples */
  101836. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101837. }
  101838. }
  101839. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101840. }
  101841. /*
  101842. * If we never got STREAMINFO, turn off MD5 checking to save
  101843. * cycles since we don't have a sum to compare to anyway
  101844. */
  101845. if(!decoder->private_->has_stream_info)
  101846. decoder->private_->do_md5_checking = false;
  101847. if(decoder->private_->do_md5_checking) {
  101848. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101849. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101850. }
  101851. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101852. }
  101853. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101854. {
  101855. if(!decoder->private_->is_seeking)
  101856. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101857. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101858. decoder->private_->unparseable_frame_count++;
  101859. }
  101860. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101861. {
  101862. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101863. FLAC__int64 pos = -1;
  101864. int i;
  101865. unsigned approx_bytes_per_frame;
  101866. FLAC__bool first_seek = true;
  101867. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101868. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101869. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101870. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101871. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101872. /* take these from the current frame in case they've changed mid-stream */
  101873. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101874. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101875. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101876. /* use values from stream info if we didn't decode a frame */
  101877. if(channels == 0)
  101878. channels = decoder->private_->stream_info.data.stream_info.channels;
  101879. if(bps == 0)
  101880. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101881. /* we are just guessing here */
  101882. if(max_framesize > 0)
  101883. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101884. /*
  101885. * Check if it's a known fixed-blocksize stream. Note that though
  101886. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101887. * never get a STREAMINFO block when decoding so the value of
  101888. * min_blocksize might be zero.
  101889. */
  101890. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101891. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101892. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101893. }
  101894. else
  101895. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101896. /*
  101897. * First, we set an upper and lower bound on where in the
  101898. * stream we will search. For now we assume the worst case
  101899. * scenario, which is our best guess at the beginning of
  101900. * the first frame and end of the stream.
  101901. */
  101902. lower_bound = first_frame_offset;
  101903. lower_bound_sample = 0;
  101904. upper_bound = stream_length;
  101905. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101906. /*
  101907. * Now we refine the bounds if we have a seektable with
  101908. * suitable points. Note that according to the spec they
  101909. * must be ordered by ascending sample number.
  101910. *
  101911. * Note: to protect against invalid seek tables we will ignore points
  101912. * that have frame_samples==0 or sample_number>=total_samples
  101913. */
  101914. if(seek_table) {
  101915. FLAC__uint64 new_lower_bound = lower_bound;
  101916. FLAC__uint64 new_upper_bound = upper_bound;
  101917. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101918. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101919. /* find the closest seek point <= target_sample, if it exists */
  101920. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101921. if(
  101922. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101923. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101924. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101925. seek_table->points[i].sample_number <= target_sample
  101926. )
  101927. break;
  101928. }
  101929. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101930. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101931. new_lower_bound_sample = seek_table->points[i].sample_number;
  101932. }
  101933. /* find the closest seek point > target_sample, if it exists */
  101934. for(i = 0; i < (int)seek_table->num_points; i++) {
  101935. if(
  101936. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101937. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101938. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101939. seek_table->points[i].sample_number > target_sample
  101940. )
  101941. break;
  101942. }
  101943. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101944. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101945. new_upper_bound_sample = seek_table->points[i].sample_number;
  101946. }
  101947. /* final protection against unsorted seek tables; keep original values if bogus */
  101948. if(new_upper_bound >= new_lower_bound) {
  101949. lower_bound = new_lower_bound;
  101950. upper_bound = new_upper_bound;
  101951. lower_bound_sample = new_lower_bound_sample;
  101952. upper_bound_sample = new_upper_bound_sample;
  101953. }
  101954. }
  101955. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101956. /* there are 2 insidious ways that the following equality occurs, which
  101957. * we need to fix:
  101958. * 1) total_samples is 0 (unknown) and target_sample is 0
  101959. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101960. * exactly equal to the last seek point in the seek table; this
  101961. * means there is no seek point above it, and upper_bound_samples
  101962. * remains equal to the estimate (of target_samples) we made above
  101963. * in either case it does not hurt to move upper_bound_sample up by 1
  101964. */
  101965. if(upper_bound_sample == lower_bound_sample)
  101966. upper_bound_sample++;
  101967. decoder->private_->target_sample = target_sample;
  101968. while(1) {
  101969. /* check if the bounds are still ok */
  101970. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101971. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101972. return false;
  101973. }
  101974. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101975. #if defined _MSC_VER || defined __MINGW32__
  101976. /* with VC++ you have to spoon feed it the casting */
  101977. 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;
  101978. #else
  101979. 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;
  101980. #endif
  101981. #else
  101982. /* a little less accurate: */
  101983. if(upper_bound - lower_bound < 0xffffffff)
  101984. 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;
  101985. else /* @@@ WATCHOUT, ~2TB limit */
  101986. 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;
  101987. #endif
  101988. if(pos >= (FLAC__int64)upper_bound)
  101989. pos = (FLAC__int64)upper_bound - 1;
  101990. if(pos < (FLAC__int64)lower_bound)
  101991. pos = (FLAC__int64)lower_bound;
  101992. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101993. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101994. return false;
  101995. }
  101996. if(!FLAC__stream_decoder_flush(decoder)) {
  101997. /* above call sets the state for us */
  101998. return false;
  101999. }
  102000. /* Now we need to get a frame. First we need to reset our
  102001. * unparseable_frame_count; if we get too many unparseable
  102002. * frames in a row, the read callback will return
  102003. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  102004. * FLAC__stream_decoder_process_single() to return false.
  102005. */
  102006. decoder->private_->unparseable_frame_count = 0;
  102007. if(!FLAC__stream_decoder_process_single(decoder)) {
  102008. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102009. return false;
  102010. }
  102011. /* our write callback will change the state when it gets to the target frame */
  102012. /* 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 */
  102013. #if 0
  102014. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  102015. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  102016. break;
  102017. #endif
  102018. if(!decoder->private_->is_seeking)
  102019. break;
  102020. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102021. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102022. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  102023. if (pos == (FLAC__int64)lower_bound) {
  102024. /* can't move back any more than the first frame, something is fatally wrong */
  102025. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102026. return false;
  102027. }
  102028. /* our last move backwards wasn't big enough, try again */
  102029. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  102030. continue;
  102031. }
  102032. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  102033. first_seek = false;
  102034. /* make sure we are not seeking in corrupted stream */
  102035. if (this_frame_sample < lower_bound_sample) {
  102036. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102037. return false;
  102038. }
  102039. /* we need to narrow the search */
  102040. if(target_sample < this_frame_sample) {
  102041. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102042. /*@@@@@@ what will decode position be if at end of stream? */
  102043. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  102044. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102045. return false;
  102046. }
  102047. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  102048. }
  102049. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  102050. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102051. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  102052. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102053. return false;
  102054. }
  102055. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  102056. }
  102057. }
  102058. return true;
  102059. }
  102060. #if FLAC__HAS_OGG
  102061. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  102062. {
  102063. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  102064. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  102065. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  102066. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  102067. FLAC__bool did_a_seek;
  102068. unsigned iteration = 0;
  102069. /* In the first iterations, we will calculate the target byte position
  102070. * by the distance from the target sample to left_sample and
  102071. * right_sample (let's call it "proportional search"). After that, we
  102072. * will switch to binary search.
  102073. */
  102074. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  102075. /* We will switch to a linear search once our current sample is less
  102076. * than this number of samples ahead of the target sample
  102077. */
  102078. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  102079. /* If the total number of samples is unknown, use a large value, and
  102080. * force binary search immediately.
  102081. */
  102082. if(right_sample == 0) {
  102083. right_sample = (FLAC__uint64)(-1);
  102084. BINARY_SEARCH_AFTER_ITERATION = 0;
  102085. }
  102086. decoder->private_->target_sample = target_sample;
  102087. for( ; ; iteration++) {
  102088. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  102089. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  102090. pos = (right_pos + left_pos) / 2;
  102091. }
  102092. else {
  102093. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102094. #if defined _MSC_VER || defined __MINGW32__
  102095. /* with MSVC you have to spoon feed it the casting */
  102096. 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));
  102097. #else
  102098. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  102099. #endif
  102100. #else
  102101. /* a little less accurate: */
  102102. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  102103. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  102104. else /* @@@ WATCHOUT, ~2TB limit */
  102105. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  102106. #endif
  102107. /* @@@ TODO: might want to limit pos to some distance
  102108. * before EOF, to make sure we land before the last frame,
  102109. * thereby getting a this_frame_sample and so having a better
  102110. * estimate.
  102111. */
  102112. }
  102113. /* physical seek */
  102114. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102115. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102116. return false;
  102117. }
  102118. if(!FLAC__stream_decoder_flush(decoder)) {
  102119. /* above call sets the state for us */
  102120. return false;
  102121. }
  102122. did_a_seek = true;
  102123. }
  102124. else
  102125. did_a_seek = false;
  102126. decoder->private_->got_a_frame = false;
  102127. if(!FLAC__stream_decoder_process_single(decoder)) {
  102128. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102129. return false;
  102130. }
  102131. if(!decoder->private_->got_a_frame) {
  102132. if(did_a_seek) {
  102133. /* this can happen if we seek to a point after the last frame; we drop
  102134. * to binary search right away in this case to avoid any wasted
  102135. * iterations of proportional search.
  102136. */
  102137. right_pos = pos;
  102138. BINARY_SEARCH_AFTER_ITERATION = 0;
  102139. }
  102140. else {
  102141. /* this can probably only happen if total_samples is unknown and the
  102142. * target_sample is past the end of the stream
  102143. */
  102144. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102145. return false;
  102146. }
  102147. }
  102148. /* our write callback will change the state when it gets to the target frame */
  102149. else if(!decoder->private_->is_seeking) {
  102150. break;
  102151. }
  102152. else {
  102153. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102154. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102155. if (did_a_seek) {
  102156. if (this_frame_sample <= target_sample) {
  102157. /* The 'equal' case should not happen, since
  102158. * FLAC__stream_decoder_process_single()
  102159. * should recognize that it has hit the
  102160. * target sample and we would exit through
  102161. * the 'break' above.
  102162. */
  102163. FLAC__ASSERT(this_frame_sample != target_sample);
  102164. left_sample = this_frame_sample;
  102165. /* sanity check to avoid infinite loop */
  102166. if (left_pos == pos) {
  102167. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102168. return false;
  102169. }
  102170. left_pos = pos;
  102171. }
  102172. else if(this_frame_sample > target_sample) {
  102173. right_sample = this_frame_sample;
  102174. /* sanity check to avoid infinite loop */
  102175. if (right_pos == pos) {
  102176. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102177. return false;
  102178. }
  102179. right_pos = pos;
  102180. }
  102181. }
  102182. }
  102183. }
  102184. return true;
  102185. }
  102186. #endif
  102187. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102188. {
  102189. (void)client_data;
  102190. if(*bytes > 0) {
  102191. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102192. if(ferror(decoder->private_->file))
  102193. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102194. else if(*bytes == 0)
  102195. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102196. else
  102197. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102198. }
  102199. else
  102200. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102201. }
  102202. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102203. {
  102204. (void)client_data;
  102205. if(decoder->private_->file == stdin)
  102206. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102207. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102208. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102209. else
  102210. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102211. }
  102212. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102213. {
  102214. off_t pos;
  102215. (void)client_data;
  102216. if(decoder->private_->file == stdin)
  102217. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102218. else if((pos = ftello(decoder->private_->file)) < 0)
  102219. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102220. else {
  102221. *absolute_byte_offset = (FLAC__uint64)pos;
  102222. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102223. }
  102224. }
  102225. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102226. {
  102227. struct stat filestats;
  102228. (void)client_data;
  102229. if(decoder->private_->file == stdin)
  102230. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102231. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102232. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102233. else {
  102234. *stream_length = (FLAC__uint64)filestats.st_size;
  102235. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102236. }
  102237. }
  102238. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102239. {
  102240. (void)client_data;
  102241. return feof(decoder->private_->file)? true : false;
  102242. }
  102243. #endif
  102244. /*** End of inlined file: stream_decoder.c ***/
  102245. /*** Start of inlined file: stream_encoder.c ***/
  102246. /*** Start of inlined file: juce_FlacHeader.h ***/
  102247. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102248. // tasks..
  102249. #define VERSION "1.2.1"
  102250. #define FLAC__NO_DLL 1
  102251. #if JUCE_MSVC
  102252. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102253. #endif
  102254. #if JUCE_MAC
  102255. #define FLAC__SYS_DARWIN 1
  102256. #endif
  102257. /*** End of inlined file: juce_FlacHeader.h ***/
  102258. #if JUCE_USE_FLAC
  102259. #if HAVE_CONFIG_H
  102260. # include <config.h>
  102261. #endif
  102262. #if defined _MSC_VER || defined __MINGW32__
  102263. #include <io.h> /* for _setmode() */
  102264. #include <fcntl.h> /* for _O_BINARY */
  102265. #endif
  102266. #if defined __CYGWIN__ || defined __EMX__
  102267. #include <io.h> /* for setmode(), O_BINARY */
  102268. #include <fcntl.h> /* for _O_BINARY */
  102269. #endif
  102270. #include <limits.h>
  102271. #include <stdio.h>
  102272. #include <stdlib.h> /* for malloc() */
  102273. #include <string.h> /* for memcpy() */
  102274. #include <sys/types.h> /* for off_t */
  102275. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102276. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102277. #define fseeko fseek
  102278. #define ftello ftell
  102279. #endif
  102280. #endif
  102281. /*** Start of inlined file: stream_encoder.h ***/
  102282. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102283. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102284. #if FLAC__HAS_OGG
  102285. #include "private/ogg_encoder_aspect.h"
  102286. #endif
  102287. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102288. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102289. typedef enum {
  102290. FLAC__APODIZATION_BARTLETT,
  102291. FLAC__APODIZATION_BARTLETT_HANN,
  102292. FLAC__APODIZATION_BLACKMAN,
  102293. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102294. FLAC__APODIZATION_CONNES,
  102295. FLAC__APODIZATION_FLATTOP,
  102296. FLAC__APODIZATION_GAUSS,
  102297. FLAC__APODIZATION_HAMMING,
  102298. FLAC__APODIZATION_HANN,
  102299. FLAC__APODIZATION_KAISER_BESSEL,
  102300. FLAC__APODIZATION_NUTTALL,
  102301. FLAC__APODIZATION_RECTANGLE,
  102302. FLAC__APODIZATION_TRIANGLE,
  102303. FLAC__APODIZATION_TUKEY,
  102304. FLAC__APODIZATION_WELCH
  102305. } FLAC__ApodizationFunction;
  102306. typedef struct {
  102307. FLAC__ApodizationFunction type;
  102308. union {
  102309. struct {
  102310. FLAC__real stddev;
  102311. } gauss;
  102312. struct {
  102313. FLAC__real p;
  102314. } tukey;
  102315. } parameters;
  102316. } FLAC__ApodizationSpecification;
  102317. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102318. typedef struct FLAC__StreamEncoderProtected {
  102319. FLAC__StreamEncoderState state;
  102320. FLAC__bool verify;
  102321. FLAC__bool streamable_subset;
  102322. FLAC__bool do_md5;
  102323. FLAC__bool do_mid_side_stereo;
  102324. FLAC__bool loose_mid_side_stereo;
  102325. unsigned channels;
  102326. unsigned bits_per_sample;
  102327. unsigned sample_rate;
  102328. unsigned blocksize;
  102329. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102330. unsigned num_apodizations;
  102331. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102332. #endif
  102333. unsigned max_lpc_order;
  102334. unsigned qlp_coeff_precision;
  102335. FLAC__bool do_qlp_coeff_prec_search;
  102336. FLAC__bool do_exhaustive_model_search;
  102337. FLAC__bool do_escape_coding;
  102338. unsigned min_residual_partition_order;
  102339. unsigned max_residual_partition_order;
  102340. unsigned rice_parameter_search_dist;
  102341. FLAC__uint64 total_samples_estimate;
  102342. FLAC__StreamMetadata **metadata;
  102343. unsigned num_metadata_blocks;
  102344. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102345. #if FLAC__HAS_OGG
  102346. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102347. #endif
  102348. } FLAC__StreamEncoderProtected;
  102349. #endif
  102350. /*** End of inlined file: stream_encoder.h ***/
  102351. #if FLAC__HAS_OGG
  102352. #include "include/private/ogg_helper.h"
  102353. #include "include/private/ogg_mapping.h"
  102354. #endif
  102355. /*** Start of inlined file: stream_encoder_framing.h ***/
  102356. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102357. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102358. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102359. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102360. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102361. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102362. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102363. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102364. #endif
  102365. /*** End of inlined file: stream_encoder_framing.h ***/
  102366. /*** Start of inlined file: window.h ***/
  102367. #ifndef FLAC__PRIVATE__WINDOW_H
  102368. #define FLAC__PRIVATE__WINDOW_H
  102369. #ifdef HAVE_CONFIG_H
  102370. #include <config.h>
  102371. #endif
  102372. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102373. /*
  102374. * FLAC__window_*()
  102375. * --------------------------------------------------------------------
  102376. * Calculates window coefficients according to different apodization
  102377. * functions.
  102378. *
  102379. * OUT window[0,L-1]
  102380. * IN L (number of points in window)
  102381. */
  102382. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102383. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102384. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102385. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102386. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102387. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102388. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102389. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102390. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102391. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102392. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102393. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102394. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102395. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102396. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102397. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102398. #endif
  102399. /*** End of inlined file: window.h ***/
  102400. #ifndef FLaC__INLINE
  102401. #define FLaC__INLINE
  102402. #endif
  102403. #ifdef min
  102404. #undef min
  102405. #endif
  102406. #define min(x,y) ((x)<(y)?(x):(y))
  102407. #ifdef max
  102408. #undef max
  102409. #endif
  102410. #define max(x,y) ((x)>(y)?(x):(y))
  102411. /* Exact Rice codeword length calculation is off by default. The simple
  102412. * (and fast) estimation (of how many bits a residual value will be
  102413. * encoded with) in this encoder is very good, almost always yielding
  102414. * compression within 0.1% of exact calculation.
  102415. */
  102416. #undef EXACT_RICE_BITS_CALCULATION
  102417. /* Rice parameter searching is off by default. The simple (and fast)
  102418. * parameter estimation in this encoder is very good, almost always
  102419. * yielding compression within 0.1% of the optimal parameters.
  102420. */
  102421. #undef ENABLE_RICE_PARAMETER_SEARCH
  102422. typedef struct {
  102423. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102424. unsigned size; /* of each data[] in samples */
  102425. unsigned tail;
  102426. } verify_input_fifo;
  102427. typedef struct {
  102428. const FLAC__byte *data;
  102429. unsigned capacity;
  102430. unsigned bytes;
  102431. } verify_output;
  102432. typedef enum {
  102433. ENCODER_IN_MAGIC = 0,
  102434. ENCODER_IN_METADATA = 1,
  102435. ENCODER_IN_AUDIO = 2
  102436. } EncoderStateHint;
  102437. static struct CompressionLevels {
  102438. FLAC__bool do_mid_side_stereo;
  102439. FLAC__bool loose_mid_side_stereo;
  102440. unsigned max_lpc_order;
  102441. unsigned qlp_coeff_precision;
  102442. FLAC__bool do_qlp_coeff_prec_search;
  102443. FLAC__bool do_escape_coding;
  102444. FLAC__bool do_exhaustive_model_search;
  102445. unsigned min_residual_partition_order;
  102446. unsigned max_residual_partition_order;
  102447. unsigned rice_parameter_search_dist;
  102448. } compression_levels_[] = {
  102449. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102450. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102451. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102452. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102453. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102454. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102455. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102456. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102457. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102458. };
  102459. /***********************************************************************
  102460. *
  102461. * Private class method prototypes
  102462. *
  102463. ***********************************************************************/
  102464. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102465. static void free_(FLAC__StreamEncoder *encoder);
  102466. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102467. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102468. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102469. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102470. #if FLAC__HAS_OGG
  102471. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102472. #endif
  102473. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102474. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102475. static FLAC__bool process_subframe_(
  102476. FLAC__StreamEncoder *encoder,
  102477. unsigned min_partition_order,
  102478. unsigned max_partition_order,
  102479. const FLAC__FrameHeader *frame_header,
  102480. unsigned subframe_bps,
  102481. const FLAC__int32 integer_signal[],
  102482. FLAC__Subframe *subframe[2],
  102483. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102484. FLAC__int32 *residual[2],
  102485. unsigned *best_subframe,
  102486. unsigned *best_bits
  102487. );
  102488. static FLAC__bool add_subframe_(
  102489. FLAC__StreamEncoder *encoder,
  102490. unsigned blocksize,
  102491. unsigned subframe_bps,
  102492. const FLAC__Subframe *subframe,
  102493. FLAC__BitWriter *frame
  102494. );
  102495. static unsigned evaluate_constant_subframe_(
  102496. FLAC__StreamEncoder *encoder,
  102497. const FLAC__int32 signal,
  102498. unsigned blocksize,
  102499. unsigned subframe_bps,
  102500. FLAC__Subframe *subframe
  102501. );
  102502. static unsigned evaluate_fixed_subframe_(
  102503. FLAC__StreamEncoder *encoder,
  102504. const FLAC__int32 signal[],
  102505. FLAC__int32 residual[],
  102506. FLAC__uint64 abs_residual_partition_sums[],
  102507. unsigned raw_bits_per_partition[],
  102508. unsigned blocksize,
  102509. unsigned subframe_bps,
  102510. unsigned order,
  102511. unsigned rice_parameter,
  102512. unsigned rice_parameter_limit,
  102513. unsigned min_partition_order,
  102514. unsigned max_partition_order,
  102515. FLAC__bool do_escape_coding,
  102516. unsigned rice_parameter_search_dist,
  102517. FLAC__Subframe *subframe,
  102518. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102519. );
  102520. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102521. static unsigned evaluate_lpc_subframe_(
  102522. FLAC__StreamEncoder *encoder,
  102523. const FLAC__int32 signal[],
  102524. FLAC__int32 residual[],
  102525. FLAC__uint64 abs_residual_partition_sums[],
  102526. unsigned raw_bits_per_partition[],
  102527. const FLAC__real lp_coeff[],
  102528. unsigned blocksize,
  102529. unsigned subframe_bps,
  102530. unsigned order,
  102531. unsigned qlp_coeff_precision,
  102532. unsigned rice_parameter,
  102533. unsigned rice_parameter_limit,
  102534. unsigned min_partition_order,
  102535. unsigned max_partition_order,
  102536. FLAC__bool do_escape_coding,
  102537. unsigned rice_parameter_search_dist,
  102538. FLAC__Subframe *subframe,
  102539. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102540. );
  102541. #endif
  102542. static unsigned evaluate_verbatim_subframe_(
  102543. FLAC__StreamEncoder *encoder,
  102544. const FLAC__int32 signal[],
  102545. unsigned blocksize,
  102546. unsigned subframe_bps,
  102547. FLAC__Subframe *subframe
  102548. );
  102549. static unsigned find_best_partition_order_(
  102550. struct FLAC__StreamEncoderPrivate *private_,
  102551. const FLAC__int32 residual[],
  102552. FLAC__uint64 abs_residual_partition_sums[],
  102553. unsigned raw_bits_per_partition[],
  102554. unsigned residual_samples,
  102555. unsigned predictor_order,
  102556. unsigned rice_parameter,
  102557. unsigned rice_parameter_limit,
  102558. unsigned min_partition_order,
  102559. unsigned max_partition_order,
  102560. unsigned bps,
  102561. FLAC__bool do_escape_coding,
  102562. unsigned rice_parameter_search_dist,
  102563. FLAC__EntropyCodingMethod *best_ecm
  102564. );
  102565. static void precompute_partition_info_sums_(
  102566. const FLAC__int32 residual[],
  102567. FLAC__uint64 abs_residual_partition_sums[],
  102568. unsigned residual_samples,
  102569. unsigned predictor_order,
  102570. unsigned min_partition_order,
  102571. unsigned max_partition_order,
  102572. unsigned bps
  102573. );
  102574. static void precompute_partition_info_escapes_(
  102575. const FLAC__int32 residual[],
  102576. unsigned raw_bits_per_partition[],
  102577. unsigned residual_samples,
  102578. unsigned predictor_order,
  102579. unsigned min_partition_order,
  102580. unsigned max_partition_order
  102581. );
  102582. static FLAC__bool set_partitioned_rice_(
  102583. #ifdef EXACT_RICE_BITS_CALCULATION
  102584. const FLAC__int32 residual[],
  102585. #endif
  102586. const FLAC__uint64 abs_residual_partition_sums[],
  102587. const unsigned raw_bits_per_partition[],
  102588. const unsigned residual_samples,
  102589. const unsigned predictor_order,
  102590. const unsigned suggested_rice_parameter,
  102591. const unsigned rice_parameter_limit,
  102592. const unsigned rice_parameter_search_dist,
  102593. const unsigned partition_order,
  102594. const FLAC__bool search_for_escapes,
  102595. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102596. unsigned *bits
  102597. );
  102598. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102599. /* verify-related routines: */
  102600. static void append_to_verify_fifo_(
  102601. verify_input_fifo *fifo,
  102602. const FLAC__int32 * const input[],
  102603. unsigned input_offset,
  102604. unsigned channels,
  102605. unsigned wide_samples
  102606. );
  102607. static void append_to_verify_fifo_interleaved_(
  102608. verify_input_fifo *fifo,
  102609. const FLAC__int32 input[],
  102610. unsigned input_offset,
  102611. unsigned channels,
  102612. unsigned wide_samples
  102613. );
  102614. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102615. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102616. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102617. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102618. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102619. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102620. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102621. 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);
  102622. static FILE *get_binary_stdout_(void);
  102623. /***********************************************************************
  102624. *
  102625. * Private class data
  102626. *
  102627. ***********************************************************************/
  102628. typedef struct FLAC__StreamEncoderPrivate {
  102629. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102630. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102631. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102632. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102633. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102634. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102635. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102636. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102637. #endif
  102638. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102639. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102640. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102641. FLAC__int32 *residual_workspace_mid_side[2][2];
  102642. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102643. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102644. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102645. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102646. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102647. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102648. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102649. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102650. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102651. unsigned best_subframe_mid_side[2];
  102652. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102653. unsigned best_subframe_bits_mid_side[2];
  102654. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102655. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102656. FLAC__BitWriter *frame; /* the current frame being worked on */
  102657. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102658. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102659. FLAC__ChannelAssignment last_channel_assignment;
  102660. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102661. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102662. unsigned current_sample_number;
  102663. unsigned current_frame_number;
  102664. FLAC__MD5Context md5context;
  102665. FLAC__CPUInfo cpuinfo;
  102666. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102667. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102668. #else
  102669. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102670. #endif
  102671. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102672. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102673. 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[]);
  102674. 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[]);
  102675. 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[]);
  102676. #endif
  102677. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102678. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102679. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102680. FLAC__bool disable_constant_subframes;
  102681. FLAC__bool disable_fixed_subframes;
  102682. FLAC__bool disable_verbatim_subframes;
  102683. #if FLAC__HAS_OGG
  102684. FLAC__bool is_ogg;
  102685. #endif
  102686. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102687. FLAC__StreamEncoderSeekCallback seek_callback;
  102688. FLAC__StreamEncoderTellCallback tell_callback;
  102689. FLAC__StreamEncoderWriteCallback write_callback;
  102690. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102691. FLAC__StreamEncoderProgressCallback progress_callback;
  102692. void *client_data;
  102693. unsigned first_seekpoint_to_check;
  102694. FILE *file; /* only used when encoding to a file */
  102695. FLAC__uint64 bytes_written;
  102696. FLAC__uint64 samples_written;
  102697. unsigned frames_written;
  102698. unsigned total_frames_estimate;
  102699. /* unaligned (original) pointers to allocated data */
  102700. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102701. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102702. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102703. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102704. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102705. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102706. FLAC__real *windowed_signal_unaligned;
  102707. #endif
  102708. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102709. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102710. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102711. unsigned *raw_bits_per_partition_unaligned;
  102712. /*
  102713. * These fields have been moved here from private function local
  102714. * declarations merely to save stack space during encoding.
  102715. */
  102716. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102717. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102718. #endif
  102719. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102720. /*
  102721. * The data for the verify section
  102722. */
  102723. struct {
  102724. FLAC__StreamDecoder *decoder;
  102725. EncoderStateHint state_hint;
  102726. FLAC__bool needs_magic_hack;
  102727. verify_input_fifo input_fifo;
  102728. verify_output output;
  102729. struct {
  102730. FLAC__uint64 absolute_sample;
  102731. unsigned frame_number;
  102732. unsigned channel;
  102733. unsigned sample;
  102734. FLAC__int32 expected;
  102735. FLAC__int32 got;
  102736. } error_stats;
  102737. } verify;
  102738. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102739. } FLAC__StreamEncoderPrivate;
  102740. /***********************************************************************
  102741. *
  102742. * Public static class data
  102743. *
  102744. ***********************************************************************/
  102745. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102746. "FLAC__STREAM_ENCODER_OK",
  102747. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102748. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102749. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102750. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102751. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102752. "FLAC__STREAM_ENCODER_IO_ERROR",
  102753. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102754. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102755. };
  102756. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102757. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102758. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102759. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102760. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102761. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102762. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102763. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102764. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102765. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102766. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102767. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102768. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102769. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102770. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102771. };
  102772. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102773. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102774. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102775. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102776. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102777. };
  102778. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102779. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102780. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102781. };
  102782. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102783. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102784. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102785. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102786. };
  102787. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102788. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102789. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102790. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102791. };
  102792. /* Number of samples that will be overread to watch for end of stream. By
  102793. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102794. * always try to read blocksize+1 samples before encoding a block, so that
  102795. * even if the stream has a total sample count that is an integral multiple
  102796. * of the blocksize, we will still notice when we are encoding the last
  102797. * block. This is needed, for example, to correctly set the end-of-stream
  102798. * marker in Ogg FLAC.
  102799. *
  102800. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102801. * not really any reason to change it.
  102802. */
  102803. static const unsigned OVERREAD_ = 1;
  102804. /***********************************************************************
  102805. *
  102806. * Class constructor/destructor
  102807. *
  102808. */
  102809. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102810. {
  102811. FLAC__StreamEncoder *encoder;
  102812. unsigned i;
  102813. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102814. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102815. if(encoder == 0) {
  102816. return 0;
  102817. }
  102818. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102819. if(encoder->protected_ == 0) {
  102820. free(encoder);
  102821. return 0;
  102822. }
  102823. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102824. if(encoder->private_ == 0) {
  102825. free(encoder->protected_);
  102826. free(encoder);
  102827. return 0;
  102828. }
  102829. encoder->private_->frame = FLAC__bitwriter_new();
  102830. if(encoder->private_->frame == 0) {
  102831. free(encoder->private_);
  102832. free(encoder->protected_);
  102833. free(encoder);
  102834. return 0;
  102835. }
  102836. encoder->private_->file = 0;
  102837. set_defaults_enc(encoder);
  102838. encoder->private_->is_being_deleted = false;
  102839. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102840. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102841. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102842. }
  102843. for(i = 0; i < 2; i++) {
  102844. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102845. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102846. }
  102847. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102848. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102849. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102850. }
  102851. for(i = 0; i < 2; i++) {
  102852. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102853. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102854. }
  102855. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102856. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102857. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102858. }
  102859. for(i = 0; i < 2; i++) {
  102860. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102861. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102862. }
  102863. for(i = 0; i < 2; i++)
  102864. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102865. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102866. return encoder;
  102867. }
  102868. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102869. {
  102870. unsigned i;
  102871. FLAC__ASSERT(0 != encoder);
  102872. FLAC__ASSERT(0 != encoder->protected_);
  102873. FLAC__ASSERT(0 != encoder->private_);
  102874. FLAC__ASSERT(0 != encoder->private_->frame);
  102875. encoder->private_->is_being_deleted = true;
  102876. (void)FLAC__stream_encoder_finish(encoder);
  102877. if(0 != encoder->private_->verify.decoder)
  102878. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102879. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102880. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102881. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102882. }
  102883. for(i = 0; i < 2; i++) {
  102884. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102885. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102886. }
  102887. for(i = 0; i < 2; i++)
  102888. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102889. FLAC__bitwriter_delete(encoder->private_->frame);
  102890. free(encoder->private_);
  102891. free(encoder->protected_);
  102892. free(encoder);
  102893. }
  102894. /***********************************************************************
  102895. *
  102896. * Public class methods
  102897. *
  102898. ***********************************************************************/
  102899. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102900. FLAC__StreamEncoder *encoder,
  102901. FLAC__StreamEncoderReadCallback read_callback,
  102902. FLAC__StreamEncoderWriteCallback write_callback,
  102903. FLAC__StreamEncoderSeekCallback seek_callback,
  102904. FLAC__StreamEncoderTellCallback tell_callback,
  102905. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102906. void *client_data,
  102907. FLAC__bool is_ogg
  102908. )
  102909. {
  102910. unsigned i;
  102911. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102912. FLAC__ASSERT(0 != encoder);
  102913. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102914. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102915. #if !FLAC__HAS_OGG
  102916. if(is_ogg)
  102917. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102918. #endif
  102919. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102920. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102921. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102922. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102923. if(encoder->protected_->channels != 2) {
  102924. encoder->protected_->do_mid_side_stereo = false;
  102925. encoder->protected_->loose_mid_side_stereo = false;
  102926. }
  102927. else if(!encoder->protected_->do_mid_side_stereo)
  102928. encoder->protected_->loose_mid_side_stereo = false;
  102929. if(encoder->protected_->bits_per_sample >= 32)
  102930. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102931. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102932. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102933. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102934. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102935. if(encoder->protected_->blocksize == 0) {
  102936. if(encoder->protected_->max_lpc_order == 0)
  102937. encoder->protected_->blocksize = 1152;
  102938. else
  102939. encoder->protected_->blocksize = 4096;
  102940. }
  102941. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102942. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102943. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102944. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102945. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102946. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102947. if(encoder->protected_->qlp_coeff_precision == 0) {
  102948. if(encoder->protected_->bits_per_sample < 16) {
  102949. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102950. /* @@@ until then we'll make a guess */
  102951. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102952. }
  102953. else if(encoder->protected_->bits_per_sample == 16) {
  102954. if(encoder->protected_->blocksize <= 192)
  102955. encoder->protected_->qlp_coeff_precision = 7;
  102956. else if(encoder->protected_->blocksize <= 384)
  102957. encoder->protected_->qlp_coeff_precision = 8;
  102958. else if(encoder->protected_->blocksize <= 576)
  102959. encoder->protected_->qlp_coeff_precision = 9;
  102960. else if(encoder->protected_->blocksize <= 1152)
  102961. encoder->protected_->qlp_coeff_precision = 10;
  102962. else if(encoder->protected_->blocksize <= 2304)
  102963. encoder->protected_->qlp_coeff_precision = 11;
  102964. else if(encoder->protected_->blocksize <= 4608)
  102965. encoder->protected_->qlp_coeff_precision = 12;
  102966. else
  102967. encoder->protected_->qlp_coeff_precision = 13;
  102968. }
  102969. else {
  102970. if(encoder->protected_->blocksize <= 384)
  102971. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102972. else if(encoder->protected_->blocksize <= 1152)
  102973. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102974. else
  102975. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102976. }
  102977. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102978. }
  102979. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102980. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102981. if(encoder->protected_->streamable_subset) {
  102982. if(
  102983. encoder->protected_->blocksize != 192 &&
  102984. encoder->protected_->blocksize != 576 &&
  102985. encoder->protected_->blocksize != 1152 &&
  102986. encoder->protected_->blocksize != 2304 &&
  102987. encoder->protected_->blocksize != 4608 &&
  102988. encoder->protected_->blocksize != 256 &&
  102989. encoder->protected_->blocksize != 512 &&
  102990. encoder->protected_->blocksize != 1024 &&
  102991. encoder->protected_->blocksize != 2048 &&
  102992. encoder->protected_->blocksize != 4096 &&
  102993. encoder->protected_->blocksize != 8192 &&
  102994. encoder->protected_->blocksize != 16384
  102995. )
  102996. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102997. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102998. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102999. if(
  103000. encoder->protected_->bits_per_sample != 8 &&
  103001. encoder->protected_->bits_per_sample != 12 &&
  103002. encoder->protected_->bits_per_sample != 16 &&
  103003. encoder->protected_->bits_per_sample != 20 &&
  103004. encoder->protected_->bits_per_sample != 24
  103005. )
  103006. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103007. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  103008. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103009. if(
  103010. encoder->protected_->sample_rate <= 48000 &&
  103011. (
  103012. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  103013. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  103014. )
  103015. ) {
  103016. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103017. }
  103018. }
  103019. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103020. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  103021. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  103022. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  103023. #if FLAC__HAS_OGG
  103024. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  103025. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  103026. unsigned i;
  103027. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  103028. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103029. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  103030. for( ; i > 0; i--)
  103031. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  103032. encoder->protected_->metadata[0] = vc;
  103033. break;
  103034. }
  103035. }
  103036. }
  103037. #endif
  103038. /* keep track of any SEEKTABLE block */
  103039. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  103040. unsigned i;
  103041. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103042. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103043. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  103044. break; /* take only the first one */
  103045. }
  103046. }
  103047. }
  103048. /* validate metadata */
  103049. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  103050. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103051. metadata_has_seektable = false;
  103052. metadata_has_vorbis_comment = false;
  103053. metadata_picture_has_type1 = false;
  103054. metadata_picture_has_type2 = false;
  103055. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103056. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  103057. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  103058. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103059. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103060. if(metadata_has_seektable) /* only one is allowed */
  103061. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103062. metadata_has_seektable = true;
  103063. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  103064. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103065. }
  103066. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103067. if(metadata_has_vorbis_comment) /* only one is allowed */
  103068. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103069. metadata_has_vorbis_comment = true;
  103070. }
  103071. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  103072. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  103073. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103074. }
  103075. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  103076. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  103077. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103078. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  103079. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  103080. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103081. metadata_picture_has_type1 = true;
  103082. /* standard icon must be 32x32 pixel PNG */
  103083. if(
  103084. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  103085. (
  103086. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  103087. m->data.picture.width != 32 ||
  103088. m->data.picture.height != 32
  103089. )
  103090. )
  103091. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103092. }
  103093. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  103094. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  103095. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103096. metadata_picture_has_type2 = true;
  103097. }
  103098. }
  103099. }
  103100. encoder->private_->input_capacity = 0;
  103101. for(i = 0; i < encoder->protected_->channels; i++) {
  103102. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  103103. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103104. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  103105. #endif
  103106. }
  103107. for(i = 0; i < 2; i++) {
  103108. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  103109. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103110. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  103111. #endif
  103112. }
  103113. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103114. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  103115. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  103116. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  103117. #endif
  103118. for(i = 0; i < encoder->protected_->channels; i++) {
  103119. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  103120. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  103121. encoder->private_->best_subframe[i] = 0;
  103122. }
  103123. for(i = 0; i < 2; i++) {
  103124. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  103125. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  103126. encoder->private_->best_subframe_mid_side[i] = 0;
  103127. }
  103128. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  103129. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  103130. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103131. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  103132. #else
  103133. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103134. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103135. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103136. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103137. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103138. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103139. 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);
  103140. #endif
  103141. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103142. encoder->private_->loose_mid_side_stereo_frames = 1;
  103143. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103144. encoder->private_->current_sample_number = 0;
  103145. encoder->private_->current_frame_number = 0;
  103146. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103147. 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? */
  103148. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103149. /*
  103150. * get the CPU info and set the function pointers
  103151. */
  103152. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103153. /* first default to the non-asm routines */
  103154. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103155. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103156. #endif
  103157. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103158. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103159. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103160. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103161. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103162. #endif
  103163. /* now override with asm where appropriate */
  103164. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103165. # ifndef FLAC__NO_ASM
  103166. if(encoder->private_->cpuinfo.use_asm) {
  103167. # ifdef FLAC__CPU_IA32
  103168. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103169. # ifdef FLAC__HAS_NASM
  103170. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103171. if(encoder->protected_->max_lpc_order < 4)
  103172. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103173. else if(encoder->protected_->max_lpc_order < 8)
  103174. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103175. else if(encoder->protected_->max_lpc_order < 12)
  103176. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103177. else
  103178. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103179. }
  103180. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103181. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103182. else
  103183. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103184. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103185. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103186. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103187. }
  103188. else {
  103189. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103190. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103191. }
  103192. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103193. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103194. # endif /* FLAC__HAS_NASM */
  103195. # endif /* FLAC__CPU_IA32 */
  103196. }
  103197. # endif /* !FLAC__NO_ASM */
  103198. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103199. /* finally override based on wide-ness if necessary */
  103200. if(encoder->private_->use_wide_by_block) {
  103201. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103202. }
  103203. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103204. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103205. #if FLAC__HAS_OGG
  103206. encoder->private_->is_ogg = is_ogg;
  103207. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103208. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103209. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103210. }
  103211. #endif
  103212. encoder->private_->read_callback = read_callback;
  103213. encoder->private_->write_callback = write_callback;
  103214. encoder->private_->seek_callback = seek_callback;
  103215. encoder->private_->tell_callback = tell_callback;
  103216. encoder->private_->metadata_callback = metadata_callback;
  103217. encoder->private_->client_data = client_data;
  103218. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103219. /* the above function sets the state for us in case of an error */
  103220. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103221. }
  103222. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103223. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103224. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103225. }
  103226. /*
  103227. * Set up the verify stuff if necessary
  103228. */
  103229. if(encoder->protected_->verify) {
  103230. /*
  103231. * First, set up the fifo which will hold the
  103232. * original signal to compare against
  103233. */
  103234. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103235. for(i = 0; i < encoder->protected_->channels; i++) {
  103236. 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))) {
  103237. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103238. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103239. }
  103240. }
  103241. encoder->private_->verify.input_fifo.tail = 0;
  103242. /*
  103243. * Now set up a stream decoder for verification
  103244. */
  103245. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103246. if(0 == encoder->private_->verify.decoder) {
  103247. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103248. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103249. }
  103250. 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) {
  103251. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103252. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103253. }
  103254. }
  103255. encoder->private_->verify.error_stats.absolute_sample = 0;
  103256. encoder->private_->verify.error_stats.frame_number = 0;
  103257. encoder->private_->verify.error_stats.channel = 0;
  103258. encoder->private_->verify.error_stats.sample = 0;
  103259. encoder->private_->verify.error_stats.expected = 0;
  103260. encoder->private_->verify.error_stats.got = 0;
  103261. /*
  103262. * These must be done before we write any metadata, because that
  103263. * calls the write_callback, which uses these values.
  103264. */
  103265. encoder->private_->first_seekpoint_to_check = 0;
  103266. encoder->private_->samples_written = 0;
  103267. encoder->protected_->streaminfo_offset = 0;
  103268. encoder->protected_->seektable_offset = 0;
  103269. encoder->protected_->audio_offset = 0;
  103270. /*
  103271. * write the stream header
  103272. */
  103273. if(encoder->protected_->verify)
  103274. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103275. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103276. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103277. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103278. }
  103279. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103280. /* the above function sets the state for us in case of an error */
  103281. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103282. }
  103283. /*
  103284. * write the STREAMINFO metadata block
  103285. */
  103286. if(encoder->protected_->verify)
  103287. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103288. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103289. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103290. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103291. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103292. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103293. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103294. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103295. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103296. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103297. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103298. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103299. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103300. if(encoder->protected_->do_md5)
  103301. FLAC__MD5Init(&encoder->private_->md5context);
  103302. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103303. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103304. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103305. }
  103306. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103307. /* the above function sets the state for us in case of an error */
  103308. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103309. }
  103310. /*
  103311. * Now that the STREAMINFO block is written, we can init this to an
  103312. * absurdly-high value...
  103313. */
  103314. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103315. /* ... and clear this to 0 */
  103316. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103317. /*
  103318. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103319. * if not, we will write an empty one (FLAC__add_metadata_block()
  103320. * automatically supplies the vendor string).
  103321. *
  103322. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103323. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103324. * true it will have already insured that the metadata list is properly
  103325. * ordered.)
  103326. */
  103327. if(!metadata_has_vorbis_comment) {
  103328. FLAC__StreamMetadata vorbis_comment;
  103329. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103330. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103331. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103332. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103333. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103334. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103335. vorbis_comment.data.vorbis_comment.comments = 0;
  103336. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103337. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103338. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103339. }
  103340. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103341. /* the above function sets the state for us in case of an error */
  103342. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103343. }
  103344. }
  103345. /*
  103346. * write the user's metadata blocks
  103347. */
  103348. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103349. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103350. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103351. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103352. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103353. }
  103354. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103355. /* the above function sets the state for us in case of an error */
  103356. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103357. }
  103358. }
  103359. /* now that all the metadata is written, we save the stream offset */
  103360. 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 */
  103361. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103362. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103363. }
  103364. if(encoder->protected_->verify)
  103365. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103366. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103367. }
  103368. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103369. FLAC__StreamEncoder *encoder,
  103370. FLAC__StreamEncoderWriteCallback write_callback,
  103371. FLAC__StreamEncoderSeekCallback seek_callback,
  103372. FLAC__StreamEncoderTellCallback tell_callback,
  103373. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103374. void *client_data
  103375. )
  103376. {
  103377. return init_stream_internal_enc(
  103378. encoder,
  103379. /*read_callback=*/0,
  103380. write_callback,
  103381. seek_callback,
  103382. tell_callback,
  103383. metadata_callback,
  103384. client_data,
  103385. /*is_ogg=*/false
  103386. );
  103387. }
  103388. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103389. FLAC__StreamEncoder *encoder,
  103390. FLAC__StreamEncoderReadCallback read_callback,
  103391. FLAC__StreamEncoderWriteCallback write_callback,
  103392. FLAC__StreamEncoderSeekCallback seek_callback,
  103393. FLAC__StreamEncoderTellCallback tell_callback,
  103394. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103395. void *client_data
  103396. )
  103397. {
  103398. return init_stream_internal_enc(
  103399. encoder,
  103400. read_callback,
  103401. write_callback,
  103402. seek_callback,
  103403. tell_callback,
  103404. metadata_callback,
  103405. client_data,
  103406. /*is_ogg=*/true
  103407. );
  103408. }
  103409. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103410. FLAC__StreamEncoder *encoder,
  103411. FILE *file,
  103412. FLAC__StreamEncoderProgressCallback progress_callback,
  103413. void *client_data,
  103414. FLAC__bool is_ogg
  103415. )
  103416. {
  103417. FLAC__StreamEncoderInitStatus init_status;
  103418. FLAC__ASSERT(0 != encoder);
  103419. FLAC__ASSERT(0 != file);
  103420. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103421. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103422. /* double protection */
  103423. if(file == 0) {
  103424. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103425. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103426. }
  103427. /*
  103428. * To make sure that our file does not go unclosed after an error, we
  103429. * must assign the FILE pointer before any further error can occur in
  103430. * this routine.
  103431. */
  103432. if(file == stdout)
  103433. file = get_binary_stdout_(); /* just to be safe */
  103434. encoder->private_->file = file;
  103435. encoder->private_->progress_callback = progress_callback;
  103436. encoder->private_->bytes_written = 0;
  103437. encoder->private_->samples_written = 0;
  103438. encoder->private_->frames_written = 0;
  103439. init_status = init_stream_internal_enc(
  103440. encoder,
  103441. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103442. file_write_callback_,
  103443. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103444. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103445. /*metadata_callback=*/0,
  103446. client_data,
  103447. is_ogg
  103448. );
  103449. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103450. /* the above function sets the state for us in case of an error */
  103451. return init_status;
  103452. }
  103453. {
  103454. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103455. FLAC__ASSERT(blocksize != 0);
  103456. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103457. }
  103458. return init_status;
  103459. }
  103460. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103461. FLAC__StreamEncoder *encoder,
  103462. FILE *file,
  103463. FLAC__StreamEncoderProgressCallback progress_callback,
  103464. void *client_data
  103465. )
  103466. {
  103467. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103468. }
  103469. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103470. FLAC__StreamEncoder *encoder,
  103471. FILE *file,
  103472. FLAC__StreamEncoderProgressCallback progress_callback,
  103473. void *client_data
  103474. )
  103475. {
  103476. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103477. }
  103478. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103479. FLAC__StreamEncoder *encoder,
  103480. const char *filename,
  103481. FLAC__StreamEncoderProgressCallback progress_callback,
  103482. void *client_data,
  103483. FLAC__bool is_ogg
  103484. )
  103485. {
  103486. FILE *file;
  103487. FLAC__ASSERT(0 != encoder);
  103488. /*
  103489. * To make sure that our file does not go unclosed after an error, we
  103490. * have to do the same entrance checks here that are later performed
  103491. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103492. */
  103493. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103494. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103495. file = filename? fopen(filename, "w+b") : stdout;
  103496. if(file == 0) {
  103497. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103498. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103499. }
  103500. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103501. }
  103502. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103503. FLAC__StreamEncoder *encoder,
  103504. const char *filename,
  103505. FLAC__StreamEncoderProgressCallback progress_callback,
  103506. void *client_data
  103507. )
  103508. {
  103509. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103510. }
  103511. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103512. FLAC__StreamEncoder *encoder,
  103513. const char *filename,
  103514. FLAC__StreamEncoderProgressCallback progress_callback,
  103515. void *client_data
  103516. )
  103517. {
  103518. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103519. }
  103520. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103521. {
  103522. FLAC__bool error = false;
  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 true;
  103528. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103529. if(encoder->private_->current_sample_number != 0) {
  103530. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103531. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103532. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103533. error = true;
  103534. }
  103535. }
  103536. if(encoder->protected_->do_md5)
  103537. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103538. if(!encoder->private_->is_being_deleted) {
  103539. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103540. if(encoder->private_->seek_callback) {
  103541. #if FLAC__HAS_OGG
  103542. if(encoder->private_->is_ogg)
  103543. update_ogg_metadata_(encoder);
  103544. else
  103545. #endif
  103546. update_metadata_(encoder);
  103547. /* check if an error occurred while updating metadata */
  103548. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103549. error = true;
  103550. }
  103551. if(encoder->private_->metadata_callback)
  103552. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103553. }
  103554. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103555. if(!error)
  103556. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103557. error = true;
  103558. }
  103559. }
  103560. if(0 != encoder->private_->file) {
  103561. if(encoder->private_->file != stdout)
  103562. fclose(encoder->private_->file);
  103563. encoder->private_->file = 0;
  103564. }
  103565. #if FLAC__HAS_OGG
  103566. if(encoder->private_->is_ogg)
  103567. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103568. #endif
  103569. free_(encoder);
  103570. set_defaults_enc(encoder);
  103571. if(!error)
  103572. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103573. return !error;
  103574. }
  103575. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103576. {
  103577. FLAC__ASSERT(0 != encoder);
  103578. FLAC__ASSERT(0 != encoder->private_);
  103579. FLAC__ASSERT(0 != encoder->protected_);
  103580. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103581. return false;
  103582. #if FLAC__HAS_OGG
  103583. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103584. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103585. return true;
  103586. #else
  103587. (void)value;
  103588. return false;
  103589. #endif
  103590. }
  103591. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103592. {
  103593. FLAC__ASSERT(0 != encoder);
  103594. FLAC__ASSERT(0 != encoder->private_);
  103595. FLAC__ASSERT(0 != encoder->protected_);
  103596. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103597. return false;
  103598. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103599. encoder->protected_->verify = value;
  103600. #endif
  103601. return true;
  103602. }
  103603. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103604. {
  103605. FLAC__ASSERT(0 != encoder);
  103606. FLAC__ASSERT(0 != encoder->private_);
  103607. FLAC__ASSERT(0 != encoder->protected_);
  103608. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103609. return false;
  103610. encoder->protected_->streamable_subset = value;
  103611. return true;
  103612. }
  103613. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103614. {
  103615. FLAC__ASSERT(0 != encoder);
  103616. FLAC__ASSERT(0 != encoder->private_);
  103617. FLAC__ASSERT(0 != encoder->protected_);
  103618. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103619. return false;
  103620. encoder->protected_->do_md5 = value;
  103621. return true;
  103622. }
  103623. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103624. {
  103625. FLAC__ASSERT(0 != encoder);
  103626. FLAC__ASSERT(0 != encoder->private_);
  103627. FLAC__ASSERT(0 != encoder->protected_);
  103628. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103629. return false;
  103630. encoder->protected_->channels = value;
  103631. return true;
  103632. }
  103633. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103634. {
  103635. FLAC__ASSERT(0 != encoder);
  103636. FLAC__ASSERT(0 != encoder->private_);
  103637. FLAC__ASSERT(0 != encoder->protected_);
  103638. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103639. return false;
  103640. encoder->protected_->bits_per_sample = value;
  103641. return true;
  103642. }
  103643. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103644. {
  103645. FLAC__ASSERT(0 != encoder);
  103646. FLAC__ASSERT(0 != encoder->private_);
  103647. FLAC__ASSERT(0 != encoder->protected_);
  103648. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103649. return false;
  103650. encoder->protected_->sample_rate = value;
  103651. return true;
  103652. }
  103653. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103654. {
  103655. FLAC__bool ok = true;
  103656. FLAC__ASSERT(0 != encoder);
  103657. FLAC__ASSERT(0 != encoder->private_);
  103658. FLAC__ASSERT(0 != encoder->protected_);
  103659. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103660. return false;
  103661. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103662. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103663. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103664. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103665. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103666. #if 0
  103667. /* was: */
  103668. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103669. /* but it's too hard to specify the string in a locale-specific way */
  103670. #else
  103671. encoder->protected_->num_apodizations = 1;
  103672. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103673. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103674. #endif
  103675. #endif
  103676. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103677. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103678. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103679. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103680. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103681. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103682. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103683. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103684. return ok;
  103685. }
  103686. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103687. {
  103688. FLAC__ASSERT(0 != encoder);
  103689. FLAC__ASSERT(0 != encoder->private_);
  103690. FLAC__ASSERT(0 != encoder->protected_);
  103691. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103692. return false;
  103693. encoder->protected_->blocksize = value;
  103694. return true;
  103695. }
  103696. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103697. {
  103698. FLAC__ASSERT(0 != encoder);
  103699. FLAC__ASSERT(0 != encoder->private_);
  103700. FLAC__ASSERT(0 != encoder->protected_);
  103701. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103702. return false;
  103703. encoder->protected_->do_mid_side_stereo = value;
  103704. return true;
  103705. }
  103706. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103707. {
  103708. FLAC__ASSERT(0 != encoder);
  103709. FLAC__ASSERT(0 != encoder->private_);
  103710. FLAC__ASSERT(0 != encoder->protected_);
  103711. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103712. return false;
  103713. encoder->protected_->loose_mid_side_stereo = value;
  103714. return true;
  103715. }
  103716. /*@@@@add to tests*/
  103717. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103718. {
  103719. FLAC__ASSERT(0 != encoder);
  103720. FLAC__ASSERT(0 != encoder->private_);
  103721. FLAC__ASSERT(0 != encoder->protected_);
  103722. FLAC__ASSERT(0 != specification);
  103723. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103724. return false;
  103725. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103726. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103727. #else
  103728. encoder->protected_->num_apodizations = 0;
  103729. while(1) {
  103730. const char *s = strchr(specification, ';');
  103731. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103732. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103733. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103734. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103735. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103736. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103737. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103738. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103739. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103740. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103741. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103742. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103743. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103744. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103745. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103746. if (stddev > 0.0 && stddev <= 0.5) {
  103747. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103748. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103749. }
  103750. }
  103751. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103752. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103753. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103754. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103755. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103756. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103757. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103758. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103759. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103760. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103761. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103762. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103763. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103764. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103765. if (p >= 0.0 && p <= 1.0) {
  103766. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103767. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103768. }
  103769. }
  103770. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103771. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103772. if (encoder->protected_->num_apodizations == 32)
  103773. break;
  103774. if (s)
  103775. specification = s+1;
  103776. else
  103777. break;
  103778. }
  103779. if(encoder->protected_->num_apodizations == 0) {
  103780. encoder->protected_->num_apodizations = 1;
  103781. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103782. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103783. }
  103784. #endif
  103785. return true;
  103786. }
  103787. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103788. {
  103789. FLAC__ASSERT(0 != encoder);
  103790. FLAC__ASSERT(0 != encoder->private_);
  103791. FLAC__ASSERT(0 != encoder->protected_);
  103792. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103793. return false;
  103794. encoder->protected_->max_lpc_order = value;
  103795. return true;
  103796. }
  103797. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103798. {
  103799. FLAC__ASSERT(0 != encoder);
  103800. FLAC__ASSERT(0 != encoder->private_);
  103801. FLAC__ASSERT(0 != encoder->protected_);
  103802. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103803. return false;
  103804. encoder->protected_->qlp_coeff_precision = value;
  103805. return true;
  103806. }
  103807. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103808. {
  103809. FLAC__ASSERT(0 != encoder);
  103810. FLAC__ASSERT(0 != encoder->private_);
  103811. FLAC__ASSERT(0 != encoder->protected_);
  103812. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103813. return false;
  103814. encoder->protected_->do_qlp_coeff_prec_search = value;
  103815. return true;
  103816. }
  103817. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103818. {
  103819. FLAC__ASSERT(0 != encoder);
  103820. FLAC__ASSERT(0 != encoder->private_);
  103821. FLAC__ASSERT(0 != encoder->protected_);
  103822. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103823. return false;
  103824. #if 0
  103825. /*@@@ deprecated: */
  103826. encoder->protected_->do_escape_coding = value;
  103827. #else
  103828. (void)value;
  103829. #endif
  103830. return true;
  103831. }
  103832. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103833. {
  103834. FLAC__ASSERT(0 != encoder);
  103835. FLAC__ASSERT(0 != encoder->private_);
  103836. FLAC__ASSERT(0 != encoder->protected_);
  103837. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103838. return false;
  103839. encoder->protected_->do_exhaustive_model_search = value;
  103840. return true;
  103841. }
  103842. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103843. {
  103844. FLAC__ASSERT(0 != encoder);
  103845. FLAC__ASSERT(0 != encoder->private_);
  103846. FLAC__ASSERT(0 != encoder->protected_);
  103847. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103848. return false;
  103849. encoder->protected_->min_residual_partition_order = value;
  103850. return true;
  103851. }
  103852. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103853. {
  103854. FLAC__ASSERT(0 != encoder);
  103855. FLAC__ASSERT(0 != encoder->private_);
  103856. FLAC__ASSERT(0 != encoder->protected_);
  103857. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103858. return false;
  103859. encoder->protected_->max_residual_partition_order = value;
  103860. return true;
  103861. }
  103862. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103863. {
  103864. FLAC__ASSERT(0 != encoder);
  103865. FLAC__ASSERT(0 != encoder->private_);
  103866. FLAC__ASSERT(0 != encoder->protected_);
  103867. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103868. return false;
  103869. #if 0
  103870. /*@@@ deprecated: */
  103871. encoder->protected_->rice_parameter_search_dist = value;
  103872. #else
  103873. (void)value;
  103874. #endif
  103875. return true;
  103876. }
  103877. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103878. {
  103879. FLAC__ASSERT(0 != encoder);
  103880. FLAC__ASSERT(0 != encoder->private_);
  103881. FLAC__ASSERT(0 != encoder->protected_);
  103882. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103883. return false;
  103884. encoder->protected_->total_samples_estimate = value;
  103885. return true;
  103886. }
  103887. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103888. {
  103889. FLAC__ASSERT(0 != encoder);
  103890. FLAC__ASSERT(0 != encoder->private_);
  103891. FLAC__ASSERT(0 != encoder->protected_);
  103892. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103893. return false;
  103894. if(0 == metadata)
  103895. num_blocks = 0;
  103896. if(0 == num_blocks)
  103897. metadata = 0;
  103898. /* realloc() does not do exactly what we want so... */
  103899. if(encoder->protected_->metadata) {
  103900. free(encoder->protected_->metadata);
  103901. encoder->protected_->metadata = 0;
  103902. encoder->protected_->num_metadata_blocks = 0;
  103903. }
  103904. if(num_blocks) {
  103905. FLAC__StreamMetadata **m;
  103906. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103907. return false;
  103908. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103909. encoder->protected_->metadata = m;
  103910. encoder->protected_->num_metadata_blocks = num_blocks;
  103911. }
  103912. #if FLAC__HAS_OGG
  103913. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103914. return false;
  103915. #endif
  103916. return true;
  103917. }
  103918. /*
  103919. * These three functions are not static, but not publically exposed in
  103920. * include/FLAC/ either. They are used by the test suite.
  103921. */
  103922. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103923. {
  103924. FLAC__ASSERT(0 != encoder);
  103925. FLAC__ASSERT(0 != encoder->private_);
  103926. FLAC__ASSERT(0 != encoder->protected_);
  103927. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103928. return false;
  103929. encoder->private_->disable_constant_subframes = value;
  103930. return true;
  103931. }
  103932. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103933. {
  103934. FLAC__ASSERT(0 != encoder);
  103935. FLAC__ASSERT(0 != encoder->private_);
  103936. FLAC__ASSERT(0 != encoder->protected_);
  103937. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103938. return false;
  103939. encoder->private_->disable_fixed_subframes = value;
  103940. return true;
  103941. }
  103942. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103943. {
  103944. FLAC__ASSERT(0 != encoder);
  103945. FLAC__ASSERT(0 != encoder->private_);
  103946. FLAC__ASSERT(0 != encoder->protected_);
  103947. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103948. return false;
  103949. encoder->private_->disable_verbatim_subframes = value;
  103950. return true;
  103951. }
  103952. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103953. {
  103954. FLAC__ASSERT(0 != encoder);
  103955. FLAC__ASSERT(0 != encoder->private_);
  103956. FLAC__ASSERT(0 != encoder->protected_);
  103957. return encoder->protected_->state;
  103958. }
  103959. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103960. {
  103961. FLAC__ASSERT(0 != encoder);
  103962. FLAC__ASSERT(0 != encoder->private_);
  103963. FLAC__ASSERT(0 != encoder->protected_);
  103964. if(encoder->protected_->verify)
  103965. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103966. else
  103967. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103968. }
  103969. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103970. {
  103971. FLAC__ASSERT(0 != encoder);
  103972. FLAC__ASSERT(0 != encoder->private_);
  103973. FLAC__ASSERT(0 != encoder->protected_);
  103974. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103975. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103976. else
  103977. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103978. }
  103979. 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)
  103980. {
  103981. FLAC__ASSERT(0 != encoder);
  103982. FLAC__ASSERT(0 != encoder->private_);
  103983. FLAC__ASSERT(0 != encoder->protected_);
  103984. if(0 != absolute_sample)
  103985. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103986. if(0 != frame_number)
  103987. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103988. if(0 != channel)
  103989. *channel = encoder->private_->verify.error_stats.channel;
  103990. if(0 != sample)
  103991. *sample = encoder->private_->verify.error_stats.sample;
  103992. if(0 != expected)
  103993. *expected = encoder->private_->verify.error_stats.expected;
  103994. if(0 != got)
  103995. *got = encoder->private_->verify.error_stats.got;
  103996. }
  103997. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103998. {
  103999. FLAC__ASSERT(0 != encoder);
  104000. FLAC__ASSERT(0 != encoder->private_);
  104001. FLAC__ASSERT(0 != encoder->protected_);
  104002. return encoder->protected_->verify;
  104003. }
  104004. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  104005. {
  104006. FLAC__ASSERT(0 != encoder);
  104007. FLAC__ASSERT(0 != encoder->private_);
  104008. FLAC__ASSERT(0 != encoder->protected_);
  104009. return encoder->protected_->streamable_subset;
  104010. }
  104011. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  104012. {
  104013. FLAC__ASSERT(0 != encoder);
  104014. FLAC__ASSERT(0 != encoder->private_);
  104015. FLAC__ASSERT(0 != encoder->protected_);
  104016. return encoder->protected_->do_md5;
  104017. }
  104018. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  104019. {
  104020. FLAC__ASSERT(0 != encoder);
  104021. FLAC__ASSERT(0 != encoder->private_);
  104022. FLAC__ASSERT(0 != encoder->protected_);
  104023. return encoder->protected_->channels;
  104024. }
  104025. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  104026. {
  104027. FLAC__ASSERT(0 != encoder);
  104028. FLAC__ASSERT(0 != encoder->private_);
  104029. FLAC__ASSERT(0 != encoder->protected_);
  104030. return encoder->protected_->bits_per_sample;
  104031. }
  104032. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  104033. {
  104034. FLAC__ASSERT(0 != encoder);
  104035. FLAC__ASSERT(0 != encoder->private_);
  104036. FLAC__ASSERT(0 != encoder->protected_);
  104037. return encoder->protected_->sample_rate;
  104038. }
  104039. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  104040. {
  104041. FLAC__ASSERT(0 != encoder);
  104042. FLAC__ASSERT(0 != encoder->private_);
  104043. FLAC__ASSERT(0 != encoder->protected_);
  104044. return encoder->protected_->blocksize;
  104045. }
  104046. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104047. {
  104048. FLAC__ASSERT(0 != encoder);
  104049. FLAC__ASSERT(0 != encoder->private_);
  104050. FLAC__ASSERT(0 != encoder->protected_);
  104051. return encoder->protected_->do_mid_side_stereo;
  104052. }
  104053. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104054. {
  104055. FLAC__ASSERT(0 != encoder);
  104056. FLAC__ASSERT(0 != encoder->private_);
  104057. FLAC__ASSERT(0 != encoder->protected_);
  104058. return encoder->protected_->loose_mid_side_stereo;
  104059. }
  104060. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  104061. {
  104062. FLAC__ASSERT(0 != encoder);
  104063. FLAC__ASSERT(0 != encoder->private_);
  104064. FLAC__ASSERT(0 != encoder->protected_);
  104065. return encoder->protected_->max_lpc_order;
  104066. }
  104067. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  104068. {
  104069. FLAC__ASSERT(0 != encoder);
  104070. FLAC__ASSERT(0 != encoder->private_);
  104071. FLAC__ASSERT(0 != encoder->protected_);
  104072. return encoder->protected_->qlp_coeff_precision;
  104073. }
  104074. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  104075. {
  104076. FLAC__ASSERT(0 != encoder);
  104077. FLAC__ASSERT(0 != encoder->private_);
  104078. FLAC__ASSERT(0 != encoder->protected_);
  104079. return encoder->protected_->do_qlp_coeff_prec_search;
  104080. }
  104081. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  104082. {
  104083. FLAC__ASSERT(0 != encoder);
  104084. FLAC__ASSERT(0 != encoder->private_);
  104085. FLAC__ASSERT(0 != encoder->protected_);
  104086. return encoder->protected_->do_escape_coding;
  104087. }
  104088. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  104089. {
  104090. FLAC__ASSERT(0 != encoder);
  104091. FLAC__ASSERT(0 != encoder->private_);
  104092. FLAC__ASSERT(0 != encoder->protected_);
  104093. return encoder->protected_->do_exhaustive_model_search;
  104094. }
  104095. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104096. {
  104097. FLAC__ASSERT(0 != encoder);
  104098. FLAC__ASSERT(0 != encoder->private_);
  104099. FLAC__ASSERT(0 != encoder->protected_);
  104100. return encoder->protected_->min_residual_partition_order;
  104101. }
  104102. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104103. {
  104104. FLAC__ASSERT(0 != encoder);
  104105. FLAC__ASSERT(0 != encoder->private_);
  104106. FLAC__ASSERT(0 != encoder->protected_);
  104107. return encoder->protected_->max_residual_partition_order;
  104108. }
  104109. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  104110. {
  104111. FLAC__ASSERT(0 != encoder);
  104112. FLAC__ASSERT(0 != encoder->private_);
  104113. FLAC__ASSERT(0 != encoder->protected_);
  104114. return encoder->protected_->rice_parameter_search_dist;
  104115. }
  104116. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  104117. {
  104118. FLAC__ASSERT(0 != encoder);
  104119. FLAC__ASSERT(0 != encoder->private_);
  104120. FLAC__ASSERT(0 != encoder->protected_);
  104121. return encoder->protected_->total_samples_estimate;
  104122. }
  104123. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  104124. {
  104125. unsigned i, j = 0, channel;
  104126. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104127. FLAC__ASSERT(0 != encoder);
  104128. FLAC__ASSERT(0 != encoder->private_);
  104129. FLAC__ASSERT(0 != encoder->protected_);
  104130. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104131. do {
  104132. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104133. if(encoder->protected_->verify)
  104134. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104135. for(channel = 0; channel < channels; channel++)
  104136. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104137. if(encoder->protected_->do_mid_side_stereo) {
  104138. FLAC__ASSERT(channels == 2);
  104139. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104140. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104141. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104142. 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' ! */
  104143. }
  104144. }
  104145. else
  104146. j += n;
  104147. encoder->private_->current_sample_number += n;
  104148. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104149. if(encoder->private_->current_sample_number > blocksize) {
  104150. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104151. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104152. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104153. return false;
  104154. /* move unprocessed overread samples to beginnings of arrays */
  104155. for(channel = 0; channel < channels; channel++)
  104156. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104157. if(encoder->protected_->do_mid_side_stereo) {
  104158. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104159. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104160. }
  104161. encoder->private_->current_sample_number = 1;
  104162. }
  104163. } while(j < samples);
  104164. return true;
  104165. }
  104166. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104167. {
  104168. unsigned i, j, k, channel;
  104169. FLAC__int32 x, mid, side;
  104170. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104171. FLAC__ASSERT(0 != encoder);
  104172. FLAC__ASSERT(0 != encoder->private_);
  104173. FLAC__ASSERT(0 != encoder->protected_);
  104174. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104175. j = k = 0;
  104176. /*
  104177. * we have several flavors of the same basic loop, optimized for
  104178. * different conditions:
  104179. */
  104180. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104181. /*
  104182. * stereo coding: unroll channel loop
  104183. */
  104184. do {
  104185. if(encoder->protected_->verify)
  104186. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104187. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104188. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104189. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104190. x = buffer[k++];
  104191. encoder->private_->integer_signal[1][i] = x;
  104192. mid += x;
  104193. side -= x;
  104194. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104195. encoder->private_->integer_signal_mid_side[1][i] = side;
  104196. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104197. }
  104198. encoder->private_->current_sample_number = i;
  104199. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104200. if(i > blocksize) {
  104201. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104202. return false;
  104203. /* move unprocessed overread samples to beginnings of arrays */
  104204. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104205. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104206. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104207. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104208. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104209. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104210. encoder->private_->current_sample_number = 1;
  104211. }
  104212. } while(j < samples);
  104213. }
  104214. else {
  104215. /*
  104216. * independent channel coding: buffer each channel in inner loop
  104217. */
  104218. do {
  104219. if(encoder->protected_->verify)
  104220. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104221. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104222. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104223. for(channel = 0; channel < channels; channel++)
  104224. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104225. }
  104226. encoder->private_->current_sample_number = i;
  104227. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104228. if(i > blocksize) {
  104229. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104230. return false;
  104231. /* move unprocessed overread samples to beginnings of arrays */
  104232. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104233. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104234. for(channel = 0; channel < channels; channel++)
  104235. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104236. encoder->private_->current_sample_number = 1;
  104237. }
  104238. } while(j < samples);
  104239. }
  104240. return true;
  104241. }
  104242. /***********************************************************************
  104243. *
  104244. * Private class methods
  104245. *
  104246. ***********************************************************************/
  104247. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104248. {
  104249. FLAC__ASSERT(0 != encoder);
  104250. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104251. encoder->protected_->verify = true;
  104252. #else
  104253. encoder->protected_->verify = false;
  104254. #endif
  104255. encoder->protected_->streamable_subset = true;
  104256. encoder->protected_->do_md5 = true;
  104257. encoder->protected_->do_mid_side_stereo = false;
  104258. encoder->protected_->loose_mid_side_stereo = false;
  104259. encoder->protected_->channels = 2;
  104260. encoder->protected_->bits_per_sample = 16;
  104261. encoder->protected_->sample_rate = 44100;
  104262. encoder->protected_->blocksize = 0;
  104263. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104264. encoder->protected_->num_apodizations = 1;
  104265. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104266. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104267. #endif
  104268. encoder->protected_->max_lpc_order = 0;
  104269. encoder->protected_->qlp_coeff_precision = 0;
  104270. encoder->protected_->do_qlp_coeff_prec_search = false;
  104271. encoder->protected_->do_exhaustive_model_search = false;
  104272. encoder->protected_->do_escape_coding = false;
  104273. encoder->protected_->min_residual_partition_order = 0;
  104274. encoder->protected_->max_residual_partition_order = 0;
  104275. encoder->protected_->rice_parameter_search_dist = 0;
  104276. encoder->protected_->total_samples_estimate = 0;
  104277. encoder->protected_->metadata = 0;
  104278. encoder->protected_->num_metadata_blocks = 0;
  104279. encoder->private_->seek_table = 0;
  104280. encoder->private_->disable_constant_subframes = false;
  104281. encoder->private_->disable_fixed_subframes = false;
  104282. encoder->private_->disable_verbatim_subframes = false;
  104283. #if FLAC__HAS_OGG
  104284. encoder->private_->is_ogg = false;
  104285. #endif
  104286. encoder->private_->read_callback = 0;
  104287. encoder->private_->write_callback = 0;
  104288. encoder->private_->seek_callback = 0;
  104289. encoder->private_->tell_callback = 0;
  104290. encoder->private_->metadata_callback = 0;
  104291. encoder->private_->progress_callback = 0;
  104292. encoder->private_->client_data = 0;
  104293. #if FLAC__HAS_OGG
  104294. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104295. #endif
  104296. }
  104297. void free_(FLAC__StreamEncoder *encoder)
  104298. {
  104299. unsigned i, channel;
  104300. FLAC__ASSERT(0 != encoder);
  104301. if(encoder->protected_->metadata) {
  104302. free(encoder->protected_->metadata);
  104303. encoder->protected_->metadata = 0;
  104304. encoder->protected_->num_metadata_blocks = 0;
  104305. }
  104306. for(i = 0; i < encoder->protected_->channels; i++) {
  104307. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104308. free(encoder->private_->integer_signal_unaligned[i]);
  104309. encoder->private_->integer_signal_unaligned[i] = 0;
  104310. }
  104311. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104312. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104313. free(encoder->private_->real_signal_unaligned[i]);
  104314. encoder->private_->real_signal_unaligned[i] = 0;
  104315. }
  104316. #endif
  104317. }
  104318. for(i = 0; i < 2; i++) {
  104319. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104320. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104321. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104322. }
  104323. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104324. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104325. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104326. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104327. }
  104328. #endif
  104329. }
  104330. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104331. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104332. if(0 != encoder->private_->window_unaligned[i]) {
  104333. free(encoder->private_->window_unaligned[i]);
  104334. encoder->private_->window_unaligned[i] = 0;
  104335. }
  104336. }
  104337. if(0 != encoder->private_->windowed_signal_unaligned) {
  104338. free(encoder->private_->windowed_signal_unaligned);
  104339. encoder->private_->windowed_signal_unaligned = 0;
  104340. }
  104341. #endif
  104342. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104343. for(i = 0; i < 2; i++) {
  104344. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104345. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104346. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104347. }
  104348. }
  104349. }
  104350. for(channel = 0; channel < 2; channel++) {
  104351. for(i = 0; i < 2; i++) {
  104352. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104353. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104354. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104355. }
  104356. }
  104357. }
  104358. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104359. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104360. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104361. }
  104362. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104363. free(encoder->private_->raw_bits_per_partition_unaligned);
  104364. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104365. }
  104366. if(encoder->protected_->verify) {
  104367. for(i = 0; i < encoder->protected_->channels; i++) {
  104368. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104369. free(encoder->private_->verify.input_fifo.data[i]);
  104370. encoder->private_->verify.input_fifo.data[i] = 0;
  104371. }
  104372. }
  104373. }
  104374. FLAC__bitwriter_free(encoder->private_->frame);
  104375. }
  104376. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104377. {
  104378. FLAC__bool ok;
  104379. unsigned i, channel;
  104380. FLAC__ASSERT(new_blocksize > 0);
  104381. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104382. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104383. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104384. if(new_blocksize <= encoder->private_->input_capacity)
  104385. return true;
  104386. ok = true;
  104387. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104388. * requires that the input arrays (in our case the integer signals)
  104389. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104390. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104391. */
  104392. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104393. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104394. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104395. encoder->private_->integer_signal[i] += 4;
  104396. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104397. #if 0 /* @@@ currently unused */
  104398. if(encoder->protected_->max_lpc_order > 0)
  104399. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104400. #endif
  104401. #endif
  104402. }
  104403. for(i = 0; ok && i < 2; i++) {
  104404. 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]);
  104405. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104406. encoder->private_->integer_signal_mid_side[i] += 4;
  104407. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104408. #if 0 /* @@@ currently unused */
  104409. if(encoder->protected_->max_lpc_order > 0)
  104410. 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]);
  104411. #endif
  104412. #endif
  104413. }
  104414. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104415. if(ok && encoder->protected_->max_lpc_order > 0) {
  104416. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104417. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104418. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104419. }
  104420. #endif
  104421. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104422. for(i = 0; ok && i < 2; i++) {
  104423. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104424. }
  104425. }
  104426. for(channel = 0; ok && channel < 2; channel++) {
  104427. for(i = 0; ok && i < 2; i++) {
  104428. 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]);
  104429. }
  104430. }
  104431. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104432. /*@@@ 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) */
  104433. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104434. if(encoder->protected_->do_escape_coding)
  104435. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104436. /* now adjust the windows if the blocksize has changed */
  104437. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104438. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104439. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104440. switch(encoder->protected_->apodizations[i].type) {
  104441. case FLAC__APODIZATION_BARTLETT:
  104442. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104443. break;
  104444. case FLAC__APODIZATION_BARTLETT_HANN:
  104445. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104446. break;
  104447. case FLAC__APODIZATION_BLACKMAN:
  104448. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104449. break;
  104450. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104451. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104452. break;
  104453. case FLAC__APODIZATION_CONNES:
  104454. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104455. break;
  104456. case FLAC__APODIZATION_FLATTOP:
  104457. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104458. break;
  104459. case FLAC__APODIZATION_GAUSS:
  104460. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104461. break;
  104462. case FLAC__APODIZATION_HAMMING:
  104463. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104464. break;
  104465. case FLAC__APODIZATION_HANN:
  104466. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104467. break;
  104468. case FLAC__APODIZATION_KAISER_BESSEL:
  104469. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104470. break;
  104471. case FLAC__APODIZATION_NUTTALL:
  104472. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104473. break;
  104474. case FLAC__APODIZATION_RECTANGLE:
  104475. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104476. break;
  104477. case FLAC__APODIZATION_TRIANGLE:
  104478. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104479. break;
  104480. case FLAC__APODIZATION_TUKEY:
  104481. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104482. break;
  104483. case FLAC__APODIZATION_WELCH:
  104484. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104485. break;
  104486. default:
  104487. FLAC__ASSERT(0);
  104488. /* double protection */
  104489. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104490. break;
  104491. }
  104492. }
  104493. }
  104494. #endif
  104495. if(ok)
  104496. encoder->private_->input_capacity = new_blocksize;
  104497. else
  104498. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104499. return ok;
  104500. }
  104501. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104502. {
  104503. const FLAC__byte *buffer;
  104504. size_t bytes;
  104505. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104506. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104507. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104508. return false;
  104509. }
  104510. if(encoder->protected_->verify) {
  104511. encoder->private_->verify.output.data = buffer;
  104512. encoder->private_->verify.output.bytes = bytes;
  104513. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104514. encoder->private_->verify.needs_magic_hack = true;
  104515. }
  104516. else {
  104517. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104518. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104519. FLAC__bitwriter_clear(encoder->private_->frame);
  104520. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104521. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104522. return false;
  104523. }
  104524. }
  104525. }
  104526. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104527. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104528. FLAC__bitwriter_clear(encoder->private_->frame);
  104529. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104530. return false;
  104531. }
  104532. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104533. FLAC__bitwriter_clear(encoder->private_->frame);
  104534. if(samples > 0) {
  104535. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104536. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104537. }
  104538. return true;
  104539. }
  104540. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104541. {
  104542. FLAC__StreamEncoderWriteStatus status;
  104543. FLAC__uint64 output_position = 0;
  104544. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104545. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104546. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104547. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104548. }
  104549. /*
  104550. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104551. */
  104552. if(samples == 0) {
  104553. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104554. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104555. encoder->protected_->streaminfo_offset = output_position;
  104556. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104557. encoder->protected_->seektable_offset = output_position;
  104558. }
  104559. /*
  104560. * Mark the current seek point if hit (if audio_offset == 0 that
  104561. * means we're still writing metadata and haven't hit the first
  104562. * frame yet)
  104563. */
  104564. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104565. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104566. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104567. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104568. FLAC__uint64 test_sample;
  104569. unsigned i;
  104570. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104571. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104572. if(test_sample > frame_last_sample) {
  104573. break;
  104574. }
  104575. else if(test_sample >= frame_first_sample) {
  104576. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104577. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104578. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104579. encoder->private_->first_seekpoint_to_check++;
  104580. /* DO NOT: "break;" and here's why:
  104581. * The seektable template may contain more than one target
  104582. * sample for any given frame; we will keep looping, generating
  104583. * duplicate seekpoints for them, and we'll clean it up later,
  104584. * just before writing the seektable back to the metadata.
  104585. */
  104586. }
  104587. else {
  104588. encoder->private_->first_seekpoint_to_check++;
  104589. }
  104590. }
  104591. }
  104592. #if FLAC__HAS_OGG
  104593. if(encoder->private_->is_ogg) {
  104594. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104595. &encoder->protected_->ogg_encoder_aspect,
  104596. buffer,
  104597. bytes,
  104598. samples,
  104599. encoder->private_->current_frame_number,
  104600. is_last_block,
  104601. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104602. encoder,
  104603. encoder->private_->client_data
  104604. );
  104605. }
  104606. else
  104607. #endif
  104608. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104609. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104610. encoder->private_->bytes_written += bytes;
  104611. encoder->private_->samples_written += samples;
  104612. /* we keep a high watermark on the number of frames written because
  104613. * when the encoder goes back to write metadata, 'current_frame'
  104614. * will drop back to 0.
  104615. */
  104616. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104617. }
  104618. else
  104619. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104620. return status;
  104621. }
  104622. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104623. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104624. {
  104625. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104626. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104627. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104628. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104629. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104630. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104631. FLAC__StreamEncoderSeekStatus seek_status;
  104632. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104633. /* All this is based on intimate knowledge of the stream header
  104634. * layout, but a change to the header format that would break this
  104635. * would also break all streams encoded in the previous format.
  104636. */
  104637. /*
  104638. * Write MD5 signature
  104639. */
  104640. {
  104641. const unsigned md5_offset =
  104642. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104643. (
  104644. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104645. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104646. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104647. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104648. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104649. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104650. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104651. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104652. ) / 8;
  104653. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104654. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104655. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104656. return;
  104657. }
  104658. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104659. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104660. return;
  104661. }
  104662. }
  104663. /*
  104664. * Write total samples
  104665. */
  104666. {
  104667. const unsigned total_samples_byte_offset =
  104668. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104669. (
  104670. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104671. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104672. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104673. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104674. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104675. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104676. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104677. - 4
  104678. ) / 8;
  104679. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104680. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104681. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104682. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104683. b[4] = (FLAC__byte)(samples & 0xFF);
  104684. 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) {
  104685. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104686. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104687. return;
  104688. }
  104689. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104690. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104691. return;
  104692. }
  104693. }
  104694. /*
  104695. * Write min/max framesize
  104696. */
  104697. {
  104698. const unsigned min_framesize_offset =
  104699. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104700. (
  104701. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104702. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104703. ) / 8;
  104704. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104705. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104706. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104707. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104708. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104709. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104710. 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) {
  104711. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104712. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104713. return;
  104714. }
  104715. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104716. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104717. return;
  104718. }
  104719. }
  104720. /*
  104721. * Write seektable
  104722. */
  104723. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104724. unsigned i;
  104725. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104726. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104727. 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) {
  104728. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104729. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104730. return;
  104731. }
  104732. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104733. FLAC__uint64 xx;
  104734. unsigned x;
  104735. xx = encoder->private_->seek_table->points[i].sample_number;
  104736. b[7] = (FLAC__byte)xx; xx >>= 8;
  104737. b[6] = (FLAC__byte)xx; xx >>= 8;
  104738. b[5] = (FLAC__byte)xx; xx >>= 8;
  104739. b[4] = (FLAC__byte)xx; xx >>= 8;
  104740. b[3] = (FLAC__byte)xx; xx >>= 8;
  104741. b[2] = (FLAC__byte)xx; xx >>= 8;
  104742. b[1] = (FLAC__byte)xx; xx >>= 8;
  104743. b[0] = (FLAC__byte)xx; xx >>= 8;
  104744. xx = encoder->private_->seek_table->points[i].stream_offset;
  104745. b[15] = (FLAC__byte)xx; xx >>= 8;
  104746. b[14] = (FLAC__byte)xx; xx >>= 8;
  104747. b[13] = (FLAC__byte)xx; xx >>= 8;
  104748. b[12] = (FLAC__byte)xx; xx >>= 8;
  104749. b[11] = (FLAC__byte)xx; xx >>= 8;
  104750. b[10] = (FLAC__byte)xx; xx >>= 8;
  104751. b[9] = (FLAC__byte)xx; xx >>= 8;
  104752. b[8] = (FLAC__byte)xx; xx >>= 8;
  104753. x = encoder->private_->seek_table->points[i].frame_samples;
  104754. b[17] = (FLAC__byte)x; x >>= 8;
  104755. b[16] = (FLAC__byte)x; x >>= 8;
  104756. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104757. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104758. return;
  104759. }
  104760. }
  104761. }
  104762. }
  104763. #if FLAC__HAS_OGG
  104764. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104765. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104766. {
  104767. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104768. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104769. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104770. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104771. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104772. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104773. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104774. FLAC__STREAM_SYNC_LENGTH
  104775. ;
  104776. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104777. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104778. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104779. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104780. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104781. ogg_page page;
  104782. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104783. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104784. /* Pre-check that client supports seeking, since we don't want the
  104785. * ogg_helper code to ever have to deal with this condition.
  104786. */
  104787. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104788. return;
  104789. /* All this is based on intimate knowledge of the stream header
  104790. * layout, but a change to the header format that would break this
  104791. * would also break all streams encoded in the previous format.
  104792. */
  104793. /**
  104794. ** Write STREAMINFO stats
  104795. **/
  104796. simple_ogg_page__init(&page);
  104797. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104798. simple_ogg_page__clear(&page);
  104799. return; /* state already set */
  104800. }
  104801. /*
  104802. * Write MD5 signature
  104803. */
  104804. {
  104805. const unsigned md5_offset =
  104806. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104807. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104808. (
  104809. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104810. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104811. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104812. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104813. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104814. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104815. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104816. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104817. ) / 8;
  104818. if(md5_offset + 16 > (unsigned)page.body_len) {
  104819. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104820. simple_ogg_page__clear(&page);
  104821. return;
  104822. }
  104823. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104824. }
  104825. /*
  104826. * Write total samples
  104827. */
  104828. {
  104829. const unsigned total_samples_byte_offset =
  104830. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104831. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104832. (
  104833. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104834. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104835. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104836. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104837. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104838. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104839. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104840. - 4
  104841. ) / 8;
  104842. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104843. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104844. simple_ogg_page__clear(&page);
  104845. return;
  104846. }
  104847. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104848. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104849. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104850. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104851. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104852. b[4] = (FLAC__byte)(samples & 0xFF);
  104853. memcpy(page.body + total_samples_byte_offset, b, 5);
  104854. }
  104855. /*
  104856. * Write min/max framesize
  104857. */
  104858. {
  104859. const unsigned min_framesize_offset =
  104860. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104861. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104862. (
  104863. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104864. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104865. ) / 8;
  104866. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104867. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104868. simple_ogg_page__clear(&page);
  104869. return;
  104870. }
  104871. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104872. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104873. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104874. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104875. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104876. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104877. memcpy(page.body + min_framesize_offset, b, 6);
  104878. }
  104879. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104880. simple_ogg_page__clear(&page);
  104881. return; /* state already set */
  104882. }
  104883. simple_ogg_page__clear(&page);
  104884. /*
  104885. * Write seektable
  104886. */
  104887. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104888. unsigned i;
  104889. FLAC__byte *p;
  104890. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104891. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104892. simple_ogg_page__init(&page);
  104893. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104894. simple_ogg_page__clear(&page);
  104895. return; /* state already set */
  104896. }
  104897. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104898. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104899. simple_ogg_page__clear(&page);
  104900. return;
  104901. }
  104902. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104903. FLAC__uint64 xx;
  104904. unsigned x;
  104905. xx = encoder->private_->seek_table->points[i].sample_number;
  104906. b[7] = (FLAC__byte)xx; xx >>= 8;
  104907. b[6] = (FLAC__byte)xx; xx >>= 8;
  104908. b[5] = (FLAC__byte)xx; xx >>= 8;
  104909. b[4] = (FLAC__byte)xx; xx >>= 8;
  104910. b[3] = (FLAC__byte)xx; xx >>= 8;
  104911. b[2] = (FLAC__byte)xx; xx >>= 8;
  104912. b[1] = (FLAC__byte)xx; xx >>= 8;
  104913. b[0] = (FLAC__byte)xx; xx >>= 8;
  104914. xx = encoder->private_->seek_table->points[i].stream_offset;
  104915. b[15] = (FLAC__byte)xx; xx >>= 8;
  104916. b[14] = (FLAC__byte)xx; xx >>= 8;
  104917. b[13] = (FLAC__byte)xx; xx >>= 8;
  104918. b[12] = (FLAC__byte)xx; xx >>= 8;
  104919. b[11] = (FLAC__byte)xx; xx >>= 8;
  104920. b[10] = (FLAC__byte)xx; xx >>= 8;
  104921. b[9] = (FLAC__byte)xx; xx >>= 8;
  104922. b[8] = (FLAC__byte)xx; xx >>= 8;
  104923. x = encoder->private_->seek_table->points[i].frame_samples;
  104924. b[17] = (FLAC__byte)x; x >>= 8;
  104925. b[16] = (FLAC__byte)x; x >>= 8;
  104926. memcpy(p, b, 18);
  104927. }
  104928. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104929. simple_ogg_page__clear(&page);
  104930. return; /* state already set */
  104931. }
  104932. simple_ogg_page__clear(&page);
  104933. }
  104934. }
  104935. #endif
  104936. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104937. {
  104938. FLAC__uint16 crc;
  104939. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104940. /*
  104941. * Accumulate raw signal to the MD5 signature
  104942. */
  104943. 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)) {
  104944. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104945. return false;
  104946. }
  104947. /*
  104948. * Process the frame header and subframes into the frame bitbuffer
  104949. */
  104950. if(!process_subframes_(encoder, is_fractional_block)) {
  104951. /* the above function sets the state for us in case of an error */
  104952. return false;
  104953. }
  104954. /*
  104955. * Zero-pad the frame to a byte_boundary
  104956. */
  104957. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104958. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104959. return false;
  104960. }
  104961. /*
  104962. * CRC-16 the whole thing
  104963. */
  104964. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104965. if(
  104966. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104967. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104968. ) {
  104969. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104970. return false;
  104971. }
  104972. /*
  104973. * Write it
  104974. */
  104975. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104976. /* the above function sets the state for us in case of an error */
  104977. return false;
  104978. }
  104979. /*
  104980. * Get ready for the next frame
  104981. */
  104982. encoder->private_->current_sample_number = 0;
  104983. encoder->private_->current_frame_number++;
  104984. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104985. return true;
  104986. }
  104987. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104988. {
  104989. FLAC__FrameHeader frame_header;
  104990. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104991. FLAC__bool do_independent, do_mid_side;
  104992. /*
  104993. * Calculate the min,max Rice partition orders
  104994. */
  104995. if(is_fractional_block) {
  104996. max_partition_order = 0;
  104997. }
  104998. else {
  104999. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  105000. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  105001. }
  105002. min_partition_order = min(min_partition_order, max_partition_order);
  105003. /*
  105004. * Setup the frame
  105005. */
  105006. frame_header.blocksize = encoder->protected_->blocksize;
  105007. frame_header.sample_rate = encoder->protected_->sample_rate;
  105008. frame_header.channels = encoder->protected_->channels;
  105009. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  105010. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  105011. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  105012. frame_header.number.frame_number = encoder->private_->current_frame_number;
  105013. /*
  105014. * Figure out what channel assignments to try
  105015. */
  105016. if(encoder->protected_->do_mid_side_stereo) {
  105017. if(encoder->protected_->loose_mid_side_stereo) {
  105018. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  105019. do_independent = true;
  105020. do_mid_side = true;
  105021. }
  105022. else {
  105023. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  105024. do_mid_side = !do_independent;
  105025. }
  105026. }
  105027. else {
  105028. do_independent = true;
  105029. do_mid_side = true;
  105030. }
  105031. }
  105032. else {
  105033. do_independent = true;
  105034. do_mid_side = false;
  105035. }
  105036. FLAC__ASSERT(do_independent || do_mid_side);
  105037. /*
  105038. * Check for wasted bits; set effective bps for each subframe
  105039. */
  105040. if(do_independent) {
  105041. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105042. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  105043. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  105044. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  105045. }
  105046. }
  105047. if(do_mid_side) {
  105048. FLAC__ASSERT(encoder->protected_->channels == 2);
  105049. for(channel = 0; channel < 2; channel++) {
  105050. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  105051. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  105052. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  105053. }
  105054. }
  105055. /*
  105056. * First do a normal encoding pass of each independent channel
  105057. */
  105058. if(do_independent) {
  105059. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105060. if(!
  105061. process_subframe_(
  105062. encoder,
  105063. min_partition_order,
  105064. max_partition_order,
  105065. &frame_header,
  105066. encoder->private_->subframe_bps[channel],
  105067. encoder->private_->integer_signal[channel],
  105068. encoder->private_->subframe_workspace_ptr[channel],
  105069. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  105070. encoder->private_->residual_workspace[channel],
  105071. encoder->private_->best_subframe+channel,
  105072. encoder->private_->best_subframe_bits+channel
  105073. )
  105074. )
  105075. return false;
  105076. }
  105077. }
  105078. /*
  105079. * Now do mid and side channels if requested
  105080. */
  105081. if(do_mid_side) {
  105082. FLAC__ASSERT(encoder->protected_->channels == 2);
  105083. for(channel = 0; channel < 2; channel++) {
  105084. if(!
  105085. process_subframe_(
  105086. encoder,
  105087. min_partition_order,
  105088. max_partition_order,
  105089. &frame_header,
  105090. encoder->private_->subframe_bps_mid_side[channel],
  105091. encoder->private_->integer_signal_mid_side[channel],
  105092. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  105093. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  105094. encoder->private_->residual_workspace_mid_side[channel],
  105095. encoder->private_->best_subframe_mid_side+channel,
  105096. encoder->private_->best_subframe_bits_mid_side+channel
  105097. )
  105098. )
  105099. return false;
  105100. }
  105101. }
  105102. /*
  105103. * Compose the frame bitbuffer
  105104. */
  105105. if(do_mid_side) {
  105106. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  105107. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  105108. FLAC__ChannelAssignment channel_assignment;
  105109. FLAC__ASSERT(encoder->protected_->channels == 2);
  105110. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  105111. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  105112. }
  105113. else {
  105114. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  105115. unsigned min_bits;
  105116. int ca;
  105117. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  105118. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  105119. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  105120. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  105121. FLAC__ASSERT(do_independent && do_mid_side);
  105122. /* We have to figure out which channel assignent results in the smallest frame */
  105123. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  105124. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  105125. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  105126. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  105127. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  105128. min_bits = bits[channel_assignment];
  105129. for(ca = 1; ca <= 3; ca++) {
  105130. if(bits[ca] < min_bits) {
  105131. min_bits = bits[ca];
  105132. channel_assignment = (FLAC__ChannelAssignment)ca;
  105133. }
  105134. }
  105135. }
  105136. frame_header.channel_assignment = channel_assignment;
  105137. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105138. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105139. return false;
  105140. }
  105141. switch(channel_assignment) {
  105142. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105143. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105144. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105145. break;
  105146. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105147. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105148. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105149. break;
  105150. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105151. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105152. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105153. break;
  105154. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105155. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105156. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105157. break;
  105158. default:
  105159. FLAC__ASSERT(0);
  105160. }
  105161. switch(channel_assignment) {
  105162. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105163. left_bps = encoder->private_->subframe_bps [0];
  105164. right_bps = encoder->private_->subframe_bps [1];
  105165. break;
  105166. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105167. left_bps = encoder->private_->subframe_bps [0];
  105168. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105169. break;
  105170. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105171. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105172. right_bps = encoder->private_->subframe_bps [1];
  105173. break;
  105174. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105175. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105176. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105177. break;
  105178. default:
  105179. FLAC__ASSERT(0);
  105180. }
  105181. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105182. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105183. return false;
  105184. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105185. return false;
  105186. }
  105187. else {
  105188. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105189. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105190. return false;
  105191. }
  105192. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105193. 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)) {
  105194. /* the above function sets the state for us in case of an error */
  105195. return false;
  105196. }
  105197. }
  105198. }
  105199. if(encoder->protected_->loose_mid_side_stereo) {
  105200. encoder->private_->loose_mid_side_stereo_frame_count++;
  105201. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105202. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105203. }
  105204. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105205. return true;
  105206. }
  105207. FLAC__bool process_subframe_(
  105208. FLAC__StreamEncoder *encoder,
  105209. unsigned min_partition_order,
  105210. unsigned max_partition_order,
  105211. const FLAC__FrameHeader *frame_header,
  105212. unsigned subframe_bps,
  105213. const FLAC__int32 integer_signal[],
  105214. FLAC__Subframe *subframe[2],
  105215. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105216. FLAC__int32 *residual[2],
  105217. unsigned *best_subframe,
  105218. unsigned *best_bits
  105219. )
  105220. {
  105221. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105222. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105223. #else
  105224. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105225. #endif
  105226. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105227. FLAC__double lpc_residual_bits_per_sample;
  105228. 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 */
  105229. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105230. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105231. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105232. #endif
  105233. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105234. unsigned rice_parameter;
  105235. unsigned _candidate_bits, _best_bits;
  105236. unsigned _best_subframe;
  105237. /* only use RICE2 partitions if stream bps > 16 */
  105238. 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;
  105239. FLAC__ASSERT(frame_header->blocksize > 0);
  105240. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105241. _best_subframe = 0;
  105242. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105243. _best_bits = UINT_MAX;
  105244. else
  105245. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105246. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105247. unsigned signal_is_constant = false;
  105248. 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);
  105249. /* check for constant subframe */
  105250. if(
  105251. !encoder->private_->disable_constant_subframes &&
  105252. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105253. fixed_residual_bits_per_sample[1] == 0.0
  105254. #else
  105255. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105256. #endif
  105257. ) {
  105258. /* the above means it's possible all samples are the same value; now double-check it: */
  105259. unsigned i;
  105260. signal_is_constant = true;
  105261. for(i = 1; i < frame_header->blocksize; i++) {
  105262. if(integer_signal[0] != integer_signal[i]) {
  105263. signal_is_constant = false;
  105264. break;
  105265. }
  105266. }
  105267. }
  105268. if(signal_is_constant) {
  105269. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105270. if(_candidate_bits < _best_bits) {
  105271. _best_subframe = !_best_subframe;
  105272. _best_bits = _candidate_bits;
  105273. }
  105274. }
  105275. else {
  105276. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105277. /* encode fixed */
  105278. if(encoder->protected_->do_exhaustive_model_search) {
  105279. min_fixed_order = 0;
  105280. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105281. }
  105282. else {
  105283. min_fixed_order = max_fixed_order = guess_fixed_order;
  105284. }
  105285. if(max_fixed_order >= frame_header->blocksize)
  105286. max_fixed_order = frame_header->blocksize - 1;
  105287. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105288. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105289. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105290. continue; /* don't even try */
  105291. 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 */
  105292. #else
  105293. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105294. continue; /* don't even try */
  105295. 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 */
  105296. #endif
  105297. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105298. if(rice_parameter >= rice_parameter_limit) {
  105299. #ifdef DEBUG_VERBOSE
  105300. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105301. #endif
  105302. rice_parameter = rice_parameter_limit - 1;
  105303. }
  105304. _candidate_bits =
  105305. evaluate_fixed_subframe_(
  105306. encoder,
  105307. integer_signal,
  105308. residual[!_best_subframe],
  105309. encoder->private_->abs_residual_partition_sums,
  105310. encoder->private_->raw_bits_per_partition,
  105311. frame_header->blocksize,
  105312. subframe_bps,
  105313. fixed_order,
  105314. rice_parameter,
  105315. rice_parameter_limit,
  105316. min_partition_order,
  105317. max_partition_order,
  105318. encoder->protected_->do_escape_coding,
  105319. encoder->protected_->rice_parameter_search_dist,
  105320. subframe[!_best_subframe],
  105321. partitioned_rice_contents[!_best_subframe]
  105322. );
  105323. if(_candidate_bits < _best_bits) {
  105324. _best_subframe = !_best_subframe;
  105325. _best_bits = _candidate_bits;
  105326. }
  105327. }
  105328. }
  105329. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105330. /* encode lpc */
  105331. if(encoder->protected_->max_lpc_order > 0) {
  105332. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105333. max_lpc_order = frame_header->blocksize-1;
  105334. else
  105335. max_lpc_order = encoder->protected_->max_lpc_order;
  105336. if(max_lpc_order > 0) {
  105337. unsigned a;
  105338. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105339. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105340. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105341. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105342. if(autoc[0] != 0.0) {
  105343. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105344. if(encoder->protected_->do_exhaustive_model_search) {
  105345. min_lpc_order = 1;
  105346. }
  105347. else {
  105348. const unsigned guess_lpc_order =
  105349. FLAC__lpc_compute_best_order(
  105350. lpc_error,
  105351. max_lpc_order,
  105352. frame_header->blocksize,
  105353. subframe_bps + (
  105354. encoder->protected_->do_qlp_coeff_prec_search?
  105355. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105356. encoder->protected_->qlp_coeff_precision
  105357. )
  105358. );
  105359. min_lpc_order = max_lpc_order = guess_lpc_order;
  105360. }
  105361. if(max_lpc_order >= frame_header->blocksize)
  105362. max_lpc_order = frame_header->blocksize - 1;
  105363. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105364. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105365. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105366. continue; /* don't even try */
  105367. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105368. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105369. if(rice_parameter >= rice_parameter_limit) {
  105370. #ifdef DEBUG_VERBOSE
  105371. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105372. #endif
  105373. rice_parameter = rice_parameter_limit - 1;
  105374. }
  105375. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105376. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105377. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105378. if(subframe_bps <= 17) {
  105379. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105380. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105381. }
  105382. else
  105383. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105384. }
  105385. else {
  105386. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105387. }
  105388. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105389. _candidate_bits =
  105390. evaluate_lpc_subframe_(
  105391. encoder,
  105392. integer_signal,
  105393. residual[!_best_subframe],
  105394. encoder->private_->abs_residual_partition_sums,
  105395. encoder->private_->raw_bits_per_partition,
  105396. encoder->private_->lp_coeff[lpc_order-1],
  105397. frame_header->blocksize,
  105398. subframe_bps,
  105399. lpc_order,
  105400. qlp_coeff_precision,
  105401. rice_parameter,
  105402. rice_parameter_limit,
  105403. min_partition_order,
  105404. max_partition_order,
  105405. encoder->protected_->do_escape_coding,
  105406. encoder->protected_->rice_parameter_search_dist,
  105407. subframe[!_best_subframe],
  105408. partitioned_rice_contents[!_best_subframe]
  105409. );
  105410. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105411. if(_candidate_bits < _best_bits) {
  105412. _best_subframe = !_best_subframe;
  105413. _best_bits = _candidate_bits;
  105414. }
  105415. }
  105416. }
  105417. }
  105418. }
  105419. }
  105420. }
  105421. }
  105422. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105423. }
  105424. }
  105425. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105426. if(_best_bits == UINT_MAX) {
  105427. FLAC__ASSERT(_best_subframe == 0);
  105428. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105429. }
  105430. *best_subframe = _best_subframe;
  105431. *best_bits = _best_bits;
  105432. return true;
  105433. }
  105434. FLAC__bool add_subframe_(
  105435. FLAC__StreamEncoder *encoder,
  105436. unsigned blocksize,
  105437. unsigned subframe_bps,
  105438. const FLAC__Subframe *subframe,
  105439. FLAC__BitWriter *frame
  105440. )
  105441. {
  105442. switch(subframe->type) {
  105443. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105444. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105445. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105446. return false;
  105447. }
  105448. break;
  105449. case FLAC__SUBFRAME_TYPE_FIXED:
  105450. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105451. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105452. return false;
  105453. }
  105454. break;
  105455. case FLAC__SUBFRAME_TYPE_LPC:
  105456. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105457. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105458. return false;
  105459. }
  105460. break;
  105461. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105462. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105463. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105464. return false;
  105465. }
  105466. break;
  105467. default:
  105468. FLAC__ASSERT(0);
  105469. }
  105470. return true;
  105471. }
  105472. #define SPOTCHECK_ESTIMATE 0
  105473. #if SPOTCHECK_ESTIMATE
  105474. static void spotcheck_subframe_estimate_(
  105475. FLAC__StreamEncoder *encoder,
  105476. unsigned blocksize,
  105477. unsigned subframe_bps,
  105478. const FLAC__Subframe *subframe,
  105479. unsigned estimate
  105480. )
  105481. {
  105482. FLAC__bool ret;
  105483. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105484. if(frame == 0) {
  105485. fprintf(stderr, "EST: can't allocate frame\n");
  105486. return;
  105487. }
  105488. if(!FLAC__bitwriter_init(frame)) {
  105489. fprintf(stderr, "EST: can't init frame\n");
  105490. return;
  105491. }
  105492. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105493. FLAC__ASSERT(ret);
  105494. {
  105495. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105496. if(estimate != actual)
  105497. 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);
  105498. }
  105499. FLAC__bitwriter_delete(frame);
  105500. }
  105501. #endif
  105502. unsigned evaluate_constant_subframe_(
  105503. FLAC__StreamEncoder *encoder,
  105504. const FLAC__int32 signal,
  105505. unsigned blocksize,
  105506. unsigned subframe_bps,
  105507. FLAC__Subframe *subframe
  105508. )
  105509. {
  105510. unsigned estimate;
  105511. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105512. subframe->data.constant.value = signal;
  105513. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105514. #if SPOTCHECK_ESTIMATE
  105515. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105516. #else
  105517. (void)encoder, (void)blocksize;
  105518. #endif
  105519. return estimate;
  105520. }
  105521. unsigned evaluate_fixed_subframe_(
  105522. FLAC__StreamEncoder *encoder,
  105523. const FLAC__int32 signal[],
  105524. FLAC__int32 residual[],
  105525. FLAC__uint64 abs_residual_partition_sums[],
  105526. unsigned raw_bits_per_partition[],
  105527. unsigned blocksize,
  105528. unsigned subframe_bps,
  105529. unsigned order,
  105530. unsigned rice_parameter,
  105531. unsigned rice_parameter_limit,
  105532. unsigned min_partition_order,
  105533. unsigned max_partition_order,
  105534. FLAC__bool do_escape_coding,
  105535. unsigned rice_parameter_search_dist,
  105536. FLAC__Subframe *subframe,
  105537. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105538. )
  105539. {
  105540. unsigned i, residual_bits, estimate;
  105541. const unsigned residual_samples = blocksize - order;
  105542. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105543. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105544. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105545. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105546. subframe->data.fixed.residual = residual;
  105547. residual_bits =
  105548. find_best_partition_order_(
  105549. encoder->private_,
  105550. residual,
  105551. abs_residual_partition_sums,
  105552. raw_bits_per_partition,
  105553. residual_samples,
  105554. order,
  105555. rice_parameter,
  105556. rice_parameter_limit,
  105557. min_partition_order,
  105558. max_partition_order,
  105559. subframe_bps,
  105560. do_escape_coding,
  105561. rice_parameter_search_dist,
  105562. &subframe->data.fixed.entropy_coding_method
  105563. );
  105564. subframe->data.fixed.order = order;
  105565. for(i = 0; i < order; i++)
  105566. subframe->data.fixed.warmup[i] = signal[i];
  105567. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105568. #if SPOTCHECK_ESTIMATE
  105569. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105570. #endif
  105571. return estimate;
  105572. }
  105573. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105574. unsigned evaluate_lpc_subframe_(
  105575. FLAC__StreamEncoder *encoder,
  105576. const FLAC__int32 signal[],
  105577. FLAC__int32 residual[],
  105578. FLAC__uint64 abs_residual_partition_sums[],
  105579. unsigned raw_bits_per_partition[],
  105580. const FLAC__real lp_coeff[],
  105581. unsigned blocksize,
  105582. unsigned subframe_bps,
  105583. unsigned order,
  105584. unsigned qlp_coeff_precision,
  105585. unsigned rice_parameter,
  105586. unsigned rice_parameter_limit,
  105587. unsigned min_partition_order,
  105588. unsigned max_partition_order,
  105589. FLAC__bool do_escape_coding,
  105590. unsigned rice_parameter_search_dist,
  105591. FLAC__Subframe *subframe,
  105592. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105593. )
  105594. {
  105595. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105596. unsigned i, residual_bits, estimate;
  105597. int quantization, ret;
  105598. const unsigned residual_samples = blocksize - order;
  105599. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105600. if(subframe_bps <= 16) {
  105601. FLAC__ASSERT(order > 0);
  105602. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105603. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105604. }
  105605. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105606. if(ret != 0)
  105607. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105608. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105609. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105610. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105611. else
  105612. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105613. else
  105614. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105615. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105616. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105617. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105618. subframe->data.lpc.residual = residual;
  105619. residual_bits =
  105620. find_best_partition_order_(
  105621. encoder->private_,
  105622. residual,
  105623. abs_residual_partition_sums,
  105624. raw_bits_per_partition,
  105625. residual_samples,
  105626. order,
  105627. rice_parameter,
  105628. rice_parameter_limit,
  105629. min_partition_order,
  105630. max_partition_order,
  105631. subframe_bps,
  105632. do_escape_coding,
  105633. rice_parameter_search_dist,
  105634. &subframe->data.lpc.entropy_coding_method
  105635. );
  105636. subframe->data.lpc.order = order;
  105637. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105638. subframe->data.lpc.quantization_level = quantization;
  105639. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105640. for(i = 0; i < order; i++)
  105641. subframe->data.lpc.warmup[i] = signal[i];
  105642. 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;
  105643. #if SPOTCHECK_ESTIMATE
  105644. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105645. #endif
  105646. return estimate;
  105647. }
  105648. #endif
  105649. unsigned evaluate_verbatim_subframe_(
  105650. FLAC__StreamEncoder *encoder,
  105651. const FLAC__int32 signal[],
  105652. unsigned blocksize,
  105653. unsigned subframe_bps,
  105654. FLAC__Subframe *subframe
  105655. )
  105656. {
  105657. unsigned estimate;
  105658. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105659. subframe->data.verbatim.data = signal;
  105660. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105661. #if SPOTCHECK_ESTIMATE
  105662. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105663. #else
  105664. (void)encoder;
  105665. #endif
  105666. return estimate;
  105667. }
  105668. unsigned find_best_partition_order_(
  105669. FLAC__StreamEncoderPrivate *private_,
  105670. const FLAC__int32 residual[],
  105671. FLAC__uint64 abs_residual_partition_sums[],
  105672. unsigned raw_bits_per_partition[],
  105673. unsigned residual_samples,
  105674. unsigned predictor_order,
  105675. unsigned rice_parameter,
  105676. unsigned rice_parameter_limit,
  105677. unsigned min_partition_order,
  105678. unsigned max_partition_order,
  105679. unsigned bps,
  105680. FLAC__bool do_escape_coding,
  105681. unsigned rice_parameter_search_dist,
  105682. FLAC__EntropyCodingMethod *best_ecm
  105683. )
  105684. {
  105685. unsigned residual_bits, best_residual_bits = 0;
  105686. unsigned best_parameters_index = 0;
  105687. unsigned best_partition_order = 0;
  105688. const unsigned blocksize = residual_samples + predictor_order;
  105689. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105690. min_partition_order = min(min_partition_order, max_partition_order);
  105691. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105692. if(do_escape_coding)
  105693. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105694. {
  105695. int partition_order;
  105696. unsigned sum;
  105697. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105698. if(!
  105699. set_partitioned_rice_(
  105700. #ifdef EXACT_RICE_BITS_CALCULATION
  105701. residual,
  105702. #endif
  105703. abs_residual_partition_sums+sum,
  105704. raw_bits_per_partition+sum,
  105705. residual_samples,
  105706. predictor_order,
  105707. rice_parameter,
  105708. rice_parameter_limit,
  105709. rice_parameter_search_dist,
  105710. (unsigned)partition_order,
  105711. do_escape_coding,
  105712. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105713. &residual_bits
  105714. )
  105715. )
  105716. {
  105717. FLAC__ASSERT(best_residual_bits != 0);
  105718. break;
  105719. }
  105720. sum += 1u << partition_order;
  105721. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105722. best_residual_bits = residual_bits;
  105723. best_parameters_index = !best_parameters_index;
  105724. best_partition_order = partition_order;
  105725. }
  105726. }
  105727. }
  105728. best_ecm->data.partitioned_rice.order = best_partition_order;
  105729. {
  105730. /*
  105731. * We are allowed to de-const the pointer based on our special
  105732. * knowledge; it is const to the outside world.
  105733. */
  105734. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105735. unsigned partition;
  105736. /* save best parameters and raw_bits */
  105737. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105738. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105739. if(do_escape_coding)
  105740. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105741. /*
  105742. * Now need to check if the type should be changed to
  105743. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105744. * size of the rice parameters.
  105745. */
  105746. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105747. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105748. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105749. break;
  105750. }
  105751. }
  105752. }
  105753. return best_residual_bits;
  105754. }
  105755. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105756. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105757. const FLAC__int32 residual[],
  105758. FLAC__uint64 abs_residual_partition_sums[],
  105759. unsigned blocksize,
  105760. unsigned predictor_order,
  105761. unsigned min_partition_order,
  105762. unsigned max_partition_order
  105763. );
  105764. #endif
  105765. void precompute_partition_info_sums_(
  105766. const FLAC__int32 residual[],
  105767. FLAC__uint64 abs_residual_partition_sums[],
  105768. unsigned residual_samples,
  105769. unsigned predictor_order,
  105770. unsigned min_partition_order,
  105771. unsigned max_partition_order,
  105772. unsigned bps
  105773. )
  105774. {
  105775. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105776. unsigned partitions = 1u << max_partition_order;
  105777. FLAC__ASSERT(default_partition_samples > predictor_order);
  105778. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105779. /* slightly pessimistic but still catches all common cases */
  105780. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105781. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105782. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105783. return;
  105784. }
  105785. #endif
  105786. /* first do max_partition_order */
  105787. {
  105788. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105789. /* slightly pessimistic but still catches all common cases */
  105790. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105791. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105792. FLAC__uint32 abs_residual_partition_sum;
  105793. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105794. end += default_partition_samples;
  105795. abs_residual_partition_sum = 0;
  105796. for( ; residual_sample < end; residual_sample++)
  105797. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105798. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105799. }
  105800. }
  105801. else { /* have to pessimistically use 64 bits for accumulator */
  105802. FLAC__uint64 abs_residual_partition_sum;
  105803. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105804. end += default_partition_samples;
  105805. abs_residual_partition_sum = 0;
  105806. for( ; residual_sample < end; residual_sample++)
  105807. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105808. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105809. }
  105810. }
  105811. }
  105812. /* now merge partitions for lower orders */
  105813. {
  105814. unsigned from_partition = 0, to_partition = partitions;
  105815. int partition_order;
  105816. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105817. unsigned i;
  105818. partitions >>= 1;
  105819. for(i = 0; i < partitions; i++) {
  105820. abs_residual_partition_sums[to_partition++] =
  105821. abs_residual_partition_sums[from_partition ] +
  105822. abs_residual_partition_sums[from_partition+1];
  105823. from_partition += 2;
  105824. }
  105825. }
  105826. }
  105827. }
  105828. void precompute_partition_info_escapes_(
  105829. const FLAC__int32 residual[],
  105830. unsigned raw_bits_per_partition[],
  105831. unsigned residual_samples,
  105832. unsigned predictor_order,
  105833. unsigned min_partition_order,
  105834. unsigned max_partition_order
  105835. )
  105836. {
  105837. int partition_order;
  105838. unsigned from_partition, to_partition = 0;
  105839. const unsigned blocksize = residual_samples + predictor_order;
  105840. /* first do max_partition_order */
  105841. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105842. FLAC__int32 r;
  105843. FLAC__uint32 rmax;
  105844. unsigned partition, partition_sample, partition_samples, residual_sample;
  105845. const unsigned partitions = 1u << partition_order;
  105846. const unsigned default_partition_samples = blocksize >> partition_order;
  105847. FLAC__ASSERT(default_partition_samples > predictor_order);
  105848. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105849. partition_samples = default_partition_samples;
  105850. if(partition == 0)
  105851. partition_samples -= predictor_order;
  105852. rmax = 0;
  105853. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105854. r = residual[residual_sample++];
  105855. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105856. if(r < 0)
  105857. rmax |= ~r;
  105858. else
  105859. rmax |= r;
  105860. }
  105861. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105862. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105863. }
  105864. to_partition = partitions;
  105865. break; /*@@@ yuck, should remove the 'for' loop instead */
  105866. }
  105867. /* now merge partitions for lower orders */
  105868. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105869. unsigned m;
  105870. unsigned i;
  105871. const unsigned partitions = 1u << partition_order;
  105872. for(i = 0; i < partitions; i++) {
  105873. m = raw_bits_per_partition[from_partition];
  105874. from_partition++;
  105875. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105876. from_partition++;
  105877. to_partition++;
  105878. }
  105879. }
  105880. }
  105881. #ifdef EXACT_RICE_BITS_CALCULATION
  105882. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105883. const unsigned rice_parameter,
  105884. const unsigned partition_samples,
  105885. const FLAC__int32 *residual
  105886. )
  105887. {
  105888. unsigned i, partition_bits =
  105889. 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 */
  105890. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105891. ;
  105892. for(i = 0; i < partition_samples; i++)
  105893. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105894. return partition_bits;
  105895. }
  105896. #else
  105897. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105898. const unsigned rice_parameter,
  105899. const unsigned partition_samples,
  105900. const FLAC__uint64 abs_residual_partition_sum
  105901. )
  105902. {
  105903. return
  105904. 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 */
  105905. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105906. (
  105907. rice_parameter?
  105908. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105909. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105910. )
  105911. - (partition_samples >> 1)
  105912. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105913. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105914. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105915. * So the subtraction term tries to guess how many extra bits were contributed.
  105916. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105917. */
  105918. ;
  105919. }
  105920. #endif
  105921. FLAC__bool set_partitioned_rice_(
  105922. #ifdef EXACT_RICE_BITS_CALCULATION
  105923. const FLAC__int32 residual[],
  105924. #endif
  105925. const FLAC__uint64 abs_residual_partition_sums[],
  105926. const unsigned raw_bits_per_partition[],
  105927. const unsigned residual_samples,
  105928. const unsigned predictor_order,
  105929. const unsigned suggested_rice_parameter,
  105930. const unsigned rice_parameter_limit,
  105931. const unsigned rice_parameter_search_dist,
  105932. const unsigned partition_order,
  105933. const FLAC__bool search_for_escapes,
  105934. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105935. unsigned *bits
  105936. )
  105937. {
  105938. unsigned rice_parameter, partition_bits;
  105939. unsigned best_partition_bits, best_rice_parameter = 0;
  105940. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105941. unsigned *parameters, *raw_bits;
  105942. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105943. unsigned min_rice_parameter, max_rice_parameter;
  105944. #else
  105945. (void)rice_parameter_search_dist;
  105946. #endif
  105947. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105948. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105949. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105950. parameters = partitioned_rice_contents->parameters;
  105951. raw_bits = partitioned_rice_contents->raw_bits;
  105952. if(partition_order == 0) {
  105953. best_partition_bits = (unsigned)(-1);
  105954. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105955. if(rice_parameter_search_dist) {
  105956. if(suggested_rice_parameter < rice_parameter_search_dist)
  105957. min_rice_parameter = 0;
  105958. else
  105959. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105960. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105961. if(max_rice_parameter >= rice_parameter_limit) {
  105962. #ifdef DEBUG_VERBOSE
  105963. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105964. #endif
  105965. max_rice_parameter = rice_parameter_limit - 1;
  105966. }
  105967. }
  105968. else
  105969. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105970. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105971. #else
  105972. rice_parameter = suggested_rice_parameter;
  105973. #endif
  105974. #ifdef EXACT_RICE_BITS_CALCULATION
  105975. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105976. #else
  105977. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105978. #endif
  105979. if(partition_bits < best_partition_bits) {
  105980. best_rice_parameter = rice_parameter;
  105981. best_partition_bits = partition_bits;
  105982. }
  105983. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105984. }
  105985. #endif
  105986. if(search_for_escapes) {
  105987. 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;
  105988. if(partition_bits <= best_partition_bits) {
  105989. raw_bits[0] = raw_bits_per_partition[0];
  105990. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105991. best_partition_bits = partition_bits;
  105992. }
  105993. else
  105994. raw_bits[0] = 0;
  105995. }
  105996. parameters[0] = best_rice_parameter;
  105997. bits_ += best_partition_bits;
  105998. }
  105999. else {
  106000. unsigned partition, residual_sample;
  106001. unsigned partition_samples;
  106002. FLAC__uint64 mean, k;
  106003. const unsigned partitions = 1u << partition_order;
  106004. for(partition = residual_sample = 0; partition < partitions; partition++) {
  106005. partition_samples = (residual_samples+predictor_order) >> partition_order;
  106006. if(partition == 0) {
  106007. if(partition_samples <= predictor_order)
  106008. return false;
  106009. else
  106010. partition_samples -= predictor_order;
  106011. }
  106012. mean = abs_residual_partition_sums[partition];
  106013. /* we are basically calculating the size in bits of the
  106014. * average residual magnitude in the partition:
  106015. * rice_parameter = floor(log2(mean/partition_samples))
  106016. * 'mean' is not a good name for the variable, it is
  106017. * actually the sum of magnitudes of all residual values
  106018. * in the partition, so the actual mean is
  106019. * mean/partition_samples
  106020. */
  106021. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  106022. ;
  106023. if(rice_parameter >= rice_parameter_limit) {
  106024. #ifdef DEBUG_VERBOSE
  106025. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  106026. #endif
  106027. rice_parameter = rice_parameter_limit - 1;
  106028. }
  106029. best_partition_bits = (unsigned)(-1);
  106030. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106031. if(rice_parameter_search_dist) {
  106032. if(rice_parameter < rice_parameter_search_dist)
  106033. min_rice_parameter = 0;
  106034. else
  106035. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  106036. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  106037. if(max_rice_parameter >= rice_parameter_limit) {
  106038. #ifdef DEBUG_VERBOSE
  106039. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  106040. #endif
  106041. max_rice_parameter = rice_parameter_limit - 1;
  106042. }
  106043. }
  106044. else
  106045. min_rice_parameter = max_rice_parameter = rice_parameter;
  106046. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106047. #endif
  106048. #ifdef EXACT_RICE_BITS_CALCULATION
  106049. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  106050. #else
  106051. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  106052. #endif
  106053. if(partition_bits < best_partition_bits) {
  106054. best_rice_parameter = rice_parameter;
  106055. best_partition_bits = partition_bits;
  106056. }
  106057. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106058. }
  106059. #endif
  106060. if(search_for_escapes) {
  106061. 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;
  106062. if(partition_bits <= best_partition_bits) {
  106063. raw_bits[partition] = raw_bits_per_partition[partition];
  106064. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106065. best_partition_bits = partition_bits;
  106066. }
  106067. else
  106068. raw_bits[partition] = 0;
  106069. }
  106070. parameters[partition] = best_rice_parameter;
  106071. bits_ += best_partition_bits;
  106072. residual_sample += partition_samples;
  106073. }
  106074. }
  106075. *bits = bits_;
  106076. return true;
  106077. }
  106078. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  106079. {
  106080. unsigned i, shift;
  106081. FLAC__int32 x = 0;
  106082. for(i = 0; i < samples && !(x&1); i++)
  106083. x |= signal[i];
  106084. if(x == 0) {
  106085. shift = 0;
  106086. }
  106087. else {
  106088. for(shift = 0; !(x&1); shift++)
  106089. x >>= 1;
  106090. }
  106091. if(shift > 0) {
  106092. for(i = 0; i < samples; i++)
  106093. signal[i] >>= shift;
  106094. }
  106095. return shift;
  106096. }
  106097. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106098. {
  106099. unsigned channel;
  106100. for(channel = 0; channel < channels; channel++)
  106101. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  106102. fifo->tail += wide_samples;
  106103. FLAC__ASSERT(fifo->tail <= fifo->size);
  106104. }
  106105. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106106. {
  106107. unsigned channel;
  106108. unsigned sample, wide_sample;
  106109. unsigned tail = fifo->tail;
  106110. sample = input_offset * channels;
  106111. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  106112. for(channel = 0; channel < channels; channel++)
  106113. fifo->data[channel][tail] = input[sample++];
  106114. tail++;
  106115. }
  106116. fifo->tail = tail;
  106117. FLAC__ASSERT(fifo->tail <= fifo->size);
  106118. }
  106119. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106120. {
  106121. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106122. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  106123. (void)decoder;
  106124. if(encoder->private_->verify.needs_magic_hack) {
  106125. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  106126. *bytes = FLAC__STREAM_SYNC_LENGTH;
  106127. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  106128. encoder->private_->verify.needs_magic_hack = false;
  106129. }
  106130. else {
  106131. if(encoded_bytes == 0) {
  106132. /*
  106133. * If we get here, a FIFO underflow has occurred,
  106134. * which means there is a bug somewhere.
  106135. */
  106136. FLAC__ASSERT(0);
  106137. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106138. }
  106139. else if(encoded_bytes < *bytes)
  106140. *bytes = encoded_bytes;
  106141. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106142. encoder->private_->verify.output.data += *bytes;
  106143. encoder->private_->verify.output.bytes -= *bytes;
  106144. }
  106145. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106146. }
  106147. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106148. {
  106149. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106150. unsigned channel;
  106151. const unsigned channels = frame->header.channels;
  106152. const unsigned blocksize = frame->header.blocksize;
  106153. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106154. (void)decoder;
  106155. for(channel = 0; channel < channels; channel++) {
  106156. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106157. unsigned i, sample = 0;
  106158. FLAC__int32 expect = 0, got = 0;
  106159. for(i = 0; i < blocksize; i++) {
  106160. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106161. sample = i;
  106162. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106163. got = (FLAC__int32)buffer[channel][i];
  106164. break;
  106165. }
  106166. }
  106167. FLAC__ASSERT(i < blocksize);
  106168. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106169. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106170. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106171. encoder->private_->verify.error_stats.channel = channel;
  106172. encoder->private_->verify.error_stats.sample = sample;
  106173. encoder->private_->verify.error_stats.expected = expect;
  106174. encoder->private_->verify.error_stats.got = got;
  106175. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106176. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106177. }
  106178. }
  106179. /* dequeue the frame from the fifo */
  106180. encoder->private_->verify.input_fifo.tail -= blocksize;
  106181. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106182. for(channel = 0; channel < channels; channel++)
  106183. 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]));
  106184. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106185. }
  106186. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106187. {
  106188. (void)decoder, (void)metadata, (void)client_data;
  106189. }
  106190. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106191. {
  106192. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106193. (void)decoder, (void)status;
  106194. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106195. }
  106196. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106197. {
  106198. (void)client_data;
  106199. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106200. if (*bytes == 0) {
  106201. if (feof(encoder->private_->file))
  106202. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106203. else if (ferror(encoder->private_->file))
  106204. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106205. }
  106206. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106207. }
  106208. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106209. {
  106210. (void)client_data;
  106211. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106212. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106213. else
  106214. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106215. }
  106216. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106217. {
  106218. off_t offset;
  106219. (void)client_data;
  106220. offset = ftello(encoder->private_->file);
  106221. if(offset < 0) {
  106222. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106223. }
  106224. else {
  106225. *absolute_byte_offset = (FLAC__uint64)offset;
  106226. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106227. }
  106228. }
  106229. #ifdef FLAC__VALGRIND_TESTING
  106230. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106231. {
  106232. size_t ret = fwrite(ptr, size, nmemb, stream);
  106233. if(!ferror(stream))
  106234. fflush(stream);
  106235. return ret;
  106236. }
  106237. #else
  106238. #define local__fwrite fwrite
  106239. #endif
  106240. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106241. {
  106242. (void)client_data, (void)current_frame;
  106243. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106244. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106245. #if FLAC__HAS_OGG
  106246. /* We would like to be able to use 'samples > 0' in the
  106247. * clause here but currently because of the nature of our
  106248. * Ogg writing implementation, 'samples' is always 0 (see
  106249. * ogg_encoder_aspect.c). The downside is extra progress
  106250. * callbacks.
  106251. */
  106252. encoder->private_->is_ogg? true :
  106253. #endif
  106254. samples > 0
  106255. );
  106256. if(call_it) {
  106257. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106258. * because at this point in the callback chain, the stats
  106259. * have not been updated. Only after we return and control
  106260. * gets back to write_frame_() are the stats updated
  106261. */
  106262. 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);
  106263. }
  106264. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106265. }
  106266. else
  106267. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106268. }
  106269. /*
  106270. * This will forcibly set stdout to binary mode (for OSes that require it)
  106271. */
  106272. FILE *get_binary_stdout_(void)
  106273. {
  106274. /* if something breaks here it is probably due to the presence or
  106275. * absence of an underscore before the identifiers 'setmode',
  106276. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106277. */
  106278. #if defined _MSC_VER || defined __MINGW32__
  106279. _setmode(_fileno(stdout), _O_BINARY);
  106280. #elif defined __CYGWIN__
  106281. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106282. setmode(_fileno(stdout), _O_BINARY);
  106283. #elif defined __EMX__
  106284. setmode(fileno(stdout), O_BINARY);
  106285. #endif
  106286. return stdout;
  106287. }
  106288. #endif
  106289. /*** End of inlined file: stream_encoder.c ***/
  106290. /*** Start of inlined file: stream_encoder_framing.c ***/
  106291. /*** Start of inlined file: juce_FlacHeader.h ***/
  106292. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106293. // tasks..
  106294. #define VERSION "1.2.1"
  106295. #define FLAC__NO_DLL 1
  106296. #if JUCE_MSVC
  106297. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106298. #endif
  106299. #if JUCE_MAC
  106300. #define FLAC__SYS_DARWIN 1
  106301. #endif
  106302. /*** End of inlined file: juce_FlacHeader.h ***/
  106303. #if JUCE_USE_FLAC
  106304. #if HAVE_CONFIG_H
  106305. # include <config.h>
  106306. #endif
  106307. #include <stdio.h>
  106308. #include <string.h> /* for strlen() */
  106309. #ifdef max
  106310. #undef max
  106311. #endif
  106312. #define max(x,y) ((x)>(y)?(x):(y))
  106313. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106314. 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);
  106315. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106316. {
  106317. unsigned i, j;
  106318. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106319. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106320. return false;
  106321. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106322. return false;
  106323. /*
  106324. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106325. */
  106326. i = metadata->length;
  106327. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106328. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106329. i -= metadata->data.vorbis_comment.vendor_string.length;
  106330. i += vendor_string_length;
  106331. }
  106332. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106333. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106334. return false;
  106335. switch(metadata->type) {
  106336. case FLAC__METADATA_TYPE_STREAMINFO:
  106337. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106338. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106339. return false;
  106340. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106341. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106342. return false;
  106343. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106344. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106345. return false;
  106346. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106347. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106348. return false;
  106349. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106350. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106351. return false;
  106352. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106353. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106354. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106355. return false;
  106356. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106357. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106358. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106359. return false;
  106360. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106361. return false;
  106362. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106363. return false;
  106364. break;
  106365. case FLAC__METADATA_TYPE_PADDING:
  106366. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106367. return false;
  106368. break;
  106369. case FLAC__METADATA_TYPE_APPLICATION:
  106370. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106371. return false;
  106372. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106373. return false;
  106374. break;
  106375. case FLAC__METADATA_TYPE_SEEKTABLE:
  106376. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106377. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106378. return false;
  106379. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106380. return false;
  106381. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106382. return false;
  106383. }
  106384. break;
  106385. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106386. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106387. return false;
  106388. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106389. return false;
  106390. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106391. return false;
  106392. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106393. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106394. return false;
  106395. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106396. return false;
  106397. }
  106398. break;
  106399. case FLAC__METADATA_TYPE_CUESHEET:
  106400. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106401. 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))
  106402. return false;
  106403. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106404. return false;
  106405. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106406. return false;
  106407. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106408. return false;
  106409. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106410. return false;
  106411. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106412. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106413. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106414. return false;
  106415. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106416. return false;
  106417. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106418. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106419. return false;
  106420. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106421. return false;
  106422. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106423. return false;
  106424. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106425. return false;
  106426. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106427. return false;
  106428. for(j = 0; j < track->num_indices; j++) {
  106429. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106430. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106431. return false;
  106432. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106433. return false;
  106434. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106435. return false;
  106436. }
  106437. }
  106438. break;
  106439. case FLAC__METADATA_TYPE_PICTURE:
  106440. {
  106441. size_t len;
  106442. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106443. return false;
  106444. len = strlen(metadata->data.picture.mime_type);
  106445. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106446. return false;
  106447. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106448. return false;
  106449. len = strlen((const char *)metadata->data.picture.description);
  106450. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106451. return false;
  106452. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106453. return false;
  106454. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106455. return false;
  106456. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106457. return false;
  106458. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106459. return false;
  106460. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106461. return false;
  106462. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106463. return false;
  106464. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106465. return false;
  106466. }
  106467. break;
  106468. default:
  106469. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106470. return false;
  106471. break;
  106472. }
  106473. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106474. return true;
  106475. }
  106476. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106477. {
  106478. unsigned u, blocksize_hint, sample_rate_hint;
  106479. FLAC__byte crc;
  106480. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106481. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106482. return false;
  106483. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106484. return false;
  106485. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106486. return false;
  106487. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106488. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106489. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106490. blocksize_hint = 0;
  106491. switch(header->blocksize) {
  106492. case 192: u = 1; break;
  106493. case 576: u = 2; break;
  106494. case 1152: u = 3; break;
  106495. case 2304: u = 4; break;
  106496. case 4608: u = 5; break;
  106497. case 256: u = 8; break;
  106498. case 512: u = 9; break;
  106499. case 1024: u = 10; break;
  106500. case 2048: u = 11; break;
  106501. case 4096: u = 12; break;
  106502. case 8192: u = 13; break;
  106503. case 16384: u = 14; break;
  106504. case 32768: u = 15; break;
  106505. default:
  106506. if(header->blocksize <= 0x100)
  106507. blocksize_hint = u = 6;
  106508. else
  106509. blocksize_hint = u = 7;
  106510. break;
  106511. }
  106512. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106513. return false;
  106514. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106515. sample_rate_hint = 0;
  106516. switch(header->sample_rate) {
  106517. case 88200: u = 1; break;
  106518. case 176400: u = 2; break;
  106519. case 192000: u = 3; break;
  106520. case 8000: u = 4; break;
  106521. case 16000: u = 5; break;
  106522. case 22050: u = 6; break;
  106523. case 24000: u = 7; break;
  106524. case 32000: u = 8; break;
  106525. case 44100: u = 9; break;
  106526. case 48000: u = 10; break;
  106527. case 96000: u = 11; break;
  106528. default:
  106529. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106530. sample_rate_hint = u = 12;
  106531. else if(header->sample_rate % 10 == 0)
  106532. sample_rate_hint = u = 14;
  106533. else if(header->sample_rate <= 0xffff)
  106534. sample_rate_hint = u = 13;
  106535. else
  106536. u = 0;
  106537. break;
  106538. }
  106539. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106540. return false;
  106541. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106542. switch(header->channel_assignment) {
  106543. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106544. u = header->channels - 1;
  106545. break;
  106546. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106547. FLAC__ASSERT(header->channels == 2);
  106548. u = 8;
  106549. break;
  106550. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106551. FLAC__ASSERT(header->channels == 2);
  106552. u = 9;
  106553. break;
  106554. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106555. FLAC__ASSERT(header->channels == 2);
  106556. u = 10;
  106557. break;
  106558. default:
  106559. FLAC__ASSERT(0);
  106560. }
  106561. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106562. return false;
  106563. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106564. switch(header->bits_per_sample) {
  106565. case 8 : u = 1; break;
  106566. case 12: u = 2; break;
  106567. case 16: u = 4; break;
  106568. case 20: u = 5; break;
  106569. case 24: u = 6; break;
  106570. default: u = 0; break;
  106571. }
  106572. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106573. return false;
  106574. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106575. return false;
  106576. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106577. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106578. return false;
  106579. }
  106580. else {
  106581. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106582. return false;
  106583. }
  106584. if(blocksize_hint)
  106585. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106586. return false;
  106587. switch(sample_rate_hint) {
  106588. case 12:
  106589. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106590. return false;
  106591. break;
  106592. case 13:
  106593. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106594. return false;
  106595. break;
  106596. case 14:
  106597. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106598. return false;
  106599. break;
  106600. }
  106601. /* write the CRC */
  106602. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106603. return false;
  106604. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106605. return false;
  106606. return true;
  106607. }
  106608. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106609. {
  106610. FLAC__bool ok;
  106611. ok =
  106612. 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) &&
  106613. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106614. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106615. ;
  106616. return ok;
  106617. }
  106618. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106619. {
  106620. unsigned i;
  106621. 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))
  106622. return false;
  106623. if(wasted_bits)
  106624. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106625. return false;
  106626. for(i = 0; i < subframe->order; i++)
  106627. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106628. return false;
  106629. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106630. return false;
  106631. switch(subframe->entropy_coding_method.type) {
  106632. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106633. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106634. if(!add_residual_partitioned_rice_(
  106635. bw,
  106636. subframe->residual,
  106637. residual_samples,
  106638. subframe->order,
  106639. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106640. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106641. subframe->entropy_coding_method.data.partitioned_rice.order,
  106642. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106643. ))
  106644. return false;
  106645. break;
  106646. default:
  106647. FLAC__ASSERT(0);
  106648. }
  106649. return true;
  106650. }
  106651. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106652. {
  106653. unsigned i;
  106654. 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))
  106655. return false;
  106656. if(wasted_bits)
  106657. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106658. return false;
  106659. for(i = 0; i < subframe->order; i++)
  106660. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106661. return false;
  106662. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106663. return false;
  106664. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106665. return false;
  106666. for(i = 0; i < subframe->order; i++)
  106667. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106668. return false;
  106669. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106670. return false;
  106671. switch(subframe->entropy_coding_method.type) {
  106672. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106673. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106674. if(!add_residual_partitioned_rice_(
  106675. bw,
  106676. subframe->residual,
  106677. residual_samples,
  106678. subframe->order,
  106679. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106680. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106681. subframe->entropy_coding_method.data.partitioned_rice.order,
  106682. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106683. ))
  106684. return false;
  106685. break;
  106686. default:
  106687. FLAC__ASSERT(0);
  106688. }
  106689. return true;
  106690. }
  106691. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106692. {
  106693. unsigned i;
  106694. const FLAC__int32 *signal = subframe->data;
  106695. 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))
  106696. return false;
  106697. if(wasted_bits)
  106698. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106699. return false;
  106700. for(i = 0; i < samples; i++)
  106701. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106702. return false;
  106703. return true;
  106704. }
  106705. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106706. {
  106707. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106708. return false;
  106709. switch(method->type) {
  106710. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106711. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106712. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106713. return false;
  106714. break;
  106715. default:
  106716. FLAC__ASSERT(0);
  106717. }
  106718. return true;
  106719. }
  106720. 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)
  106721. {
  106722. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106723. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106724. if(partition_order == 0) {
  106725. unsigned i;
  106726. if(raw_bits[0] == 0) {
  106727. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106728. return false;
  106729. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106730. return false;
  106731. }
  106732. else {
  106733. FLAC__ASSERT(rice_parameters[0] == 0);
  106734. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106735. return false;
  106736. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106737. return false;
  106738. for(i = 0; i < residual_samples; i++) {
  106739. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106740. return false;
  106741. }
  106742. }
  106743. return true;
  106744. }
  106745. else {
  106746. unsigned i, j, k = 0, k_last = 0;
  106747. unsigned partition_samples;
  106748. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106749. for(i = 0; i < (1u<<partition_order); i++) {
  106750. partition_samples = default_partition_samples;
  106751. if(i == 0)
  106752. partition_samples -= predictor_order;
  106753. k += partition_samples;
  106754. if(raw_bits[i] == 0) {
  106755. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106756. return false;
  106757. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106758. return false;
  106759. }
  106760. else {
  106761. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106762. return false;
  106763. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106764. return false;
  106765. for(j = k_last; j < k; j++) {
  106766. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106767. return false;
  106768. }
  106769. }
  106770. k_last = k;
  106771. }
  106772. return true;
  106773. }
  106774. }
  106775. #endif
  106776. /*** End of inlined file: stream_encoder_framing.c ***/
  106777. /*** Start of inlined file: window_flac.c ***/
  106778. /*** Start of inlined file: juce_FlacHeader.h ***/
  106779. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106780. // tasks..
  106781. #define VERSION "1.2.1"
  106782. #define FLAC__NO_DLL 1
  106783. #if JUCE_MSVC
  106784. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106785. #endif
  106786. #if JUCE_MAC
  106787. #define FLAC__SYS_DARWIN 1
  106788. #endif
  106789. /*** End of inlined file: juce_FlacHeader.h ***/
  106790. #if JUCE_USE_FLAC
  106791. #if HAVE_CONFIG_H
  106792. # include <config.h>
  106793. #endif
  106794. #include <math.h>
  106795. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106796. #ifndef M_PI
  106797. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106798. #define M_PI 3.14159265358979323846
  106799. #endif
  106800. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106801. {
  106802. const FLAC__int32 N = L - 1;
  106803. FLAC__int32 n;
  106804. if (L & 1) {
  106805. for (n = 0; n <= N/2; n++)
  106806. window[n] = 2.0f * n / (float)N;
  106807. for (; n <= N; n++)
  106808. window[n] = 2.0f - 2.0f * n / (float)N;
  106809. }
  106810. else {
  106811. for (n = 0; n <= L/2-1; n++)
  106812. window[n] = 2.0f * n / (float)N;
  106813. for (; n <= N; n++)
  106814. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106815. }
  106816. }
  106817. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106818. {
  106819. const FLAC__int32 N = L - 1;
  106820. FLAC__int32 n;
  106821. for (n = 0; n < L; n++)
  106822. 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)));
  106823. }
  106824. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106825. {
  106826. const FLAC__int32 N = L - 1;
  106827. FLAC__int32 n;
  106828. for (n = 0; n < L; n++)
  106829. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106830. }
  106831. /* 4-term -92dB side-lobe */
  106832. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106833. {
  106834. const FLAC__int32 N = L - 1;
  106835. FLAC__int32 n;
  106836. for (n = 0; n <= N; n++)
  106837. 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));
  106838. }
  106839. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106840. {
  106841. const FLAC__int32 N = L - 1;
  106842. const double N2 = (double)N / 2.;
  106843. FLAC__int32 n;
  106844. for (n = 0; n <= N; n++) {
  106845. double k = ((double)n - N2) / N2;
  106846. k = 1.0f - k * k;
  106847. window[n] = (FLAC__real)(k * k);
  106848. }
  106849. }
  106850. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106851. {
  106852. const FLAC__int32 N = L - 1;
  106853. FLAC__int32 n;
  106854. for (n = 0; n < L; n++)
  106855. 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));
  106856. }
  106857. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106858. {
  106859. const FLAC__int32 N = L - 1;
  106860. const double N2 = (double)N / 2.;
  106861. FLAC__int32 n;
  106862. for (n = 0; n <= N; n++) {
  106863. const double k = ((double)n - N2) / (stddev * N2);
  106864. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106865. }
  106866. }
  106867. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106868. {
  106869. const FLAC__int32 N = L - 1;
  106870. FLAC__int32 n;
  106871. for (n = 0; n < L; n++)
  106872. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106873. }
  106874. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106875. {
  106876. const FLAC__int32 N = L - 1;
  106877. FLAC__int32 n;
  106878. for (n = 0; n < L; n++)
  106879. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106880. }
  106881. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106882. {
  106883. const FLAC__int32 N = L - 1;
  106884. FLAC__int32 n;
  106885. for (n = 0; n < L; n++)
  106886. 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));
  106887. }
  106888. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106889. {
  106890. const FLAC__int32 N = L - 1;
  106891. FLAC__int32 n;
  106892. for (n = 0; n < L; n++)
  106893. 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));
  106894. }
  106895. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106896. {
  106897. FLAC__int32 n;
  106898. for (n = 0; n < L; n++)
  106899. window[n] = 1.0f;
  106900. }
  106901. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106902. {
  106903. FLAC__int32 n;
  106904. if (L & 1) {
  106905. for (n = 1; n <= L+1/2; n++)
  106906. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106907. for (; n <= L; n++)
  106908. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106909. }
  106910. else {
  106911. for (n = 1; n <= L/2; n++)
  106912. window[n-1] = 2.0f * n / (float)L;
  106913. for (; n <= L; n++)
  106914. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106915. }
  106916. }
  106917. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106918. {
  106919. if (p <= 0.0)
  106920. FLAC__window_rectangle(window, L);
  106921. else if (p >= 1.0)
  106922. FLAC__window_hann(window, L);
  106923. else {
  106924. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106925. FLAC__int32 n;
  106926. /* start with rectangle... */
  106927. FLAC__window_rectangle(window, L);
  106928. /* ...replace ends with hann */
  106929. if (Np > 0) {
  106930. for (n = 0; n <= Np; n++) {
  106931. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106932. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106933. }
  106934. }
  106935. }
  106936. }
  106937. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106938. {
  106939. const FLAC__int32 N = L - 1;
  106940. const double N2 = (double)N / 2.;
  106941. FLAC__int32 n;
  106942. for (n = 0; n <= N; n++) {
  106943. const double k = ((double)n - N2) / N2;
  106944. window[n] = (FLAC__real)(1.0f - k * k);
  106945. }
  106946. }
  106947. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106948. #endif
  106949. /*** End of inlined file: window_flac.c ***/
  106950. #else
  106951. #include <FLAC/all.h>
  106952. #endif
  106953. }
  106954. #undef max
  106955. #undef min
  106956. BEGIN_JUCE_NAMESPACE
  106957. static const char* const flacFormatName = "FLAC file";
  106958. static const char* const flacExtensions[] = { ".flac", 0 };
  106959. class FlacReader : public AudioFormatReader
  106960. {
  106961. public:
  106962. FlacReader (InputStream* const in)
  106963. : AudioFormatReader (in, TRANS (flacFormatName)),
  106964. reservoir (2, 0),
  106965. reservoirStart (0),
  106966. samplesInReservoir (0),
  106967. scanningForLength (false)
  106968. {
  106969. using namespace FlacNamespace;
  106970. lengthInSamples = 0;
  106971. decoder = FLAC__stream_decoder_new();
  106972. ok = FLAC__stream_decoder_init_stream (decoder,
  106973. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106974. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106975. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106976. if (ok)
  106977. {
  106978. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106979. if (lengthInSamples == 0 && sampleRate > 0)
  106980. {
  106981. // the length hasn't been stored in the metadata, so we'll need to
  106982. // work it out the length the hard way, by scanning the whole file..
  106983. scanningForLength = true;
  106984. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106985. scanningForLength = false;
  106986. const int64 tempLength = lengthInSamples;
  106987. FLAC__stream_decoder_reset (decoder);
  106988. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106989. lengthInSamples = tempLength;
  106990. }
  106991. }
  106992. }
  106993. ~FlacReader()
  106994. {
  106995. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106996. }
  106997. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106998. {
  106999. sampleRate = info.sample_rate;
  107000. bitsPerSample = info.bits_per_sample;
  107001. lengthInSamples = (unsigned int) info.total_samples;
  107002. numChannels = info.channels;
  107003. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  107004. }
  107005. // returns the number of samples read
  107006. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  107007. int64 startSampleInFile, int numSamples)
  107008. {
  107009. using namespace FlacNamespace;
  107010. if (! ok)
  107011. return false;
  107012. while (numSamples > 0)
  107013. {
  107014. if (startSampleInFile >= reservoirStart
  107015. && startSampleInFile < reservoirStart + samplesInReservoir)
  107016. {
  107017. const int num = (int) jmin ((int64) numSamples,
  107018. reservoirStart + samplesInReservoir - startSampleInFile);
  107019. jassert (num > 0);
  107020. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  107021. if (destSamples[i] != 0)
  107022. memcpy (destSamples[i] + startOffsetInDestBuffer,
  107023. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  107024. sizeof (int) * num);
  107025. startOffsetInDestBuffer += num;
  107026. startSampleInFile += num;
  107027. numSamples -= num;
  107028. }
  107029. else
  107030. {
  107031. if (startSampleInFile >= (int) lengthInSamples)
  107032. {
  107033. samplesInReservoir = 0;
  107034. }
  107035. else if (startSampleInFile < reservoirStart
  107036. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  107037. {
  107038. // had some problems with flac crashing if the read pos is aligned more
  107039. // accurately than this. Probably fixed in newer versions of the library, though.
  107040. reservoirStart = (int) (startSampleInFile & ~511);
  107041. samplesInReservoir = 0;
  107042. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  107043. }
  107044. else
  107045. {
  107046. reservoirStart += samplesInReservoir;
  107047. samplesInReservoir = 0;
  107048. FLAC__stream_decoder_process_single (decoder);
  107049. }
  107050. if (samplesInReservoir == 0)
  107051. break;
  107052. }
  107053. }
  107054. if (numSamples > 0)
  107055. {
  107056. for (int i = numDestChannels; --i >= 0;)
  107057. if (destSamples[i] != 0)
  107058. zeromem (destSamples[i] + startOffsetInDestBuffer,
  107059. sizeof (int) * numSamples);
  107060. }
  107061. return true;
  107062. }
  107063. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  107064. {
  107065. if (scanningForLength)
  107066. {
  107067. lengthInSamples += numSamples;
  107068. }
  107069. else
  107070. {
  107071. if (numSamples > reservoir.getNumSamples())
  107072. reservoir.setSize (numChannels, numSamples, false, false, true);
  107073. const int bitsToShift = 32 - bitsPerSample;
  107074. for (int i = 0; i < (int) numChannels; ++i)
  107075. {
  107076. const FlacNamespace::FLAC__int32* src = buffer[i];
  107077. int n = i;
  107078. while (src == 0 && n > 0)
  107079. src = buffer [--n];
  107080. if (src != 0)
  107081. {
  107082. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  107083. for (int j = 0; j < numSamples; ++j)
  107084. dest[j] = src[j] << bitsToShift;
  107085. }
  107086. }
  107087. samplesInReservoir = numSamples;
  107088. }
  107089. }
  107090. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  107091. {
  107092. using namespace FlacNamespace;
  107093. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  107094. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  107095. }
  107096. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  107097. {
  107098. using namespace FlacNamespace;
  107099. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  107100. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  107101. }
  107102. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107103. {
  107104. using namespace FlacNamespace;
  107105. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  107106. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  107107. }
  107108. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  107109. {
  107110. using namespace FlacNamespace;
  107111. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  107112. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  107113. }
  107114. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  107115. {
  107116. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  107117. }
  107118. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107119. const FlacNamespace::FLAC__Frame* frame,
  107120. const FlacNamespace::FLAC__int32* const buffer[],
  107121. void* client_data)
  107122. {
  107123. using namespace FlacNamespace;
  107124. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  107125. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  107126. }
  107127. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107128. const FlacNamespace::FLAC__StreamMetadata* metadata,
  107129. void* client_data)
  107130. {
  107131. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  107132. }
  107133. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107134. {
  107135. }
  107136. juce_UseDebuggingNewOperator
  107137. private:
  107138. FlacNamespace::FLAC__StreamDecoder* decoder;
  107139. AudioSampleBuffer reservoir;
  107140. int reservoirStart, samplesInReservoir;
  107141. bool ok, scanningForLength;
  107142. FlacReader (const FlacReader&);
  107143. FlacReader& operator= (const FlacReader&);
  107144. };
  107145. class FlacWriter : public AudioFormatWriter
  107146. {
  107147. public:
  107148. FlacWriter (OutputStream* const out,
  107149. const double sampleRate_,
  107150. const int numChannels_,
  107151. const int bitsPerSample_)
  107152. : AudioFormatWriter (out, TRANS (flacFormatName),
  107153. sampleRate_,
  107154. numChannels_,
  107155. bitsPerSample_)
  107156. {
  107157. using namespace FlacNamespace;
  107158. encoder = FLAC__stream_encoder_new();
  107159. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107160. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107161. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107162. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107163. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107164. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107165. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107166. ok = FLAC__stream_encoder_init_stream (encoder,
  107167. encodeWriteCallback, encodeSeekCallback,
  107168. encodeTellCallback, encodeMetadataCallback,
  107169. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107170. }
  107171. ~FlacWriter()
  107172. {
  107173. if (ok)
  107174. {
  107175. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107176. output->flush();
  107177. }
  107178. else
  107179. {
  107180. output = 0; // to stop the base class deleting this, as it needs to be returned
  107181. // to the caller of createWriter()
  107182. }
  107183. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107184. }
  107185. bool write (const int** samplesToWrite, int numSamples)
  107186. {
  107187. using namespace FlacNamespace;
  107188. if (! ok)
  107189. return false;
  107190. int* buf[3];
  107191. const int bitsToShift = 32 - bitsPerSample;
  107192. if (bitsToShift > 0)
  107193. {
  107194. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107195. HeapBlock<int> temp (numSamples * numChannelsToWrite);
  107196. buf[0] = temp.getData();
  107197. buf[1] = temp.getData() + numSamples;
  107198. buf[2] = 0;
  107199. for (int i = numChannelsToWrite; --i >= 0;)
  107200. {
  107201. if (samplesToWrite[i] != 0)
  107202. {
  107203. for (int j = 0; j < numSamples; ++j)
  107204. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107205. }
  107206. }
  107207. samplesToWrite = const_cast<const int**> (buf);
  107208. }
  107209. return FLAC__stream_encoder_process (encoder,
  107210. (const FLAC__int32**) samplesToWrite,
  107211. numSamples) != 0;
  107212. }
  107213. bool writeData (const void* const data, const int size) const
  107214. {
  107215. return output->write (data, size);
  107216. }
  107217. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107218. {
  107219. using namespace FlacNamespace;
  107220. b += bytes;
  107221. for (int i = 0; i < bytes; ++i)
  107222. {
  107223. *(--b) = (FLAC__byte) (val & 0xff);
  107224. val >>= 8;
  107225. }
  107226. }
  107227. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107228. {
  107229. using namespace FlacNamespace;
  107230. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107231. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107232. const unsigned int channelsMinus1 = info.channels - 1;
  107233. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107234. packUint32 (info.min_blocksize, buffer, 2);
  107235. packUint32 (info.max_blocksize, buffer + 2, 2);
  107236. packUint32 (info.min_framesize, buffer + 4, 3);
  107237. packUint32 (info.max_framesize, buffer + 7, 3);
  107238. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107239. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107240. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107241. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107242. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107243. memcpy (buffer + 18, info.md5sum, 16);
  107244. const bool seekOk = output->setPosition (4);
  107245. (void) seekOk;
  107246. // if this fails, you've given it an output stream that can't seek! It needs
  107247. // to be able to seek back to write the header
  107248. jassert (seekOk);
  107249. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107250. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107251. }
  107252. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107253. const FlacNamespace::FLAC__byte buffer[],
  107254. size_t bytes,
  107255. unsigned int /*samples*/,
  107256. unsigned int /*current_frame*/,
  107257. void* client_data)
  107258. {
  107259. using namespace FlacNamespace;
  107260. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107261. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107262. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107263. }
  107264. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107265. {
  107266. using namespace FlacNamespace;
  107267. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107268. }
  107269. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107270. {
  107271. using namespace FlacNamespace;
  107272. if (client_data == 0)
  107273. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107274. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107275. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107276. }
  107277. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107278. {
  107279. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107280. }
  107281. juce_UseDebuggingNewOperator
  107282. bool ok;
  107283. private:
  107284. FlacNamespace::FLAC__StreamEncoder* encoder;
  107285. FlacWriter (const FlacWriter&);
  107286. FlacWriter& operator= (const FlacWriter&);
  107287. };
  107288. FlacAudioFormat::FlacAudioFormat()
  107289. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107290. {
  107291. }
  107292. FlacAudioFormat::~FlacAudioFormat()
  107293. {
  107294. }
  107295. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107296. {
  107297. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107298. return Array <int> (rates);
  107299. }
  107300. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107301. {
  107302. const int depths[] = { 16, 24, 0 };
  107303. return Array <int> (depths);
  107304. }
  107305. bool FlacAudioFormat::canDoStereo()
  107306. {
  107307. return true;
  107308. }
  107309. bool FlacAudioFormat::canDoMono()
  107310. {
  107311. return true;
  107312. }
  107313. bool FlacAudioFormat::isCompressed()
  107314. {
  107315. return true;
  107316. }
  107317. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107318. const bool deleteStreamIfOpeningFails)
  107319. {
  107320. ScopedPointer<FlacReader> r (new FlacReader (in));
  107321. if (r->sampleRate != 0)
  107322. return r.release();
  107323. if (! deleteStreamIfOpeningFails)
  107324. r->input = 0;
  107325. return 0;
  107326. }
  107327. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107328. double sampleRate,
  107329. unsigned int numberOfChannels,
  107330. int bitsPerSample,
  107331. const StringPairArray& /*metadataValues*/,
  107332. int /*qualityOptionIndex*/)
  107333. {
  107334. if (getPossibleBitDepths().contains (bitsPerSample))
  107335. {
  107336. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  107337. if (w->ok)
  107338. return w.release();
  107339. }
  107340. return 0;
  107341. }
  107342. END_JUCE_NAMESPACE
  107343. #endif
  107344. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107345. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107346. #if JUCE_USE_OGGVORBIS
  107347. #if JUCE_MAC
  107348. #define __MACOSX__ 1
  107349. #endif
  107350. namespace OggVorbisNamespace
  107351. {
  107352. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107353. /*** Start of inlined file: vorbisenc.h ***/
  107354. #ifndef _OV_ENC_H_
  107355. #define _OV_ENC_H_
  107356. #ifdef __cplusplus
  107357. extern "C"
  107358. {
  107359. #endif /* __cplusplus */
  107360. /*** Start of inlined file: codec.h ***/
  107361. #ifndef _vorbis_codec_h_
  107362. #define _vorbis_codec_h_
  107363. #ifdef __cplusplus
  107364. extern "C"
  107365. {
  107366. #endif /* __cplusplus */
  107367. /*** Start of inlined file: ogg.h ***/
  107368. #ifndef _OGG_H
  107369. #define _OGG_H
  107370. #ifdef __cplusplus
  107371. extern "C" {
  107372. #endif
  107373. /*** Start of inlined file: os_types.h ***/
  107374. #ifndef _OS_TYPES_H
  107375. #define _OS_TYPES_H
  107376. /* make it easy on the folks that want to compile the libs with a
  107377. different malloc than stdlib */
  107378. #define _ogg_malloc malloc
  107379. #define _ogg_calloc calloc
  107380. #define _ogg_realloc realloc
  107381. #define _ogg_free free
  107382. #if defined(_WIN32)
  107383. # if defined(__CYGWIN__)
  107384. # include <_G_config.h>
  107385. typedef _G_int64_t ogg_int64_t;
  107386. typedef _G_int32_t ogg_int32_t;
  107387. typedef _G_uint32_t ogg_uint32_t;
  107388. typedef _G_int16_t ogg_int16_t;
  107389. typedef _G_uint16_t ogg_uint16_t;
  107390. # elif defined(__MINGW32__)
  107391. typedef short ogg_int16_t;
  107392. typedef unsigned short ogg_uint16_t;
  107393. typedef int ogg_int32_t;
  107394. typedef unsigned int ogg_uint32_t;
  107395. typedef long long ogg_int64_t;
  107396. typedef unsigned long long ogg_uint64_t;
  107397. # elif defined(__MWERKS__)
  107398. typedef long long ogg_int64_t;
  107399. typedef int ogg_int32_t;
  107400. typedef unsigned int ogg_uint32_t;
  107401. typedef short ogg_int16_t;
  107402. typedef unsigned short ogg_uint16_t;
  107403. # else
  107404. /* MSVC/Borland */
  107405. typedef __int64 ogg_int64_t;
  107406. typedef __int32 ogg_int32_t;
  107407. typedef unsigned __int32 ogg_uint32_t;
  107408. typedef __int16 ogg_int16_t;
  107409. typedef unsigned __int16 ogg_uint16_t;
  107410. # endif
  107411. #elif defined(__MACOS__)
  107412. # include <sys/types.h>
  107413. typedef SInt16 ogg_int16_t;
  107414. typedef UInt16 ogg_uint16_t;
  107415. typedef SInt32 ogg_int32_t;
  107416. typedef UInt32 ogg_uint32_t;
  107417. typedef SInt64 ogg_int64_t;
  107418. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107419. # include <sys/types.h>
  107420. typedef int16_t ogg_int16_t;
  107421. typedef u_int16_t ogg_uint16_t;
  107422. typedef int32_t ogg_int32_t;
  107423. typedef u_int32_t ogg_uint32_t;
  107424. typedef int64_t ogg_int64_t;
  107425. #elif defined(__BEOS__)
  107426. /* Be */
  107427. # include <inttypes.h>
  107428. typedef int16_t ogg_int16_t;
  107429. typedef u_int16_t ogg_uint16_t;
  107430. typedef int32_t ogg_int32_t;
  107431. typedef u_int32_t ogg_uint32_t;
  107432. typedef int64_t ogg_int64_t;
  107433. #elif defined (__EMX__)
  107434. /* OS/2 GCC */
  107435. typedef short ogg_int16_t;
  107436. typedef unsigned short ogg_uint16_t;
  107437. typedef int ogg_int32_t;
  107438. typedef unsigned int ogg_uint32_t;
  107439. typedef long long ogg_int64_t;
  107440. #elif defined (DJGPP)
  107441. /* DJGPP */
  107442. typedef short ogg_int16_t;
  107443. typedef int ogg_int32_t;
  107444. typedef unsigned int ogg_uint32_t;
  107445. typedef long long ogg_int64_t;
  107446. #elif defined(R5900)
  107447. /* PS2 EE */
  107448. typedef long ogg_int64_t;
  107449. typedef int ogg_int32_t;
  107450. typedef unsigned ogg_uint32_t;
  107451. typedef short ogg_int16_t;
  107452. #elif defined(__SYMBIAN32__)
  107453. /* Symbian GCC */
  107454. typedef signed short ogg_int16_t;
  107455. typedef unsigned short ogg_uint16_t;
  107456. typedef signed int ogg_int32_t;
  107457. typedef unsigned int ogg_uint32_t;
  107458. typedef long long int ogg_int64_t;
  107459. #else
  107460. # include <sys/types.h>
  107461. /*** Start of inlined file: config_types.h ***/
  107462. #ifndef __CONFIG_TYPES_H__
  107463. #define __CONFIG_TYPES_H__
  107464. typedef int16_t ogg_int16_t;
  107465. typedef unsigned short ogg_uint16_t;
  107466. typedef int32_t ogg_int32_t;
  107467. typedef unsigned int ogg_uint32_t;
  107468. typedef int64_t ogg_int64_t;
  107469. #endif
  107470. /*** End of inlined file: config_types.h ***/
  107471. #endif
  107472. #endif /* _OS_TYPES_H */
  107473. /*** End of inlined file: os_types.h ***/
  107474. typedef struct {
  107475. long endbyte;
  107476. int endbit;
  107477. unsigned char *buffer;
  107478. unsigned char *ptr;
  107479. long storage;
  107480. } oggpack_buffer;
  107481. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107482. typedef struct {
  107483. unsigned char *header;
  107484. long header_len;
  107485. unsigned char *body;
  107486. long body_len;
  107487. } ogg_page;
  107488. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107489. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107490. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107491. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107492. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107493. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107494. }
  107495. /* ogg_stream_state contains the current encode/decode state of a logical
  107496. Ogg bitstream **********************************************************/
  107497. typedef struct {
  107498. unsigned char *body_data; /* bytes from packet bodies */
  107499. long body_storage; /* storage elements allocated */
  107500. long body_fill; /* elements stored; fill mark */
  107501. long body_returned; /* elements of fill returned */
  107502. int *lacing_vals; /* The values that will go to the segment table */
  107503. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107504. this way, but it is simple coupled to the
  107505. lacing fifo */
  107506. long lacing_storage;
  107507. long lacing_fill;
  107508. long lacing_packet;
  107509. long lacing_returned;
  107510. unsigned char header[282]; /* working space for header encode */
  107511. int header_fill;
  107512. int e_o_s; /* set when we have buffered the last packet in the
  107513. logical bitstream */
  107514. int b_o_s; /* set after we've written the initial page
  107515. of a logical bitstream */
  107516. long serialno;
  107517. long pageno;
  107518. ogg_int64_t packetno; /* sequence number for decode; the framing
  107519. knows where there's a hole in the data,
  107520. but we need coupling so that the codec
  107521. (which is in a seperate abstraction
  107522. layer) also knows about the gap */
  107523. ogg_int64_t granulepos;
  107524. } ogg_stream_state;
  107525. /* ogg_packet is used to encapsulate the data and metadata belonging
  107526. to a single raw Ogg/Vorbis packet *************************************/
  107527. typedef struct {
  107528. unsigned char *packet;
  107529. long bytes;
  107530. long b_o_s;
  107531. long e_o_s;
  107532. ogg_int64_t granulepos;
  107533. ogg_int64_t packetno; /* sequence number for decode; the framing
  107534. knows where there's a hole in the data,
  107535. but we need coupling so that the codec
  107536. (which is in a seperate abstraction
  107537. layer) also knows about the gap */
  107538. } ogg_packet;
  107539. typedef struct {
  107540. unsigned char *data;
  107541. int storage;
  107542. int fill;
  107543. int returned;
  107544. int unsynced;
  107545. int headerbytes;
  107546. int bodybytes;
  107547. } ogg_sync_state;
  107548. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107549. extern void oggpack_writeinit(oggpack_buffer *b);
  107550. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107551. extern void oggpack_writealign(oggpack_buffer *b);
  107552. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107553. extern void oggpack_reset(oggpack_buffer *b);
  107554. extern void oggpack_writeclear(oggpack_buffer *b);
  107555. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107556. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107557. extern long oggpack_look(oggpack_buffer *b,int bits);
  107558. extern long oggpack_look1(oggpack_buffer *b);
  107559. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107560. extern void oggpack_adv1(oggpack_buffer *b);
  107561. extern long oggpack_read(oggpack_buffer *b,int bits);
  107562. extern long oggpack_read1(oggpack_buffer *b);
  107563. extern long oggpack_bytes(oggpack_buffer *b);
  107564. extern long oggpack_bits(oggpack_buffer *b);
  107565. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107566. extern void oggpackB_writeinit(oggpack_buffer *b);
  107567. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107568. extern void oggpackB_writealign(oggpack_buffer *b);
  107569. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107570. extern void oggpackB_reset(oggpack_buffer *b);
  107571. extern void oggpackB_writeclear(oggpack_buffer *b);
  107572. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107573. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107574. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107575. extern long oggpackB_look1(oggpack_buffer *b);
  107576. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107577. extern void oggpackB_adv1(oggpack_buffer *b);
  107578. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107579. extern long oggpackB_read1(oggpack_buffer *b);
  107580. extern long oggpackB_bytes(oggpack_buffer *b);
  107581. extern long oggpackB_bits(oggpack_buffer *b);
  107582. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107583. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107584. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107585. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107586. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107587. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107588. extern int ogg_sync_init(ogg_sync_state *oy);
  107589. extern int ogg_sync_clear(ogg_sync_state *oy);
  107590. extern int ogg_sync_reset(ogg_sync_state *oy);
  107591. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107592. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107593. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107594. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107595. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107596. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107597. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107598. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107599. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107600. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107601. extern int ogg_stream_clear(ogg_stream_state *os);
  107602. extern int ogg_stream_reset(ogg_stream_state *os);
  107603. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107604. extern int ogg_stream_destroy(ogg_stream_state *os);
  107605. extern int ogg_stream_eos(ogg_stream_state *os);
  107606. extern void ogg_page_checksum_set(ogg_page *og);
  107607. extern int ogg_page_version(ogg_page *og);
  107608. extern int ogg_page_continued(ogg_page *og);
  107609. extern int ogg_page_bos(ogg_page *og);
  107610. extern int ogg_page_eos(ogg_page *og);
  107611. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107612. extern int ogg_page_serialno(ogg_page *og);
  107613. extern long ogg_page_pageno(ogg_page *og);
  107614. extern int ogg_page_packets(ogg_page *og);
  107615. extern void ogg_packet_clear(ogg_packet *op);
  107616. #ifdef __cplusplus
  107617. }
  107618. #endif
  107619. #endif /* _OGG_H */
  107620. /*** End of inlined file: ogg.h ***/
  107621. typedef struct vorbis_info{
  107622. int version;
  107623. int channels;
  107624. long rate;
  107625. /* The below bitrate declarations are *hints*.
  107626. Combinations of the three values carry the following implications:
  107627. all three set to the same value:
  107628. implies a fixed rate bitstream
  107629. only nominal set:
  107630. implies a VBR stream that averages the nominal bitrate. No hard
  107631. upper/lower limit
  107632. upper and or lower set:
  107633. implies a VBR bitstream that obeys the bitrate limits. nominal
  107634. may also be set to give a nominal rate.
  107635. none set:
  107636. the coder does not care to speculate.
  107637. */
  107638. long bitrate_upper;
  107639. long bitrate_nominal;
  107640. long bitrate_lower;
  107641. long bitrate_window;
  107642. void *codec_setup;
  107643. } vorbis_info;
  107644. /* vorbis_dsp_state buffers the current vorbis audio
  107645. analysis/synthesis state. The DSP state belongs to a specific
  107646. logical bitstream ****************************************************/
  107647. typedef struct vorbis_dsp_state{
  107648. int analysisp;
  107649. vorbis_info *vi;
  107650. float **pcm;
  107651. float **pcmret;
  107652. int pcm_storage;
  107653. int pcm_current;
  107654. int pcm_returned;
  107655. int preextrapolate;
  107656. int eofflag;
  107657. long lW;
  107658. long W;
  107659. long nW;
  107660. long centerW;
  107661. ogg_int64_t granulepos;
  107662. ogg_int64_t sequence;
  107663. ogg_int64_t glue_bits;
  107664. ogg_int64_t time_bits;
  107665. ogg_int64_t floor_bits;
  107666. ogg_int64_t res_bits;
  107667. void *backend_state;
  107668. } vorbis_dsp_state;
  107669. typedef struct vorbis_block{
  107670. /* necessary stream state for linking to the framing abstraction */
  107671. float **pcm; /* this is a pointer into local storage */
  107672. oggpack_buffer opb;
  107673. long lW;
  107674. long W;
  107675. long nW;
  107676. int pcmend;
  107677. int mode;
  107678. int eofflag;
  107679. ogg_int64_t granulepos;
  107680. ogg_int64_t sequence;
  107681. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107682. /* local storage to avoid remallocing; it's up to the mapping to
  107683. structure it */
  107684. void *localstore;
  107685. long localtop;
  107686. long localalloc;
  107687. long totaluse;
  107688. struct alloc_chain *reap;
  107689. /* bitmetrics for the frame */
  107690. long glue_bits;
  107691. long time_bits;
  107692. long floor_bits;
  107693. long res_bits;
  107694. void *internal;
  107695. } vorbis_block;
  107696. /* vorbis_block is a single block of data to be processed as part of
  107697. the analysis/synthesis stream; it belongs to a specific logical
  107698. bitstream, but is independant from other vorbis_blocks belonging to
  107699. that logical bitstream. *************************************************/
  107700. struct alloc_chain{
  107701. void *ptr;
  107702. struct alloc_chain *next;
  107703. };
  107704. /* vorbis_info contains all the setup information specific to the
  107705. specific compression/decompression mode in progress (eg,
  107706. psychoacoustic settings, channel setup, options, codebook
  107707. etc). vorbis_info and substructures are in backends.h.
  107708. *********************************************************************/
  107709. /* the comments are not part of vorbis_info so that vorbis_info can be
  107710. static storage */
  107711. typedef struct vorbis_comment{
  107712. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107713. whatever vendor is set to in encode */
  107714. char **user_comments;
  107715. int *comment_lengths;
  107716. int comments;
  107717. char *vendor;
  107718. } vorbis_comment;
  107719. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107720. and produce a packet (see docs/analysis.txt). The packet is then
  107721. coded into a framed OggSquish bitstream by the second layer (see
  107722. docs/framing.txt). Decode is the reverse process; we sync/frame
  107723. the bitstream and extract individual packets, then decode the
  107724. packet back into PCM audio.
  107725. The extra framing/packetizing is used in streaming formats, such as
  107726. files. Over the net (such as with UDP), the framing and
  107727. packetization aren't necessary as they're provided by the transport
  107728. and the streaming layer is not used */
  107729. /* Vorbis PRIMITIVES: general ***************************************/
  107730. extern void vorbis_info_init(vorbis_info *vi);
  107731. extern void vorbis_info_clear(vorbis_info *vi);
  107732. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107733. extern void vorbis_comment_init(vorbis_comment *vc);
  107734. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107735. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107736. const char *tag, char *contents);
  107737. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107738. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107739. extern void vorbis_comment_clear(vorbis_comment *vc);
  107740. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107741. extern int vorbis_block_clear(vorbis_block *vb);
  107742. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107743. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107744. ogg_int64_t granulepos);
  107745. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107746. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107747. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107748. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107749. vorbis_comment *vc,
  107750. ogg_packet *op,
  107751. ogg_packet *op_comm,
  107752. ogg_packet *op_code);
  107753. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107754. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107755. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107756. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107757. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107758. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107759. ogg_packet *op);
  107760. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107761. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107762. ogg_packet *op);
  107763. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107764. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107765. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107766. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107767. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107768. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107769. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107770. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107771. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107772. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107773. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107774. /* Vorbis ERRORS and return codes ***********************************/
  107775. #define OV_FALSE -1
  107776. #define OV_EOF -2
  107777. #define OV_HOLE -3
  107778. #define OV_EREAD -128
  107779. #define OV_EFAULT -129
  107780. #define OV_EIMPL -130
  107781. #define OV_EINVAL -131
  107782. #define OV_ENOTVORBIS -132
  107783. #define OV_EBADHEADER -133
  107784. #define OV_EVERSION -134
  107785. #define OV_ENOTAUDIO -135
  107786. #define OV_EBADPACKET -136
  107787. #define OV_EBADLINK -137
  107788. #define OV_ENOSEEK -138
  107789. #ifdef __cplusplus
  107790. }
  107791. #endif /* __cplusplus */
  107792. #endif
  107793. /*** End of inlined file: codec.h ***/
  107794. extern int vorbis_encode_init(vorbis_info *vi,
  107795. long channels,
  107796. long rate,
  107797. long max_bitrate,
  107798. long nominal_bitrate,
  107799. long min_bitrate);
  107800. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107801. long channels,
  107802. long rate,
  107803. long max_bitrate,
  107804. long nominal_bitrate,
  107805. long min_bitrate);
  107806. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107807. long channels,
  107808. long rate,
  107809. float quality /* quality level from 0. (lo) to 1. (hi) */
  107810. );
  107811. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107812. long channels,
  107813. long rate,
  107814. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107815. );
  107816. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107817. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107818. /* deprecated rate management supported only for compatability */
  107819. #define OV_ECTL_RATEMANAGE_GET 0x10
  107820. #define OV_ECTL_RATEMANAGE_SET 0x11
  107821. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107822. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107823. struct ovectl_ratemanage_arg {
  107824. int management_active;
  107825. long bitrate_hard_min;
  107826. long bitrate_hard_max;
  107827. double bitrate_hard_window;
  107828. long bitrate_av_lo;
  107829. long bitrate_av_hi;
  107830. double bitrate_av_window;
  107831. double bitrate_av_window_center;
  107832. };
  107833. /* new rate setup */
  107834. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107835. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107836. struct ovectl_ratemanage2_arg {
  107837. int management_active;
  107838. long bitrate_limit_min_kbps;
  107839. long bitrate_limit_max_kbps;
  107840. long bitrate_limit_reservoir_bits;
  107841. double bitrate_limit_reservoir_bias;
  107842. long bitrate_average_kbps;
  107843. double bitrate_average_damping;
  107844. };
  107845. #define OV_ECTL_LOWPASS_GET 0x20
  107846. #define OV_ECTL_LOWPASS_SET 0x21
  107847. #define OV_ECTL_IBLOCK_GET 0x30
  107848. #define OV_ECTL_IBLOCK_SET 0x31
  107849. #ifdef __cplusplus
  107850. }
  107851. #endif /* __cplusplus */
  107852. #endif
  107853. /*** End of inlined file: vorbisenc.h ***/
  107854. /*** Start of inlined file: vorbisfile.h ***/
  107855. #ifndef _OV_FILE_H_
  107856. #define _OV_FILE_H_
  107857. #ifdef __cplusplus
  107858. extern "C"
  107859. {
  107860. #endif /* __cplusplus */
  107861. #include <stdio.h>
  107862. /* The function prototypes for the callbacks are basically the same as for
  107863. * the stdio functions fread, fseek, fclose, ftell.
  107864. * The one difference is that the FILE * arguments have been replaced with
  107865. * a void * - this is to be used as a pointer to whatever internal data these
  107866. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107867. *
  107868. * If you use other functions, check the docs for these functions and return
  107869. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107870. * unseekable
  107871. */
  107872. typedef struct {
  107873. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107874. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107875. int (*close_func) (void *datasource);
  107876. long (*tell_func) (void *datasource);
  107877. } ov_callbacks;
  107878. #define NOTOPEN 0
  107879. #define PARTOPEN 1
  107880. #define OPENED 2
  107881. #define STREAMSET 3
  107882. #define INITSET 4
  107883. typedef struct OggVorbis_File {
  107884. void *datasource; /* Pointer to a FILE *, etc. */
  107885. int seekable;
  107886. ogg_int64_t offset;
  107887. ogg_int64_t end;
  107888. ogg_sync_state oy;
  107889. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107890. stream appears */
  107891. int links;
  107892. ogg_int64_t *offsets;
  107893. ogg_int64_t *dataoffsets;
  107894. long *serialnos;
  107895. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107896. compatability; x2 size, stores both
  107897. beginning and end values */
  107898. vorbis_info *vi;
  107899. vorbis_comment *vc;
  107900. /* Decoding working state local storage */
  107901. ogg_int64_t pcm_offset;
  107902. int ready_state;
  107903. long current_serialno;
  107904. int current_link;
  107905. double bittrack;
  107906. double samptrack;
  107907. ogg_stream_state os; /* take physical pages, weld into a logical
  107908. stream of packets */
  107909. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107910. vorbis_block vb; /* local working space for packet->PCM decode */
  107911. ov_callbacks callbacks;
  107912. } OggVorbis_File;
  107913. extern int ov_clear(OggVorbis_File *vf);
  107914. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107915. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107916. char *initial, long ibytes, ov_callbacks callbacks);
  107917. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107918. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107919. char *initial, long ibytes, ov_callbacks callbacks);
  107920. extern int ov_test_open(OggVorbis_File *vf);
  107921. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107922. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107923. extern long ov_streams(OggVorbis_File *vf);
  107924. extern long ov_seekable(OggVorbis_File *vf);
  107925. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107926. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107927. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107928. extern double ov_time_total(OggVorbis_File *vf,int i);
  107929. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107930. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107931. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107932. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107933. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107934. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107935. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107936. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107937. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107938. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107939. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107940. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107941. extern double ov_time_tell(OggVorbis_File *vf);
  107942. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107943. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107944. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107945. int *bitstream);
  107946. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107947. int bigendianp,int word,int sgned,int *bitstream);
  107948. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107949. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107950. extern int ov_halfrate_p(OggVorbis_File *vf);
  107951. #ifdef __cplusplus
  107952. }
  107953. #endif /* __cplusplus */
  107954. #endif
  107955. /*** End of inlined file: vorbisfile.h ***/
  107956. /*** Start of inlined file: bitwise.c ***/
  107957. /* We're 'LSb' endian; if we write a word but read individual bits,
  107958. then we'll read the lsb first */
  107959. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107960. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107961. // tasks..
  107962. #if JUCE_MSVC
  107963. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107964. #endif
  107965. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107966. #if JUCE_USE_OGGVORBIS
  107967. #include <string.h>
  107968. #include <stdlib.h>
  107969. #define BUFFER_INCREMENT 256
  107970. static const unsigned long mask[]=
  107971. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107972. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107973. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107974. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107975. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107976. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107977. 0x3fffffff,0x7fffffff,0xffffffff };
  107978. static const unsigned int mask8B[]=
  107979. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107980. void oggpack_writeinit(oggpack_buffer *b){
  107981. memset(b,0,sizeof(*b));
  107982. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107983. b->buffer[0]='\0';
  107984. b->storage=BUFFER_INCREMENT;
  107985. }
  107986. void oggpackB_writeinit(oggpack_buffer *b){
  107987. oggpack_writeinit(b);
  107988. }
  107989. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107990. long bytes=bits>>3;
  107991. bits-=bytes*8;
  107992. b->ptr=b->buffer+bytes;
  107993. b->endbit=bits;
  107994. b->endbyte=bytes;
  107995. *b->ptr&=mask[bits];
  107996. }
  107997. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107998. long bytes=bits>>3;
  107999. bits-=bytes*8;
  108000. b->ptr=b->buffer+bytes;
  108001. b->endbit=bits;
  108002. b->endbyte=bytes;
  108003. *b->ptr&=mask8B[bits];
  108004. }
  108005. /* Takes only up to 32 bits. */
  108006. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  108007. if(b->endbyte+4>=b->storage){
  108008. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108009. b->storage+=BUFFER_INCREMENT;
  108010. b->ptr=b->buffer+b->endbyte;
  108011. }
  108012. value&=mask[bits];
  108013. bits+=b->endbit;
  108014. b->ptr[0]|=value<<b->endbit;
  108015. if(bits>=8){
  108016. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  108017. if(bits>=16){
  108018. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  108019. if(bits>=24){
  108020. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  108021. if(bits>=32){
  108022. if(b->endbit)
  108023. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  108024. else
  108025. b->ptr[4]=0;
  108026. }
  108027. }
  108028. }
  108029. }
  108030. b->endbyte+=bits/8;
  108031. b->ptr+=bits/8;
  108032. b->endbit=bits&7;
  108033. }
  108034. /* Takes only up to 32 bits. */
  108035. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  108036. if(b->endbyte+4>=b->storage){
  108037. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108038. b->storage+=BUFFER_INCREMENT;
  108039. b->ptr=b->buffer+b->endbyte;
  108040. }
  108041. value=(value&mask[bits])<<(32-bits);
  108042. bits+=b->endbit;
  108043. b->ptr[0]|=value>>(24+b->endbit);
  108044. if(bits>=8){
  108045. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  108046. if(bits>=16){
  108047. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  108048. if(bits>=24){
  108049. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  108050. if(bits>=32){
  108051. if(b->endbit)
  108052. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  108053. else
  108054. b->ptr[4]=0;
  108055. }
  108056. }
  108057. }
  108058. }
  108059. b->endbyte+=bits/8;
  108060. b->ptr+=bits/8;
  108061. b->endbit=bits&7;
  108062. }
  108063. void oggpack_writealign(oggpack_buffer *b){
  108064. int bits=8-b->endbit;
  108065. if(bits<8)
  108066. oggpack_write(b,0,bits);
  108067. }
  108068. void oggpackB_writealign(oggpack_buffer *b){
  108069. int bits=8-b->endbit;
  108070. if(bits<8)
  108071. oggpackB_write(b,0,bits);
  108072. }
  108073. static void oggpack_writecopy_helper(oggpack_buffer *b,
  108074. void *source,
  108075. long bits,
  108076. void (*w)(oggpack_buffer *,
  108077. unsigned long,
  108078. int),
  108079. int msb){
  108080. unsigned char *ptr=(unsigned char *)source;
  108081. long bytes=bits/8;
  108082. bits-=bytes*8;
  108083. if(b->endbit){
  108084. int i;
  108085. /* unaligned copy. Do it the hard way. */
  108086. for(i=0;i<bytes;i++)
  108087. w(b,(unsigned long)(ptr[i]),8);
  108088. }else{
  108089. /* aligned block copy */
  108090. if(b->endbyte+bytes+1>=b->storage){
  108091. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  108092. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  108093. b->ptr=b->buffer+b->endbyte;
  108094. }
  108095. memmove(b->ptr,source,bytes);
  108096. b->ptr+=bytes;
  108097. b->endbyte+=bytes;
  108098. *b->ptr=0;
  108099. }
  108100. if(bits){
  108101. if(msb)
  108102. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  108103. else
  108104. w(b,(unsigned long)(ptr[bytes]),bits);
  108105. }
  108106. }
  108107. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  108108. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  108109. }
  108110. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  108111. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  108112. }
  108113. void oggpack_reset(oggpack_buffer *b){
  108114. b->ptr=b->buffer;
  108115. b->buffer[0]=0;
  108116. b->endbit=b->endbyte=0;
  108117. }
  108118. void oggpackB_reset(oggpack_buffer *b){
  108119. oggpack_reset(b);
  108120. }
  108121. void oggpack_writeclear(oggpack_buffer *b){
  108122. _ogg_free(b->buffer);
  108123. memset(b,0,sizeof(*b));
  108124. }
  108125. void oggpackB_writeclear(oggpack_buffer *b){
  108126. oggpack_writeclear(b);
  108127. }
  108128. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108129. memset(b,0,sizeof(*b));
  108130. b->buffer=b->ptr=buf;
  108131. b->storage=bytes;
  108132. }
  108133. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108134. oggpack_readinit(b,buf,bytes);
  108135. }
  108136. /* Read in bits without advancing the bitptr; bits <= 32 */
  108137. long oggpack_look(oggpack_buffer *b,int bits){
  108138. unsigned long ret;
  108139. unsigned long m=mask[bits];
  108140. bits+=b->endbit;
  108141. if(b->endbyte+4>=b->storage){
  108142. /* not the main path */
  108143. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108144. }
  108145. ret=b->ptr[0]>>b->endbit;
  108146. if(bits>8){
  108147. ret|=b->ptr[1]<<(8-b->endbit);
  108148. if(bits>16){
  108149. ret|=b->ptr[2]<<(16-b->endbit);
  108150. if(bits>24){
  108151. ret|=b->ptr[3]<<(24-b->endbit);
  108152. if(bits>32 && b->endbit)
  108153. ret|=b->ptr[4]<<(32-b->endbit);
  108154. }
  108155. }
  108156. }
  108157. return(m&ret);
  108158. }
  108159. /* Read in bits without advancing the bitptr; bits <= 32 */
  108160. long oggpackB_look(oggpack_buffer *b,int bits){
  108161. unsigned long ret;
  108162. int m=32-bits;
  108163. bits+=b->endbit;
  108164. if(b->endbyte+4>=b->storage){
  108165. /* not the main path */
  108166. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108167. }
  108168. ret=b->ptr[0]<<(24+b->endbit);
  108169. if(bits>8){
  108170. ret|=b->ptr[1]<<(16+b->endbit);
  108171. if(bits>16){
  108172. ret|=b->ptr[2]<<(8+b->endbit);
  108173. if(bits>24){
  108174. ret|=b->ptr[3]<<(b->endbit);
  108175. if(bits>32 && b->endbit)
  108176. ret|=b->ptr[4]>>(8-b->endbit);
  108177. }
  108178. }
  108179. }
  108180. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108181. }
  108182. long oggpack_look1(oggpack_buffer *b){
  108183. if(b->endbyte>=b->storage)return(-1);
  108184. return((b->ptr[0]>>b->endbit)&1);
  108185. }
  108186. long oggpackB_look1(oggpack_buffer *b){
  108187. if(b->endbyte>=b->storage)return(-1);
  108188. return((b->ptr[0]>>(7-b->endbit))&1);
  108189. }
  108190. void oggpack_adv(oggpack_buffer *b,int bits){
  108191. bits+=b->endbit;
  108192. b->ptr+=bits/8;
  108193. b->endbyte+=bits/8;
  108194. b->endbit=bits&7;
  108195. }
  108196. void oggpackB_adv(oggpack_buffer *b,int bits){
  108197. oggpack_adv(b,bits);
  108198. }
  108199. void oggpack_adv1(oggpack_buffer *b){
  108200. if(++(b->endbit)>7){
  108201. b->endbit=0;
  108202. b->ptr++;
  108203. b->endbyte++;
  108204. }
  108205. }
  108206. void oggpackB_adv1(oggpack_buffer *b){
  108207. oggpack_adv1(b);
  108208. }
  108209. /* bits <= 32 */
  108210. long oggpack_read(oggpack_buffer *b,int bits){
  108211. long ret;
  108212. unsigned long m=mask[bits];
  108213. bits+=b->endbit;
  108214. if(b->endbyte+4>=b->storage){
  108215. /* not the main path */
  108216. ret=-1L;
  108217. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108218. }
  108219. ret=b->ptr[0]>>b->endbit;
  108220. if(bits>8){
  108221. ret|=b->ptr[1]<<(8-b->endbit);
  108222. if(bits>16){
  108223. ret|=b->ptr[2]<<(16-b->endbit);
  108224. if(bits>24){
  108225. ret|=b->ptr[3]<<(24-b->endbit);
  108226. if(bits>32 && b->endbit){
  108227. ret|=b->ptr[4]<<(32-b->endbit);
  108228. }
  108229. }
  108230. }
  108231. }
  108232. ret&=m;
  108233. overflow:
  108234. b->ptr+=bits/8;
  108235. b->endbyte+=bits/8;
  108236. b->endbit=bits&7;
  108237. return(ret);
  108238. }
  108239. /* bits <= 32 */
  108240. long oggpackB_read(oggpack_buffer *b,int bits){
  108241. long ret;
  108242. long m=32-bits;
  108243. bits+=b->endbit;
  108244. if(b->endbyte+4>=b->storage){
  108245. /* not the main path */
  108246. ret=-1L;
  108247. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108248. }
  108249. ret=b->ptr[0]<<(24+b->endbit);
  108250. if(bits>8){
  108251. ret|=b->ptr[1]<<(16+b->endbit);
  108252. if(bits>16){
  108253. ret|=b->ptr[2]<<(8+b->endbit);
  108254. if(bits>24){
  108255. ret|=b->ptr[3]<<(b->endbit);
  108256. if(bits>32 && b->endbit)
  108257. ret|=b->ptr[4]>>(8-b->endbit);
  108258. }
  108259. }
  108260. }
  108261. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108262. overflow:
  108263. b->ptr+=bits/8;
  108264. b->endbyte+=bits/8;
  108265. b->endbit=bits&7;
  108266. return(ret);
  108267. }
  108268. long oggpack_read1(oggpack_buffer *b){
  108269. long ret;
  108270. if(b->endbyte>=b->storage){
  108271. /* not the main path */
  108272. ret=-1L;
  108273. goto overflow;
  108274. }
  108275. ret=(b->ptr[0]>>b->endbit)&1;
  108276. overflow:
  108277. b->endbit++;
  108278. if(b->endbit>7){
  108279. b->endbit=0;
  108280. b->ptr++;
  108281. b->endbyte++;
  108282. }
  108283. return(ret);
  108284. }
  108285. long oggpackB_read1(oggpack_buffer *b){
  108286. long ret;
  108287. if(b->endbyte>=b->storage){
  108288. /* not the main path */
  108289. ret=-1L;
  108290. goto overflow;
  108291. }
  108292. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108293. overflow:
  108294. b->endbit++;
  108295. if(b->endbit>7){
  108296. b->endbit=0;
  108297. b->ptr++;
  108298. b->endbyte++;
  108299. }
  108300. return(ret);
  108301. }
  108302. long oggpack_bytes(oggpack_buffer *b){
  108303. return(b->endbyte+(b->endbit+7)/8);
  108304. }
  108305. long oggpack_bits(oggpack_buffer *b){
  108306. return(b->endbyte*8+b->endbit);
  108307. }
  108308. long oggpackB_bytes(oggpack_buffer *b){
  108309. return oggpack_bytes(b);
  108310. }
  108311. long oggpackB_bits(oggpack_buffer *b){
  108312. return oggpack_bits(b);
  108313. }
  108314. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108315. return(b->buffer);
  108316. }
  108317. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108318. return oggpack_get_buffer(b);
  108319. }
  108320. /* Self test of the bitwise routines; everything else is based on
  108321. them, so they damned well better be solid. */
  108322. #ifdef _V_SELFTEST
  108323. #include <stdio.h>
  108324. static int ilog(unsigned int v){
  108325. int ret=0;
  108326. while(v){
  108327. ret++;
  108328. v>>=1;
  108329. }
  108330. return(ret);
  108331. }
  108332. oggpack_buffer o;
  108333. oggpack_buffer r;
  108334. void report(char *in){
  108335. fprintf(stderr,"%s",in);
  108336. exit(1);
  108337. }
  108338. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108339. long bytes,i;
  108340. unsigned char *buffer;
  108341. oggpack_reset(&o);
  108342. for(i=0;i<vals;i++)
  108343. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108344. buffer=oggpack_get_buffer(&o);
  108345. bytes=oggpack_bytes(&o);
  108346. if(bytes!=compsize)report("wrong number of bytes!\n");
  108347. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108348. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108349. report("wrote incorrect value!\n");
  108350. }
  108351. oggpack_readinit(&r,buffer,bytes);
  108352. for(i=0;i<vals;i++){
  108353. int tbit=bits?bits:ilog(b[i]);
  108354. if(oggpack_look(&r,tbit)==-1)
  108355. report("out of data!\n");
  108356. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108357. report("looked at incorrect value!\n");
  108358. if(tbit==1)
  108359. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108360. report("looked at single bit incorrect value!\n");
  108361. if(tbit==1){
  108362. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108363. report("read incorrect single bit value!\n");
  108364. }else{
  108365. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108366. report("read incorrect value!\n");
  108367. }
  108368. }
  108369. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108370. }
  108371. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108372. long bytes,i;
  108373. unsigned char *buffer;
  108374. oggpackB_reset(&o);
  108375. for(i=0;i<vals;i++)
  108376. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108377. buffer=oggpackB_get_buffer(&o);
  108378. bytes=oggpackB_bytes(&o);
  108379. if(bytes!=compsize)report("wrong number of bytes!\n");
  108380. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108381. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108382. report("wrote incorrect value!\n");
  108383. }
  108384. oggpackB_readinit(&r,buffer,bytes);
  108385. for(i=0;i<vals;i++){
  108386. int tbit=bits?bits:ilog(b[i]);
  108387. if(oggpackB_look(&r,tbit)==-1)
  108388. report("out of data!\n");
  108389. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108390. report("looked at incorrect value!\n");
  108391. if(tbit==1)
  108392. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108393. report("looked at single bit incorrect value!\n");
  108394. if(tbit==1){
  108395. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108396. report("read incorrect single bit value!\n");
  108397. }else{
  108398. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108399. report("read incorrect value!\n");
  108400. }
  108401. }
  108402. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108403. }
  108404. int main(void){
  108405. unsigned char *buffer;
  108406. long bytes,i;
  108407. static unsigned long testbuffer1[]=
  108408. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108409. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108410. int test1size=43;
  108411. static unsigned long testbuffer2[]=
  108412. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108413. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108414. 85525151,0,12321,1,349528352};
  108415. int test2size=21;
  108416. static unsigned long testbuffer3[]=
  108417. {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,
  108418. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108419. int test3size=56;
  108420. static unsigned long large[]=
  108421. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108422. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108423. 85525151,0,12321,1,2146528352};
  108424. int onesize=33;
  108425. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108426. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108427. 223,4};
  108428. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108429. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108430. 245,251,128};
  108431. int twosize=6;
  108432. static int two[6]={61,255,255,251,231,29};
  108433. static int twoB[6]={247,63,255,253,249,120};
  108434. int threesize=54;
  108435. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108436. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108437. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108438. 100,52,4,14,18,86,77,1};
  108439. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108440. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108441. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108442. 200,20,254,4,58,106,176,144,0};
  108443. int foursize=38;
  108444. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108445. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108446. 28,2,133,0,1};
  108447. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108448. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108449. 129,10,4,32};
  108450. int fivesize=45;
  108451. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108452. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108453. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108454. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108455. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108456. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108457. int sixsize=7;
  108458. static int six[7]={17,177,170,242,169,19,148};
  108459. static int sixB[7]={136,141,85,79,149,200,41};
  108460. /* Test read/write together */
  108461. /* Later we test against pregenerated bitstreams */
  108462. oggpack_writeinit(&o);
  108463. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108464. cliptest(testbuffer1,test1size,0,one,onesize);
  108465. fprintf(stderr,"ok.");
  108466. fprintf(stderr,"\nNull bit call (LSb): ");
  108467. cliptest(testbuffer3,test3size,0,two,twosize);
  108468. fprintf(stderr,"ok.");
  108469. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108470. cliptest(testbuffer2,test2size,0,three,threesize);
  108471. fprintf(stderr,"ok.");
  108472. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108473. oggpack_reset(&o);
  108474. for(i=0;i<test2size;i++)
  108475. oggpack_write(&o,large[i],32);
  108476. buffer=oggpack_get_buffer(&o);
  108477. bytes=oggpack_bytes(&o);
  108478. oggpack_readinit(&r,buffer,bytes);
  108479. for(i=0;i<test2size;i++){
  108480. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108481. if(oggpack_look(&r,32)!=large[i]){
  108482. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108483. oggpack_look(&r,32),large[i]);
  108484. report("read incorrect value!\n");
  108485. }
  108486. oggpack_adv(&r,32);
  108487. }
  108488. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108489. fprintf(stderr,"ok.");
  108490. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108491. cliptest(testbuffer1,test1size,7,four,foursize);
  108492. fprintf(stderr,"ok.");
  108493. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108494. cliptest(testbuffer2,test2size,17,five,fivesize);
  108495. fprintf(stderr,"ok.");
  108496. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108497. cliptest(testbuffer3,test3size,1,six,sixsize);
  108498. fprintf(stderr,"ok.");
  108499. fprintf(stderr,"\nTesting read past end (LSb): ");
  108500. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108501. for(i=0;i<64;i++){
  108502. if(oggpack_read(&r,1)!=0){
  108503. fprintf(stderr,"failed; got -1 prematurely.\n");
  108504. exit(1);
  108505. }
  108506. }
  108507. if(oggpack_look(&r,1)!=-1 ||
  108508. oggpack_read(&r,1)!=-1){
  108509. fprintf(stderr,"failed; read past end without -1.\n");
  108510. exit(1);
  108511. }
  108512. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108513. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108514. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108515. exit(1);
  108516. }
  108517. if(oggpack_look(&r,18)!=0 ||
  108518. oggpack_look(&r,18)!=0){
  108519. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108520. exit(1);
  108521. }
  108522. if(oggpack_look(&r,19)!=-1 ||
  108523. oggpack_look(&r,19)!=-1){
  108524. fprintf(stderr,"failed; read past end without -1.\n");
  108525. exit(1);
  108526. }
  108527. if(oggpack_look(&r,32)!=-1 ||
  108528. oggpack_look(&r,32)!=-1){
  108529. fprintf(stderr,"failed; read past end without -1.\n");
  108530. exit(1);
  108531. }
  108532. oggpack_writeclear(&o);
  108533. fprintf(stderr,"ok.\n");
  108534. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108535. /* Test read/write together */
  108536. /* Later we test against pregenerated bitstreams */
  108537. oggpackB_writeinit(&o);
  108538. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108539. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108540. fprintf(stderr,"ok.");
  108541. fprintf(stderr,"\nNull bit call (MSb): ");
  108542. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108543. fprintf(stderr,"ok.");
  108544. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108545. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108546. fprintf(stderr,"ok.");
  108547. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108548. oggpackB_reset(&o);
  108549. for(i=0;i<test2size;i++)
  108550. oggpackB_write(&o,large[i],32);
  108551. buffer=oggpackB_get_buffer(&o);
  108552. bytes=oggpackB_bytes(&o);
  108553. oggpackB_readinit(&r,buffer,bytes);
  108554. for(i=0;i<test2size;i++){
  108555. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108556. if(oggpackB_look(&r,32)!=large[i]){
  108557. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108558. oggpackB_look(&r,32),large[i]);
  108559. report("read incorrect value!\n");
  108560. }
  108561. oggpackB_adv(&r,32);
  108562. }
  108563. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108564. fprintf(stderr,"ok.");
  108565. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108566. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108567. fprintf(stderr,"ok.");
  108568. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108569. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108570. fprintf(stderr,"ok.");
  108571. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108572. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108573. fprintf(stderr,"ok.");
  108574. fprintf(stderr,"\nTesting read past end (MSb): ");
  108575. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108576. for(i=0;i<64;i++){
  108577. if(oggpackB_read(&r,1)!=0){
  108578. fprintf(stderr,"failed; got -1 prematurely.\n");
  108579. exit(1);
  108580. }
  108581. }
  108582. if(oggpackB_look(&r,1)!=-1 ||
  108583. oggpackB_read(&r,1)!=-1){
  108584. fprintf(stderr,"failed; read past end without -1.\n");
  108585. exit(1);
  108586. }
  108587. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108588. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108589. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108590. exit(1);
  108591. }
  108592. if(oggpackB_look(&r,18)!=0 ||
  108593. oggpackB_look(&r,18)!=0){
  108594. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108595. exit(1);
  108596. }
  108597. if(oggpackB_look(&r,19)!=-1 ||
  108598. oggpackB_look(&r,19)!=-1){
  108599. fprintf(stderr,"failed; read past end without -1.\n");
  108600. exit(1);
  108601. }
  108602. if(oggpackB_look(&r,32)!=-1 ||
  108603. oggpackB_look(&r,32)!=-1){
  108604. fprintf(stderr,"failed; read past end without -1.\n");
  108605. exit(1);
  108606. }
  108607. oggpackB_writeclear(&o);
  108608. fprintf(stderr,"ok.\n\n");
  108609. return(0);
  108610. }
  108611. #endif /* _V_SELFTEST */
  108612. #undef BUFFER_INCREMENT
  108613. #endif
  108614. /*** End of inlined file: bitwise.c ***/
  108615. /*** Start of inlined file: framing.c ***/
  108616. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108617. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108618. // tasks..
  108619. #if JUCE_MSVC
  108620. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108621. #endif
  108622. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108623. #if JUCE_USE_OGGVORBIS
  108624. #include <stdlib.h>
  108625. #include <string.h>
  108626. /* A complete description of Ogg framing exists in docs/framing.html */
  108627. int ogg_page_version(ogg_page *og){
  108628. return((int)(og->header[4]));
  108629. }
  108630. int ogg_page_continued(ogg_page *og){
  108631. return((int)(og->header[5]&0x01));
  108632. }
  108633. int ogg_page_bos(ogg_page *og){
  108634. return((int)(og->header[5]&0x02));
  108635. }
  108636. int ogg_page_eos(ogg_page *og){
  108637. return((int)(og->header[5]&0x04));
  108638. }
  108639. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108640. unsigned char *page=og->header;
  108641. ogg_int64_t granulepos=page[13]&(0xff);
  108642. granulepos= (granulepos<<8)|(page[12]&0xff);
  108643. granulepos= (granulepos<<8)|(page[11]&0xff);
  108644. granulepos= (granulepos<<8)|(page[10]&0xff);
  108645. granulepos= (granulepos<<8)|(page[9]&0xff);
  108646. granulepos= (granulepos<<8)|(page[8]&0xff);
  108647. granulepos= (granulepos<<8)|(page[7]&0xff);
  108648. granulepos= (granulepos<<8)|(page[6]&0xff);
  108649. return(granulepos);
  108650. }
  108651. int ogg_page_serialno(ogg_page *og){
  108652. return(og->header[14] |
  108653. (og->header[15]<<8) |
  108654. (og->header[16]<<16) |
  108655. (og->header[17]<<24));
  108656. }
  108657. long ogg_page_pageno(ogg_page *og){
  108658. return(og->header[18] |
  108659. (og->header[19]<<8) |
  108660. (og->header[20]<<16) |
  108661. (og->header[21]<<24));
  108662. }
  108663. /* returns the number of packets that are completed on this page (if
  108664. the leading packet is begun on a previous page, but ends on this
  108665. page, it's counted */
  108666. /* NOTE:
  108667. If a page consists of a packet begun on a previous page, and a new
  108668. packet begun (but not completed) on this page, the return will be:
  108669. ogg_page_packets(page) ==1,
  108670. ogg_page_continued(page) !=0
  108671. If a page happens to be a single packet that was begun on a
  108672. previous page, and spans to the next page (in the case of a three or
  108673. more page packet), the return will be:
  108674. ogg_page_packets(page) ==0,
  108675. ogg_page_continued(page) !=0
  108676. */
  108677. int ogg_page_packets(ogg_page *og){
  108678. int i,n=og->header[26],count=0;
  108679. for(i=0;i<n;i++)
  108680. if(og->header[27+i]<255)count++;
  108681. return(count);
  108682. }
  108683. #if 0
  108684. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108685. use the static init below) */
  108686. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108687. int i;
  108688. unsigned long r;
  108689. r = index << 24;
  108690. for (i=0; i<8; i++)
  108691. if (r & 0x80000000UL)
  108692. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108693. polynomial, although we use an
  108694. unreflected alg and an init/final
  108695. of 0, not 0xffffffff */
  108696. else
  108697. r<<=1;
  108698. return (r & 0xffffffffUL);
  108699. }
  108700. #endif
  108701. static const ogg_uint32_t crc_lookup[256]={
  108702. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108703. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108704. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108705. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108706. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108707. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108708. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108709. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108710. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108711. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108712. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108713. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108714. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108715. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108716. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108717. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108718. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108719. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108720. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108721. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108722. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108723. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108724. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108725. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108726. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108727. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108728. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108729. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108730. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108731. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108732. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108733. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108734. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108735. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108736. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108737. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108738. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108739. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108740. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108741. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108742. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108743. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108744. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108745. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108746. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108747. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108748. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108749. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108750. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108751. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108752. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108753. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108754. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108755. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108756. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108757. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108758. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108759. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108760. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108761. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108762. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108763. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108764. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108765. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108766. /* init the encode/decode logical stream state */
  108767. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108768. if(os){
  108769. memset(os,0,sizeof(*os));
  108770. os->body_storage=16*1024;
  108771. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108772. os->lacing_storage=1024;
  108773. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108774. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108775. os->serialno=serialno;
  108776. return(0);
  108777. }
  108778. return(-1);
  108779. }
  108780. /* _clear does not free os, only the non-flat storage within */
  108781. int ogg_stream_clear(ogg_stream_state *os){
  108782. if(os){
  108783. if(os->body_data)_ogg_free(os->body_data);
  108784. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108785. if(os->granule_vals)_ogg_free(os->granule_vals);
  108786. memset(os,0,sizeof(*os));
  108787. }
  108788. return(0);
  108789. }
  108790. int ogg_stream_destroy(ogg_stream_state *os){
  108791. if(os){
  108792. ogg_stream_clear(os);
  108793. _ogg_free(os);
  108794. }
  108795. return(0);
  108796. }
  108797. /* Helpers for ogg_stream_encode; this keeps the structure and
  108798. what's happening fairly clear */
  108799. static void _os_body_expand(ogg_stream_state *os,int needed){
  108800. if(os->body_storage<=os->body_fill+needed){
  108801. os->body_storage+=(needed+1024);
  108802. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108803. }
  108804. }
  108805. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108806. if(os->lacing_storage<=os->lacing_fill+needed){
  108807. os->lacing_storage+=(needed+32);
  108808. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108809. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108810. }
  108811. }
  108812. /* checksum the page */
  108813. /* Direct table CRC; note that this will be faster in the future if we
  108814. perform the checksum silmultaneously with other copies */
  108815. void ogg_page_checksum_set(ogg_page *og){
  108816. if(og){
  108817. ogg_uint32_t crc_reg=0;
  108818. int i;
  108819. /* safety; needed for API behavior, but not framing code */
  108820. og->header[22]=0;
  108821. og->header[23]=0;
  108822. og->header[24]=0;
  108823. og->header[25]=0;
  108824. for(i=0;i<og->header_len;i++)
  108825. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108826. for(i=0;i<og->body_len;i++)
  108827. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108828. og->header[22]=(unsigned char)(crc_reg&0xff);
  108829. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108830. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108831. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108832. }
  108833. }
  108834. /* submit data to the internal buffer of the framing engine */
  108835. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108836. int lacing_vals=op->bytes/255+1,i;
  108837. if(os->body_returned){
  108838. /* advance packet data according to the body_returned pointer. We
  108839. had to keep it around to return a pointer into the buffer last
  108840. call */
  108841. os->body_fill-=os->body_returned;
  108842. if(os->body_fill)
  108843. memmove(os->body_data,os->body_data+os->body_returned,
  108844. os->body_fill);
  108845. os->body_returned=0;
  108846. }
  108847. /* make sure we have the buffer storage */
  108848. _os_body_expand(os,op->bytes);
  108849. _os_lacing_expand(os,lacing_vals);
  108850. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108851. the liability of overly clean abstraction for the time being. It
  108852. will actually be fairly easy to eliminate the extra copy in the
  108853. future */
  108854. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108855. os->body_fill+=op->bytes;
  108856. /* Store lacing vals for this packet */
  108857. for(i=0;i<lacing_vals-1;i++){
  108858. os->lacing_vals[os->lacing_fill+i]=255;
  108859. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108860. }
  108861. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108862. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108863. /* flag the first segment as the beginning of the packet */
  108864. os->lacing_vals[os->lacing_fill]|= 0x100;
  108865. os->lacing_fill+=lacing_vals;
  108866. /* for the sake of completeness */
  108867. os->packetno++;
  108868. if(op->e_o_s)os->e_o_s=1;
  108869. return(0);
  108870. }
  108871. /* This will flush remaining packets into a page (returning nonzero),
  108872. even if there is not enough data to trigger a flush normally
  108873. (undersized page). If there are no packets or partial packets to
  108874. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108875. try to flush a normal sized page like ogg_stream_pageout; a call to
  108876. ogg_stream_flush does not guarantee that all packets have flushed.
  108877. Only a return value of 0 from ogg_stream_flush indicates all packet
  108878. data is flushed into pages.
  108879. since ogg_stream_flush will flush the last page in a stream even if
  108880. it's undersized, you almost certainly want to use ogg_stream_pageout
  108881. (and *not* ogg_stream_flush) unless you specifically need to flush
  108882. an page regardless of size in the middle of a stream. */
  108883. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108884. int i;
  108885. int vals=0;
  108886. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108887. int bytes=0;
  108888. long acc=0;
  108889. ogg_int64_t granule_pos=-1;
  108890. if(maxvals==0)return(0);
  108891. /* construct a page */
  108892. /* decide how many segments to include */
  108893. /* If this is the initial header case, the first page must only include
  108894. the initial header packet */
  108895. if(os->b_o_s==0){ /* 'initial header page' case */
  108896. granule_pos=0;
  108897. for(vals=0;vals<maxvals;vals++){
  108898. if((os->lacing_vals[vals]&0x0ff)<255){
  108899. vals++;
  108900. break;
  108901. }
  108902. }
  108903. }else{
  108904. for(vals=0;vals<maxvals;vals++){
  108905. if(acc>4096)break;
  108906. acc+=os->lacing_vals[vals]&0x0ff;
  108907. if((os->lacing_vals[vals]&0xff)<255)
  108908. granule_pos=os->granule_vals[vals];
  108909. }
  108910. }
  108911. /* construct the header in temp storage */
  108912. memcpy(os->header,"OggS",4);
  108913. /* stream structure version */
  108914. os->header[4]=0x00;
  108915. /* continued packet flag? */
  108916. os->header[5]=0x00;
  108917. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108918. /* first page flag? */
  108919. if(os->b_o_s==0)os->header[5]|=0x02;
  108920. /* last page flag? */
  108921. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108922. os->b_o_s=1;
  108923. /* 64 bits of PCM position */
  108924. for(i=6;i<14;i++){
  108925. os->header[i]=(unsigned char)(granule_pos&0xff);
  108926. granule_pos>>=8;
  108927. }
  108928. /* 32 bits of stream serial number */
  108929. {
  108930. long serialno=os->serialno;
  108931. for(i=14;i<18;i++){
  108932. os->header[i]=(unsigned char)(serialno&0xff);
  108933. serialno>>=8;
  108934. }
  108935. }
  108936. /* 32 bits of page counter (we have both counter and page header
  108937. because this val can roll over) */
  108938. if(os->pageno==-1)os->pageno=0; /* because someone called
  108939. stream_reset; this would be a
  108940. strange thing to do in an
  108941. encode stream, but it has
  108942. plausible uses */
  108943. {
  108944. long pageno=os->pageno++;
  108945. for(i=18;i<22;i++){
  108946. os->header[i]=(unsigned char)(pageno&0xff);
  108947. pageno>>=8;
  108948. }
  108949. }
  108950. /* zero for computation; filled in later */
  108951. os->header[22]=0;
  108952. os->header[23]=0;
  108953. os->header[24]=0;
  108954. os->header[25]=0;
  108955. /* segment table */
  108956. os->header[26]=(unsigned char)(vals&0xff);
  108957. for(i=0;i<vals;i++)
  108958. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108959. /* set pointers in the ogg_page struct */
  108960. og->header=os->header;
  108961. og->header_len=os->header_fill=vals+27;
  108962. og->body=os->body_data+os->body_returned;
  108963. og->body_len=bytes;
  108964. /* advance the lacing data and set the body_returned pointer */
  108965. os->lacing_fill-=vals;
  108966. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108967. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108968. os->body_returned+=bytes;
  108969. /* calculate the checksum */
  108970. ogg_page_checksum_set(og);
  108971. /* done */
  108972. return(1);
  108973. }
  108974. /* This constructs pages from buffered packet segments. The pointers
  108975. returned are to static buffers; do not free. The returned buffers are
  108976. good only until the next call (using the same ogg_stream_state) */
  108977. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108978. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108979. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108980. os->lacing_fill>=255 || /* 'segment table full' case */
  108981. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108982. return(ogg_stream_flush(os,og));
  108983. }
  108984. /* not enough data to construct a page and not end of stream */
  108985. return(0);
  108986. }
  108987. int ogg_stream_eos(ogg_stream_state *os){
  108988. return os->e_o_s;
  108989. }
  108990. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108991. /* This has two layers to place more of the multi-serialno and paging
  108992. control in the application's hands. First, we expose a data buffer
  108993. using ogg_sync_buffer(). The app either copies into the
  108994. buffer, or passes it directly to read(), etc. We then call
  108995. ogg_sync_wrote() to tell how many bytes we just added.
  108996. Pages are returned (pointers into the buffer in ogg_sync_state)
  108997. by ogg_sync_pageout(). The page is then submitted to
  108998. ogg_stream_pagein() along with the appropriate
  108999. ogg_stream_state* (ie, matching serialno). We then get raw
  109000. packets out calling ogg_stream_packetout() with a
  109001. ogg_stream_state. */
  109002. /* initialize the struct to a known state */
  109003. int ogg_sync_init(ogg_sync_state *oy){
  109004. if(oy){
  109005. memset(oy,0,sizeof(*oy));
  109006. }
  109007. return(0);
  109008. }
  109009. /* clear non-flat storage within */
  109010. int ogg_sync_clear(ogg_sync_state *oy){
  109011. if(oy){
  109012. if(oy->data)_ogg_free(oy->data);
  109013. ogg_sync_init(oy);
  109014. }
  109015. return(0);
  109016. }
  109017. int ogg_sync_destroy(ogg_sync_state *oy){
  109018. if(oy){
  109019. ogg_sync_clear(oy);
  109020. _ogg_free(oy);
  109021. }
  109022. return(0);
  109023. }
  109024. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  109025. /* first, clear out any space that has been previously returned */
  109026. if(oy->returned){
  109027. oy->fill-=oy->returned;
  109028. if(oy->fill>0)
  109029. memmove(oy->data,oy->data+oy->returned,oy->fill);
  109030. oy->returned=0;
  109031. }
  109032. if(size>oy->storage-oy->fill){
  109033. /* We need to extend the internal buffer */
  109034. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  109035. if(oy->data)
  109036. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  109037. else
  109038. oy->data=(unsigned char*) _ogg_malloc(newsize);
  109039. oy->storage=newsize;
  109040. }
  109041. /* expose a segment at least as large as requested at the fill mark */
  109042. return((char *)oy->data+oy->fill);
  109043. }
  109044. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  109045. if(oy->fill+bytes>oy->storage)return(-1);
  109046. oy->fill+=bytes;
  109047. return(0);
  109048. }
  109049. /* sync the stream. This is meant to be useful for finding page
  109050. boundaries.
  109051. return values for this:
  109052. -n) skipped n bytes
  109053. 0) page not ready; more data (no bytes skipped)
  109054. n) page synced at current location; page length n bytes
  109055. */
  109056. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  109057. unsigned char *page=oy->data+oy->returned;
  109058. unsigned char *next;
  109059. long bytes=oy->fill-oy->returned;
  109060. if(oy->headerbytes==0){
  109061. int headerbytes,i;
  109062. if(bytes<27)return(0); /* not enough for a header */
  109063. /* verify capture pattern */
  109064. if(memcmp(page,"OggS",4))goto sync_fail;
  109065. headerbytes=page[26]+27;
  109066. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  109067. /* count up body length in the segment table */
  109068. for(i=0;i<page[26];i++)
  109069. oy->bodybytes+=page[27+i];
  109070. oy->headerbytes=headerbytes;
  109071. }
  109072. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  109073. /* The whole test page is buffered. Verify the checksum */
  109074. {
  109075. /* Grab the checksum bytes, set the header field to zero */
  109076. char chksum[4];
  109077. ogg_page log;
  109078. memcpy(chksum,page+22,4);
  109079. memset(page+22,0,4);
  109080. /* set up a temp page struct and recompute the checksum */
  109081. log.header=page;
  109082. log.header_len=oy->headerbytes;
  109083. log.body=page+oy->headerbytes;
  109084. log.body_len=oy->bodybytes;
  109085. ogg_page_checksum_set(&log);
  109086. /* Compare */
  109087. if(memcmp(chksum,page+22,4)){
  109088. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  109089. at all) */
  109090. /* replace the computed checksum with the one actually read in */
  109091. memcpy(page+22,chksum,4);
  109092. /* Bad checksum. Lose sync */
  109093. goto sync_fail;
  109094. }
  109095. }
  109096. /* yes, have a whole page all ready to go */
  109097. {
  109098. unsigned char *page=oy->data+oy->returned;
  109099. long bytes;
  109100. if(og){
  109101. og->header=page;
  109102. og->header_len=oy->headerbytes;
  109103. og->body=page+oy->headerbytes;
  109104. og->body_len=oy->bodybytes;
  109105. }
  109106. oy->unsynced=0;
  109107. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  109108. oy->headerbytes=0;
  109109. oy->bodybytes=0;
  109110. return(bytes);
  109111. }
  109112. sync_fail:
  109113. oy->headerbytes=0;
  109114. oy->bodybytes=0;
  109115. /* search for possible capture */
  109116. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  109117. if(!next)
  109118. next=oy->data+oy->fill;
  109119. oy->returned=next-oy->data;
  109120. return(-(next-page));
  109121. }
  109122. /* sync the stream and get a page. Keep trying until we find a page.
  109123. Supress 'sync errors' after reporting the first.
  109124. return values:
  109125. -1) recapture (hole in data)
  109126. 0) need more data
  109127. 1) page returned
  109128. Returns pointers into buffered data; invalidated by next call to
  109129. _stream, _clear, _init, or _buffer */
  109130. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  109131. /* all we need to do is verify a page at the head of the stream
  109132. buffer. If it doesn't verify, we look for the next potential
  109133. frame */
  109134. for(;;){
  109135. long ret=ogg_sync_pageseek(oy,og);
  109136. if(ret>0){
  109137. /* have a page */
  109138. return(1);
  109139. }
  109140. if(ret==0){
  109141. /* need more data */
  109142. return(0);
  109143. }
  109144. /* head did not start a synced page... skipped some bytes */
  109145. if(!oy->unsynced){
  109146. oy->unsynced=1;
  109147. return(-1);
  109148. }
  109149. /* loop. keep looking */
  109150. }
  109151. }
  109152. /* add the incoming page to the stream state; we decompose the page
  109153. into packet segments here as well. */
  109154. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109155. unsigned char *header=og->header;
  109156. unsigned char *body=og->body;
  109157. long bodysize=og->body_len;
  109158. int segptr=0;
  109159. int version=ogg_page_version(og);
  109160. int continued=ogg_page_continued(og);
  109161. int bos=ogg_page_bos(og);
  109162. int eos=ogg_page_eos(og);
  109163. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109164. int serialno=ogg_page_serialno(og);
  109165. long pageno=ogg_page_pageno(og);
  109166. int segments=header[26];
  109167. /* clean up 'returned data' */
  109168. {
  109169. long lr=os->lacing_returned;
  109170. long br=os->body_returned;
  109171. /* body data */
  109172. if(br){
  109173. os->body_fill-=br;
  109174. if(os->body_fill)
  109175. memmove(os->body_data,os->body_data+br,os->body_fill);
  109176. os->body_returned=0;
  109177. }
  109178. if(lr){
  109179. /* segment table */
  109180. if(os->lacing_fill-lr){
  109181. memmove(os->lacing_vals,os->lacing_vals+lr,
  109182. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109183. memmove(os->granule_vals,os->granule_vals+lr,
  109184. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109185. }
  109186. os->lacing_fill-=lr;
  109187. os->lacing_packet-=lr;
  109188. os->lacing_returned=0;
  109189. }
  109190. }
  109191. /* check the serial number */
  109192. if(serialno!=os->serialno)return(-1);
  109193. if(version>0)return(-1);
  109194. _os_lacing_expand(os,segments+1);
  109195. /* are we in sequence? */
  109196. if(pageno!=os->pageno){
  109197. int i;
  109198. /* unroll previous partial packet (if any) */
  109199. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109200. os->body_fill-=os->lacing_vals[i]&0xff;
  109201. os->lacing_fill=os->lacing_packet;
  109202. /* make a note of dropped data in segment table */
  109203. if(os->pageno!=-1){
  109204. os->lacing_vals[os->lacing_fill++]=0x400;
  109205. os->lacing_packet++;
  109206. }
  109207. }
  109208. /* are we a 'continued packet' page? If so, we may need to skip
  109209. some segments */
  109210. if(continued){
  109211. if(os->lacing_fill<1 ||
  109212. os->lacing_vals[os->lacing_fill-1]==0x400){
  109213. bos=0;
  109214. for(;segptr<segments;segptr++){
  109215. int val=header[27+segptr];
  109216. body+=val;
  109217. bodysize-=val;
  109218. if(val<255){
  109219. segptr++;
  109220. break;
  109221. }
  109222. }
  109223. }
  109224. }
  109225. if(bodysize){
  109226. _os_body_expand(os,bodysize);
  109227. memcpy(os->body_data+os->body_fill,body,bodysize);
  109228. os->body_fill+=bodysize;
  109229. }
  109230. {
  109231. int saved=-1;
  109232. while(segptr<segments){
  109233. int val=header[27+segptr];
  109234. os->lacing_vals[os->lacing_fill]=val;
  109235. os->granule_vals[os->lacing_fill]=-1;
  109236. if(bos){
  109237. os->lacing_vals[os->lacing_fill]|=0x100;
  109238. bos=0;
  109239. }
  109240. if(val<255)saved=os->lacing_fill;
  109241. os->lacing_fill++;
  109242. segptr++;
  109243. if(val<255)os->lacing_packet=os->lacing_fill;
  109244. }
  109245. /* set the granulepos on the last granuleval of the last full packet */
  109246. if(saved!=-1){
  109247. os->granule_vals[saved]=granulepos;
  109248. }
  109249. }
  109250. if(eos){
  109251. os->e_o_s=1;
  109252. if(os->lacing_fill>0)
  109253. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109254. }
  109255. os->pageno=pageno+1;
  109256. return(0);
  109257. }
  109258. /* clear things to an initial state. Good to call, eg, before seeking */
  109259. int ogg_sync_reset(ogg_sync_state *oy){
  109260. oy->fill=0;
  109261. oy->returned=0;
  109262. oy->unsynced=0;
  109263. oy->headerbytes=0;
  109264. oy->bodybytes=0;
  109265. return(0);
  109266. }
  109267. int ogg_stream_reset(ogg_stream_state *os){
  109268. os->body_fill=0;
  109269. os->body_returned=0;
  109270. os->lacing_fill=0;
  109271. os->lacing_packet=0;
  109272. os->lacing_returned=0;
  109273. os->header_fill=0;
  109274. os->e_o_s=0;
  109275. os->b_o_s=0;
  109276. os->pageno=-1;
  109277. os->packetno=0;
  109278. os->granulepos=0;
  109279. return(0);
  109280. }
  109281. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109282. ogg_stream_reset(os);
  109283. os->serialno=serialno;
  109284. return(0);
  109285. }
  109286. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109287. /* The last part of decode. We have the stream broken into packet
  109288. segments. Now we need to group them into packets (or return the
  109289. out of sync markers) */
  109290. int ptr=os->lacing_returned;
  109291. if(os->lacing_packet<=ptr)return(0);
  109292. if(os->lacing_vals[ptr]&0x400){
  109293. /* we need to tell the codec there's a gap; it might need to
  109294. handle previous packet dependencies. */
  109295. os->lacing_returned++;
  109296. os->packetno++;
  109297. return(-1);
  109298. }
  109299. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109300. to ask if there's a whole packet
  109301. waiting */
  109302. /* Gather the whole packet. We'll have no holes or a partial packet */
  109303. {
  109304. int size=os->lacing_vals[ptr]&0xff;
  109305. int bytes=size;
  109306. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109307. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109308. while(size==255){
  109309. int val=os->lacing_vals[++ptr];
  109310. size=val&0xff;
  109311. if(val&0x200)eos=0x200;
  109312. bytes+=size;
  109313. }
  109314. if(op){
  109315. op->e_o_s=eos;
  109316. op->b_o_s=bos;
  109317. op->packet=os->body_data+os->body_returned;
  109318. op->packetno=os->packetno;
  109319. op->granulepos=os->granule_vals[ptr];
  109320. op->bytes=bytes;
  109321. }
  109322. if(adv){
  109323. os->body_returned+=bytes;
  109324. os->lacing_returned=ptr+1;
  109325. os->packetno++;
  109326. }
  109327. }
  109328. return(1);
  109329. }
  109330. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109331. return _packetout(os,op,1);
  109332. }
  109333. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109334. return _packetout(os,op,0);
  109335. }
  109336. void ogg_packet_clear(ogg_packet *op) {
  109337. _ogg_free(op->packet);
  109338. memset(op, 0, sizeof(*op));
  109339. }
  109340. #ifdef _V_SELFTEST
  109341. #include <stdio.h>
  109342. ogg_stream_state os_en, os_de;
  109343. ogg_sync_state oy;
  109344. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109345. long j;
  109346. static int sequence=0;
  109347. static int lastno=0;
  109348. if(op->bytes!=len){
  109349. fprintf(stderr,"incorrect packet length!\n");
  109350. exit(1);
  109351. }
  109352. if(op->granulepos!=pos){
  109353. fprintf(stderr,"incorrect packet position!\n");
  109354. exit(1);
  109355. }
  109356. /* packet number just follows sequence/gap; adjust the input number
  109357. for that */
  109358. if(no==0){
  109359. sequence=0;
  109360. }else{
  109361. sequence++;
  109362. if(no>lastno+1)
  109363. sequence++;
  109364. }
  109365. lastno=no;
  109366. if(op->packetno!=sequence){
  109367. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109368. (long)(op->packetno),sequence);
  109369. exit(1);
  109370. }
  109371. /* Test data */
  109372. for(j=0;j<op->bytes;j++)
  109373. if(op->packet[j]!=((j+no)&0xff)){
  109374. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109375. j,op->packet[j],(j+no)&0xff);
  109376. exit(1);
  109377. }
  109378. }
  109379. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109380. long j;
  109381. /* Test data */
  109382. for(j=0;j<og->body_len;j++)
  109383. if(og->body[j]!=data[j]){
  109384. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109385. j,data[j],og->body[j]);
  109386. exit(1);
  109387. }
  109388. /* Test header */
  109389. for(j=0;j<og->header_len;j++){
  109390. if(og->header[j]!=header[j]){
  109391. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109392. for(j=0;j<header[26]+27;j++)
  109393. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109394. fprintf(stderr,"\n");
  109395. exit(1);
  109396. }
  109397. }
  109398. if(og->header_len!=header[26]+27){
  109399. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109400. og->header_len,header[26]+27);
  109401. exit(1);
  109402. }
  109403. }
  109404. void print_header(ogg_page *og){
  109405. int j;
  109406. fprintf(stderr,"\nHEADER:\n");
  109407. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109408. og->header[0],og->header[1],og->header[2],og->header[3],
  109409. (int)og->header[4],(int)og->header[5]);
  109410. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109411. (og->header[9]<<24)|(og->header[8]<<16)|
  109412. (og->header[7]<<8)|og->header[6],
  109413. (og->header[17]<<24)|(og->header[16]<<16)|
  109414. (og->header[15]<<8)|og->header[14],
  109415. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109416. (og->header[19]<<8)|og->header[18]);
  109417. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109418. (int)og->header[22],(int)og->header[23],
  109419. (int)og->header[24],(int)og->header[25],
  109420. (int)og->header[26]);
  109421. for(j=27;j<og->header_len;j++)
  109422. fprintf(stderr,"%d ",(int)og->header[j]);
  109423. fprintf(stderr,")\n\n");
  109424. }
  109425. void copy_page(ogg_page *og){
  109426. unsigned char *temp=_ogg_malloc(og->header_len);
  109427. memcpy(temp,og->header,og->header_len);
  109428. og->header=temp;
  109429. temp=_ogg_malloc(og->body_len);
  109430. memcpy(temp,og->body,og->body_len);
  109431. og->body=temp;
  109432. }
  109433. void free_page(ogg_page *og){
  109434. _ogg_free (og->header);
  109435. _ogg_free (og->body);
  109436. }
  109437. void error(void){
  109438. fprintf(stderr,"error!\n");
  109439. exit(1);
  109440. }
  109441. /* 17 only */
  109442. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109443. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109444. 0x01,0x02,0x03,0x04,0,0,0,0,
  109445. 0x15,0xed,0xec,0x91,
  109446. 1,
  109447. 17};
  109448. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109449. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109450. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109451. 0x01,0x02,0x03,0x04,0,0,0,0,
  109452. 0x59,0x10,0x6c,0x2c,
  109453. 1,
  109454. 17};
  109455. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109456. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109457. 0x01,0x02,0x03,0x04,1,0,0,0,
  109458. 0x89,0x33,0x85,0xce,
  109459. 13,
  109460. 254,255,0,255,1,255,245,255,255,0,
  109461. 255,255,90};
  109462. /* nil packets; beginning,middle,end */
  109463. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109464. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109465. 0x01,0x02,0x03,0x04,0,0,0,0,
  109466. 0xff,0x7b,0x23,0x17,
  109467. 1,
  109468. 0};
  109469. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109470. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109471. 0x01,0x02,0x03,0x04,1,0,0,0,
  109472. 0x5c,0x3f,0x66,0xcb,
  109473. 17,
  109474. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109475. 255,255,90,0};
  109476. /* large initial packet */
  109477. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109478. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109479. 0x01,0x02,0x03,0x04,0,0,0,0,
  109480. 0x01,0x27,0x31,0xaa,
  109481. 18,
  109482. 255,255,255,255,255,255,255,255,
  109483. 255,255,255,255,255,255,255,255,255,10};
  109484. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109485. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109486. 0x01,0x02,0x03,0x04,1,0,0,0,
  109487. 0x7f,0x4e,0x8a,0xd2,
  109488. 4,
  109489. 255,4,255,0};
  109490. /* continuing packet test */
  109491. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109492. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109493. 0x01,0x02,0x03,0x04,0,0,0,0,
  109494. 0xff,0x7b,0x23,0x17,
  109495. 1,
  109496. 0};
  109497. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109498. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109499. 0x01,0x02,0x03,0x04,1,0,0,0,
  109500. 0x54,0x05,0x51,0xc8,
  109501. 17,
  109502. 255,255,255,255,255,255,255,255,
  109503. 255,255,255,255,255,255,255,255,255};
  109504. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109505. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109506. 0x01,0x02,0x03,0x04,2,0,0,0,
  109507. 0xc8,0xc3,0xcb,0xed,
  109508. 5,
  109509. 10,255,4,255,0};
  109510. /* page with the 255 segment limit */
  109511. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109512. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109513. 0x01,0x02,0x03,0x04,0,0,0,0,
  109514. 0xff,0x7b,0x23,0x17,
  109515. 1,
  109516. 0};
  109517. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109518. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109519. 0x01,0x02,0x03,0x04,1,0,0,0,
  109520. 0xed,0x2a,0x2e,0xa7,
  109521. 255,
  109522. 10,10,10,10,10,10,10,10,
  109523. 10,10,10,10,10,10,10,10,
  109524. 10,10,10,10,10,10,10,10,
  109525. 10,10,10,10,10,10,10,10,
  109526. 10,10,10,10,10,10,10,10,
  109527. 10,10,10,10,10,10,10,10,
  109528. 10,10,10,10,10,10,10,10,
  109529. 10,10,10,10,10,10,10,10,
  109530. 10,10,10,10,10,10,10,10,
  109531. 10,10,10,10,10,10,10,10,
  109532. 10,10,10,10,10,10,10,10,
  109533. 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};
  109554. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109555. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109556. 0x01,0x02,0x03,0x04,2,0,0,0,
  109557. 0x6c,0x3b,0x82,0x3d,
  109558. 1,
  109559. 50};
  109560. /* packet that overspans over an entire page */
  109561. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109562. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109563. 0x01,0x02,0x03,0x04,0,0,0,0,
  109564. 0xff,0x7b,0x23,0x17,
  109565. 1,
  109566. 0};
  109567. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109568. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109569. 0x01,0x02,0x03,0x04,1,0,0,0,
  109570. 0x3c,0xd9,0x4d,0x3f,
  109571. 17,
  109572. 100,255,255,255,255,255,255,255,255,
  109573. 255,255,255,255,255,255,255,255};
  109574. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109575. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109576. 0x01,0x02,0x03,0x04,2,0,0,0,
  109577. 0x01,0xd2,0xe5,0xe5,
  109578. 17,
  109579. 255,255,255,255,255,255,255,255,
  109580. 255,255,255,255,255,255,255,255,255};
  109581. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109582. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109583. 0x01,0x02,0x03,0x04,3,0,0,0,
  109584. 0xef,0xdd,0x88,0xde,
  109585. 7,
  109586. 255,255,75,255,4,255,0};
  109587. /* packet that overspans over an entire page */
  109588. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109589. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109590. 0x01,0x02,0x03,0x04,0,0,0,0,
  109591. 0xff,0x7b,0x23,0x17,
  109592. 1,
  109593. 0};
  109594. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109595. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109596. 0x01,0x02,0x03,0x04,1,0,0,0,
  109597. 0x3c,0xd9,0x4d,0x3f,
  109598. 17,
  109599. 100,255,255,255,255,255,255,255,255,
  109600. 255,255,255,255,255,255,255,255};
  109601. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109602. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109603. 0x01,0x02,0x03,0x04,2,0,0,0,
  109604. 0xd4,0xe0,0x60,0xe5,
  109605. 1,0};
  109606. void test_pack(const int *pl, const int **headers, int byteskip,
  109607. int pageskip, int packetskip){
  109608. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109609. long inptr=0;
  109610. long outptr=0;
  109611. long deptr=0;
  109612. long depacket=0;
  109613. long granule_pos=7,pageno=0;
  109614. int i,j,packets,pageout=pageskip;
  109615. int eosflag=0;
  109616. int bosflag=0;
  109617. int byteskipcount=0;
  109618. ogg_stream_reset(&os_en);
  109619. ogg_stream_reset(&os_de);
  109620. ogg_sync_reset(&oy);
  109621. for(packets=0;packets<packetskip;packets++)
  109622. depacket+=pl[packets];
  109623. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109624. for(i=0;i<packets;i++){
  109625. /* construct a test packet */
  109626. ogg_packet op;
  109627. int len=pl[i];
  109628. op.packet=data+inptr;
  109629. op.bytes=len;
  109630. op.e_o_s=(pl[i+1]<0?1:0);
  109631. op.granulepos=granule_pos;
  109632. granule_pos+=1024;
  109633. for(j=0;j<len;j++)data[inptr++]=i+j;
  109634. /* submit the test packet */
  109635. ogg_stream_packetin(&os_en,&op);
  109636. /* retrieve any finished pages */
  109637. {
  109638. ogg_page og;
  109639. while(ogg_stream_pageout(&os_en,&og)){
  109640. /* We have a page. Check it carefully */
  109641. fprintf(stderr,"%ld, ",pageno);
  109642. if(headers[pageno]==NULL){
  109643. fprintf(stderr,"coded too many pages!\n");
  109644. exit(1);
  109645. }
  109646. check_page(data+outptr,headers[pageno],&og);
  109647. outptr+=og.body_len;
  109648. pageno++;
  109649. if(pageskip){
  109650. bosflag=1;
  109651. pageskip--;
  109652. deptr+=og.body_len;
  109653. }
  109654. /* have a complete page; submit it to sync/decode */
  109655. {
  109656. ogg_page og_de;
  109657. ogg_packet op_de,op_de2;
  109658. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109659. char *next=buf;
  109660. byteskipcount+=og.header_len;
  109661. if(byteskipcount>byteskip){
  109662. memcpy(next,og.header,byteskipcount-byteskip);
  109663. next+=byteskipcount-byteskip;
  109664. byteskipcount=byteskip;
  109665. }
  109666. byteskipcount+=og.body_len;
  109667. if(byteskipcount>byteskip){
  109668. memcpy(next,og.body,byteskipcount-byteskip);
  109669. next+=byteskipcount-byteskip;
  109670. byteskipcount=byteskip;
  109671. }
  109672. ogg_sync_wrote(&oy,next-buf);
  109673. while(1){
  109674. int ret=ogg_sync_pageout(&oy,&og_de);
  109675. if(ret==0)break;
  109676. if(ret<0)continue;
  109677. /* got a page. Happy happy. Verify that it's good. */
  109678. fprintf(stderr,"(%ld), ",pageout);
  109679. check_page(data+deptr,headers[pageout],&og_de);
  109680. deptr+=og_de.body_len;
  109681. pageout++;
  109682. /* submit it to deconstitution */
  109683. ogg_stream_pagein(&os_de,&og_de);
  109684. /* packets out? */
  109685. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109686. ogg_stream_packetpeek(&os_de,NULL);
  109687. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109688. /* verify peek and out match */
  109689. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109690. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109691. depacket);
  109692. exit(1);
  109693. }
  109694. /* verify the packet! */
  109695. /* check data */
  109696. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109697. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109698. depacket);
  109699. exit(1);
  109700. }
  109701. /* check bos flag */
  109702. if(bosflag==0 && op_de.b_o_s==0){
  109703. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109704. exit(1);
  109705. }
  109706. if(bosflag && op_de.b_o_s){
  109707. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109708. exit(1);
  109709. }
  109710. bosflag=1;
  109711. depacket+=op_de.bytes;
  109712. /* check eos flag */
  109713. if(eosflag){
  109714. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109715. exit(1);
  109716. }
  109717. if(op_de.e_o_s)eosflag=1;
  109718. /* check granulepos flag */
  109719. if(op_de.granulepos!=-1){
  109720. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109721. }
  109722. }
  109723. }
  109724. }
  109725. }
  109726. }
  109727. }
  109728. _ogg_free(data);
  109729. if(headers[pageno]!=NULL){
  109730. fprintf(stderr,"did not write last page!\n");
  109731. exit(1);
  109732. }
  109733. if(headers[pageout]!=NULL){
  109734. fprintf(stderr,"did not decode last page!\n");
  109735. exit(1);
  109736. }
  109737. if(inptr!=outptr){
  109738. fprintf(stderr,"encoded page data incomplete!\n");
  109739. exit(1);
  109740. }
  109741. if(inptr!=deptr){
  109742. fprintf(stderr,"decoded page data incomplete!\n");
  109743. exit(1);
  109744. }
  109745. if(inptr!=depacket){
  109746. fprintf(stderr,"decoded packet data incomplete!\n");
  109747. exit(1);
  109748. }
  109749. if(!eosflag){
  109750. fprintf(stderr,"Never got a packet with EOS set!\n");
  109751. exit(1);
  109752. }
  109753. fprintf(stderr,"ok.\n");
  109754. }
  109755. int main(void){
  109756. ogg_stream_init(&os_en,0x04030201);
  109757. ogg_stream_init(&os_de,0x04030201);
  109758. ogg_sync_init(&oy);
  109759. /* Exercise each code path in the framing code. Also verify that
  109760. the checksums are working. */
  109761. {
  109762. /* 17 only */
  109763. const int packets[]={17, -1};
  109764. const int *headret[]={head1_0,NULL};
  109765. fprintf(stderr,"testing single page encoding... ");
  109766. test_pack(packets,headret,0,0,0);
  109767. }
  109768. {
  109769. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109770. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109771. const int *headret[]={head1_1,head2_1,NULL};
  109772. fprintf(stderr,"testing basic page encoding... ");
  109773. test_pack(packets,headret,0,0,0);
  109774. }
  109775. {
  109776. /* nil packets; beginning,middle,end */
  109777. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109778. const int *headret[]={head1_2,head2_2,NULL};
  109779. fprintf(stderr,"testing basic nil packets... ");
  109780. test_pack(packets,headret,0,0,0);
  109781. }
  109782. {
  109783. /* large initial packet */
  109784. const int packets[]={4345,259,255,-1};
  109785. const int *headret[]={head1_3,head2_3,NULL};
  109786. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109787. test_pack(packets,headret,0,0,0);
  109788. }
  109789. {
  109790. /* continuing packet test */
  109791. const int packets[]={0,4345,259,255,-1};
  109792. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109793. fprintf(stderr,"testing single packet page span... ");
  109794. test_pack(packets,headret,0,0,0);
  109795. }
  109796. /* page with the 255 segment limit */
  109797. {
  109798. const int packets[]={0,10,10,10,10,10,10,10,10,
  109799. 10,10,10,10,10,10,10,10,
  109800. 10,10,10,10,10,10,10,10,
  109801. 10,10,10,10,10,10,10,10,
  109802. 10,10,10,10,10,10,10,10,
  109803. 10,10,10,10,10,10,10,10,
  109804. 10,10,10,10,10,10,10,10,
  109805. 10,10,10,10,10,10,10,10,
  109806. 10,10,10,10,10,10,10,10,
  109807. 10,10,10,10,10,10,10,10,
  109808. 10,10,10,10,10,10,10,10,
  109809. 10,10,10,10,10,10,10,10,
  109810. 10,10,10,10,10,10,10,10,
  109811. 10,10,10,10,10,10,10,10,
  109812. 10,10,10,10,10,10,10,10,
  109813. 10,10,10,10,10,10,10,10,
  109814. 10,10,10,10,10,10,10,10,
  109815. 10,10,10,10,10,10,10,10,
  109816. 10,10,10,10,10,10,10,10,
  109817. 10,10,10,10,10,10,10,10,
  109818. 10,10,10,10,10,10,10,10,
  109819. 10,10,10,10,10,10,10,10,
  109820. 10,10,10,10,10,10,10,10,
  109821. 10,10,10,10,10,10,10,10,
  109822. 10,10,10,10,10,10,10,10,
  109823. 10,10,10,10,10,10,10,10,
  109824. 10,10,10,10,10,10,10,10,
  109825. 10,10,10,10,10,10,10,10,
  109826. 10,10,10,10,10,10,10,10,
  109827. 10,10,10,10,10,10,10,10,
  109828. 10,10,10,10,10,10,10,10,
  109829. 10,10,10,10,10,10,10,50,-1};
  109830. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109831. fprintf(stderr,"testing max packet segments... ");
  109832. test_pack(packets,headret,0,0,0);
  109833. }
  109834. {
  109835. /* packet that overspans over an entire page */
  109836. const int packets[]={0,100,9000,259,255,-1};
  109837. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109838. fprintf(stderr,"testing very large packets... ");
  109839. test_pack(packets,headret,0,0,0);
  109840. }
  109841. {
  109842. /* test for the libogg 1.1.1 resync in large continuation bug
  109843. found by Josh Coalson) */
  109844. const int packets[]={0,100,9000,259,255,-1};
  109845. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109846. fprintf(stderr,"testing continuation resync in very large packets... ");
  109847. test_pack(packets,headret,100,2,3);
  109848. }
  109849. {
  109850. /* term only page. why not? */
  109851. const int packets[]={0,100,4080,-1};
  109852. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109853. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109854. test_pack(packets,headret,0,0,0);
  109855. }
  109856. {
  109857. /* build a bunch of pages for testing */
  109858. unsigned char *data=_ogg_malloc(1024*1024);
  109859. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109860. int inptr=0,i,j;
  109861. ogg_page og[5];
  109862. ogg_stream_reset(&os_en);
  109863. for(i=0;pl[i]!=-1;i++){
  109864. ogg_packet op;
  109865. int len=pl[i];
  109866. op.packet=data+inptr;
  109867. op.bytes=len;
  109868. op.e_o_s=(pl[i+1]<0?1:0);
  109869. op.granulepos=(i+1)*1000;
  109870. for(j=0;j<len;j++)data[inptr++]=i+j;
  109871. ogg_stream_packetin(&os_en,&op);
  109872. }
  109873. _ogg_free(data);
  109874. /* retrieve finished pages */
  109875. for(i=0;i<5;i++){
  109876. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109877. fprintf(stderr,"Too few pages output building sync tests!\n");
  109878. exit(1);
  109879. }
  109880. copy_page(&og[i]);
  109881. }
  109882. /* Test lost pages on pagein/packetout: no rollback */
  109883. {
  109884. ogg_page temp;
  109885. ogg_packet test;
  109886. fprintf(stderr,"Testing loss of pages... ");
  109887. ogg_sync_reset(&oy);
  109888. ogg_stream_reset(&os_de);
  109889. for(i=0;i<5;i++){
  109890. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109891. og[i].header_len);
  109892. ogg_sync_wrote(&oy,og[i].header_len);
  109893. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109894. ogg_sync_wrote(&oy,og[i].body_len);
  109895. }
  109896. ogg_sync_pageout(&oy,&temp);
  109897. ogg_stream_pagein(&os_de,&temp);
  109898. ogg_sync_pageout(&oy,&temp);
  109899. ogg_stream_pagein(&os_de,&temp);
  109900. ogg_sync_pageout(&oy,&temp);
  109901. /* skip */
  109902. ogg_sync_pageout(&oy,&temp);
  109903. ogg_stream_pagein(&os_de,&temp);
  109904. /* do we get the expected results/packets? */
  109905. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109906. checkpacket(&test,0,0,0);
  109907. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109908. checkpacket(&test,100,1,-1);
  109909. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109910. checkpacket(&test,4079,2,3000);
  109911. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109912. fprintf(stderr,"Error: loss of page did not return error\n");
  109913. exit(1);
  109914. }
  109915. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109916. checkpacket(&test,76,5,-1);
  109917. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109918. checkpacket(&test,34,6,-1);
  109919. fprintf(stderr,"ok.\n");
  109920. }
  109921. /* Test lost pages on pagein/packetout: rollback with continuation */
  109922. {
  109923. ogg_page temp;
  109924. ogg_packet test;
  109925. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109926. ogg_sync_reset(&oy);
  109927. ogg_stream_reset(&os_de);
  109928. for(i=0;i<5;i++){
  109929. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109930. og[i].header_len);
  109931. ogg_sync_wrote(&oy,og[i].header_len);
  109932. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109933. ogg_sync_wrote(&oy,og[i].body_len);
  109934. }
  109935. ogg_sync_pageout(&oy,&temp);
  109936. ogg_stream_pagein(&os_de,&temp);
  109937. ogg_sync_pageout(&oy,&temp);
  109938. ogg_stream_pagein(&os_de,&temp);
  109939. ogg_sync_pageout(&oy,&temp);
  109940. ogg_stream_pagein(&os_de,&temp);
  109941. ogg_sync_pageout(&oy,&temp);
  109942. /* skip */
  109943. ogg_sync_pageout(&oy,&temp);
  109944. ogg_stream_pagein(&os_de,&temp);
  109945. /* do we get the expected results/packets? */
  109946. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109947. checkpacket(&test,0,0,0);
  109948. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109949. checkpacket(&test,100,1,-1);
  109950. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109951. checkpacket(&test,4079,2,3000);
  109952. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109953. checkpacket(&test,2956,3,4000);
  109954. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109955. fprintf(stderr,"Error: loss of page did not return error\n");
  109956. exit(1);
  109957. }
  109958. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109959. checkpacket(&test,300,13,14000);
  109960. fprintf(stderr,"ok.\n");
  109961. }
  109962. /* the rest only test sync */
  109963. {
  109964. ogg_page og_de;
  109965. /* Test fractional page inputs: incomplete capture */
  109966. fprintf(stderr,"Testing sync on partial inputs... ");
  109967. ogg_sync_reset(&oy);
  109968. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109969. 3);
  109970. ogg_sync_wrote(&oy,3);
  109971. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109972. /* Test fractional page inputs: incomplete fixed header */
  109973. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109974. 20);
  109975. ogg_sync_wrote(&oy,20);
  109976. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109977. /* Test fractional page inputs: incomplete header */
  109978. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109979. 5);
  109980. ogg_sync_wrote(&oy,5);
  109981. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109982. /* Test fractional page inputs: incomplete body */
  109983. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109984. og[1].header_len-28);
  109985. ogg_sync_wrote(&oy,og[1].header_len-28);
  109986. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109987. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109988. ogg_sync_wrote(&oy,1000);
  109989. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109990. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109991. og[1].body_len-1000);
  109992. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109993. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109994. fprintf(stderr,"ok.\n");
  109995. }
  109996. /* Test fractional page inputs: page + incomplete capture */
  109997. {
  109998. ogg_page og_de;
  109999. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  110000. ogg_sync_reset(&oy);
  110001. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110002. og[1].header_len);
  110003. ogg_sync_wrote(&oy,og[1].header_len);
  110004. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110005. og[1].body_len);
  110006. ogg_sync_wrote(&oy,og[1].body_len);
  110007. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110008. 20);
  110009. ogg_sync_wrote(&oy,20);
  110010. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110011. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110012. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  110013. og[1].header_len-20);
  110014. ogg_sync_wrote(&oy,og[1].header_len-20);
  110015. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110016. og[1].body_len);
  110017. ogg_sync_wrote(&oy,og[1].body_len);
  110018. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110019. fprintf(stderr,"ok.\n");
  110020. }
  110021. /* Test recapture: garbage + page */
  110022. {
  110023. ogg_page og_de;
  110024. fprintf(stderr,"Testing search for capture... ");
  110025. ogg_sync_reset(&oy);
  110026. /* 'garbage' */
  110027. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110028. og[1].body_len);
  110029. ogg_sync_wrote(&oy,og[1].body_len);
  110030. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110031. og[1].header_len);
  110032. ogg_sync_wrote(&oy,og[1].header_len);
  110033. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110034. og[1].body_len);
  110035. ogg_sync_wrote(&oy,og[1].body_len);
  110036. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110037. 20);
  110038. ogg_sync_wrote(&oy,20);
  110039. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110040. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110041. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110042. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  110043. og[2].header_len-20);
  110044. ogg_sync_wrote(&oy,og[2].header_len-20);
  110045. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110046. og[2].body_len);
  110047. ogg_sync_wrote(&oy,og[2].body_len);
  110048. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110049. fprintf(stderr,"ok.\n");
  110050. }
  110051. /* Test recapture: page + garbage + page */
  110052. {
  110053. ogg_page og_de;
  110054. fprintf(stderr,"Testing recapture... ");
  110055. ogg_sync_reset(&oy);
  110056. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110057. og[1].header_len);
  110058. ogg_sync_wrote(&oy,og[1].header_len);
  110059. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110060. og[1].body_len);
  110061. ogg_sync_wrote(&oy,og[1].body_len);
  110062. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110063. og[2].header_len);
  110064. ogg_sync_wrote(&oy,og[2].header_len);
  110065. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110066. og[2].header_len);
  110067. ogg_sync_wrote(&oy,og[2].header_len);
  110068. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110069. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110070. og[2].body_len-5);
  110071. ogg_sync_wrote(&oy,og[2].body_len-5);
  110072. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  110073. og[3].header_len);
  110074. ogg_sync_wrote(&oy,og[3].header_len);
  110075. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  110076. og[3].body_len);
  110077. ogg_sync_wrote(&oy,og[3].body_len);
  110078. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110079. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110080. fprintf(stderr,"ok.\n");
  110081. }
  110082. /* Free page data that was previously copied */
  110083. {
  110084. for(i=0;i<5;i++){
  110085. free_page(&og[i]);
  110086. }
  110087. }
  110088. }
  110089. return(0);
  110090. }
  110091. #endif
  110092. #endif
  110093. /*** End of inlined file: framing.c ***/
  110094. /*** Start of inlined file: analysis.c ***/
  110095. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110096. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110097. // tasks..
  110098. #if JUCE_MSVC
  110099. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110100. #endif
  110101. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110102. #if JUCE_USE_OGGVORBIS
  110103. #include <stdio.h>
  110104. #include <string.h>
  110105. #include <math.h>
  110106. /*** Start of inlined file: codec_internal.h ***/
  110107. #ifndef _V_CODECI_H_
  110108. #define _V_CODECI_H_
  110109. /*** Start of inlined file: envelope.h ***/
  110110. #ifndef _V_ENVELOPE_
  110111. #define _V_ENVELOPE_
  110112. /*** Start of inlined file: mdct.h ***/
  110113. #ifndef _OGG_mdct_H_
  110114. #define _OGG_mdct_H_
  110115. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  110116. #ifdef MDCT_INTEGERIZED
  110117. #define DATA_TYPE int
  110118. #define REG_TYPE register int
  110119. #define TRIGBITS 14
  110120. #define cPI3_8 6270
  110121. #define cPI2_8 11585
  110122. #define cPI1_8 15137
  110123. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  110124. #define MULT_NORM(x) ((x)>>TRIGBITS)
  110125. #define HALVE(x) ((x)>>1)
  110126. #else
  110127. #define DATA_TYPE float
  110128. #define REG_TYPE float
  110129. #define cPI3_8 .38268343236508977175F
  110130. #define cPI2_8 .70710678118654752441F
  110131. #define cPI1_8 .92387953251128675613F
  110132. #define FLOAT_CONV(x) (x)
  110133. #define MULT_NORM(x) (x)
  110134. #define HALVE(x) ((x)*.5f)
  110135. #endif
  110136. typedef struct {
  110137. int n;
  110138. int log2n;
  110139. DATA_TYPE *trig;
  110140. int *bitrev;
  110141. DATA_TYPE scale;
  110142. } mdct_lookup;
  110143. extern void mdct_init(mdct_lookup *lookup,int n);
  110144. extern void mdct_clear(mdct_lookup *l);
  110145. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110146. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110147. #endif
  110148. /*** End of inlined file: mdct.h ***/
  110149. #define VE_PRE 16
  110150. #define VE_WIN 4
  110151. #define VE_POST 2
  110152. #define VE_AMP (VE_PRE+VE_POST-1)
  110153. #define VE_BANDS 7
  110154. #define VE_NEARDC 15
  110155. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110156. #define VE_MAXSTRETCH 12 /* one-third full block */
  110157. typedef struct {
  110158. float ampbuf[VE_AMP];
  110159. int ampptr;
  110160. float nearDC[VE_NEARDC];
  110161. float nearDC_acc;
  110162. float nearDC_partialacc;
  110163. int nearptr;
  110164. } envelope_filter_state;
  110165. typedef struct {
  110166. int begin;
  110167. int end;
  110168. float *window;
  110169. float total;
  110170. } envelope_band;
  110171. typedef struct {
  110172. int ch;
  110173. int winlength;
  110174. int searchstep;
  110175. float minenergy;
  110176. mdct_lookup mdct;
  110177. float *mdct_win;
  110178. envelope_band band[VE_BANDS];
  110179. envelope_filter_state *filter;
  110180. int stretch;
  110181. int *mark;
  110182. long storage;
  110183. long current;
  110184. long curmark;
  110185. long cursor;
  110186. } envelope_lookup;
  110187. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110188. extern void _ve_envelope_clear(envelope_lookup *e);
  110189. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110190. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110191. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110192. #endif
  110193. /*** End of inlined file: envelope.h ***/
  110194. /*** Start of inlined file: codebook.h ***/
  110195. #ifndef _V_CODEBOOK_H_
  110196. #define _V_CODEBOOK_H_
  110197. /* This structure encapsulates huffman and VQ style encoding books; it
  110198. doesn't do anything specific to either.
  110199. valuelist/quantlist are nonNULL (and q_* significant) only if
  110200. there's entry->value mapping to be done.
  110201. If encode-side mapping must be done (and thus the entry needs to be
  110202. hunted), the auxiliary encode pointer will point to a decision
  110203. tree. This is true of both VQ and huffman, but is mostly useful
  110204. with VQ.
  110205. */
  110206. typedef struct static_codebook{
  110207. long dim; /* codebook dimensions (elements per vector) */
  110208. long entries; /* codebook entries */
  110209. long *lengthlist; /* codeword lengths in bits */
  110210. /* mapping ***************************************************************/
  110211. int maptype; /* 0=none
  110212. 1=implicitly populated values from map column
  110213. 2=listed arbitrary values */
  110214. /* The below does a linear, single monotonic sequence mapping. */
  110215. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110216. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110217. int q_quant; /* bits: 0 < quant <= 16 */
  110218. int q_sequencep; /* bitflag */
  110219. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110220. map == 2: list of dim*entries quantized entry vals
  110221. */
  110222. /* encode helpers ********************************************************/
  110223. struct encode_aux_nearestmatch *nearest_tree;
  110224. struct encode_aux_threshmatch *thresh_tree;
  110225. struct encode_aux_pigeonhole *pigeon_tree;
  110226. int allocedp;
  110227. } static_codebook;
  110228. /* this structures an arbitrary trained book to quickly find the
  110229. nearest cell match */
  110230. typedef struct encode_aux_nearestmatch{
  110231. /* pre-calculated partitioning tree */
  110232. long *ptr0;
  110233. long *ptr1;
  110234. long *p; /* decision points (each is an entry) */
  110235. long *q; /* decision points (each is an entry) */
  110236. long aux; /* number of tree entries */
  110237. long alloc;
  110238. } encode_aux_nearestmatch;
  110239. /* assumes a maptype of 1; encode side only, so that's OK */
  110240. typedef struct encode_aux_threshmatch{
  110241. float *quantthresh;
  110242. long *quantmap;
  110243. int quantvals;
  110244. int threshvals;
  110245. } encode_aux_threshmatch;
  110246. typedef struct encode_aux_pigeonhole{
  110247. float min;
  110248. float del;
  110249. int mapentries;
  110250. int quantvals;
  110251. long *pigeonmap;
  110252. long fittotal;
  110253. long *fitlist;
  110254. long *fitmap;
  110255. long *fitlength;
  110256. } encode_aux_pigeonhole;
  110257. typedef struct codebook{
  110258. long dim; /* codebook dimensions (elements per vector) */
  110259. long entries; /* codebook entries */
  110260. long used_entries; /* populated codebook entries */
  110261. const static_codebook *c;
  110262. /* for encode, the below are entry-ordered, fully populated */
  110263. /* for decode, the below are ordered by bitreversed codeword and only
  110264. used entries are populated */
  110265. float *valuelist; /* list of dim*entries actual entry values */
  110266. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110267. int *dec_index; /* only used if sparseness collapsed */
  110268. char *dec_codelengths;
  110269. ogg_uint32_t *dec_firsttable;
  110270. int dec_firsttablen;
  110271. int dec_maxlength;
  110272. } codebook;
  110273. extern void vorbis_staticbook_clear(static_codebook *b);
  110274. extern void vorbis_staticbook_destroy(static_codebook *b);
  110275. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110276. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110277. extern void vorbis_book_clear(codebook *b);
  110278. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110279. extern float *_book_logdist(const static_codebook *b,float *vals);
  110280. extern float _float32_unpack(long val);
  110281. extern long _float32_pack(float val);
  110282. extern int _best(codebook *book, float *a, int step);
  110283. extern int _ilog(unsigned int v);
  110284. extern long _book_maptype1_quantvals(const static_codebook *b);
  110285. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110286. extern long vorbis_book_codeword(codebook *book,int entry);
  110287. extern long vorbis_book_codelen(codebook *book,int entry);
  110288. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110289. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110290. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110291. extern int vorbis_book_errorv(codebook *book, float *a);
  110292. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110293. oggpack_buffer *b);
  110294. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110295. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110296. oggpack_buffer *b,int n);
  110297. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110298. oggpack_buffer *b,int n);
  110299. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110300. oggpack_buffer *b,int n);
  110301. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110302. long off,int ch,
  110303. oggpack_buffer *b,int n);
  110304. #endif
  110305. /*** End of inlined file: codebook.h ***/
  110306. #define BLOCKTYPE_IMPULSE 0
  110307. #define BLOCKTYPE_PADDING 1
  110308. #define BLOCKTYPE_TRANSITION 0
  110309. #define BLOCKTYPE_LONG 1
  110310. #define PACKETBLOBS 15
  110311. typedef struct vorbis_block_internal{
  110312. float **pcmdelay; /* this is a pointer into local storage */
  110313. float ampmax;
  110314. int blocktype;
  110315. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110316. blob [PACKETBLOBS/2] points to
  110317. the oggpack_buffer in the
  110318. main vorbis_block */
  110319. } vorbis_block_internal;
  110320. typedef void vorbis_look_floor;
  110321. typedef void vorbis_look_residue;
  110322. typedef void vorbis_look_transform;
  110323. /* mode ************************************************************/
  110324. typedef struct {
  110325. int blockflag;
  110326. int windowtype;
  110327. int transformtype;
  110328. int mapping;
  110329. } vorbis_info_mode;
  110330. typedef void vorbis_info_floor;
  110331. typedef void vorbis_info_residue;
  110332. typedef void vorbis_info_mapping;
  110333. /*** Start of inlined file: psy.h ***/
  110334. #ifndef _V_PSY_H_
  110335. #define _V_PSY_H_
  110336. /*** Start of inlined file: smallft.h ***/
  110337. #ifndef _V_SMFT_H_
  110338. #define _V_SMFT_H_
  110339. typedef struct {
  110340. int n;
  110341. float *trigcache;
  110342. int *splitcache;
  110343. } drft_lookup;
  110344. extern void drft_forward(drft_lookup *l,float *data);
  110345. extern void drft_backward(drft_lookup *l,float *data);
  110346. extern void drft_init(drft_lookup *l,int n);
  110347. extern void drft_clear(drft_lookup *l);
  110348. #endif
  110349. /*** End of inlined file: smallft.h ***/
  110350. /*** Start of inlined file: backends.h ***/
  110351. /* this is exposed up here because we need it for static modes.
  110352. Lookups for each backend aren't exposed because there's no reason
  110353. to do so */
  110354. #ifndef _vorbis_backend_h_
  110355. #define _vorbis_backend_h_
  110356. /* this would all be simpler/shorter with templates, but.... */
  110357. /* Floor backend generic *****************************************/
  110358. typedef struct{
  110359. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110360. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110361. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110362. void (*free_info) (vorbis_info_floor *);
  110363. void (*free_look) (vorbis_look_floor *);
  110364. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110365. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110366. void *buffer,float *);
  110367. } vorbis_func_floor;
  110368. typedef struct{
  110369. int order;
  110370. long rate;
  110371. long barkmap;
  110372. int ampbits;
  110373. int ampdB;
  110374. int numbooks; /* <= 16 */
  110375. int books[16];
  110376. float lessthan; /* encode-only config setting hacks for libvorbis */
  110377. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110378. } vorbis_info_floor0;
  110379. #define VIF_POSIT 63
  110380. #define VIF_CLASS 16
  110381. #define VIF_PARTS 31
  110382. typedef struct{
  110383. int partitions; /* 0 to 31 */
  110384. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110385. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110386. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110387. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110388. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110389. int mult; /* 1 2 3 or 4 */
  110390. int postlist[VIF_POSIT+2]; /* first two implicit */
  110391. /* encode side analysis parameters */
  110392. float maxover;
  110393. float maxunder;
  110394. float maxerr;
  110395. float twofitweight;
  110396. float twofitatten;
  110397. int n;
  110398. } vorbis_info_floor1;
  110399. /* Residue backend generic *****************************************/
  110400. typedef struct{
  110401. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110402. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110403. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110404. vorbis_info_residue *);
  110405. void (*free_info) (vorbis_info_residue *);
  110406. void (*free_look) (vorbis_look_residue *);
  110407. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110408. float **,int *,int);
  110409. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110410. vorbis_look_residue *,
  110411. float **,float **,int *,int,long **);
  110412. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110413. float **,int *,int);
  110414. } vorbis_func_residue;
  110415. typedef struct vorbis_info_residue0{
  110416. /* block-partitioned VQ coded straight residue */
  110417. long begin;
  110418. long end;
  110419. /* first stage (lossless partitioning) */
  110420. int grouping; /* group n vectors per partition */
  110421. int partitions; /* possible codebooks for a partition */
  110422. int groupbook; /* huffbook for partitioning */
  110423. int secondstages[64]; /* expanded out to pointers in lookup */
  110424. int booklist[256]; /* list of second stage books */
  110425. float classmetric1[64];
  110426. float classmetric2[64];
  110427. } vorbis_info_residue0;
  110428. /* Mapping backend generic *****************************************/
  110429. typedef struct{
  110430. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110431. oggpack_buffer *);
  110432. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110433. void (*free_info) (vorbis_info_mapping *);
  110434. int (*forward) (struct vorbis_block *vb);
  110435. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110436. } vorbis_func_mapping;
  110437. typedef struct vorbis_info_mapping0{
  110438. int submaps; /* <= 16 */
  110439. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110440. int floorsubmap[16]; /* [mux] submap to floors */
  110441. int residuesubmap[16]; /* [mux] submap to residue */
  110442. int coupling_steps;
  110443. int coupling_mag[256];
  110444. int coupling_ang[256];
  110445. } vorbis_info_mapping0;
  110446. #endif
  110447. /*** End of inlined file: backends.h ***/
  110448. #ifndef EHMER_MAX
  110449. #define EHMER_MAX 56
  110450. #endif
  110451. /* psychoacoustic setup ********************************************/
  110452. #define P_BANDS 17 /* 62Hz to 16kHz */
  110453. #define P_LEVELS 8 /* 30dB to 100dB */
  110454. #define P_LEVEL_0 30. /* 30 dB */
  110455. #define P_NOISECURVES 3
  110456. #define NOISE_COMPAND_LEVELS 40
  110457. typedef struct vorbis_info_psy{
  110458. int blockflag;
  110459. float ath_adjatt;
  110460. float ath_maxatt;
  110461. float tone_masteratt[P_NOISECURVES];
  110462. float tone_centerboost;
  110463. float tone_decay;
  110464. float tone_abs_limit;
  110465. float toneatt[P_BANDS];
  110466. int noisemaskp;
  110467. float noisemaxsupp;
  110468. float noisewindowlo;
  110469. float noisewindowhi;
  110470. int noisewindowlomin;
  110471. int noisewindowhimin;
  110472. int noisewindowfixed;
  110473. float noiseoff[P_NOISECURVES][P_BANDS];
  110474. float noisecompand[NOISE_COMPAND_LEVELS];
  110475. float max_curve_dB;
  110476. int normal_channel_p;
  110477. int normal_point_p;
  110478. int normal_start;
  110479. int normal_partition;
  110480. double normal_thresh;
  110481. } vorbis_info_psy;
  110482. typedef struct{
  110483. int eighth_octave_lines;
  110484. /* for block long/short tuning; encode only */
  110485. float preecho_thresh[VE_BANDS];
  110486. float postecho_thresh[VE_BANDS];
  110487. float stretch_penalty;
  110488. float preecho_minenergy;
  110489. float ampmax_att_per_sec;
  110490. /* channel coupling config */
  110491. int coupling_pkHz[PACKETBLOBS];
  110492. int coupling_pointlimit[2][PACKETBLOBS];
  110493. int coupling_prepointamp[PACKETBLOBS];
  110494. int coupling_postpointamp[PACKETBLOBS];
  110495. int sliding_lowpass[2][PACKETBLOBS];
  110496. } vorbis_info_psy_global;
  110497. typedef struct {
  110498. float ampmax;
  110499. int channels;
  110500. vorbis_info_psy_global *gi;
  110501. int coupling_pointlimit[2][P_NOISECURVES];
  110502. } vorbis_look_psy_global;
  110503. typedef struct {
  110504. int n;
  110505. struct vorbis_info_psy *vi;
  110506. float ***tonecurves;
  110507. float **noiseoffset;
  110508. float *ath;
  110509. long *octave; /* in n.ocshift format */
  110510. long *bark;
  110511. long firstoc;
  110512. long shiftoc;
  110513. int eighth_octave_lines; /* power of two, please */
  110514. int total_octave_lines;
  110515. long rate; /* cache it */
  110516. float m_val; /* Masking compensation value */
  110517. } vorbis_look_psy;
  110518. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110519. vorbis_info_psy_global *gi,int n,long rate);
  110520. extern void _vp_psy_clear(vorbis_look_psy *p);
  110521. extern void *_vi_psy_dup(void *source);
  110522. extern void _vi_psy_free(vorbis_info_psy *i);
  110523. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110524. extern void _vp_remove_floor(vorbis_look_psy *p,
  110525. float *mdct,
  110526. int *icodedflr,
  110527. float *residue,
  110528. int sliding_lowpass);
  110529. extern void _vp_noisemask(vorbis_look_psy *p,
  110530. float *logmdct,
  110531. float *logmask);
  110532. extern void _vp_tonemask(vorbis_look_psy *p,
  110533. float *logfft,
  110534. float *logmask,
  110535. float global_specmax,
  110536. float local_specmax);
  110537. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110538. float *noise,
  110539. float *tone,
  110540. int offset_select,
  110541. float *logmask,
  110542. float *mdct,
  110543. float *logmdct);
  110544. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110545. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110546. vorbis_info_psy_global *g,
  110547. vorbis_look_psy *p,
  110548. vorbis_info_mapping0 *vi,
  110549. float **mdct);
  110550. extern void _vp_couple(int blobno,
  110551. vorbis_info_psy_global *g,
  110552. vorbis_look_psy *p,
  110553. vorbis_info_mapping0 *vi,
  110554. float **res,
  110555. float **mag_memo,
  110556. int **mag_sort,
  110557. int **ifloor,
  110558. int *nonzero,
  110559. int sliding_lowpass);
  110560. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110561. float *in,float *out,int *sortedindex);
  110562. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110563. float *magnitudes,int *sortedindex);
  110564. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110565. vorbis_look_psy *p,
  110566. vorbis_info_mapping0 *vi,
  110567. float **mags);
  110568. extern void hf_reduction(vorbis_info_psy_global *g,
  110569. vorbis_look_psy *p,
  110570. vorbis_info_mapping0 *vi,
  110571. float **mdct);
  110572. #endif
  110573. /*** End of inlined file: psy.h ***/
  110574. /*** Start of inlined file: bitrate.h ***/
  110575. #ifndef _V_BITRATE_H_
  110576. #define _V_BITRATE_H_
  110577. /*** Start of inlined file: os.h ***/
  110578. #ifndef _OS_H
  110579. #define _OS_H
  110580. /********************************************************************
  110581. * *
  110582. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110583. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110584. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110585. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110586. * *
  110587. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110588. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110589. * *
  110590. ********************************************************************
  110591. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110592. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110593. ********************************************************************/
  110594. #ifdef HAVE_CONFIG_H
  110595. #include "config.h"
  110596. #endif
  110597. #include <math.h>
  110598. /*** Start of inlined file: misc.h ***/
  110599. #ifndef _V_RANDOM_H_
  110600. #define _V_RANDOM_H_
  110601. extern int analysis_noisy;
  110602. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110603. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110604. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110605. ogg_int64_t off);
  110606. #ifdef DEBUG_MALLOC
  110607. #define _VDBG_GRAPHFILE "malloc.m"
  110608. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110609. extern void _VDBG_free(void *ptr,char *file,long line);
  110610. #ifndef MISC_C
  110611. #undef _ogg_malloc
  110612. #undef _ogg_calloc
  110613. #undef _ogg_realloc
  110614. #undef _ogg_free
  110615. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110616. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110617. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110618. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110619. #endif
  110620. #endif
  110621. #endif
  110622. /*** End of inlined file: misc.h ***/
  110623. #ifndef _V_IFDEFJAIL_H_
  110624. # define _V_IFDEFJAIL_H_
  110625. # ifdef __GNUC__
  110626. # define STIN static __inline__
  110627. # elif _WIN32
  110628. # define STIN static __inline
  110629. # else
  110630. # define STIN static
  110631. # endif
  110632. #ifdef DJGPP
  110633. # define rint(x) (floor((x)+0.5f))
  110634. #endif
  110635. #ifndef M_PI
  110636. # define M_PI (3.1415926536f)
  110637. #endif
  110638. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110639. # include <malloc.h>
  110640. # define rint(x) (floor((x)+0.5f))
  110641. # define NO_FLOAT_MATH_LIB
  110642. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110643. #endif
  110644. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110645. void *_alloca(size_t size);
  110646. # define alloca _alloca
  110647. #endif
  110648. #ifndef FAST_HYPOT
  110649. # define FAST_HYPOT hypot
  110650. #endif
  110651. #endif
  110652. #ifdef HAVE_ALLOCA_H
  110653. # include <alloca.h>
  110654. #endif
  110655. #ifdef USE_MEMORY_H
  110656. # include <memory.h>
  110657. #endif
  110658. #ifndef min
  110659. # define min(x,y) ((x)>(y)?(y):(x))
  110660. #endif
  110661. #ifndef max
  110662. # define max(x,y) ((x)<(y)?(y):(x))
  110663. #endif
  110664. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110665. # define VORBIS_FPU_CONTROL
  110666. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110667. Because of encapsulation constraints (GCC can't see inside the asm
  110668. block and so we end up doing stupid things like a store/load that
  110669. is collectively a noop), we do it this way */
  110670. /* we must set up the fpu before this works!! */
  110671. typedef ogg_int16_t vorbis_fpu_control;
  110672. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110673. ogg_int16_t ret;
  110674. ogg_int16_t temp;
  110675. __asm__ __volatile__("fnstcw %0\n\t"
  110676. "movw %0,%%dx\n\t"
  110677. "orw $62463,%%dx\n\t"
  110678. "movw %%dx,%1\n\t"
  110679. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110680. *fpu=ret;
  110681. }
  110682. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110683. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110684. }
  110685. /* assumes the FPU is in round mode! */
  110686. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110687. we get extra fst/fld to
  110688. truncate precision */
  110689. int i;
  110690. __asm__("fistl %0": "=m"(i) : "t"(f));
  110691. return(i);
  110692. }
  110693. #endif
  110694. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110695. # define VORBIS_FPU_CONTROL
  110696. typedef ogg_int16_t vorbis_fpu_control;
  110697. static __inline int vorbis_ftoi(double f){
  110698. int i;
  110699. __asm{
  110700. fld f
  110701. fistp i
  110702. }
  110703. return i;
  110704. }
  110705. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110706. }
  110707. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110708. }
  110709. #endif
  110710. #ifndef VORBIS_FPU_CONTROL
  110711. typedef int vorbis_fpu_control;
  110712. static int vorbis_ftoi(double f){
  110713. return (int)(f+.5);
  110714. }
  110715. /* We don't have special code for this compiler/arch, so do it the slow way */
  110716. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110717. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110718. #endif
  110719. #endif /* _OS_H */
  110720. /*** End of inlined file: os.h ***/
  110721. /* encode side bitrate tracking */
  110722. typedef struct bitrate_manager_state {
  110723. int managed;
  110724. long avg_reservoir;
  110725. long minmax_reservoir;
  110726. long avg_bitsper;
  110727. long min_bitsper;
  110728. long max_bitsper;
  110729. long short_per_long;
  110730. double avgfloat;
  110731. vorbis_block *vb;
  110732. int choice;
  110733. } bitrate_manager_state;
  110734. typedef struct bitrate_manager_info{
  110735. long avg_rate;
  110736. long min_rate;
  110737. long max_rate;
  110738. long reservoir_bits;
  110739. double reservoir_bias;
  110740. double slew_damp;
  110741. } bitrate_manager_info;
  110742. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110743. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110744. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110745. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110746. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110747. #endif
  110748. /*** End of inlined file: bitrate.h ***/
  110749. static int ilog(unsigned int v){
  110750. int ret=0;
  110751. while(v){
  110752. ret++;
  110753. v>>=1;
  110754. }
  110755. return(ret);
  110756. }
  110757. static int ilog2(unsigned int v){
  110758. int ret=0;
  110759. if(v)--v;
  110760. while(v){
  110761. ret++;
  110762. v>>=1;
  110763. }
  110764. return(ret);
  110765. }
  110766. typedef struct private_state {
  110767. /* local lookup storage */
  110768. envelope_lookup *ve; /* envelope lookup */
  110769. int window[2];
  110770. vorbis_look_transform **transform[2]; /* block, type */
  110771. drft_lookup fft_look[2];
  110772. int modebits;
  110773. vorbis_look_floor **flr;
  110774. vorbis_look_residue **residue;
  110775. vorbis_look_psy *psy;
  110776. vorbis_look_psy_global *psy_g_look;
  110777. /* local storage, only used on the encoding side. This way the
  110778. application does not need to worry about freeing some packets'
  110779. memory and not others'; packet storage is always tracked.
  110780. Cleared next call to a _dsp_ function */
  110781. unsigned char *header;
  110782. unsigned char *header1;
  110783. unsigned char *header2;
  110784. bitrate_manager_state bms;
  110785. ogg_int64_t sample_count;
  110786. } private_state;
  110787. /* codec_setup_info contains all the setup information specific to the
  110788. specific compression/decompression mode in progress (eg,
  110789. psychoacoustic settings, channel setup, options, codebook
  110790. etc).
  110791. *********************************************************************/
  110792. /*** Start of inlined file: highlevel.h ***/
  110793. typedef struct highlevel_byblocktype {
  110794. double tone_mask_setting;
  110795. double tone_peaklimit_setting;
  110796. double noise_bias_setting;
  110797. double noise_compand_setting;
  110798. } highlevel_byblocktype;
  110799. typedef struct highlevel_encode_setup {
  110800. void *setup;
  110801. int set_in_stone;
  110802. double base_setting;
  110803. double long_setting;
  110804. double short_setting;
  110805. double impulse_noisetune;
  110806. int managed;
  110807. long bitrate_min;
  110808. long bitrate_av;
  110809. double bitrate_av_damp;
  110810. long bitrate_max;
  110811. long bitrate_reservoir;
  110812. double bitrate_reservoir_bias;
  110813. int impulse_block_p;
  110814. int noise_normalize_p;
  110815. double stereo_point_setting;
  110816. double lowpass_kHz;
  110817. double ath_floating_dB;
  110818. double ath_absolute_dB;
  110819. double amplitude_track_dBpersec;
  110820. double trigger_setting;
  110821. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110822. } highlevel_encode_setup;
  110823. /*** End of inlined file: highlevel.h ***/
  110824. typedef struct codec_setup_info {
  110825. /* Vorbis supports only short and long blocks, but allows the
  110826. encoder to choose the sizes */
  110827. long blocksizes[2];
  110828. /* modes are the primary means of supporting on-the-fly different
  110829. blocksizes, different channel mappings (LR or M/A),
  110830. different residue backends, etc. Each mode consists of a
  110831. blocksize flag and a mapping (along with the mapping setup */
  110832. int modes;
  110833. int maps;
  110834. int floors;
  110835. int residues;
  110836. int books;
  110837. int psys; /* encode only */
  110838. vorbis_info_mode *mode_param[64];
  110839. int map_type[64];
  110840. vorbis_info_mapping *map_param[64];
  110841. int floor_type[64];
  110842. vorbis_info_floor *floor_param[64];
  110843. int residue_type[64];
  110844. vorbis_info_residue *residue_param[64];
  110845. static_codebook *book_param[256];
  110846. codebook *fullbooks;
  110847. vorbis_info_psy *psy_param[4]; /* encode only */
  110848. vorbis_info_psy_global psy_g_param;
  110849. bitrate_manager_info bi;
  110850. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110851. highly redundant structure, but
  110852. improves clarity of program flow. */
  110853. int halfrate_flag; /* painless downsample for decode */
  110854. } codec_setup_info;
  110855. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110856. extern void _vp_global_free(vorbis_look_psy_global *look);
  110857. #endif
  110858. /*** End of inlined file: codec_internal.h ***/
  110859. /*** Start of inlined file: registry.h ***/
  110860. #ifndef _V_REG_H_
  110861. #define _V_REG_H_
  110862. #define VI_TRANSFORMB 1
  110863. #define VI_WINDOWB 1
  110864. #define VI_TIMEB 1
  110865. #define VI_FLOORB 2
  110866. #define VI_RESB 3
  110867. #define VI_MAPB 1
  110868. extern vorbis_func_floor *_floor_P[];
  110869. extern vorbis_func_residue *_residue_P[];
  110870. extern vorbis_func_mapping *_mapping_P[];
  110871. #endif
  110872. /*** End of inlined file: registry.h ***/
  110873. /*** Start of inlined file: scales.h ***/
  110874. #ifndef _V_SCALES_H_
  110875. #define _V_SCALES_H_
  110876. #include <math.h>
  110877. /* 20log10(x) */
  110878. #define VORBIS_IEEE_FLOAT32 1
  110879. #ifdef VORBIS_IEEE_FLOAT32
  110880. static float unitnorm(float x){
  110881. union {
  110882. ogg_uint32_t i;
  110883. float f;
  110884. } ix;
  110885. ix.f = x;
  110886. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110887. return ix.f;
  110888. }
  110889. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110890. static float todB(const float *x){
  110891. union {
  110892. ogg_uint32_t i;
  110893. float f;
  110894. } ix;
  110895. ix.f = *x;
  110896. ix.i = ix.i&0x7fffffff;
  110897. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110898. }
  110899. #define todB_nn(x) todB(x)
  110900. #else
  110901. static float unitnorm(float x){
  110902. if(x<0)return(-1.f);
  110903. return(1.f);
  110904. }
  110905. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110906. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110907. #endif
  110908. #define fromdB(x) (exp((x)*.11512925f))
  110909. /* The bark scale equations are approximations, since the original
  110910. table was somewhat hand rolled. The below are chosen to have the
  110911. best possible fit to the rolled tables, thus their somewhat odd
  110912. appearance (these are more accurate and over a longer range than
  110913. the oft-quoted bark equations found in the texts I have). The
  110914. approximations are valid from 0 - 30kHz (nyquist) or so.
  110915. all f in Hz, z in Bark */
  110916. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110917. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110918. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110919. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110920. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110921. 0.0 */
  110922. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110923. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110924. #endif
  110925. /*** End of inlined file: scales.h ***/
  110926. int analysis_noisy=1;
  110927. /* decides between modes, dispatches to the appropriate mapping. */
  110928. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110929. int ret,i;
  110930. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110931. vb->glue_bits=0;
  110932. vb->time_bits=0;
  110933. vb->floor_bits=0;
  110934. vb->res_bits=0;
  110935. /* first things first. Make sure encode is ready */
  110936. for(i=0;i<PACKETBLOBS;i++)
  110937. oggpack_reset(vbi->packetblob[i]);
  110938. /* we only have one mapping type (0), and we let the mapping code
  110939. itself figure out what soft mode to use. This allows easier
  110940. bitrate management */
  110941. if((ret=_mapping_P[0]->forward(vb)))
  110942. return(ret);
  110943. if(op){
  110944. if(vorbis_bitrate_managed(vb))
  110945. /* The app is using a bitmanaged mode... but not using the
  110946. bitrate management interface. */
  110947. return(OV_EINVAL);
  110948. op->packet=oggpack_get_buffer(&vb->opb);
  110949. op->bytes=oggpack_bytes(&vb->opb);
  110950. op->b_o_s=0;
  110951. op->e_o_s=vb->eofflag;
  110952. op->granulepos=vb->granulepos;
  110953. op->packetno=vb->sequence; /* for sake of completeness */
  110954. }
  110955. return(0);
  110956. }
  110957. /* there was no great place to put this.... */
  110958. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110959. int j;
  110960. FILE *of;
  110961. char buffer[80];
  110962. /* if(i==5870){*/
  110963. sprintf(buffer,"%s_%d.m",base,i);
  110964. of=fopen(buffer,"w");
  110965. if(!of)perror("failed to open data dump file");
  110966. for(j=0;j<n;j++){
  110967. if(bark){
  110968. float b=toBARK((4000.f*j/n)+.25);
  110969. fprintf(of,"%f ",b);
  110970. }else
  110971. if(off!=0)
  110972. fprintf(of,"%f ",(double)(j+off)/8000.);
  110973. else
  110974. fprintf(of,"%f ",(double)j);
  110975. if(dB){
  110976. float val;
  110977. if(v[j]==0.)
  110978. val=-140.;
  110979. else
  110980. val=todB(v+j);
  110981. fprintf(of,"%f\n",val);
  110982. }else{
  110983. fprintf(of,"%f\n",v[j]);
  110984. }
  110985. }
  110986. fclose(of);
  110987. /* } */
  110988. }
  110989. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110990. ogg_int64_t off){
  110991. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110992. }
  110993. #endif
  110994. /*** End of inlined file: analysis.c ***/
  110995. /*** Start of inlined file: bitrate.c ***/
  110996. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110997. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110998. // tasks..
  110999. #if JUCE_MSVC
  111000. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111001. #endif
  111002. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111003. #if JUCE_USE_OGGVORBIS
  111004. #include <stdlib.h>
  111005. #include <string.h>
  111006. #include <math.h>
  111007. /* compute bitrate tracking setup */
  111008. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  111009. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111010. bitrate_manager_info *bi=&ci->bi;
  111011. memset(bm,0,sizeof(*bm));
  111012. if(bi && (bi->reservoir_bits>0)){
  111013. long ratesamples=vi->rate;
  111014. int halfsamples=ci->blocksizes[0]>>1;
  111015. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  111016. bm->managed=1;
  111017. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  111018. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  111019. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  111020. bm->avgfloat=PACKETBLOBS/2;
  111021. /* not a necessary fix, but one that leads to a more balanced
  111022. typical initialization */
  111023. {
  111024. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111025. bm->minmax_reservoir=desired_fill;
  111026. bm->avg_reservoir=desired_fill;
  111027. }
  111028. }
  111029. }
  111030. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  111031. memset(bm,0,sizeof(*bm));
  111032. return;
  111033. }
  111034. int vorbis_bitrate_managed(vorbis_block *vb){
  111035. vorbis_dsp_state *vd=vb->vd;
  111036. private_state *b=(private_state*)vd->backend_state;
  111037. bitrate_manager_state *bm=&b->bms;
  111038. if(bm && bm->managed)return(1);
  111039. return(0);
  111040. }
  111041. /* finish taking in the block we just processed */
  111042. int vorbis_bitrate_addblock(vorbis_block *vb){
  111043. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111044. vorbis_dsp_state *vd=vb->vd;
  111045. private_state *b=(private_state*)vd->backend_state;
  111046. bitrate_manager_state *bm=&b->bms;
  111047. vorbis_info *vi=vd->vi;
  111048. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111049. bitrate_manager_info *bi=&ci->bi;
  111050. int choice=rint(bm->avgfloat);
  111051. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111052. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  111053. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  111054. int samples=ci->blocksizes[vb->W]>>1;
  111055. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111056. if(!bm->managed){
  111057. /* not a bitrate managed stream, but for API simplicity, we'll
  111058. buffer the packet to keep the code path clean */
  111059. if(bm->vb)return(-1); /* one has been submitted without
  111060. being claimed */
  111061. bm->vb=vb;
  111062. return(0);
  111063. }
  111064. bm->vb=vb;
  111065. /* look ahead for avg floater */
  111066. if(bm->avg_bitsper>0){
  111067. double slew=0.;
  111068. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111069. double slewlimit= 15./bi->slew_damp;
  111070. /* choosing a new floater:
  111071. if we're over target, we slew down
  111072. if we're under target, we slew up
  111073. choose slew as follows: look through packetblobs of this frame
  111074. and set slew as the first in the appropriate direction that
  111075. gives us the slew we want. This may mean no slew if delta is
  111076. already favorable.
  111077. Then limit slew to slew max */
  111078. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111079. while(choice>0 && this_bits>avg_target_bits &&
  111080. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111081. choice--;
  111082. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111083. }
  111084. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111085. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  111086. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111087. choice++;
  111088. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111089. }
  111090. }
  111091. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  111092. if(slew<-slewlimit)slew=-slewlimit;
  111093. if(slew>slewlimit)slew=slewlimit;
  111094. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  111095. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111096. }
  111097. /* enforce min(if used) on the current floater (if used) */
  111098. if(bm->min_bitsper>0){
  111099. /* do we need to force the bitrate up? */
  111100. if(this_bits<min_target_bits){
  111101. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  111102. choice++;
  111103. if(choice>=PACKETBLOBS)break;
  111104. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111105. }
  111106. }
  111107. }
  111108. /* enforce max (if used) on the current floater (if used) */
  111109. if(bm->max_bitsper>0){
  111110. /* do we need to force the bitrate down? */
  111111. if(this_bits>max_target_bits){
  111112. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  111113. choice--;
  111114. if(choice<0)break;
  111115. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111116. }
  111117. }
  111118. }
  111119. /* Choice of packetblobs now made based on floater, and min/max
  111120. requirements. Now boundary check extreme choices */
  111121. if(choice<0){
  111122. /* choosing a smaller packetblob is insufficient to trim bitrate.
  111123. frame will need to be truncated */
  111124. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  111125. bm->choice=choice=0;
  111126. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  111127. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  111128. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111129. }
  111130. }else{
  111131. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  111132. if(choice>=PACKETBLOBS)
  111133. choice=PACKETBLOBS-1;
  111134. bm->choice=choice;
  111135. /* prop up bitrate according to demand. pad this frame out with zeroes */
  111136. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  111137. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  111138. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111139. }
  111140. /* now we have the final packet and the final packet size. Update statistics */
  111141. /* min and max reservoir */
  111142. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  111143. if(max_target_bits>0 && this_bits>max_target_bits){
  111144. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111145. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111146. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111147. }else{
  111148. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111149. if(bm->minmax_reservoir>desired_fill){
  111150. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111151. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111152. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111153. }else{
  111154. bm->minmax_reservoir=desired_fill;
  111155. }
  111156. }else{
  111157. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111158. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111159. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111160. }else{
  111161. bm->minmax_reservoir=desired_fill;
  111162. }
  111163. }
  111164. }
  111165. }
  111166. /* avg reservoir */
  111167. if(bm->avg_bitsper>0){
  111168. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111169. bm->avg_reservoir+=this_bits-avg_target_bits;
  111170. }
  111171. return(0);
  111172. }
  111173. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111174. private_state *b=(private_state*)vd->backend_state;
  111175. bitrate_manager_state *bm=&b->bms;
  111176. vorbis_block *vb=bm->vb;
  111177. int choice=PACKETBLOBS/2;
  111178. if(!vb)return 0;
  111179. if(op){
  111180. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111181. if(vorbis_bitrate_managed(vb))
  111182. choice=bm->choice;
  111183. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111184. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111185. op->b_o_s=0;
  111186. op->e_o_s=vb->eofflag;
  111187. op->granulepos=vb->granulepos;
  111188. op->packetno=vb->sequence; /* for sake of completeness */
  111189. }
  111190. bm->vb=0;
  111191. return(1);
  111192. }
  111193. #endif
  111194. /*** End of inlined file: bitrate.c ***/
  111195. /*** Start of inlined file: block.c ***/
  111196. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111197. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111198. // tasks..
  111199. #if JUCE_MSVC
  111200. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111201. #endif
  111202. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111203. #if JUCE_USE_OGGVORBIS
  111204. #include <stdio.h>
  111205. #include <stdlib.h>
  111206. #include <string.h>
  111207. /*** Start of inlined file: window.h ***/
  111208. #ifndef _V_WINDOW_
  111209. #define _V_WINDOW_
  111210. extern float *_vorbis_window_get(int n);
  111211. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111212. int lW,int W,int nW);
  111213. #endif
  111214. /*** End of inlined file: window.h ***/
  111215. /*** Start of inlined file: lpc.h ***/
  111216. #ifndef _V_LPC_H_
  111217. #define _V_LPC_H_
  111218. /* simple linear scale LPC code */
  111219. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111220. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111221. float *data,long n);
  111222. #endif
  111223. /*** End of inlined file: lpc.h ***/
  111224. /* pcm accumulator examples (not exhaustive):
  111225. <-------------- lW ---------------->
  111226. <--------------- W ---------------->
  111227. : .....|..... _______________ |
  111228. : .''' | '''_--- | |\ |
  111229. :.....''' |_____--- '''......| | \_______|
  111230. :.................|__________________|_______|__|______|
  111231. |<------ Sl ------>| > Sr < |endW
  111232. |beginSl |endSl | |endSr
  111233. |beginW |endlW |beginSr
  111234. |< lW >|
  111235. <--------------- W ---------------->
  111236. | | .. ______________ |
  111237. | | ' `/ | ---_ |
  111238. |___.'___/`. | ---_____|
  111239. |_______|__|_______|_________________|
  111240. | >|Sl|< |<------ Sr ----->|endW
  111241. | | |endSl |beginSr |endSr
  111242. |beginW | |endlW
  111243. mult[0] |beginSl mult[n]
  111244. <-------------- lW ----------------->
  111245. |<--W-->|
  111246. : .............. ___ | |
  111247. : .''' |`/ \ | |
  111248. :.....''' |/`....\|...|
  111249. :.........................|___|___|___|
  111250. |Sl |Sr |endW
  111251. | | |endSr
  111252. | |beginSr
  111253. | |endSl
  111254. |beginSl
  111255. |beginW
  111256. */
  111257. /* block abstraction setup *********************************************/
  111258. #ifndef WORD_ALIGN
  111259. #define WORD_ALIGN 8
  111260. #endif
  111261. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111262. int i;
  111263. memset(vb,0,sizeof(*vb));
  111264. vb->vd=v;
  111265. vb->localalloc=0;
  111266. vb->localstore=NULL;
  111267. if(v->analysisp){
  111268. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111269. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111270. vbi->ampmax=-9999;
  111271. for(i=0;i<PACKETBLOBS;i++){
  111272. if(i==PACKETBLOBS/2){
  111273. vbi->packetblob[i]=&vb->opb;
  111274. }else{
  111275. vbi->packetblob[i]=
  111276. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111277. }
  111278. oggpack_writeinit(vbi->packetblob[i]);
  111279. }
  111280. }
  111281. return(0);
  111282. }
  111283. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111284. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111285. if(bytes+vb->localtop>vb->localalloc){
  111286. /* can't just _ogg_realloc... there are outstanding pointers */
  111287. if(vb->localstore){
  111288. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111289. vb->totaluse+=vb->localtop;
  111290. link->next=vb->reap;
  111291. link->ptr=vb->localstore;
  111292. vb->reap=link;
  111293. }
  111294. /* highly conservative */
  111295. vb->localalloc=bytes;
  111296. vb->localstore=_ogg_malloc(vb->localalloc);
  111297. vb->localtop=0;
  111298. }
  111299. {
  111300. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111301. vb->localtop+=bytes;
  111302. return ret;
  111303. }
  111304. }
  111305. /* reap the chain, pull the ripcord */
  111306. void _vorbis_block_ripcord(vorbis_block *vb){
  111307. /* reap the chain */
  111308. struct alloc_chain *reap=vb->reap;
  111309. while(reap){
  111310. struct alloc_chain *next=reap->next;
  111311. _ogg_free(reap->ptr);
  111312. memset(reap,0,sizeof(*reap));
  111313. _ogg_free(reap);
  111314. reap=next;
  111315. }
  111316. /* consolidate storage */
  111317. if(vb->totaluse){
  111318. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111319. vb->localalloc+=vb->totaluse;
  111320. vb->totaluse=0;
  111321. }
  111322. /* pull the ripcord */
  111323. vb->localtop=0;
  111324. vb->reap=NULL;
  111325. }
  111326. int vorbis_block_clear(vorbis_block *vb){
  111327. int i;
  111328. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111329. _vorbis_block_ripcord(vb);
  111330. if(vb->localstore)_ogg_free(vb->localstore);
  111331. if(vbi){
  111332. for(i=0;i<PACKETBLOBS;i++){
  111333. oggpack_writeclear(vbi->packetblob[i]);
  111334. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111335. }
  111336. _ogg_free(vbi);
  111337. }
  111338. memset(vb,0,sizeof(*vb));
  111339. return(0);
  111340. }
  111341. /* Analysis side code, but directly related to blocking. Thus it's
  111342. here and not in analysis.c (which is for analysis transforms only).
  111343. The init is here because some of it is shared */
  111344. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111345. int i;
  111346. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111347. private_state *b=NULL;
  111348. int hs;
  111349. if(ci==NULL) return 1;
  111350. hs=ci->halfrate_flag;
  111351. memset(v,0,sizeof(*v));
  111352. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111353. v->vi=vi;
  111354. b->modebits=ilog2(ci->modes);
  111355. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111356. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111357. /* MDCT is tranform 0 */
  111358. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111359. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111360. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111361. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111362. /* Vorbis I uses only window type 0 */
  111363. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111364. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111365. if(encp){ /* encode/decode differ here */
  111366. /* analysis always needs an fft */
  111367. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111368. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111369. /* finish the codebooks */
  111370. if(!ci->fullbooks){
  111371. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111372. for(i=0;i<ci->books;i++)
  111373. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111374. }
  111375. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111376. for(i=0;i<ci->psys;i++){
  111377. _vp_psy_init(b->psy+i,
  111378. ci->psy_param[i],
  111379. &ci->psy_g_param,
  111380. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111381. vi->rate);
  111382. }
  111383. v->analysisp=1;
  111384. }else{
  111385. /* finish the codebooks */
  111386. if(!ci->fullbooks){
  111387. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111388. for(i=0;i<ci->books;i++){
  111389. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111390. /* decode codebooks are now standalone after init */
  111391. vorbis_staticbook_destroy(ci->book_param[i]);
  111392. ci->book_param[i]=NULL;
  111393. }
  111394. }
  111395. }
  111396. /* initialize the storage vectors. blocksize[1] is small for encode,
  111397. but the correct size for decode */
  111398. v->pcm_storage=ci->blocksizes[1];
  111399. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111400. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111401. {
  111402. int i;
  111403. for(i=0;i<vi->channels;i++)
  111404. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111405. }
  111406. /* all 1 (large block) or 0 (small block) */
  111407. /* explicitly set for the sake of clarity */
  111408. v->lW=0; /* previous window size */
  111409. v->W=0; /* current window size */
  111410. /* all vector indexes */
  111411. v->centerW=ci->blocksizes[1]/2;
  111412. v->pcm_current=v->centerW;
  111413. /* initialize all the backend lookups */
  111414. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111415. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111416. for(i=0;i<ci->floors;i++)
  111417. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111418. look(v,ci->floor_param[i]);
  111419. for(i=0;i<ci->residues;i++)
  111420. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111421. look(v,ci->residue_param[i]);
  111422. return 0;
  111423. }
  111424. /* arbitrary settings and spec-mandated numbers get filled in here */
  111425. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111426. private_state *b=NULL;
  111427. if(_vds_shared_init(v,vi,1))return 1;
  111428. b=(private_state*)v->backend_state;
  111429. b->psy_g_look=_vp_global_look(vi);
  111430. /* Initialize the envelope state storage */
  111431. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111432. _ve_envelope_init(b->ve,vi);
  111433. vorbis_bitrate_init(vi,&b->bms);
  111434. /* compressed audio packets start after the headers
  111435. with sequence number 3 */
  111436. v->sequence=3;
  111437. return(0);
  111438. }
  111439. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111440. int i;
  111441. if(v){
  111442. vorbis_info *vi=v->vi;
  111443. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111444. private_state *b=(private_state*)v->backend_state;
  111445. if(b){
  111446. if(b->ve){
  111447. _ve_envelope_clear(b->ve);
  111448. _ogg_free(b->ve);
  111449. }
  111450. if(b->transform[0]){
  111451. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111452. _ogg_free(b->transform[0][0]);
  111453. _ogg_free(b->transform[0]);
  111454. }
  111455. if(b->transform[1]){
  111456. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111457. _ogg_free(b->transform[1][0]);
  111458. _ogg_free(b->transform[1]);
  111459. }
  111460. if(b->flr){
  111461. for(i=0;i<ci->floors;i++)
  111462. _floor_P[ci->floor_type[i]]->
  111463. free_look(b->flr[i]);
  111464. _ogg_free(b->flr);
  111465. }
  111466. if(b->residue){
  111467. for(i=0;i<ci->residues;i++)
  111468. _residue_P[ci->residue_type[i]]->
  111469. free_look(b->residue[i]);
  111470. _ogg_free(b->residue);
  111471. }
  111472. if(b->psy){
  111473. for(i=0;i<ci->psys;i++)
  111474. _vp_psy_clear(b->psy+i);
  111475. _ogg_free(b->psy);
  111476. }
  111477. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111478. vorbis_bitrate_clear(&b->bms);
  111479. drft_clear(&b->fft_look[0]);
  111480. drft_clear(&b->fft_look[1]);
  111481. }
  111482. if(v->pcm){
  111483. for(i=0;i<vi->channels;i++)
  111484. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111485. _ogg_free(v->pcm);
  111486. if(v->pcmret)_ogg_free(v->pcmret);
  111487. }
  111488. if(b){
  111489. /* free header, header1, header2 */
  111490. if(b->header)_ogg_free(b->header);
  111491. if(b->header1)_ogg_free(b->header1);
  111492. if(b->header2)_ogg_free(b->header2);
  111493. _ogg_free(b);
  111494. }
  111495. memset(v,0,sizeof(*v));
  111496. }
  111497. }
  111498. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111499. int i;
  111500. vorbis_info *vi=v->vi;
  111501. private_state *b=(private_state*)v->backend_state;
  111502. /* free header, header1, header2 */
  111503. if(b->header)_ogg_free(b->header);b->header=NULL;
  111504. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111505. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111506. /* Do we have enough storage space for the requested buffer? If not,
  111507. expand the PCM (and envelope) storage */
  111508. if(v->pcm_current+vals>=v->pcm_storage){
  111509. v->pcm_storage=v->pcm_current+vals*2;
  111510. for(i=0;i<vi->channels;i++){
  111511. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111512. }
  111513. }
  111514. for(i=0;i<vi->channels;i++)
  111515. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111516. return(v->pcmret);
  111517. }
  111518. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111519. int i;
  111520. int order=32;
  111521. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111522. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111523. long j;
  111524. v->preextrapolate=1;
  111525. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111526. for(i=0;i<v->vi->channels;i++){
  111527. /* need to run the extrapolation in reverse! */
  111528. for(j=0;j<v->pcm_current;j++)
  111529. work[j]=v->pcm[i][v->pcm_current-j-1];
  111530. /* prime as above */
  111531. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111532. /* run the predictor filter */
  111533. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111534. order,
  111535. work+v->pcm_current-v->centerW,
  111536. v->centerW);
  111537. for(j=0;j<v->pcm_current;j++)
  111538. v->pcm[i][v->pcm_current-j-1]=work[j];
  111539. }
  111540. }
  111541. }
  111542. /* call with val<=0 to set eof */
  111543. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111544. vorbis_info *vi=v->vi;
  111545. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111546. if(vals<=0){
  111547. int order=32;
  111548. int i;
  111549. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111550. /* if it wasn't done earlier (very short sample) */
  111551. if(!v->preextrapolate)
  111552. _preextrapolate_helper(v);
  111553. /* We're encoding the end of the stream. Just make sure we have
  111554. [at least] a few full blocks of zeroes at the end. */
  111555. /* actually, we don't want zeroes; that could drop a large
  111556. amplitude off a cliff, creating spread spectrum noise that will
  111557. suck to encode. Extrapolate for the sake of cleanliness. */
  111558. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111559. v->eofflag=v->pcm_current;
  111560. v->pcm_current+=ci->blocksizes[1]*3;
  111561. for(i=0;i<vi->channels;i++){
  111562. if(v->eofflag>order*2){
  111563. /* extrapolate with LPC to fill in */
  111564. long n;
  111565. /* make a predictor filter */
  111566. n=v->eofflag;
  111567. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111568. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111569. /* run the predictor filter */
  111570. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111571. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111572. }else{
  111573. /* not enough data to extrapolate (unlikely to happen due to
  111574. guarding the overlap, but bulletproof in case that
  111575. assumtion goes away). zeroes will do. */
  111576. memset(v->pcm[i]+v->eofflag,0,
  111577. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111578. }
  111579. }
  111580. }else{
  111581. if(v->pcm_current+vals>v->pcm_storage)
  111582. return(OV_EINVAL);
  111583. v->pcm_current+=vals;
  111584. /* we may want to reverse extrapolate the beginning of a stream
  111585. too... in case we're beginning on a cliff! */
  111586. /* clumsy, but simple. It only runs once, so simple is good. */
  111587. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111588. _preextrapolate_helper(v);
  111589. }
  111590. return(0);
  111591. }
  111592. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111593. the next block on which to continue analysis */
  111594. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111595. int i;
  111596. vorbis_info *vi=v->vi;
  111597. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111598. private_state *b=(private_state*)v->backend_state;
  111599. vorbis_look_psy_global *g=b->psy_g_look;
  111600. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111601. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111602. /* check to see if we're started... */
  111603. if(!v->preextrapolate)return(0);
  111604. /* check to see if we're done... */
  111605. if(v->eofflag==-1)return(0);
  111606. /* By our invariant, we have lW, W and centerW set. Search for
  111607. the next boundary so we can determine nW (the next window size)
  111608. which lets us compute the shape of the current block's window */
  111609. /* we do an envelope search even on a single blocksize; we may still
  111610. be throwing more bits at impulses, and envelope search handles
  111611. marking impulses too. */
  111612. {
  111613. long bp=_ve_envelope_search(v);
  111614. if(bp==-1){
  111615. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111616. full long block */
  111617. v->nW=0;
  111618. }else{
  111619. if(ci->blocksizes[0]==ci->blocksizes[1])
  111620. v->nW=0;
  111621. else
  111622. v->nW=bp;
  111623. }
  111624. }
  111625. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111626. {
  111627. /* center of next block + next block maximum right side. */
  111628. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111629. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111630. although this check is
  111631. less strict that the
  111632. _ve_envelope_search,
  111633. the search is not run
  111634. if we only use one
  111635. block size */
  111636. }
  111637. /* fill in the block. Note that for a short window, lW and nW are *short*
  111638. regardless of actual settings in the stream */
  111639. _vorbis_block_ripcord(vb);
  111640. vb->lW=v->lW;
  111641. vb->W=v->W;
  111642. vb->nW=v->nW;
  111643. if(v->W){
  111644. if(!v->lW || !v->nW){
  111645. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111646. /*fprintf(stderr,"-");*/
  111647. }else{
  111648. vbi->blocktype=BLOCKTYPE_LONG;
  111649. /*fprintf(stderr,"_");*/
  111650. }
  111651. }else{
  111652. if(_ve_envelope_mark(v)){
  111653. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111654. /*fprintf(stderr,"|");*/
  111655. }else{
  111656. vbi->blocktype=BLOCKTYPE_PADDING;
  111657. /*fprintf(stderr,".");*/
  111658. }
  111659. }
  111660. vb->vd=v;
  111661. vb->sequence=v->sequence++;
  111662. vb->granulepos=v->granulepos;
  111663. vb->pcmend=ci->blocksizes[v->W];
  111664. /* copy the vectors; this uses the local storage in vb */
  111665. /* this tracks 'strongest peak' for later psychoacoustics */
  111666. /* moved to the global psy state; clean this mess up */
  111667. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111668. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111669. vbi->ampmax=g->ampmax;
  111670. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111671. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111672. for(i=0;i<vi->channels;i++){
  111673. vbi->pcmdelay[i]=
  111674. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111675. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111676. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111677. /* before we added the delay
  111678. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111679. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111680. */
  111681. }
  111682. /* handle eof detection: eof==0 means that we've not yet received EOF
  111683. eof>0 marks the last 'real' sample in pcm[]
  111684. eof<0 'no more to do'; doesn't get here */
  111685. if(v->eofflag){
  111686. if(v->centerW>=v->eofflag){
  111687. v->eofflag=-1;
  111688. vb->eofflag=1;
  111689. return(1);
  111690. }
  111691. }
  111692. /* advance storage vectors and clean up */
  111693. {
  111694. int new_centerNext=ci->blocksizes[1]/2;
  111695. int movementW=centerNext-new_centerNext;
  111696. if(movementW>0){
  111697. _ve_envelope_shift(b->ve,movementW);
  111698. v->pcm_current-=movementW;
  111699. for(i=0;i<vi->channels;i++)
  111700. memmove(v->pcm[i],v->pcm[i]+movementW,
  111701. v->pcm_current*sizeof(*v->pcm[i]));
  111702. v->lW=v->W;
  111703. v->W=v->nW;
  111704. v->centerW=new_centerNext;
  111705. if(v->eofflag){
  111706. v->eofflag-=movementW;
  111707. if(v->eofflag<=0)v->eofflag=-1;
  111708. /* do not add padding to end of stream! */
  111709. if(v->centerW>=v->eofflag){
  111710. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111711. }else{
  111712. v->granulepos+=movementW;
  111713. }
  111714. }else{
  111715. v->granulepos+=movementW;
  111716. }
  111717. }
  111718. }
  111719. /* done */
  111720. return(1);
  111721. }
  111722. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111723. vorbis_info *vi=v->vi;
  111724. codec_setup_info *ci;
  111725. int hs;
  111726. if(!v->backend_state)return -1;
  111727. if(!vi)return -1;
  111728. ci=(codec_setup_info*) vi->codec_setup;
  111729. if(!ci)return -1;
  111730. hs=ci->halfrate_flag;
  111731. v->centerW=ci->blocksizes[1]>>(hs+1);
  111732. v->pcm_current=v->centerW>>hs;
  111733. v->pcm_returned=-1;
  111734. v->granulepos=-1;
  111735. v->sequence=-1;
  111736. v->eofflag=0;
  111737. ((private_state *)(v->backend_state))->sample_count=-1;
  111738. return(0);
  111739. }
  111740. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111741. if(_vds_shared_init(v,vi,0)) return 1;
  111742. vorbis_synthesis_restart(v);
  111743. return 0;
  111744. }
  111745. /* Unlike in analysis, the window is only partially applied for each
  111746. block. The time domain envelope is not yet handled at the point of
  111747. calling (as it relies on the previous block). */
  111748. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111749. vorbis_info *vi=v->vi;
  111750. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111751. private_state *b=(private_state*)v->backend_state;
  111752. int hs=ci->halfrate_flag;
  111753. int i,j;
  111754. if(!vb)return(OV_EINVAL);
  111755. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111756. v->lW=v->W;
  111757. v->W=vb->W;
  111758. v->nW=-1;
  111759. if((v->sequence==-1)||
  111760. (v->sequence+1 != vb->sequence)){
  111761. v->granulepos=-1; /* out of sequence; lose count */
  111762. b->sample_count=-1;
  111763. }
  111764. v->sequence=vb->sequence;
  111765. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111766. was called on block */
  111767. int n=ci->blocksizes[v->W]>>(hs+1);
  111768. int n0=ci->blocksizes[0]>>(hs+1);
  111769. int n1=ci->blocksizes[1]>>(hs+1);
  111770. int thisCenter;
  111771. int prevCenter;
  111772. v->glue_bits+=vb->glue_bits;
  111773. v->time_bits+=vb->time_bits;
  111774. v->floor_bits+=vb->floor_bits;
  111775. v->res_bits+=vb->res_bits;
  111776. if(v->centerW){
  111777. thisCenter=n1;
  111778. prevCenter=0;
  111779. }else{
  111780. thisCenter=0;
  111781. prevCenter=n1;
  111782. }
  111783. /* v->pcm is now used like a two-stage double buffer. We don't want
  111784. to have to constantly shift *or* adjust memory usage. Don't
  111785. accept a new block until the old is shifted out */
  111786. for(j=0;j<vi->channels;j++){
  111787. /* the overlap/add section */
  111788. if(v->lW){
  111789. if(v->W){
  111790. /* large/large */
  111791. float *w=_vorbis_window_get(b->window[1]-hs);
  111792. float *pcm=v->pcm[j]+prevCenter;
  111793. float *p=vb->pcm[j];
  111794. for(i=0;i<n1;i++)
  111795. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111796. }else{
  111797. /* large/small */
  111798. float *w=_vorbis_window_get(b->window[0]-hs);
  111799. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111800. float *p=vb->pcm[j];
  111801. for(i=0;i<n0;i++)
  111802. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111803. }
  111804. }else{
  111805. if(v->W){
  111806. /* small/large */
  111807. float *w=_vorbis_window_get(b->window[0]-hs);
  111808. float *pcm=v->pcm[j]+prevCenter;
  111809. float *p=vb->pcm[j]+n1/2-n0/2;
  111810. for(i=0;i<n0;i++)
  111811. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111812. for(;i<n1/2+n0/2;i++)
  111813. pcm[i]=p[i];
  111814. }else{
  111815. /* small/small */
  111816. float *w=_vorbis_window_get(b->window[0]-hs);
  111817. float *pcm=v->pcm[j]+prevCenter;
  111818. float *p=vb->pcm[j];
  111819. for(i=0;i<n0;i++)
  111820. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111821. }
  111822. }
  111823. /* the copy section */
  111824. {
  111825. float *pcm=v->pcm[j]+thisCenter;
  111826. float *p=vb->pcm[j]+n;
  111827. for(i=0;i<n;i++)
  111828. pcm[i]=p[i];
  111829. }
  111830. }
  111831. if(v->centerW)
  111832. v->centerW=0;
  111833. else
  111834. v->centerW=n1;
  111835. /* deal with initial packet state; we do this using the explicit
  111836. pcm_returned==-1 flag otherwise we're sensitive to first block
  111837. being short or long */
  111838. if(v->pcm_returned==-1){
  111839. v->pcm_returned=thisCenter;
  111840. v->pcm_current=thisCenter;
  111841. }else{
  111842. v->pcm_returned=prevCenter;
  111843. v->pcm_current=prevCenter+
  111844. ((ci->blocksizes[v->lW]/4+
  111845. ci->blocksizes[v->W]/4)>>hs);
  111846. }
  111847. }
  111848. /* track the frame number... This is for convenience, but also
  111849. making sure our last packet doesn't end with added padding. If
  111850. the last packet is partial, the number of samples we'll have to
  111851. return will be past the vb->granulepos.
  111852. This is not foolproof! It will be confused if we begin
  111853. decoding at the last page after a seek or hole. In that case,
  111854. we don't have a starting point to judge where the last frame
  111855. is. For this reason, vorbisfile will always try to make sure
  111856. it reads the last two marked pages in proper sequence */
  111857. if(b->sample_count==-1){
  111858. b->sample_count=0;
  111859. }else{
  111860. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111861. }
  111862. if(v->granulepos==-1){
  111863. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111864. v->granulepos=vb->granulepos;
  111865. /* is this a short page? */
  111866. if(b->sample_count>v->granulepos){
  111867. /* corner case; if this is both the first and last audio page,
  111868. then spec says the end is cut, not beginning */
  111869. if(vb->eofflag){
  111870. /* trim the end */
  111871. /* no preceeding granulepos; assume we started at zero (we'd
  111872. have to in a short single-page stream) */
  111873. /* granulepos could be -1 due to a seek, but that would result
  111874. in a long count, not short count */
  111875. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111876. }else{
  111877. /* trim the beginning */
  111878. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111879. if(v->pcm_returned>v->pcm_current)
  111880. v->pcm_returned=v->pcm_current;
  111881. }
  111882. }
  111883. }
  111884. }else{
  111885. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111886. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111887. if(v->granulepos>vb->granulepos){
  111888. long extra=v->granulepos-vb->granulepos;
  111889. if(extra)
  111890. if(vb->eofflag){
  111891. /* partial last frame. Strip the extra samples off */
  111892. v->pcm_current-=extra>>hs;
  111893. } /* else {Shouldn't happen *unless* the bitstream is out of
  111894. spec. Either way, believe the bitstream } */
  111895. } /* else {Shouldn't happen *unless* the bitstream is out of
  111896. spec. Either way, believe the bitstream } */
  111897. v->granulepos=vb->granulepos;
  111898. }
  111899. }
  111900. /* Update, cleanup */
  111901. if(vb->eofflag)v->eofflag=1;
  111902. return(0);
  111903. }
  111904. /* pcm==NULL indicates we just want the pending samples, no more */
  111905. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111906. vorbis_info *vi=v->vi;
  111907. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111908. if(pcm){
  111909. int i;
  111910. for(i=0;i<vi->channels;i++)
  111911. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111912. *pcm=v->pcmret;
  111913. }
  111914. return(v->pcm_current-v->pcm_returned);
  111915. }
  111916. return(0);
  111917. }
  111918. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111919. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111920. v->pcm_returned+=n;
  111921. return(0);
  111922. }
  111923. /* intended for use with a specific vorbisfile feature; we want access
  111924. to the [usually synthetic/postextrapolated] buffer and lapping at
  111925. the end of a decode cycle, specifically, a half-short-block worth.
  111926. This funtion works like pcmout above, except it will also expose
  111927. this implicit buffer data not normally decoded. */
  111928. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111929. vorbis_info *vi=v->vi;
  111930. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111931. int hs=ci->halfrate_flag;
  111932. int n=ci->blocksizes[v->W]>>(hs+1);
  111933. int n0=ci->blocksizes[0]>>(hs+1);
  111934. int n1=ci->blocksizes[1]>>(hs+1);
  111935. int i,j;
  111936. if(v->pcm_returned<0)return 0;
  111937. /* our returned data ends at pcm_returned; because the synthesis pcm
  111938. buffer is a two-fragment ring, that means our data block may be
  111939. fragmented by buffering, wrapping or a short block not filling
  111940. out a buffer. To simplify things, we unfragment if it's at all
  111941. possibly needed. Otherwise, we'd need to call lapout more than
  111942. once as well as hold additional dsp state. Opt for
  111943. simplicity. */
  111944. /* centerW was advanced by blockin; it would be the center of the
  111945. *next* block */
  111946. if(v->centerW==n1){
  111947. /* the data buffer wraps; swap the halves */
  111948. /* slow, sure, small */
  111949. for(j=0;j<vi->channels;j++){
  111950. float *p=v->pcm[j];
  111951. for(i=0;i<n1;i++){
  111952. float temp=p[i];
  111953. p[i]=p[i+n1];
  111954. p[i+n1]=temp;
  111955. }
  111956. }
  111957. v->pcm_current-=n1;
  111958. v->pcm_returned-=n1;
  111959. v->centerW=0;
  111960. }
  111961. /* solidify buffer into contiguous space */
  111962. if((v->lW^v->W)==1){
  111963. /* long/short or short/long */
  111964. for(j=0;j<vi->channels;j++){
  111965. float *s=v->pcm[j];
  111966. float *d=v->pcm[j]+(n1-n0)/2;
  111967. for(i=(n1+n0)/2-1;i>=0;--i)
  111968. d[i]=s[i];
  111969. }
  111970. v->pcm_returned+=(n1-n0)/2;
  111971. v->pcm_current+=(n1-n0)/2;
  111972. }else{
  111973. if(v->lW==0){
  111974. /* short/short */
  111975. for(j=0;j<vi->channels;j++){
  111976. float *s=v->pcm[j];
  111977. float *d=v->pcm[j]+n1-n0;
  111978. for(i=n0-1;i>=0;--i)
  111979. d[i]=s[i];
  111980. }
  111981. v->pcm_returned+=n1-n0;
  111982. v->pcm_current+=n1-n0;
  111983. }
  111984. }
  111985. if(pcm){
  111986. int i;
  111987. for(i=0;i<vi->channels;i++)
  111988. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111989. *pcm=v->pcmret;
  111990. }
  111991. return(n1+n-v->pcm_returned);
  111992. }
  111993. float *vorbis_window(vorbis_dsp_state *v,int W){
  111994. vorbis_info *vi=v->vi;
  111995. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111996. int hs=ci->halfrate_flag;
  111997. private_state *b=(private_state*)v->backend_state;
  111998. if(b->window[W]-1<0)return NULL;
  111999. return _vorbis_window_get(b->window[W]-hs);
  112000. }
  112001. #endif
  112002. /*** End of inlined file: block.c ***/
  112003. /*** Start of inlined file: codebook.c ***/
  112004. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112005. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112006. // tasks..
  112007. #if JUCE_MSVC
  112008. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112009. #endif
  112010. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112011. #if JUCE_USE_OGGVORBIS
  112012. #include <stdlib.h>
  112013. #include <string.h>
  112014. #include <math.h>
  112015. /* packs the given codebook into the bitstream **************************/
  112016. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  112017. long i,j;
  112018. int ordered=0;
  112019. /* first the basic parameters */
  112020. oggpack_write(opb,0x564342,24);
  112021. oggpack_write(opb,c->dim,16);
  112022. oggpack_write(opb,c->entries,24);
  112023. /* pack the codewords. There are two packings; length ordered and
  112024. length random. Decide between the two now. */
  112025. for(i=1;i<c->entries;i++)
  112026. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  112027. if(i==c->entries)ordered=1;
  112028. if(ordered){
  112029. /* length ordered. We only need to say how many codewords of
  112030. each length. The actual codewords are generated
  112031. deterministically */
  112032. long count=0;
  112033. oggpack_write(opb,1,1); /* ordered */
  112034. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  112035. for(i=1;i<c->entries;i++){
  112036. long thisx=c->lengthlist[i];
  112037. long last=c->lengthlist[i-1];
  112038. if(thisx>last){
  112039. for(j=last;j<thisx;j++){
  112040. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112041. count=i;
  112042. }
  112043. }
  112044. }
  112045. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112046. }else{
  112047. /* length random. Again, we don't code the codeword itself, just
  112048. the length. This time, though, we have to encode each length */
  112049. oggpack_write(opb,0,1); /* unordered */
  112050. /* algortihmic mapping has use for 'unused entries', which we tag
  112051. here. The algorithmic mapping happens as usual, but the unused
  112052. entry has no codeword. */
  112053. for(i=0;i<c->entries;i++)
  112054. if(c->lengthlist[i]==0)break;
  112055. if(i==c->entries){
  112056. oggpack_write(opb,0,1); /* no unused entries */
  112057. for(i=0;i<c->entries;i++)
  112058. oggpack_write(opb,c->lengthlist[i]-1,5);
  112059. }else{
  112060. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  112061. for(i=0;i<c->entries;i++){
  112062. if(c->lengthlist[i]==0){
  112063. oggpack_write(opb,0,1);
  112064. }else{
  112065. oggpack_write(opb,1,1);
  112066. oggpack_write(opb,c->lengthlist[i]-1,5);
  112067. }
  112068. }
  112069. }
  112070. }
  112071. /* is the entry number the desired return value, or do we have a
  112072. mapping? If we have a mapping, what type? */
  112073. oggpack_write(opb,c->maptype,4);
  112074. switch(c->maptype){
  112075. case 0:
  112076. /* no mapping */
  112077. break;
  112078. case 1:case 2:
  112079. /* implicitly populated value mapping */
  112080. /* explicitly populated value mapping */
  112081. if(!c->quantlist){
  112082. /* no quantlist? error */
  112083. return(-1);
  112084. }
  112085. /* values that define the dequantization */
  112086. oggpack_write(opb,c->q_min,32);
  112087. oggpack_write(opb,c->q_delta,32);
  112088. oggpack_write(opb,c->q_quant-1,4);
  112089. oggpack_write(opb,c->q_sequencep,1);
  112090. {
  112091. int quantvals;
  112092. switch(c->maptype){
  112093. case 1:
  112094. /* a single column of (c->entries/c->dim) quantized values for
  112095. building a full value list algorithmically (square lattice) */
  112096. quantvals=_book_maptype1_quantvals(c);
  112097. break;
  112098. case 2:
  112099. /* every value (c->entries*c->dim total) specified explicitly */
  112100. quantvals=c->entries*c->dim;
  112101. break;
  112102. default: /* NOT_REACHABLE */
  112103. quantvals=-1;
  112104. }
  112105. /* quantized values */
  112106. for(i=0;i<quantvals;i++)
  112107. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  112108. }
  112109. break;
  112110. default:
  112111. /* error case; we don't have any other map types now */
  112112. return(-1);
  112113. }
  112114. return(0);
  112115. }
  112116. /* unpacks a codebook from the packet buffer into the codebook struct,
  112117. readies the codebook auxiliary structures for decode *************/
  112118. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  112119. long i,j;
  112120. memset(s,0,sizeof(*s));
  112121. s->allocedp=1;
  112122. /* make sure alignment is correct */
  112123. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  112124. /* first the basic parameters */
  112125. s->dim=oggpack_read(opb,16);
  112126. s->entries=oggpack_read(opb,24);
  112127. if(s->entries==-1)goto _eofout;
  112128. /* codeword ordering.... length ordered or unordered? */
  112129. switch((int)oggpack_read(opb,1)){
  112130. case 0:
  112131. /* unordered */
  112132. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112133. /* allocated but unused entries? */
  112134. if(oggpack_read(opb,1)){
  112135. /* yes, unused entries */
  112136. for(i=0;i<s->entries;i++){
  112137. if(oggpack_read(opb,1)){
  112138. long num=oggpack_read(opb,5);
  112139. if(num==-1)goto _eofout;
  112140. s->lengthlist[i]=num+1;
  112141. }else
  112142. s->lengthlist[i]=0;
  112143. }
  112144. }else{
  112145. /* all entries used; no tagging */
  112146. for(i=0;i<s->entries;i++){
  112147. long num=oggpack_read(opb,5);
  112148. if(num==-1)goto _eofout;
  112149. s->lengthlist[i]=num+1;
  112150. }
  112151. }
  112152. break;
  112153. case 1:
  112154. /* ordered */
  112155. {
  112156. long length=oggpack_read(opb,5)+1;
  112157. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112158. for(i=0;i<s->entries;){
  112159. long num=oggpack_read(opb,_ilog(s->entries-i));
  112160. if(num==-1)goto _eofout;
  112161. for(j=0;j<num && i<s->entries;j++,i++)
  112162. s->lengthlist[i]=length;
  112163. length++;
  112164. }
  112165. }
  112166. break;
  112167. default:
  112168. /* EOF */
  112169. return(-1);
  112170. }
  112171. /* Do we have a mapping to unpack? */
  112172. switch((s->maptype=oggpack_read(opb,4))){
  112173. case 0:
  112174. /* no mapping */
  112175. break;
  112176. case 1: case 2:
  112177. /* implicitly populated value mapping */
  112178. /* explicitly populated value mapping */
  112179. s->q_min=oggpack_read(opb,32);
  112180. s->q_delta=oggpack_read(opb,32);
  112181. s->q_quant=oggpack_read(opb,4)+1;
  112182. s->q_sequencep=oggpack_read(opb,1);
  112183. {
  112184. int quantvals=0;
  112185. switch(s->maptype){
  112186. case 1:
  112187. quantvals=_book_maptype1_quantvals(s);
  112188. break;
  112189. case 2:
  112190. quantvals=s->entries*s->dim;
  112191. break;
  112192. }
  112193. /* quantized values */
  112194. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112195. for(i=0;i<quantvals;i++)
  112196. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112197. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112198. }
  112199. break;
  112200. default:
  112201. goto _errout;
  112202. }
  112203. /* all set */
  112204. return(0);
  112205. _errout:
  112206. _eofout:
  112207. vorbis_staticbook_clear(s);
  112208. return(-1);
  112209. }
  112210. /* returns the number of bits ************************************************/
  112211. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112212. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112213. return(book->c->lengthlist[a]);
  112214. }
  112215. /* One the encode side, our vector writers are each designed for a
  112216. specific purpose, and the encoder is not flexible without modification:
  112217. The LSP vector coder uses a single stage nearest-match with no
  112218. interleave, so no step and no error return. This is specced by floor0
  112219. and doesn't change.
  112220. Residue0 encoding interleaves, uses multiple stages, and each stage
  112221. peels of a specific amount of resolution from a lattice (thus we want
  112222. to match by threshold, not nearest match). Residue doesn't *have* to
  112223. be encoded that way, but to change it, one will need to add more
  112224. infrastructure on the encode side (decode side is specced and simpler) */
  112225. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112226. /* returns entry number and *modifies a* to the quantization value *****/
  112227. int vorbis_book_errorv(codebook *book,float *a){
  112228. int dim=book->dim,k;
  112229. int best=_best(book,a,1);
  112230. for(k=0;k<dim;k++)
  112231. a[k]=(book->valuelist+best*dim)[k];
  112232. return(best);
  112233. }
  112234. /* returns the number of bits and *modifies a* to the quantization value *****/
  112235. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112236. int k,dim=book->dim;
  112237. for(k=0;k<dim;k++)
  112238. a[k]=(book->valuelist+best*dim)[k];
  112239. return(vorbis_book_encode(book,best,b));
  112240. }
  112241. /* the 'eliminate the decode tree' optimization actually requires the
  112242. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112243. (and one of the first places where carefully thought out design
  112244. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112245. to an MSb bitpacker), but not actually the huge hit it appears to
  112246. be. The first-stage decode table catches most words so that
  112247. bitreverse is not in the main execution path. */
  112248. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112249. int read=book->dec_maxlength;
  112250. long lo,hi;
  112251. long lok = oggpack_look(b,book->dec_firsttablen);
  112252. if (lok >= 0) {
  112253. long entry = book->dec_firsttable[lok];
  112254. if(entry&0x80000000UL){
  112255. lo=(entry>>15)&0x7fff;
  112256. hi=book->used_entries-(entry&0x7fff);
  112257. }else{
  112258. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112259. return(entry-1);
  112260. }
  112261. }else{
  112262. lo=0;
  112263. hi=book->used_entries;
  112264. }
  112265. lok = oggpack_look(b, read);
  112266. while(lok<0 && read>1)
  112267. lok = oggpack_look(b, --read);
  112268. if(lok<0)return -1;
  112269. /* bisect search for the codeword in the ordered list */
  112270. {
  112271. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112272. while(hi-lo>1){
  112273. long p=(hi-lo)>>1;
  112274. long test=book->codelist[lo+p]>testword;
  112275. lo+=p&(test-1);
  112276. hi-=p&(-test);
  112277. }
  112278. if(book->dec_codelengths[lo]<=read){
  112279. oggpack_adv(b, book->dec_codelengths[lo]);
  112280. return(lo);
  112281. }
  112282. }
  112283. oggpack_adv(b, read);
  112284. return(-1);
  112285. }
  112286. /* Decode side is specced and easier, because we don't need to find
  112287. matches using different criteria; we simply read and map. There are
  112288. two things we need to do 'depending':
  112289. We may need to support interleave. We don't really, but it's
  112290. convenient to do it here rather than rebuild the vector later.
  112291. Cascades may be additive or multiplicitive; this is not inherent in
  112292. the codebook, but set in the code using the codebook. Like
  112293. interleaving, it's easiest to do it here.
  112294. addmul==0 -> declarative (set the value)
  112295. addmul==1 -> additive
  112296. addmul==2 -> multiplicitive */
  112297. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112298. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112299. long packed_entry=decode_packed_entry_number(book,b);
  112300. if(packed_entry>=0)
  112301. return(book->dec_index[packed_entry]);
  112302. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112303. return(packed_entry);
  112304. }
  112305. /* returns 0 on OK or -1 on eof *************************************/
  112306. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112307. int step=n/book->dim;
  112308. long *entry = (long*)alloca(sizeof(*entry)*step);
  112309. float **t = (float**)alloca(sizeof(*t)*step);
  112310. int i,j,o;
  112311. for (i = 0; i < step; i++) {
  112312. entry[i]=decode_packed_entry_number(book,b);
  112313. if(entry[i]==-1)return(-1);
  112314. t[i] = book->valuelist+entry[i]*book->dim;
  112315. }
  112316. for(i=0,o=0;i<book->dim;i++,o+=step)
  112317. for (j=0;j<step;j++)
  112318. a[o+j]+=t[j][i];
  112319. return(0);
  112320. }
  112321. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112322. int i,j,entry;
  112323. float *t;
  112324. if(book->dim>8){
  112325. for(i=0;i<n;){
  112326. entry = decode_packed_entry_number(book,b);
  112327. if(entry==-1)return(-1);
  112328. t = book->valuelist+entry*book->dim;
  112329. for (j=0;j<book->dim;)
  112330. a[i++]+=t[j++];
  112331. }
  112332. }else{
  112333. for(i=0;i<n;){
  112334. entry = decode_packed_entry_number(book,b);
  112335. if(entry==-1)return(-1);
  112336. t = book->valuelist+entry*book->dim;
  112337. j=0;
  112338. switch((int)book->dim){
  112339. case 8:
  112340. a[i++]+=t[j++];
  112341. case 7:
  112342. a[i++]+=t[j++];
  112343. case 6:
  112344. a[i++]+=t[j++];
  112345. case 5:
  112346. a[i++]+=t[j++];
  112347. case 4:
  112348. a[i++]+=t[j++];
  112349. case 3:
  112350. a[i++]+=t[j++];
  112351. case 2:
  112352. a[i++]+=t[j++];
  112353. case 1:
  112354. a[i++]+=t[j++];
  112355. case 0:
  112356. break;
  112357. }
  112358. }
  112359. }
  112360. return(0);
  112361. }
  112362. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112363. int i,j,entry;
  112364. float *t;
  112365. for(i=0;i<n;){
  112366. entry = decode_packed_entry_number(book,b);
  112367. if(entry==-1)return(-1);
  112368. t = book->valuelist+entry*book->dim;
  112369. for (j=0;j<book->dim;)
  112370. a[i++]=t[j++];
  112371. }
  112372. return(0);
  112373. }
  112374. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112375. oggpack_buffer *b,int n){
  112376. long i,j,entry;
  112377. int chptr=0;
  112378. for(i=offset/ch;i<(offset+n)/ch;){
  112379. entry = decode_packed_entry_number(book,b);
  112380. if(entry==-1)return(-1);
  112381. {
  112382. const float *t = book->valuelist+entry*book->dim;
  112383. for (j=0;j<book->dim;j++){
  112384. a[chptr++][i]+=t[j];
  112385. if(chptr==ch){
  112386. chptr=0;
  112387. i++;
  112388. }
  112389. }
  112390. }
  112391. }
  112392. return(0);
  112393. }
  112394. #ifdef _V_SELFTEST
  112395. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112396. number of vectors through (keeping track of the quantized values),
  112397. and decode using the unpacked book. quantized version of in should
  112398. exactly equal out */
  112399. #include <stdio.h>
  112400. #include "vorbis/book/lsp20_0.vqh"
  112401. #include "vorbis/book/res0a_13.vqh"
  112402. #define TESTSIZE 40
  112403. float test1[TESTSIZE]={
  112404. 0.105939f,
  112405. 0.215373f,
  112406. 0.429117f,
  112407. 0.587974f,
  112408. 0.181173f,
  112409. 0.296583f,
  112410. 0.515707f,
  112411. 0.715261f,
  112412. 0.162327f,
  112413. 0.263834f,
  112414. 0.342876f,
  112415. 0.406025f,
  112416. 0.103571f,
  112417. 0.223561f,
  112418. 0.368513f,
  112419. 0.540313f,
  112420. 0.136672f,
  112421. 0.395882f,
  112422. 0.587183f,
  112423. 0.652476f,
  112424. 0.114338f,
  112425. 0.417300f,
  112426. 0.525486f,
  112427. 0.698679f,
  112428. 0.147492f,
  112429. 0.324481f,
  112430. 0.643089f,
  112431. 0.757582f,
  112432. 0.139556f,
  112433. 0.215795f,
  112434. 0.324559f,
  112435. 0.399387f,
  112436. 0.120236f,
  112437. 0.267420f,
  112438. 0.446940f,
  112439. 0.608760f,
  112440. 0.115587f,
  112441. 0.287234f,
  112442. 0.571081f,
  112443. 0.708603f,
  112444. };
  112445. float test3[TESTSIZE]={
  112446. 0,1,-2,3,4,-5,6,7,8,9,
  112447. 8,-2,7,-1,4,6,8,3,1,-9,
  112448. 10,11,12,13,14,15,26,17,18,19,
  112449. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112450. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112451. &_vq_book_res0a_13,NULL};
  112452. float *testvec[]={test1,test3};
  112453. int main(){
  112454. oggpack_buffer write;
  112455. oggpack_buffer read;
  112456. long ptr=0,i;
  112457. oggpack_writeinit(&write);
  112458. fprintf(stderr,"Testing codebook abstraction...:\n");
  112459. while(testlist[ptr]){
  112460. codebook c;
  112461. static_codebook s;
  112462. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112463. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112464. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112465. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112466. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112467. /* pack the codebook, write the testvector */
  112468. oggpack_reset(&write);
  112469. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112470. we can write */
  112471. vorbis_staticbook_pack(testlist[ptr],&write);
  112472. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112473. for(i=0;i<TESTSIZE;i+=c.dim){
  112474. int best=_best(&c,qv+i,1);
  112475. vorbis_book_encodev(&c,best,qv+i,&write);
  112476. }
  112477. vorbis_book_clear(&c);
  112478. fprintf(stderr,"OK.\n");
  112479. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112480. /* transfer the write data to a read buffer and unpack/read */
  112481. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112482. if(vorbis_staticbook_unpack(&read,&s)){
  112483. fprintf(stderr,"Error unpacking codebook.\n");
  112484. exit(1);
  112485. }
  112486. if(vorbis_book_init_decode(&c,&s)){
  112487. fprintf(stderr,"Error initializing codebook.\n");
  112488. exit(1);
  112489. }
  112490. for(i=0;i<TESTSIZE;i+=c.dim)
  112491. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112492. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112493. exit(1);
  112494. }
  112495. for(i=0;i<TESTSIZE;i++)
  112496. if(fabs(qv[i]-iv[i])>.000001){
  112497. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112498. iv[i],qv[i],i);
  112499. exit(1);
  112500. }
  112501. fprintf(stderr,"OK\n");
  112502. ptr++;
  112503. }
  112504. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112505. exit(0);
  112506. }
  112507. #endif
  112508. #endif
  112509. /*** End of inlined file: codebook.c ***/
  112510. /*** Start of inlined file: envelope.c ***/
  112511. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112512. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112513. // tasks..
  112514. #if JUCE_MSVC
  112515. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112516. #endif
  112517. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112518. #if JUCE_USE_OGGVORBIS
  112519. #include <stdlib.h>
  112520. #include <string.h>
  112521. #include <stdio.h>
  112522. #include <math.h>
  112523. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112524. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112525. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112526. int ch=vi->channels;
  112527. int i,j;
  112528. int n=e->winlength=128;
  112529. e->searchstep=64; /* not random */
  112530. e->minenergy=gi->preecho_minenergy;
  112531. e->ch=ch;
  112532. e->storage=128;
  112533. e->cursor=ci->blocksizes[1]/2;
  112534. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112535. mdct_init(&e->mdct,n);
  112536. for(i=0;i<n;i++){
  112537. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112538. e->mdct_win[i]*=e->mdct_win[i];
  112539. }
  112540. /* magic follows */
  112541. e->band[0].begin=2; e->band[0].end=4;
  112542. e->band[1].begin=4; e->band[1].end=5;
  112543. e->band[2].begin=6; e->band[2].end=6;
  112544. e->band[3].begin=9; e->band[3].end=8;
  112545. e->band[4].begin=13; e->band[4].end=8;
  112546. e->band[5].begin=17; e->band[5].end=8;
  112547. e->band[6].begin=22; e->band[6].end=8;
  112548. for(j=0;j<VE_BANDS;j++){
  112549. n=e->band[j].end;
  112550. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112551. for(i=0;i<n;i++){
  112552. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112553. e->band[j].total+=e->band[j].window[i];
  112554. }
  112555. e->band[j].total=1./e->band[j].total;
  112556. }
  112557. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112558. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112559. }
  112560. void _ve_envelope_clear(envelope_lookup *e){
  112561. int i;
  112562. mdct_clear(&e->mdct);
  112563. for(i=0;i<VE_BANDS;i++)
  112564. _ogg_free(e->band[i].window);
  112565. _ogg_free(e->mdct_win);
  112566. _ogg_free(e->filter);
  112567. _ogg_free(e->mark);
  112568. memset(e,0,sizeof(*e));
  112569. }
  112570. /* fairly straight threshhold-by-band based until we find something
  112571. that works better and isn't patented. */
  112572. static int _ve_amp(envelope_lookup *ve,
  112573. vorbis_info_psy_global *gi,
  112574. float *data,
  112575. envelope_band *bands,
  112576. envelope_filter_state *filters,
  112577. long pos){
  112578. long n=ve->winlength;
  112579. int ret=0;
  112580. long i,j;
  112581. float decay;
  112582. /* we want to have a 'minimum bar' for energy, else we're just
  112583. basing blocks on quantization noise that outweighs the signal
  112584. itself (for low power signals) */
  112585. float minV=ve->minenergy;
  112586. float *vec=(float*) alloca(n*sizeof(*vec));
  112587. /* stretch is used to gradually lengthen the number of windows
  112588. considered prevoius-to-potential-trigger */
  112589. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112590. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112591. if(penalty<0.f)penalty=0.f;
  112592. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112593. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112594. totalshift+pos*ve->searchstep);*/
  112595. /* window and transform */
  112596. for(i=0;i<n;i++)
  112597. vec[i]=data[i]*ve->mdct_win[i];
  112598. mdct_forward(&ve->mdct,vec,vec);
  112599. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112600. /* near-DC spreading function; this has nothing to do with
  112601. psychoacoustics, just sidelobe leakage and window size */
  112602. {
  112603. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112604. int ptr=filters->nearptr;
  112605. /* the accumulation is regularly refreshed from scratch to avoid
  112606. floating point creep */
  112607. if(ptr==0){
  112608. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112609. filters->nearDC_partialacc=temp;
  112610. }else{
  112611. decay=filters->nearDC_acc+=temp;
  112612. filters->nearDC_partialacc+=temp;
  112613. }
  112614. filters->nearDC_acc-=filters->nearDC[ptr];
  112615. filters->nearDC[ptr]=temp;
  112616. decay*=(1./(VE_NEARDC+1));
  112617. filters->nearptr++;
  112618. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112619. decay=todB(&decay)*.5-15.f;
  112620. }
  112621. /* perform spreading and limiting, also smooth the spectrum. yes,
  112622. the MDCT results in all real coefficients, but it still *behaves*
  112623. like real/imaginary pairs */
  112624. for(i=0;i<n/2;i+=2){
  112625. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112626. val=todB(&val)*.5f;
  112627. if(val<decay)val=decay;
  112628. if(val<minV)val=minV;
  112629. vec[i>>1]=val;
  112630. decay-=8.;
  112631. }
  112632. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112633. /* perform preecho/postecho triggering by band */
  112634. for(j=0;j<VE_BANDS;j++){
  112635. float acc=0.;
  112636. float valmax,valmin;
  112637. /* accumulate amplitude */
  112638. for(i=0;i<bands[j].end;i++)
  112639. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112640. acc*=bands[j].total;
  112641. /* convert amplitude to delta */
  112642. {
  112643. int p,thisx=filters[j].ampptr;
  112644. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112645. p=thisx;
  112646. p--;
  112647. if(p<0)p+=VE_AMP;
  112648. postmax=max(acc,filters[j].ampbuf[p]);
  112649. postmin=min(acc,filters[j].ampbuf[p]);
  112650. for(i=0;i<stretch;i++){
  112651. p--;
  112652. if(p<0)p+=VE_AMP;
  112653. premax=max(premax,filters[j].ampbuf[p]);
  112654. premin=min(premin,filters[j].ampbuf[p]);
  112655. }
  112656. valmin=postmin-premin;
  112657. valmax=postmax-premax;
  112658. /*filters[j].markers[pos]=valmax;*/
  112659. filters[j].ampbuf[thisx]=acc;
  112660. filters[j].ampptr++;
  112661. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112662. }
  112663. /* look at min/max, decide trigger */
  112664. if(valmax>gi->preecho_thresh[j]+penalty){
  112665. ret|=1;
  112666. ret|=4;
  112667. }
  112668. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112669. }
  112670. return(ret);
  112671. }
  112672. #if 0
  112673. static int seq=0;
  112674. static ogg_int64_t totalshift=-1024;
  112675. #endif
  112676. long _ve_envelope_search(vorbis_dsp_state *v){
  112677. vorbis_info *vi=v->vi;
  112678. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112679. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112680. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112681. long i,j;
  112682. int first=ve->current/ve->searchstep;
  112683. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112684. if(first<0)first=0;
  112685. /* make sure we have enough storage to match the PCM */
  112686. if(last+VE_WIN+VE_POST>ve->storage){
  112687. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112688. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112689. }
  112690. for(j=first;j<last;j++){
  112691. int ret=0;
  112692. ve->stretch++;
  112693. if(ve->stretch>VE_MAXSTRETCH*2)
  112694. ve->stretch=VE_MAXSTRETCH*2;
  112695. for(i=0;i<ve->ch;i++){
  112696. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112697. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112698. }
  112699. ve->mark[j+VE_POST]=0;
  112700. if(ret&1){
  112701. ve->mark[j]=1;
  112702. ve->mark[j+1]=1;
  112703. }
  112704. if(ret&2){
  112705. ve->mark[j]=1;
  112706. if(j>0)ve->mark[j-1]=1;
  112707. }
  112708. if(ret&4)ve->stretch=-1;
  112709. }
  112710. ve->current=last*ve->searchstep;
  112711. {
  112712. long centerW=v->centerW;
  112713. long testW=
  112714. centerW+
  112715. ci->blocksizes[v->W]/4+
  112716. ci->blocksizes[1]/2+
  112717. ci->blocksizes[0]/4;
  112718. j=ve->cursor;
  112719. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112720. working back one window */
  112721. if(j>=testW)return(1);
  112722. ve->cursor=j;
  112723. if(ve->mark[j/ve->searchstep]){
  112724. if(j>centerW){
  112725. #if 0
  112726. if(j>ve->curmark){
  112727. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112728. int l,m;
  112729. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112730. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112731. seq,
  112732. (totalshift+ve->cursor)/44100.,
  112733. (totalshift+j)/44100.);
  112734. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112735. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112736. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112737. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112738. for(m=0;m<VE_BANDS;m++){
  112739. char buf[80];
  112740. sprintf(buf,"delL%d",m);
  112741. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112742. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112743. }
  112744. for(m=0;m<VE_BANDS;m++){
  112745. char buf[80];
  112746. sprintf(buf,"delR%d",m);
  112747. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112748. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112749. }
  112750. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112751. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112752. seq++;
  112753. }
  112754. #endif
  112755. ve->curmark=j;
  112756. if(j>=testW)return(1);
  112757. return(0);
  112758. }
  112759. }
  112760. j+=ve->searchstep;
  112761. }
  112762. }
  112763. return(-1);
  112764. }
  112765. int _ve_envelope_mark(vorbis_dsp_state *v){
  112766. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112767. vorbis_info *vi=v->vi;
  112768. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112769. long centerW=v->centerW;
  112770. long beginW=centerW-ci->blocksizes[v->W]/4;
  112771. long endW=centerW+ci->blocksizes[v->W]/4;
  112772. if(v->W){
  112773. beginW-=ci->blocksizes[v->lW]/4;
  112774. endW+=ci->blocksizes[v->nW]/4;
  112775. }else{
  112776. beginW-=ci->blocksizes[0]/4;
  112777. endW+=ci->blocksizes[0]/4;
  112778. }
  112779. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112780. {
  112781. long first=beginW/ve->searchstep;
  112782. long last=endW/ve->searchstep;
  112783. long i;
  112784. for(i=first;i<last;i++)
  112785. if(ve->mark[i])return(1);
  112786. }
  112787. return(0);
  112788. }
  112789. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112790. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112791. ahead of ve->current */
  112792. int smallshift=shift/e->searchstep;
  112793. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112794. #if 0
  112795. for(i=0;i<VE_BANDS*e->ch;i++)
  112796. memmove(e->filter[i].markers,
  112797. e->filter[i].markers+smallshift,
  112798. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112799. totalshift+=shift;
  112800. #endif
  112801. e->current-=shift;
  112802. if(e->curmark>=0)
  112803. e->curmark-=shift;
  112804. e->cursor-=shift;
  112805. }
  112806. #endif
  112807. /*** End of inlined file: envelope.c ***/
  112808. /*** Start of inlined file: floor0.c ***/
  112809. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112810. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112811. // tasks..
  112812. #if JUCE_MSVC
  112813. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112814. #endif
  112815. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112816. #if JUCE_USE_OGGVORBIS
  112817. #include <stdlib.h>
  112818. #include <string.h>
  112819. #include <math.h>
  112820. /*** Start of inlined file: lsp.h ***/
  112821. #ifndef _V_LSP_H_
  112822. #define _V_LSP_H_
  112823. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112824. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112825. float *lsp,int m,
  112826. float amp,float ampoffset);
  112827. #endif
  112828. /*** End of inlined file: lsp.h ***/
  112829. #include <stdio.h>
  112830. typedef struct {
  112831. int ln;
  112832. int m;
  112833. int **linearmap;
  112834. int n[2];
  112835. vorbis_info_floor0 *vi;
  112836. long bits;
  112837. long frames;
  112838. } vorbis_look_floor0;
  112839. /***********************************************/
  112840. static void floor0_free_info(vorbis_info_floor *i){
  112841. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112842. if(info){
  112843. memset(info,0,sizeof(*info));
  112844. _ogg_free(info);
  112845. }
  112846. }
  112847. static void floor0_free_look(vorbis_look_floor *i){
  112848. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112849. if(look){
  112850. if(look->linearmap){
  112851. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112852. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112853. _ogg_free(look->linearmap);
  112854. }
  112855. memset(look,0,sizeof(*look));
  112856. _ogg_free(look);
  112857. }
  112858. }
  112859. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112860. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112861. int j;
  112862. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112863. info->order=oggpack_read(opb,8);
  112864. info->rate=oggpack_read(opb,16);
  112865. info->barkmap=oggpack_read(opb,16);
  112866. info->ampbits=oggpack_read(opb,6);
  112867. info->ampdB=oggpack_read(opb,8);
  112868. info->numbooks=oggpack_read(opb,4)+1;
  112869. if(info->order<1)goto err_out;
  112870. if(info->rate<1)goto err_out;
  112871. if(info->barkmap<1)goto err_out;
  112872. if(info->numbooks<1)goto err_out;
  112873. for(j=0;j<info->numbooks;j++){
  112874. info->books[j]=oggpack_read(opb,8);
  112875. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112876. }
  112877. return(info);
  112878. err_out:
  112879. floor0_free_info(info);
  112880. return(NULL);
  112881. }
  112882. /* initialize Bark scale and normalization lookups. We could do this
  112883. with static tables, but Vorbis allows a number of possible
  112884. combinations, so it's best to do it computationally.
  112885. The below is authoritative in terms of defining scale mapping.
  112886. Note that the scale depends on the sampling rate as well as the
  112887. linear block and mapping sizes */
  112888. static void floor0_map_lazy_init(vorbis_block *vb,
  112889. vorbis_info_floor *infoX,
  112890. vorbis_look_floor0 *look){
  112891. if(!look->linearmap[vb->W]){
  112892. vorbis_dsp_state *vd=vb->vd;
  112893. vorbis_info *vi=vd->vi;
  112894. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112895. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112896. int W=vb->W;
  112897. int n=ci->blocksizes[W]/2,j;
  112898. /* we choose a scaling constant so that:
  112899. floor(bark(rate/2-1)*C)=mapped-1
  112900. floor(bark(rate/2)*C)=mapped */
  112901. float scale=look->ln/toBARK(info->rate/2.f);
  112902. /* the mapping from a linear scale to a smaller bark scale is
  112903. straightforward. We do *not* make sure that the linear mapping
  112904. does not skip bark-scale bins; the decoder simply skips them and
  112905. the encoder may do what it wishes in filling them. They're
  112906. necessary in some mapping combinations to keep the scale spacing
  112907. accurate */
  112908. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112909. for(j=0;j<n;j++){
  112910. int val=floor( toBARK((info->rate/2.f)/n*j)
  112911. *scale); /* bark numbers represent band edges */
  112912. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112913. look->linearmap[W][j]=val;
  112914. }
  112915. look->linearmap[W][j]=-1;
  112916. look->n[W]=n;
  112917. }
  112918. }
  112919. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112920. vorbis_info_floor *i){
  112921. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112922. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112923. look->m=info->order;
  112924. look->ln=info->barkmap;
  112925. look->vi=info;
  112926. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112927. return look;
  112928. }
  112929. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112930. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112931. vorbis_info_floor0 *info=look->vi;
  112932. int j,k;
  112933. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112934. if(ampraw>0){ /* also handles the -1 out of data case */
  112935. long maxval=(1<<info->ampbits)-1;
  112936. float amp=(float)ampraw/maxval*info->ampdB;
  112937. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112938. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112939. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112940. codebook *b=ci->fullbooks+info->books[booknum];
  112941. float last=0.f;
  112942. /* the additional b->dim is a guard against any possible stack
  112943. smash; b->dim is provably more than we can overflow the
  112944. vector */
  112945. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112946. for(j=0;j<look->m;j+=b->dim)
  112947. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112948. for(j=0;j<look->m;){
  112949. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112950. last=lsp[j-1];
  112951. }
  112952. lsp[look->m]=amp;
  112953. return(lsp);
  112954. }
  112955. }
  112956. eop:
  112957. return(NULL);
  112958. }
  112959. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112960. void *memo,float *out){
  112961. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112962. vorbis_info_floor0 *info=look->vi;
  112963. floor0_map_lazy_init(vb,info,look);
  112964. if(memo){
  112965. float *lsp=(float *)memo;
  112966. float amp=lsp[look->m];
  112967. /* take the coefficients back to a spectral envelope curve */
  112968. vorbis_lsp_to_curve(out,
  112969. look->linearmap[vb->W],
  112970. look->n[vb->W],
  112971. look->ln,
  112972. lsp,look->m,amp,(float)info->ampdB);
  112973. return(1);
  112974. }
  112975. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112976. return(0);
  112977. }
  112978. /* export hooks */
  112979. vorbis_func_floor floor0_exportbundle={
  112980. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112981. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112982. };
  112983. #endif
  112984. /*** End of inlined file: floor0.c ***/
  112985. /*** Start of inlined file: floor1.c ***/
  112986. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112987. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112988. // tasks..
  112989. #if JUCE_MSVC
  112990. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112991. #endif
  112992. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112993. #if JUCE_USE_OGGVORBIS
  112994. #include <stdlib.h>
  112995. #include <string.h>
  112996. #include <math.h>
  112997. #include <stdio.h>
  112998. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112999. typedef struct {
  113000. int sorted_index[VIF_POSIT+2];
  113001. int forward_index[VIF_POSIT+2];
  113002. int reverse_index[VIF_POSIT+2];
  113003. int hineighbor[VIF_POSIT];
  113004. int loneighbor[VIF_POSIT];
  113005. int posts;
  113006. int n;
  113007. int quant_q;
  113008. vorbis_info_floor1 *vi;
  113009. long phrasebits;
  113010. long postbits;
  113011. long frames;
  113012. } vorbis_look_floor1;
  113013. typedef struct lsfit_acc{
  113014. long x0;
  113015. long x1;
  113016. long xa;
  113017. long ya;
  113018. long x2a;
  113019. long y2a;
  113020. long xya;
  113021. long an;
  113022. } lsfit_acc;
  113023. /***********************************************/
  113024. static void floor1_free_info(vorbis_info_floor *i){
  113025. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113026. if(info){
  113027. memset(info,0,sizeof(*info));
  113028. _ogg_free(info);
  113029. }
  113030. }
  113031. static void floor1_free_look(vorbis_look_floor *i){
  113032. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  113033. if(look){
  113034. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  113035. (float)look->phrasebits/look->frames,
  113036. (float)look->postbits/look->frames,
  113037. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113038. memset(look,0,sizeof(*look));
  113039. _ogg_free(look);
  113040. }
  113041. }
  113042. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  113043. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113044. int j,k;
  113045. int count=0;
  113046. int rangebits;
  113047. int maxposit=info->postlist[1];
  113048. int maxclass=-1;
  113049. /* save out partitions */
  113050. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  113051. for(j=0;j<info->partitions;j++){
  113052. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  113053. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113054. }
  113055. /* save out partition classes */
  113056. for(j=0;j<maxclass+1;j++){
  113057. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  113058. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  113059. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  113060. for(k=0;k<(1<<info->class_subs[j]);k++)
  113061. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  113062. }
  113063. /* save out the post list */
  113064. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  113065. oggpack_write(opb,ilog2(maxposit),4);
  113066. rangebits=ilog2(maxposit);
  113067. for(j=0,k=0;j<info->partitions;j++){
  113068. count+=info->class_dim[info->partitionclass[j]];
  113069. for(;k<count;k++)
  113070. oggpack_write(opb,info->postlist[k+2],rangebits);
  113071. }
  113072. }
  113073. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  113074. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113075. int j,k,count=0,maxclass=-1,rangebits;
  113076. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  113077. /* read partitions */
  113078. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  113079. for(j=0;j<info->partitions;j++){
  113080. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  113081. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113082. }
  113083. /* read partition classes */
  113084. for(j=0;j<maxclass+1;j++){
  113085. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  113086. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  113087. if(info->class_subs[j]<0)
  113088. goto err_out;
  113089. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  113090. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  113091. goto err_out;
  113092. for(k=0;k<(1<<info->class_subs[j]);k++){
  113093. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  113094. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  113095. goto err_out;
  113096. }
  113097. }
  113098. /* read the post list */
  113099. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  113100. rangebits=oggpack_read(opb,4);
  113101. for(j=0,k=0;j<info->partitions;j++){
  113102. count+=info->class_dim[info->partitionclass[j]];
  113103. for(;k<count;k++){
  113104. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  113105. if(t<0 || t>=(1<<rangebits))
  113106. goto err_out;
  113107. }
  113108. }
  113109. info->postlist[0]=0;
  113110. info->postlist[1]=1<<rangebits;
  113111. return(info);
  113112. err_out:
  113113. floor1_free_info(info);
  113114. return(NULL);
  113115. }
  113116. static int icomp(const void *a,const void *b){
  113117. return(**(int **)a-**(int **)b);
  113118. }
  113119. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  113120. vorbis_info_floor *in){
  113121. int *sortpointer[VIF_POSIT+2];
  113122. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  113123. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  113124. int i,j,n=0;
  113125. look->vi=info;
  113126. look->n=info->postlist[1];
  113127. /* we drop each position value in-between already decoded values,
  113128. and use linear interpolation to predict each new value past the
  113129. edges. The positions are read in the order of the position
  113130. list... we precompute the bounding positions in the lookup. Of
  113131. course, the neighbors can change (if a position is declined), but
  113132. this is an initial mapping */
  113133. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  113134. n+=2;
  113135. look->posts=n;
  113136. /* also store a sorted position index */
  113137. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  113138. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  113139. /* points from sort order back to range number */
  113140. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  113141. /* points from range order to sorted position */
  113142. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  113143. /* we actually need the post values too */
  113144. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113145. /* quantize values to multiplier spec */
  113146. switch(info->mult){
  113147. case 1: /* 1024 -> 256 */
  113148. look->quant_q=256;
  113149. break;
  113150. case 2: /* 1024 -> 128 */
  113151. look->quant_q=128;
  113152. break;
  113153. case 3: /* 1024 -> 86 */
  113154. look->quant_q=86;
  113155. break;
  113156. case 4: /* 1024 -> 64 */
  113157. look->quant_q=64;
  113158. break;
  113159. }
  113160. /* discover our neighbors for decode where we don't use fit flags
  113161. (that would push the neighbors outward) */
  113162. for(i=0;i<n-2;i++){
  113163. int lo=0;
  113164. int hi=1;
  113165. int lx=0;
  113166. int hx=look->n;
  113167. int currentx=info->postlist[i+2];
  113168. for(j=0;j<i+2;j++){
  113169. int x=info->postlist[j];
  113170. if(x>lx && x<currentx){
  113171. lo=j;
  113172. lx=x;
  113173. }
  113174. if(x<hx && x>currentx){
  113175. hi=j;
  113176. hx=x;
  113177. }
  113178. }
  113179. look->loneighbor[i]=lo;
  113180. look->hineighbor[i]=hi;
  113181. }
  113182. return(look);
  113183. }
  113184. static int render_point(int x0,int x1,int y0,int y1,int x){
  113185. y0&=0x7fff; /* mask off flag */
  113186. y1&=0x7fff;
  113187. {
  113188. int dy=y1-y0;
  113189. int adx=x1-x0;
  113190. int ady=abs(dy);
  113191. int err=ady*(x-x0);
  113192. int off=err/adx;
  113193. if(dy<0)return(y0-off);
  113194. return(y0+off);
  113195. }
  113196. }
  113197. static int vorbis_dBquant(const float *x){
  113198. int i= *x*7.3142857f+1023.5f;
  113199. if(i>1023)return(1023);
  113200. if(i<0)return(0);
  113201. return i;
  113202. }
  113203. static float FLOOR1_fromdB_LOOKUP[256]={
  113204. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113205. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113206. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113207. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113208. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113209. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113210. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113211. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113212. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113213. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113214. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113215. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113216. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113217. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113218. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113219. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113220. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113221. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113222. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113223. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113224. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113225. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113226. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113227. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113228. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113229. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113230. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113231. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113232. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113233. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113234. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113235. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113236. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113237. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113238. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113239. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113240. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113241. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113242. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113243. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113244. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113245. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113246. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113247. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113248. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113249. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113250. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113251. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113252. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113253. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113254. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113255. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113256. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113257. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113258. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113259. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113260. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113261. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113262. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113263. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113264. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113265. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113266. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113267. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113268. };
  113269. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113270. int dy=y1-y0;
  113271. int adx=x1-x0;
  113272. int ady=abs(dy);
  113273. int base=dy/adx;
  113274. int sy=(dy<0?base-1:base+1);
  113275. int x=x0;
  113276. int y=y0;
  113277. int err=0;
  113278. ady-=abs(base*adx);
  113279. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113280. while(++x<x1){
  113281. err=err+ady;
  113282. if(err>=adx){
  113283. err-=adx;
  113284. y+=sy;
  113285. }else{
  113286. y+=base;
  113287. }
  113288. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113289. }
  113290. }
  113291. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113292. int dy=y1-y0;
  113293. int adx=x1-x0;
  113294. int ady=abs(dy);
  113295. int base=dy/adx;
  113296. int sy=(dy<0?base-1:base+1);
  113297. int x=x0;
  113298. int y=y0;
  113299. int err=0;
  113300. ady-=abs(base*adx);
  113301. d[x]=y;
  113302. while(++x<x1){
  113303. err=err+ady;
  113304. if(err>=adx){
  113305. err-=adx;
  113306. y+=sy;
  113307. }else{
  113308. y+=base;
  113309. }
  113310. d[x]=y;
  113311. }
  113312. }
  113313. /* the floor has already been filtered to only include relevant sections */
  113314. static int accumulate_fit(const float *flr,const float *mdct,
  113315. int x0, int x1,lsfit_acc *a,
  113316. int n,vorbis_info_floor1 *info){
  113317. long i;
  113318. 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;
  113319. memset(a,0,sizeof(*a));
  113320. a->x0=x0;
  113321. a->x1=x1;
  113322. if(x1>=n)x1=n-1;
  113323. for(i=x0;i<=x1;i++){
  113324. int quantized=vorbis_dBquant(flr+i);
  113325. if(quantized){
  113326. if(mdct[i]+info->twofitatten>=flr[i]){
  113327. xa += i;
  113328. ya += quantized;
  113329. x2a += i*i;
  113330. y2a += quantized*quantized;
  113331. xya += i*quantized;
  113332. na++;
  113333. }else{
  113334. xb += i;
  113335. yb += quantized;
  113336. x2b += i*i;
  113337. y2b += quantized*quantized;
  113338. xyb += i*quantized;
  113339. nb++;
  113340. }
  113341. }
  113342. }
  113343. xb+=xa;
  113344. yb+=ya;
  113345. x2b+=x2a;
  113346. y2b+=y2a;
  113347. xyb+=xya;
  113348. nb+=na;
  113349. /* weight toward the actually used frequencies if we meet the threshhold */
  113350. {
  113351. int weight=nb*info->twofitweight/(na+1);
  113352. a->xa=xa*weight+xb;
  113353. a->ya=ya*weight+yb;
  113354. a->x2a=x2a*weight+x2b;
  113355. a->y2a=y2a*weight+y2b;
  113356. a->xya=xya*weight+xyb;
  113357. a->an=na*weight+nb;
  113358. }
  113359. return(na);
  113360. }
  113361. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113362. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113363. long x0=a[0].x0;
  113364. long x1=a[fits-1].x1;
  113365. for(i=0;i<fits;i++){
  113366. x+=a[i].xa;
  113367. y+=a[i].ya;
  113368. x2+=a[i].x2a;
  113369. y2+=a[i].y2a;
  113370. xy+=a[i].xya;
  113371. an+=a[i].an;
  113372. }
  113373. if(*y0>=0){
  113374. x+= x0;
  113375. y+= *y0;
  113376. x2+= x0 * x0;
  113377. y2+= *y0 * *y0;
  113378. xy+= *y0 * x0;
  113379. an++;
  113380. }
  113381. if(*y1>=0){
  113382. x+= x1;
  113383. y+= *y1;
  113384. x2+= x1 * x1;
  113385. y2+= *y1 * *y1;
  113386. xy+= *y1 * x1;
  113387. an++;
  113388. }
  113389. if(an){
  113390. /* need 64 bit multiplies, which C doesn't give portably as int */
  113391. double fx=x;
  113392. double fy=y;
  113393. double fx2=x2;
  113394. double fxy=xy;
  113395. double denom=1./(an*fx2-fx*fx);
  113396. double a=(fy*fx2-fxy*fx)*denom;
  113397. double b=(an*fxy-fx*fy)*denom;
  113398. *y0=rint(a+b*x0);
  113399. *y1=rint(a+b*x1);
  113400. /* limit to our range! */
  113401. if(*y0>1023)*y0=1023;
  113402. if(*y1>1023)*y1=1023;
  113403. if(*y0<0)*y0=0;
  113404. if(*y1<0)*y1=0;
  113405. }else{
  113406. *y0=0;
  113407. *y1=0;
  113408. }
  113409. }
  113410. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113411. long y=0;
  113412. int i;
  113413. for(i=0;i<fits && y==0;i++)
  113414. y+=a[i].ya;
  113415. *y0=*y1=y;
  113416. }*/
  113417. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113418. const float *mdct,
  113419. vorbis_info_floor1 *info){
  113420. int dy=y1-y0;
  113421. int adx=x1-x0;
  113422. int ady=abs(dy);
  113423. int base=dy/adx;
  113424. int sy=(dy<0?base-1:base+1);
  113425. int x=x0;
  113426. int y=y0;
  113427. int err=0;
  113428. int val=vorbis_dBquant(mask+x);
  113429. int mse=0;
  113430. int n=0;
  113431. ady-=abs(base*adx);
  113432. mse=(y-val);
  113433. mse*=mse;
  113434. n++;
  113435. if(mdct[x]+info->twofitatten>=mask[x]){
  113436. if(y+info->maxover<val)return(1);
  113437. if(y-info->maxunder>val)return(1);
  113438. }
  113439. while(++x<x1){
  113440. err=err+ady;
  113441. if(err>=adx){
  113442. err-=adx;
  113443. y+=sy;
  113444. }else{
  113445. y+=base;
  113446. }
  113447. val=vorbis_dBquant(mask+x);
  113448. mse+=((y-val)*(y-val));
  113449. n++;
  113450. if(mdct[x]+info->twofitatten>=mask[x]){
  113451. if(val){
  113452. if(y+info->maxover<val)return(1);
  113453. if(y-info->maxunder>val)return(1);
  113454. }
  113455. }
  113456. }
  113457. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113458. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113459. if(mse/n>info->maxerr)return(1);
  113460. return(0);
  113461. }
  113462. static int post_Y(int *A,int *B,int pos){
  113463. if(A[pos]<0)
  113464. return B[pos];
  113465. if(B[pos]<0)
  113466. return A[pos];
  113467. return (A[pos]+B[pos])>>1;
  113468. }
  113469. int *floor1_fit(vorbis_block *vb,void *look_,
  113470. const float *logmdct, /* in */
  113471. const float *logmask){
  113472. long i,j;
  113473. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113474. vorbis_info_floor1 *info=look->vi;
  113475. long n=look->n;
  113476. long posts=look->posts;
  113477. long nonzero=0;
  113478. lsfit_acc fits[VIF_POSIT+1];
  113479. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113480. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113481. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113482. int hineighbor[VIF_POSIT+2];
  113483. int *output=NULL;
  113484. int memo[VIF_POSIT+2];
  113485. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113486. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113487. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113488. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113489. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113490. /* quantize the relevant floor points and collect them into line fit
  113491. structures (one per minimal division) at the same time */
  113492. if(posts==0){
  113493. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113494. }else{
  113495. for(i=0;i<posts-1;i++)
  113496. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113497. look->sorted_index[i+1],fits+i,
  113498. n,info);
  113499. }
  113500. if(nonzero){
  113501. /* start by fitting the implicit base case.... */
  113502. int y0=-200;
  113503. int y1=-200;
  113504. fit_line(fits,posts-1,&y0,&y1);
  113505. fit_valueA[0]=y0;
  113506. fit_valueB[0]=y0;
  113507. fit_valueB[1]=y1;
  113508. fit_valueA[1]=y1;
  113509. /* Non degenerate case */
  113510. /* start progressive splitting. This is a greedy, non-optimal
  113511. algorithm, but simple and close enough to the best
  113512. answer. */
  113513. for(i=2;i<posts;i++){
  113514. int sortpos=look->reverse_index[i];
  113515. int ln=loneighbor[sortpos];
  113516. int hn=hineighbor[sortpos];
  113517. /* eliminate repeat searches of a particular range with a memo */
  113518. if(memo[ln]!=hn){
  113519. /* haven't performed this error search yet */
  113520. int lsortpos=look->reverse_index[ln];
  113521. int hsortpos=look->reverse_index[hn];
  113522. memo[ln]=hn;
  113523. {
  113524. /* A note: we want to bound/minimize *local*, not global, error */
  113525. int lx=info->postlist[ln];
  113526. int hx=info->postlist[hn];
  113527. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113528. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113529. if(ly==-1 || hy==-1){
  113530. exit(1);
  113531. }
  113532. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113533. /* outside error bounds/begin search area. Split it. */
  113534. int ly0=-200;
  113535. int ly1=-200;
  113536. int hy0=-200;
  113537. int hy1=-200;
  113538. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113539. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113540. /* store new edge values */
  113541. fit_valueB[ln]=ly0;
  113542. if(ln==0)fit_valueA[ln]=ly0;
  113543. fit_valueA[i]=ly1;
  113544. fit_valueB[i]=hy0;
  113545. fit_valueA[hn]=hy1;
  113546. if(hn==1)fit_valueB[hn]=hy1;
  113547. if(ly1>=0 || hy0>=0){
  113548. /* store new neighbor values */
  113549. for(j=sortpos-1;j>=0;j--)
  113550. if(hineighbor[j]==hn)
  113551. hineighbor[j]=i;
  113552. else
  113553. break;
  113554. for(j=sortpos+1;j<posts;j++)
  113555. if(loneighbor[j]==ln)
  113556. loneighbor[j]=i;
  113557. else
  113558. break;
  113559. }
  113560. }else{
  113561. fit_valueA[i]=-200;
  113562. fit_valueB[i]=-200;
  113563. }
  113564. }
  113565. }
  113566. }
  113567. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113568. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113569. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113570. /* fill in posts marked as not using a fit; we will zero
  113571. back out to 'unused' when encoding them so long as curve
  113572. interpolation doesn't force them into use */
  113573. for(i=2;i<posts;i++){
  113574. int ln=look->loneighbor[i-2];
  113575. int hn=look->hineighbor[i-2];
  113576. int x0=info->postlist[ln];
  113577. int x1=info->postlist[hn];
  113578. int y0=output[ln];
  113579. int y1=output[hn];
  113580. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113581. int vx=post_Y(fit_valueA,fit_valueB,i);
  113582. if(vx>=0 && predicted!=vx){
  113583. output[i]=vx;
  113584. }else{
  113585. output[i]= predicted|0x8000;
  113586. }
  113587. }
  113588. }
  113589. return(output);
  113590. }
  113591. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113592. int *A,int *B,
  113593. int del){
  113594. long i;
  113595. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113596. long posts=look->posts;
  113597. int *output=NULL;
  113598. if(A && B){
  113599. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113600. for(i=0;i<posts;i++){
  113601. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113602. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113603. }
  113604. }
  113605. return(output);
  113606. }
  113607. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113608. void*look_,
  113609. int *post,int *ilogmask){
  113610. long i,j;
  113611. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113612. vorbis_info_floor1 *info=look->vi;
  113613. long posts=look->posts;
  113614. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113615. int out[VIF_POSIT+2];
  113616. static_codebook **sbooks=ci->book_param;
  113617. codebook *books=ci->fullbooks;
  113618. static long seq=0;
  113619. /* quantize values to multiplier spec */
  113620. if(post){
  113621. for(i=0;i<posts;i++){
  113622. int val=post[i]&0x7fff;
  113623. switch(info->mult){
  113624. case 1: /* 1024 -> 256 */
  113625. val>>=2;
  113626. break;
  113627. case 2: /* 1024 -> 128 */
  113628. val>>=3;
  113629. break;
  113630. case 3: /* 1024 -> 86 */
  113631. val/=12;
  113632. break;
  113633. case 4: /* 1024 -> 64 */
  113634. val>>=4;
  113635. break;
  113636. }
  113637. post[i]=val | (post[i]&0x8000);
  113638. }
  113639. out[0]=post[0];
  113640. out[1]=post[1];
  113641. /* find prediction values for each post and subtract them */
  113642. for(i=2;i<posts;i++){
  113643. int ln=look->loneighbor[i-2];
  113644. int hn=look->hineighbor[i-2];
  113645. int x0=info->postlist[ln];
  113646. int x1=info->postlist[hn];
  113647. int y0=post[ln];
  113648. int y1=post[hn];
  113649. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113650. if((post[i]&0x8000) || (predicted==post[i])){
  113651. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113652. in interpolation */
  113653. out[i]=0;
  113654. }else{
  113655. int headroom=(look->quant_q-predicted<predicted?
  113656. look->quant_q-predicted:predicted);
  113657. int val=post[i]-predicted;
  113658. /* at this point the 'deviation' value is in the range +/- max
  113659. range, but the real, unique range can always be mapped to
  113660. only [0-maxrange). So we want to wrap the deviation into
  113661. this limited range, but do it in the way that least screws
  113662. an essentially gaussian probability distribution. */
  113663. if(val<0)
  113664. if(val<-headroom)
  113665. val=headroom-val-1;
  113666. else
  113667. val=-1-(val<<1);
  113668. else
  113669. if(val>=headroom)
  113670. val= val+headroom;
  113671. else
  113672. val<<=1;
  113673. out[i]=val;
  113674. post[ln]&=0x7fff;
  113675. post[hn]&=0x7fff;
  113676. }
  113677. }
  113678. /* we have everything we need. pack it out */
  113679. /* mark nontrivial floor */
  113680. oggpack_write(opb,1,1);
  113681. /* beginning/end post */
  113682. look->frames++;
  113683. look->postbits+=ilog(look->quant_q-1)*2;
  113684. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113685. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113686. /* partition by partition */
  113687. for(i=0,j=2;i<info->partitions;i++){
  113688. int classx=info->partitionclass[i];
  113689. int cdim=info->class_dim[classx];
  113690. int csubbits=info->class_subs[classx];
  113691. int csub=1<<csubbits;
  113692. int bookas[8]={0,0,0,0,0,0,0,0};
  113693. int cval=0;
  113694. int cshift=0;
  113695. int k,l;
  113696. /* generate the partition's first stage cascade value */
  113697. if(csubbits){
  113698. int maxval[8];
  113699. for(k=0;k<csub;k++){
  113700. int booknum=info->class_subbook[classx][k];
  113701. if(booknum<0){
  113702. maxval[k]=1;
  113703. }else{
  113704. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113705. }
  113706. }
  113707. for(k=0;k<cdim;k++){
  113708. for(l=0;l<csub;l++){
  113709. int val=out[j+k];
  113710. if(val<maxval[l]){
  113711. bookas[k]=l;
  113712. break;
  113713. }
  113714. }
  113715. cval|= bookas[k]<<cshift;
  113716. cshift+=csubbits;
  113717. }
  113718. /* write it */
  113719. look->phrasebits+=
  113720. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113721. #ifdef TRAIN_FLOOR1
  113722. {
  113723. FILE *of;
  113724. char buffer[80];
  113725. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113726. vb->pcmend/2,posts-2,class);
  113727. of=fopen(buffer,"a");
  113728. fprintf(of,"%d\n",cval);
  113729. fclose(of);
  113730. }
  113731. #endif
  113732. }
  113733. /* write post values */
  113734. for(k=0;k<cdim;k++){
  113735. int book=info->class_subbook[classx][bookas[k]];
  113736. if(book>=0){
  113737. /* hack to allow training with 'bad' books */
  113738. if(out[j+k]<(books+book)->entries)
  113739. look->postbits+=vorbis_book_encode(books+book,
  113740. out[j+k],opb);
  113741. /*else
  113742. fprintf(stderr,"+!");*/
  113743. #ifdef TRAIN_FLOOR1
  113744. {
  113745. FILE *of;
  113746. char buffer[80];
  113747. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113748. vb->pcmend/2,posts-2,class,bookas[k]);
  113749. of=fopen(buffer,"a");
  113750. fprintf(of,"%d\n",out[j+k]);
  113751. fclose(of);
  113752. }
  113753. #endif
  113754. }
  113755. }
  113756. j+=cdim;
  113757. }
  113758. {
  113759. /* generate quantized floor equivalent to what we'd unpack in decode */
  113760. /* render the lines */
  113761. int hx=0;
  113762. int lx=0;
  113763. int ly=post[0]*info->mult;
  113764. for(j=1;j<look->posts;j++){
  113765. int current=look->forward_index[j];
  113766. int hy=post[current]&0x7fff;
  113767. if(hy==post[current]){
  113768. hy*=info->mult;
  113769. hx=info->postlist[current];
  113770. render_line0(lx,hx,ly,hy,ilogmask);
  113771. lx=hx;
  113772. ly=hy;
  113773. }
  113774. }
  113775. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113776. seq++;
  113777. return(1);
  113778. }
  113779. }else{
  113780. oggpack_write(opb,0,1);
  113781. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113782. seq++;
  113783. return(0);
  113784. }
  113785. }
  113786. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113787. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113788. vorbis_info_floor1 *info=look->vi;
  113789. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113790. int i,j,k;
  113791. codebook *books=ci->fullbooks;
  113792. /* unpack wrapped/predicted values from stream */
  113793. if(oggpack_read(&vb->opb,1)==1){
  113794. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113795. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113796. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113797. /* partition by partition */
  113798. for(i=0,j=2;i<info->partitions;i++){
  113799. int classx=info->partitionclass[i];
  113800. int cdim=info->class_dim[classx];
  113801. int csubbits=info->class_subs[classx];
  113802. int csub=1<<csubbits;
  113803. int cval=0;
  113804. /* decode the partition's first stage cascade value */
  113805. if(csubbits){
  113806. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113807. if(cval==-1)goto eop;
  113808. }
  113809. for(k=0;k<cdim;k++){
  113810. int book=info->class_subbook[classx][cval&(csub-1)];
  113811. cval>>=csubbits;
  113812. if(book>=0){
  113813. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113814. goto eop;
  113815. }else{
  113816. fit_value[j+k]=0;
  113817. }
  113818. }
  113819. j+=cdim;
  113820. }
  113821. /* unwrap positive values and reconsitute via linear interpolation */
  113822. for(i=2;i<look->posts;i++){
  113823. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113824. info->postlist[look->hineighbor[i-2]],
  113825. fit_value[look->loneighbor[i-2]],
  113826. fit_value[look->hineighbor[i-2]],
  113827. info->postlist[i]);
  113828. int hiroom=look->quant_q-predicted;
  113829. int loroom=predicted;
  113830. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113831. int val=fit_value[i];
  113832. if(val){
  113833. if(val>=room){
  113834. if(hiroom>loroom){
  113835. val = val-loroom;
  113836. }else{
  113837. val = -1-(val-hiroom);
  113838. }
  113839. }else{
  113840. if(val&1){
  113841. val= -((val+1)>>1);
  113842. }else{
  113843. val>>=1;
  113844. }
  113845. }
  113846. fit_value[i]=val+predicted;
  113847. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113848. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113849. }else{
  113850. fit_value[i]=predicted|0x8000;
  113851. }
  113852. }
  113853. return(fit_value);
  113854. }
  113855. eop:
  113856. return(NULL);
  113857. }
  113858. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113859. float *out){
  113860. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113861. vorbis_info_floor1 *info=look->vi;
  113862. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113863. int n=ci->blocksizes[vb->W]/2;
  113864. int j;
  113865. if(memo){
  113866. /* render the lines */
  113867. int *fit_value=(int *)memo;
  113868. int hx=0;
  113869. int lx=0;
  113870. int ly=fit_value[0]*info->mult;
  113871. for(j=1;j<look->posts;j++){
  113872. int current=look->forward_index[j];
  113873. int hy=fit_value[current]&0x7fff;
  113874. if(hy==fit_value[current]){
  113875. hy*=info->mult;
  113876. hx=info->postlist[current];
  113877. render_line(lx,hx,ly,hy,out);
  113878. lx=hx;
  113879. ly=hy;
  113880. }
  113881. }
  113882. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113883. return(1);
  113884. }
  113885. memset(out,0,sizeof(*out)*n);
  113886. return(0);
  113887. }
  113888. /* export hooks */
  113889. vorbis_func_floor floor1_exportbundle={
  113890. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113891. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113892. };
  113893. #endif
  113894. /*** End of inlined file: floor1.c ***/
  113895. /*** Start of inlined file: info.c ***/
  113896. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113897. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113898. // tasks..
  113899. #if JUCE_MSVC
  113900. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113901. #endif
  113902. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113903. #if JUCE_USE_OGGVORBIS
  113904. /* general handling of the header and the vorbis_info structure (and
  113905. substructures) */
  113906. #include <stdlib.h>
  113907. #include <string.h>
  113908. #include <ctype.h>
  113909. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113910. while(bytes--){
  113911. oggpack_write(o,*s++,8);
  113912. }
  113913. }
  113914. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113915. while(bytes--){
  113916. *buf++=oggpack_read(o,8);
  113917. }
  113918. }
  113919. void vorbis_comment_init(vorbis_comment *vc){
  113920. memset(vc,0,sizeof(*vc));
  113921. }
  113922. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113923. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113924. (vc->comments+2)*sizeof(*vc->user_comments));
  113925. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113926. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113927. vc->comment_lengths[vc->comments]=strlen(comment);
  113928. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113929. strcpy(vc->user_comments[vc->comments], comment);
  113930. vc->comments++;
  113931. vc->user_comments[vc->comments]=NULL;
  113932. }
  113933. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113934. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113935. strcpy(comment, tag);
  113936. strcat(comment, "=");
  113937. strcat(comment, contents);
  113938. vorbis_comment_add(vc, comment);
  113939. }
  113940. /* This is more or less the same as strncasecmp - but that doesn't exist
  113941. * everywhere, and this is a fairly trivial function, so we include it */
  113942. static int tagcompare(const char *s1, const char *s2, int n){
  113943. int c=0;
  113944. while(c < n){
  113945. if(toupper(s1[c]) != toupper(s2[c]))
  113946. return !0;
  113947. c++;
  113948. }
  113949. return 0;
  113950. }
  113951. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113952. long i;
  113953. int found = 0;
  113954. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113955. char *fulltag = (char*)alloca(taglen+ 1);
  113956. strcpy(fulltag, tag);
  113957. strcat(fulltag, "=");
  113958. for(i=0;i<vc->comments;i++){
  113959. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113960. if(count == found)
  113961. /* We return a pointer to the data, not a copy */
  113962. return vc->user_comments[i] + taglen;
  113963. else
  113964. found++;
  113965. }
  113966. }
  113967. return NULL; /* didn't find anything */
  113968. }
  113969. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113970. int i,count=0;
  113971. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113972. char *fulltag = (char*)alloca(taglen+1);
  113973. strcpy(fulltag,tag);
  113974. strcat(fulltag, "=");
  113975. for(i=0;i<vc->comments;i++){
  113976. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113977. count++;
  113978. }
  113979. return count;
  113980. }
  113981. void vorbis_comment_clear(vorbis_comment *vc){
  113982. if(vc){
  113983. long i;
  113984. for(i=0;i<vc->comments;i++)
  113985. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113986. if(vc->user_comments)_ogg_free(vc->user_comments);
  113987. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113988. if(vc->vendor)_ogg_free(vc->vendor);
  113989. }
  113990. memset(vc,0,sizeof(*vc));
  113991. }
  113992. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113993. They may be equal, but short will never ge greater than long */
  113994. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113995. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113996. return ci ? ci->blocksizes[zo] : -1;
  113997. }
  113998. /* used by synthesis, which has a full, alloced vi */
  113999. void vorbis_info_init(vorbis_info *vi){
  114000. memset(vi,0,sizeof(*vi));
  114001. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  114002. }
  114003. void vorbis_info_clear(vorbis_info *vi){
  114004. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114005. int i;
  114006. if(ci){
  114007. for(i=0;i<ci->modes;i++)
  114008. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  114009. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  114010. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  114011. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  114012. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  114013. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  114014. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  114015. for(i=0;i<ci->books;i++){
  114016. if(ci->book_param[i]){
  114017. /* knows if the book was not alloced */
  114018. vorbis_staticbook_destroy(ci->book_param[i]);
  114019. }
  114020. if(ci->fullbooks)
  114021. vorbis_book_clear(ci->fullbooks+i);
  114022. }
  114023. if(ci->fullbooks)
  114024. _ogg_free(ci->fullbooks);
  114025. for(i=0;i<ci->psys;i++)
  114026. _vi_psy_free(ci->psy_param[i]);
  114027. _ogg_free(ci);
  114028. }
  114029. memset(vi,0,sizeof(*vi));
  114030. }
  114031. /* Header packing/unpacking ********************************************/
  114032. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  114033. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114034. if(!ci)return(OV_EFAULT);
  114035. vi->version=oggpack_read(opb,32);
  114036. if(vi->version!=0)return(OV_EVERSION);
  114037. vi->channels=oggpack_read(opb,8);
  114038. vi->rate=oggpack_read(opb,32);
  114039. vi->bitrate_upper=oggpack_read(opb,32);
  114040. vi->bitrate_nominal=oggpack_read(opb,32);
  114041. vi->bitrate_lower=oggpack_read(opb,32);
  114042. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  114043. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  114044. if(vi->rate<1)goto err_out;
  114045. if(vi->channels<1)goto err_out;
  114046. if(ci->blocksizes[0]<8)goto err_out;
  114047. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  114048. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114049. return(0);
  114050. err_out:
  114051. vorbis_info_clear(vi);
  114052. return(OV_EBADHEADER);
  114053. }
  114054. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  114055. int i;
  114056. int vendorlen=oggpack_read(opb,32);
  114057. if(vendorlen<0)goto err_out;
  114058. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  114059. _v_readstring(opb,vc->vendor,vendorlen);
  114060. vc->comments=oggpack_read(opb,32);
  114061. if(vc->comments<0)goto err_out;
  114062. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  114063. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  114064. for(i=0;i<vc->comments;i++){
  114065. int len=oggpack_read(opb,32);
  114066. if(len<0)goto err_out;
  114067. vc->comment_lengths[i]=len;
  114068. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  114069. _v_readstring(opb,vc->user_comments[i],len);
  114070. }
  114071. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114072. return(0);
  114073. err_out:
  114074. vorbis_comment_clear(vc);
  114075. return(OV_EBADHEADER);
  114076. }
  114077. /* all of the real encoding details are here. The modes, books,
  114078. everything */
  114079. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  114080. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114081. int i;
  114082. if(!ci)return(OV_EFAULT);
  114083. /* codebooks */
  114084. ci->books=oggpack_read(opb,8)+1;
  114085. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  114086. for(i=0;i<ci->books;i++){
  114087. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  114088. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  114089. }
  114090. /* time backend settings; hooks are unused */
  114091. {
  114092. int times=oggpack_read(opb,6)+1;
  114093. for(i=0;i<times;i++){
  114094. int test=oggpack_read(opb,16);
  114095. if(test<0 || test>=VI_TIMEB)goto err_out;
  114096. }
  114097. }
  114098. /* floor backend settings */
  114099. ci->floors=oggpack_read(opb,6)+1;
  114100. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  114101. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  114102. for(i=0;i<ci->floors;i++){
  114103. ci->floor_type[i]=oggpack_read(opb,16);
  114104. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  114105. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  114106. if(!ci->floor_param[i])goto err_out;
  114107. }
  114108. /* residue backend settings */
  114109. ci->residues=oggpack_read(opb,6)+1;
  114110. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  114111. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  114112. for(i=0;i<ci->residues;i++){
  114113. ci->residue_type[i]=oggpack_read(opb,16);
  114114. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  114115. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  114116. if(!ci->residue_param[i])goto err_out;
  114117. }
  114118. /* map backend settings */
  114119. ci->maps=oggpack_read(opb,6)+1;
  114120. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  114121. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  114122. for(i=0;i<ci->maps;i++){
  114123. ci->map_type[i]=oggpack_read(opb,16);
  114124. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  114125. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  114126. if(!ci->map_param[i])goto err_out;
  114127. }
  114128. /* mode settings */
  114129. ci->modes=oggpack_read(opb,6)+1;
  114130. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  114131. for(i=0;i<ci->modes;i++){
  114132. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  114133. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  114134. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  114135. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  114136. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  114137. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  114138. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  114139. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  114140. }
  114141. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  114142. return(0);
  114143. err_out:
  114144. vorbis_info_clear(vi);
  114145. return(OV_EBADHEADER);
  114146. }
  114147. /* The Vorbis header is in three packets; the initial small packet in
  114148. the first page that identifies basic parameters, a second packet
  114149. with bitstream comments and a third packet that holds the
  114150. codebook. */
  114151. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114152. oggpack_buffer opb;
  114153. if(op){
  114154. oggpack_readinit(&opb,op->packet,op->bytes);
  114155. /* Which of the three types of header is this? */
  114156. /* Also verify header-ness, vorbis */
  114157. {
  114158. char buffer[6];
  114159. int packtype=oggpack_read(&opb,8);
  114160. memset(buffer,0,6);
  114161. _v_readstring(&opb,buffer,6);
  114162. if(memcmp(buffer,"vorbis",6)){
  114163. /* not a vorbis header */
  114164. return(OV_ENOTVORBIS);
  114165. }
  114166. switch(packtype){
  114167. case 0x01: /* least significant *bit* is read first */
  114168. if(!op->b_o_s){
  114169. /* Not the initial packet */
  114170. return(OV_EBADHEADER);
  114171. }
  114172. if(vi->rate!=0){
  114173. /* previously initialized info header */
  114174. return(OV_EBADHEADER);
  114175. }
  114176. return(_vorbis_unpack_info(vi,&opb));
  114177. case 0x03: /* least significant *bit* is read first */
  114178. if(vi->rate==0){
  114179. /* um... we didn't get the initial header */
  114180. return(OV_EBADHEADER);
  114181. }
  114182. return(_vorbis_unpack_comment(vc,&opb));
  114183. case 0x05: /* least significant *bit* is read first */
  114184. if(vi->rate==0 || vc->vendor==NULL){
  114185. /* um... we didn;t get the initial header or comments yet */
  114186. return(OV_EBADHEADER);
  114187. }
  114188. return(_vorbis_unpack_books(vi,&opb));
  114189. default:
  114190. /* Not a valid vorbis header type */
  114191. return(OV_EBADHEADER);
  114192. break;
  114193. }
  114194. }
  114195. }
  114196. return(OV_EBADHEADER);
  114197. }
  114198. /* pack side **********************************************************/
  114199. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114200. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114201. if(!ci)return(OV_EFAULT);
  114202. /* preamble */
  114203. oggpack_write(opb,0x01,8);
  114204. _v_writestring(opb,"vorbis", 6);
  114205. /* basic information about the stream */
  114206. oggpack_write(opb,0x00,32);
  114207. oggpack_write(opb,vi->channels,8);
  114208. oggpack_write(opb,vi->rate,32);
  114209. oggpack_write(opb,vi->bitrate_upper,32);
  114210. oggpack_write(opb,vi->bitrate_nominal,32);
  114211. oggpack_write(opb,vi->bitrate_lower,32);
  114212. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114213. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114214. oggpack_write(opb,1,1);
  114215. return(0);
  114216. }
  114217. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114218. char temp[]="Xiph.Org libVorbis I 20050304";
  114219. int bytes = strlen(temp);
  114220. /* preamble */
  114221. oggpack_write(opb,0x03,8);
  114222. _v_writestring(opb,"vorbis", 6);
  114223. /* vendor */
  114224. oggpack_write(opb,bytes,32);
  114225. _v_writestring(opb,temp, bytes);
  114226. /* comments */
  114227. oggpack_write(opb,vc->comments,32);
  114228. if(vc->comments){
  114229. int i;
  114230. for(i=0;i<vc->comments;i++){
  114231. if(vc->user_comments[i]){
  114232. oggpack_write(opb,vc->comment_lengths[i],32);
  114233. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114234. }else{
  114235. oggpack_write(opb,0,32);
  114236. }
  114237. }
  114238. }
  114239. oggpack_write(opb,1,1);
  114240. return(0);
  114241. }
  114242. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114243. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114244. int i;
  114245. if(!ci)return(OV_EFAULT);
  114246. oggpack_write(opb,0x05,8);
  114247. _v_writestring(opb,"vorbis", 6);
  114248. /* books */
  114249. oggpack_write(opb,ci->books-1,8);
  114250. for(i=0;i<ci->books;i++)
  114251. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114252. /* times; hook placeholders */
  114253. oggpack_write(opb,0,6);
  114254. oggpack_write(opb,0,16);
  114255. /* floors */
  114256. oggpack_write(opb,ci->floors-1,6);
  114257. for(i=0;i<ci->floors;i++){
  114258. oggpack_write(opb,ci->floor_type[i],16);
  114259. if(_floor_P[ci->floor_type[i]]->pack)
  114260. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114261. else
  114262. goto err_out;
  114263. }
  114264. /* residues */
  114265. oggpack_write(opb,ci->residues-1,6);
  114266. for(i=0;i<ci->residues;i++){
  114267. oggpack_write(opb,ci->residue_type[i],16);
  114268. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114269. }
  114270. /* maps */
  114271. oggpack_write(opb,ci->maps-1,6);
  114272. for(i=0;i<ci->maps;i++){
  114273. oggpack_write(opb,ci->map_type[i],16);
  114274. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114275. }
  114276. /* modes */
  114277. oggpack_write(opb,ci->modes-1,6);
  114278. for(i=0;i<ci->modes;i++){
  114279. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114280. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114281. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114282. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114283. }
  114284. oggpack_write(opb,1,1);
  114285. return(0);
  114286. err_out:
  114287. return(-1);
  114288. }
  114289. int vorbis_commentheader_out(vorbis_comment *vc,
  114290. ogg_packet *op){
  114291. oggpack_buffer opb;
  114292. oggpack_writeinit(&opb);
  114293. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114294. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114295. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114296. op->bytes=oggpack_bytes(&opb);
  114297. op->b_o_s=0;
  114298. op->e_o_s=0;
  114299. op->granulepos=0;
  114300. op->packetno=1;
  114301. return 0;
  114302. }
  114303. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114304. vorbis_comment *vc,
  114305. ogg_packet *op,
  114306. ogg_packet *op_comm,
  114307. ogg_packet *op_code){
  114308. int ret=OV_EIMPL;
  114309. vorbis_info *vi=v->vi;
  114310. oggpack_buffer opb;
  114311. private_state *b=(private_state*)v->backend_state;
  114312. if(!b){
  114313. ret=OV_EFAULT;
  114314. goto err_out;
  114315. }
  114316. /* first header packet **********************************************/
  114317. oggpack_writeinit(&opb);
  114318. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114319. /* build the packet */
  114320. if(b->header)_ogg_free(b->header);
  114321. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114322. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114323. op->packet=b->header;
  114324. op->bytes=oggpack_bytes(&opb);
  114325. op->b_o_s=1;
  114326. op->e_o_s=0;
  114327. op->granulepos=0;
  114328. op->packetno=0;
  114329. /* second header packet (comments) **********************************/
  114330. oggpack_reset(&opb);
  114331. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114332. if(b->header1)_ogg_free(b->header1);
  114333. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114334. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114335. op_comm->packet=b->header1;
  114336. op_comm->bytes=oggpack_bytes(&opb);
  114337. op_comm->b_o_s=0;
  114338. op_comm->e_o_s=0;
  114339. op_comm->granulepos=0;
  114340. op_comm->packetno=1;
  114341. /* third header packet (modes/codebooks) ****************************/
  114342. oggpack_reset(&opb);
  114343. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114344. if(b->header2)_ogg_free(b->header2);
  114345. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114346. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114347. op_code->packet=b->header2;
  114348. op_code->bytes=oggpack_bytes(&opb);
  114349. op_code->b_o_s=0;
  114350. op_code->e_o_s=0;
  114351. op_code->granulepos=0;
  114352. op_code->packetno=2;
  114353. oggpack_writeclear(&opb);
  114354. return(0);
  114355. err_out:
  114356. oggpack_writeclear(&opb);
  114357. memset(op,0,sizeof(*op));
  114358. memset(op_comm,0,sizeof(*op_comm));
  114359. memset(op_code,0,sizeof(*op_code));
  114360. if(b->header)_ogg_free(b->header);
  114361. if(b->header1)_ogg_free(b->header1);
  114362. if(b->header2)_ogg_free(b->header2);
  114363. b->header=NULL;
  114364. b->header1=NULL;
  114365. b->header2=NULL;
  114366. return(ret);
  114367. }
  114368. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114369. if(granulepos>=0)
  114370. return((double)granulepos/v->vi->rate);
  114371. return(-1);
  114372. }
  114373. #endif
  114374. /*** End of inlined file: info.c ***/
  114375. /*** Start of inlined file: lpc.c ***/
  114376. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114377. are derived from code written by Jutta Degener and Carsten Bormann;
  114378. thus we include their copyright below. The entirety of this file
  114379. is freely redistributable on the condition that both of these
  114380. copyright notices are preserved without modification. */
  114381. /* Preserved Copyright: *********************************************/
  114382. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114383. Technische Universita"t Berlin
  114384. Any use of this software is permitted provided that this notice is not
  114385. removed and that neither the authors nor the Technische Universita"t
  114386. Berlin are deemed to have made any representations as to the
  114387. suitability of this software for any purpose nor are held responsible
  114388. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114389. THIS SOFTWARE.
  114390. As a matter of courtesy, the authors request to be informed about uses
  114391. this software has found, about bugs in this software, and about any
  114392. improvements that may be of general interest.
  114393. Berlin, 28.11.1994
  114394. Jutta Degener
  114395. Carsten Bormann
  114396. *********************************************************************/
  114397. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114398. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114399. // tasks..
  114400. #if JUCE_MSVC
  114401. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114402. #endif
  114403. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114404. #if JUCE_USE_OGGVORBIS
  114405. #include <stdlib.h>
  114406. #include <string.h>
  114407. #include <math.h>
  114408. /* Autocorrelation LPC coeff generation algorithm invented by
  114409. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114410. /* Input : n elements of time doamin data
  114411. Output: m lpc coefficients, excitation energy */
  114412. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114413. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114414. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114415. double error;
  114416. int i,j;
  114417. /* autocorrelation, p+1 lag coefficients */
  114418. j=m+1;
  114419. while(j--){
  114420. double d=0; /* double needed for accumulator depth */
  114421. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114422. aut[j]=d;
  114423. }
  114424. /* Generate lpc coefficients from autocorr values */
  114425. error=aut[0];
  114426. for(i=0;i<m;i++){
  114427. double r= -aut[i+1];
  114428. if(error==0){
  114429. memset(lpci,0,m*sizeof(*lpci));
  114430. return 0;
  114431. }
  114432. /* Sum up this iteration's reflection coefficient; note that in
  114433. Vorbis we don't save it. If anyone wants to recycle this code
  114434. and needs reflection coefficients, save the results of 'r' from
  114435. each iteration. */
  114436. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114437. r/=error;
  114438. /* Update LPC coefficients and total error */
  114439. lpc[i]=r;
  114440. for(j=0;j<i/2;j++){
  114441. double tmp=lpc[j];
  114442. lpc[j]+=r*lpc[i-1-j];
  114443. lpc[i-1-j]+=r*tmp;
  114444. }
  114445. if(i%2)lpc[j]+=lpc[j]*r;
  114446. error*=1.f-r*r;
  114447. }
  114448. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114449. /* we need the error value to know how big an impulse to hit the
  114450. filter with later */
  114451. return error;
  114452. }
  114453. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114454. float *data,long n){
  114455. /* in: coeff[0...m-1] LPC coefficients
  114456. prime[0...m-1] initial values (allocated size of n+m-1)
  114457. out: data[0...n-1] data samples */
  114458. long i,j,o,p;
  114459. float y;
  114460. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114461. if(!prime)
  114462. for(i=0;i<m;i++)
  114463. work[i]=0.f;
  114464. else
  114465. for(i=0;i<m;i++)
  114466. work[i]=prime[i];
  114467. for(i=0;i<n;i++){
  114468. y=0;
  114469. o=i;
  114470. p=m;
  114471. for(j=0;j<m;j++)
  114472. y-=work[o++]*coeff[--p];
  114473. data[i]=work[o]=y;
  114474. }
  114475. }
  114476. #endif
  114477. /*** End of inlined file: lpc.c ***/
  114478. /*** Start of inlined file: lsp.c ***/
  114479. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114480. an iterative root polisher (CACM algorithm 283). It *is* possible
  114481. to confuse this algorithm into not converging; that should only
  114482. happen with absurdly closely spaced roots (very sharp peaks in the
  114483. LPC f response) which in turn should be impossible in our use of
  114484. the code. If this *does* happen anyway, it's a bug in the floor
  114485. finder; find the cause of the confusion (probably a single bin
  114486. spike or accidental near-float-limit resolution problems) and
  114487. correct it. */
  114488. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114489. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114490. // tasks..
  114491. #if JUCE_MSVC
  114492. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114493. #endif
  114494. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114495. #if JUCE_USE_OGGVORBIS
  114496. #include <math.h>
  114497. #include <string.h>
  114498. #include <stdlib.h>
  114499. /*** Start of inlined file: lookup.h ***/
  114500. #ifndef _V_LOOKUP_H_
  114501. #ifdef FLOAT_LOOKUP
  114502. extern float vorbis_coslook(float a);
  114503. extern float vorbis_invsqlook(float a);
  114504. extern float vorbis_invsq2explook(int a);
  114505. extern float vorbis_fromdBlook(float a);
  114506. #endif
  114507. #ifdef INT_LOOKUP
  114508. extern long vorbis_invsqlook_i(long a,long e);
  114509. extern long vorbis_coslook_i(long a);
  114510. extern float vorbis_fromdBlook_i(long a);
  114511. #endif
  114512. #endif
  114513. /*** End of inlined file: lookup.h ***/
  114514. /* three possible LSP to f curve functions; the exact computation
  114515. (float), a lookup based float implementation, and an integer
  114516. implementation. The float lookup is likely the optimal choice on
  114517. any machine with an FPU. The integer implementation is *not* fixed
  114518. point (due to the need for a large dynamic range and thus a
  114519. seperately tracked exponent) and thus much more complex than the
  114520. relatively simple float implementations. It's mostly for future
  114521. work on a fully fixed point implementation for processors like the
  114522. ARM family. */
  114523. /* undefine both for the 'old' but more precise implementation */
  114524. #define FLOAT_LOOKUP
  114525. #undef INT_LOOKUP
  114526. #ifdef FLOAT_LOOKUP
  114527. /*** Start of inlined file: lookup.c ***/
  114528. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114529. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114530. // tasks..
  114531. #if JUCE_MSVC
  114532. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114533. #endif
  114534. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114535. #if JUCE_USE_OGGVORBIS
  114536. #include <math.h>
  114537. /*** Start of inlined file: lookup.h ***/
  114538. #ifndef _V_LOOKUP_H_
  114539. #ifdef FLOAT_LOOKUP
  114540. extern float vorbis_coslook(float a);
  114541. extern float vorbis_invsqlook(float a);
  114542. extern float vorbis_invsq2explook(int a);
  114543. extern float vorbis_fromdBlook(float a);
  114544. #endif
  114545. #ifdef INT_LOOKUP
  114546. extern long vorbis_invsqlook_i(long a,long e);
  114547. extern long vorbis_coslook_i(long a);
  114548. extern float vorbis_fromdBlook_i(long a);
  114549. #endif
  114550. #endif
  114551. /*** End of inlined file: lookup.h ***/
  114552. /*** Start of inlined file: lookup_data.h ***/
  114553. #ifndef _V_LOOKUP_DATA_H_
  114554. #ifdef FLOAT_LOOKUP
  114555. #define COS_LOOKUP_SZ 128
  114556. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114557. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114558. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114559. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114560. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114561. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114562. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114563. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114564. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114565. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114566. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114567. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114568. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114569. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114570. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114571. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114572. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114573. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114574. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114575. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114576. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114577. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114578. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114579. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114580. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114581. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114582. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114583. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114584. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114585. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114586. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114587. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114588. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114589. -1.0000000000000f,
  114590. };
  114591. #define INVSQ_LOOKUP_SZ 32
  114592. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114593. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114594. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114595. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114596. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114597. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114598. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114599. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114600. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114601. 1.000000000000f,
  114602. };
  114603. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114604. #define INVSQ2EXP_LOOKUP_MAX 32
  114605. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114606. INVSQ2EXP_LOOKUP_MIN+1]={
  114607. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114608. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114609. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114610. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114611. 256.f, 181.019336f, 128.f, 90.50966799f,
  114612. 64.f, 45.254834f, 32.f, 22.627417f,
  114613. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114614. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114615. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114616. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114617. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114618. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114619. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114620. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114621. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114622. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114623. 1.525878906e-05f,
  114624. };
  114625. #endif
  114626. #define FROMdB_LOOKUP_SZ 35
  114627. #define FROMdB2_LOOKUP_SZ 32
  114628. #define FROMdB_SHIFT 5
  114629. #define FROMdB2_SHIFT 3
  114630. #define FROMdB2_MASK 31
  114631. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114632. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114633. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114634. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114635. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114636. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114637. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114638. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114639. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114640. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114641. };
  114642. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114643. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114644. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114645. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114646. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114647. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114648. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114649. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114650. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114651. };
  114652. #ifdef INT_LOOKUP
  114653. #define INVSQ_LOOKUP_I_SHIFT 10
  114654. #define INVSQ_LOOKUP_I_MASK 1023
  114655. static long INVSQ_LOOKUP_I[64+1]={
  114656. 92682l, 91966l, 91267l, 90583l,
  114657. 89915l, 89261l, 88621l, 87995l,
  114658. 87381l, 86781l, 86192l, 85616l,
  114659. 85051l, 84497l, 83953l, 83420l,
  114660. 82897l, 82384l, 81880l, 81385l,
  114661. 80899l, 80422l, 79953l, 79492l,
  114662. 79039l, 78594l, 78156l, 77726l,
  114663. 77302l, 76885l, 76475l, 76072l,
  114664. 75674l, 75283l, 74898l, 74519l,
  114665. 74146l, 73778l, 73415l, 73058l,
  114666. 72706l, 72359l, 72016l, 71679l,
  114667. 71347l, 71019l, 70695l, 70376l,
  114668. 70061l, 69750l, 69444l, 69141l,
  114669. 68842l, 68548l, 68256l, 67969l,
  114670. 67685l, 67405l, 67128l, 66855l,
  114671. 66585l, 66318l, 66054l, 65794l,
  114672. 65536l,
  114673. };
  114674. #define COS_LOOKUP_I_SHIFT 9
  114675. #define COS_LOOKUP_I_MASK 511
  114676. #define COS_LOOKUP_I_SZ 128
  114677. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114678. 16384l, 16379l, 16364l, 16340l,
  114679. 16305l, 16261l, 16207l, 16143l,
  114680. 16069l, 15986l, 15893l, 15791l,
  114681. 15679l, 15557l, 15426l, 15286l,
  114682. 15137l, 14978l, 14811l, 14635l,
  114683. 14449l, 14256l, 14053l, 13842l,
  114684. 13623l, 13395l, 13160l, 12916l,
  114685. 12665l, 12406l, 12140l, 11866l,
  114686. 11585l, 11297l, 11003l, 10702l,
  114687. 10394l, 10080l, 9760l, 9434l,
  114688. 9102l, 8765l, 8423l, 8076l,
  114689. 7723l, 7366l, 7005l, 6639l,
  114690. 6270l, 5897l, 5520l, 5139l,
  114691. 4756l, 4370l, 3981l, 3590l,
  114692. 3196l, 2801l, 2404l, 2006l,
  114693. 1606l, 1205l, 804l, 402l,
  114694. 0l, -401l, -803l, -1204l,
  114695. -1605l, -2005l, -2403l, -2800l,
  114696. -3195l, -3589l, -3980l, -4369l,
  114697. -4755l, -5138l, -5519l, -5896l,
  114698. -6269l, -6638l, -7004l, -7365l,
  114699. -7722l, -8075l, -8422l, -8764l,
  114700. -9101l, -9433l, -9759l, -10079l,
  114701. -10393l, -10701l, -11002l, -11296l,
  114702. -11584l, -11865l, -12139l, -12405l,
  114703. -12664l, -12915l, -13159l, -13394l,
  114704. -13622l, -13841l, -14052l, -14255l,
  114705. -14448l, -14634l, -14810l, -14977l,
  114706. -15136l, -15285l, -15425l, -15556l,
  114707. -15678l, -15790l, -15892l, -15985l,
  114708. -16068l, -16142l, -16206l, -16260l,
  114709. -16304l, -16339l, -16363l, -16378l,
  114710. -16383l,
  114711. };
  114712. #endif
  114713. #endif
  114714. /*** End of inlined file: lookup_data.h ***/
  114715. #ifdef FLOAT_LOOKUP
  114716. /* interpolated lookup based cos function, domain 0 to PI only */
  114717. float vorbis_coslook(float a){
  114718. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114719. int i=vorbis_ftoi(d-.5);
  114720. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114721. }
  114722. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114723. float vorbis_invsqlook(float a){
  114724. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114725. int i=vorbis_ftoi(d-.5f);
  114726. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114727. }
  114728. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114729. float vorbis_invsq2explook(int a){
  114730. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114731. }
  114732. #include <stdio.h>
  114733. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114734. float vorbis_fromdBlook(float a){
  114735. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114736. return (i<0)?1.f:
  114737. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114738. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114739. }
  114740. #endif
  114741. #ifdef INT_LOOKUP
  114742. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114743. 16.16 format
  114744. returns in m.8 format */
  114745. long vorbis_invsqlook_i(long a,long e){
  114746. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114747. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114748. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114749. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114750. d)>>16); /* result 1.16 */
  114751. e+=32;
  114752. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114753. e=(e>>1)-8;
  114754. return(val>>e);
  114755. }
  114756. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114757. /* a is in n.12 format */
  114758. float vorbis_fromdBlook_i(long a){
  114759. int i=(-a)>>(12-FROMdB2_SHIFT);
  114760. return (i<0)?1.f:
  114761. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114762. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114763. }
  114764. /* interpolated lookup based cos function, domain 0 to PI only */
  114765. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114766. long vorbis_coslook_i(long a){
  114767. int i=a>>COS_LOOKUP_I_SHIFT;
  114768. int d=a&COS_LOOKUP_I_MASK;
  114769. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114770. COS_LOOKUP_I_SHIFT);
  114771. }
  114772. #endif
  114773. #endif
  114774. /*** End of inlined file: lookup.c ***/
  114775. /* catch this in the build system; we #include for
  114776. compilers (like gcc) that can't inline across
  114777. modules */
  114778. /* side effect: changes *lsp to cosines of lsp */
  114779. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114780. float amp,float ampoffset){
  114781. int i;
  114782. float wdel=M_PI/ln;
  114783. vorbis_fpu_control fpu;
  114784. (void) fpu; // to avoid an unused variable warning
  114785. vorbis_fpu_setround(&fpu);
  114786. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114787. i=0;
  114788. while(i<n){
  114789. int k=map[i];
  114790. int qexp;
  114791. float p=.7071067812f;
  114792. float q=.7071067812f;
  114793. float w=vorbis_coslook(wdel*k);
  114794. float *ftmp=lsp;
  114795. int c=m>>1;
  114796. do{
  114797. q*=ftmp[0]-w;
  114798. p*=ftmp[1]-w;
  114799. ftmp+=2;
  114800. }while(--c);
  114801. if(m&1){
  114802. /* odd order filter; slightly assymetric */
  114803. /* the last coefficient */
  114804. q*=ftmp[0]-w;
  114805. q*=q;
  114806. p*=p*(1.f-w*w);
  114807. }else{
  114808. /* even order filter; still symmetric */
  114809. q*=q*(1.f+w);
  114810. p*=p*(1.f-w);
  114811. }
  114812. q=frexp(p+q,&qexp);
  114813. q=vorbis_fromdBlook(amp*
  114814. vorbis_invsqlook(q)*
  114815. vorbis_invsq2explook(qexp+m)-
  114816. ampoffset);
  114817. do{
  114818. curve[i++]*=q;
  114819. }while(map[i]==k);
  114820. }
  114821. vorbis_fpu_restore(fpu);
  114822. }
  114823. #else
  114824. #ifdef INT_LOOKUP
  114825. /*** Start of inlined file: lookup.c ***/
  114826. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114827. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114828. // tasks..
  114829. #if JUCE_MSVC
  114830. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114831. #endif
  114832. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114833. #if JUCE_USE_OGGVORBIS
  114834. #include <math.h>
  114835. /*** Start of inlined file: lookup.h ***/
  114836. #ifndef _V_LOOKUP_H_
  114837. #ifdef FLOAT_LOOKUP
  114838. extern float vorbis_coslook(float a);
  114839. extern float vorbis_invsqlook(float a);
  114840. extern float vorbis_invsq2explook(int a);
  114841. extern float vorbis_fromdBlook(float a);
  114842. #endif
  114843. #ifdef INT_LOOKUP
  114844. extern long vorbis_invsqlook_i(long a,long e);
  114845. extern long vorbis_coslook_i(long a);
  114846. extern float vorbis_fromdBlook_i(long a);
  114847. #endif
  114848. #endif
  114849. /*** End of inlined file: lookup.h ***/
  114850. /*** Start of inlined file: lookup_data.h ***/
  114851. #ifndef _V_LOOKUP_DATA_H_
  114852. #ifdef FLOAT_LOOKUP
  114853. #define COS_LOOKUP_SZ 128
  114854. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114855. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114856. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114857. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114858. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114859. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114860. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114861. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114862. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114863. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114864. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114865. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114866. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114867. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114868. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114869. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114870. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114871. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114872. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114873. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114874. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114875. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114876. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114877. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114878. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114879. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114880. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114881. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114882. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114883. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114884. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114885. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114886. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114887. -1.0000000000000f,
  114888. };
  114889. #define INVSQ_LOOKUP_SZ 32
  114890. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114891. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114892. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114893. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114894. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114895. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114896. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114897. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114898. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114899. 1.000000000000f,
  114900. };
  114901. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114902. #define INVSQ2EXP_LOOKUP_MAX 32
  114903. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114904. INVSQ2EXP_LOOKUP_MIN+1]={
  114905. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114906. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114907. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114908. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114909. 256.f, 181.019336f, 128.f, 90.50966799f,
  114910. 64.f, 45.254834f, 32.f, 22.627417f,
  114911. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114912. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114913. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114914. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114915. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114916. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114917. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114918. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114919. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114920. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114921. 1.525878906e-05f,
  114922. };
  114923. #endif
  114924. #define FROMdB_LOOKUP_SZ 35
  114925. #define FROMdB2_LOOKUP_SZ 32
  114926. #define FROMdB_SHIFT 5
  114927. #define FROMdB2_SHIFT 3
  114928. #define FROMdB2_MASK 31
  114929. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114930. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114931. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114932. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114933. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114934. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114935. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114936. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114937. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114938. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114939. };
  114940. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114941. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114942. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114943. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114944. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114945. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114946. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114947. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114948. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114949. };
  114950. #ifdef INT_LOOKUP
  114951. #define INVSQ_LOOKUP_I_SHIFT 10
  114952. #define INVSQ_LOOKUP_I_MASK 1023
  114953. static long INVSQ_LOOKUP_I[64+1]={
  114954. 92682l, 91966l, 91267l, 90583l,
  114955. 89915l, 89261l, 88621l, 87995l,
  114956. 87381l, 86781l, 86192l, 85616l,
  114957. 85051l, 84497l, 83953l, 83420l,
  114958. 82897l, 82384l, 81880l, 81385l,
  114959. 80899l, 80422l, 79953l, 79492l,
  114960. 79039l, 78594l, 78156l, 77726l,
  114961. 77302l, 76885l, 76475l, 76072l,
  114962. 75674l, 75283l, 74898l, 74519l,
  114963. 74146l, 73778l, 73415l, 73058l,
  114964. 72706l, 72359l, 72016l, 71679l,
  114965. 71347l, 71019l, 70695l, 70376l,
  114966. 70061l, 69750l, 69444l, 69141l,
  114967. 68842l, 68548l, 68256l, 67969l,
  114968. 67685l, 67405l, 67128l, 66855l,
  114969. 66585l, 66318l, 66054l, 65794l,
  114970. 65536l,
  114971. };
  114972. #define COS_LOOKUP_I_SHIFT 9
  114973. #define COS_LOOKUP_I_MASK 511
  114974. #define COS_LOOKUP_I_SZ 128
  114975. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114976. 16384l, 16379l, 16364l, 16340l,
  114977. 16305l, 16261l, 16207l, 16143l,
  114978. 16069l, 15986l, 15893l, 15791l,
  114979. 15679l, 15557l, 15426l, 15286l,
  114980. 15137l, 14978l, 14811l, 14635l,
  114981. 14449l, 14256l, 14053l, 13842l,
  114982. 13623l, 13395l, 13160l, 12916l,
  114983. 12665l, 12406l, 12140l, 11866l,
  114984. 11585l, 11297l, 11003l, 10702l,
  114985. 10394l, 10080l, 9760l, 9434l,
  114986. 9102l, 8765l, 8423l, 8076l,
  114987. 7723l, 7366l, 7005l, 6639l,
  114988. 6270l, 5897l, 5520l, 5139l,
  114989. 4756l, 4370l, 3981l, 3590l,
  114990. 3196l, 2801l, 2404l, 2006l,
  114991. 1606l, 1205l, 804l, 402l,
  114992. 0l, -401l, -803l, -1204l,
  114993. -1605l, -2005l, -2403l, -2800l,
  114994. -3195l, -3589l, -3980l, -4369l,
  114995. -4755l, -5138l, -5519l, -5896l,
  114996. -6269l, -6638l, -7004l, -7365l,
  114997. -7722l, -8075l, -8422l, -8764l,
  114998. -9101l, -9433l, -9759l, -10079l,
  114999. -10393l, -10701l, -11002l, -11296l,
  115000. -11584l, -11865l, -12139l, -12405l,
  115001. -12664l, -12915l, -13159l, -13394l,
  115002. -13622l, -13841l, -14052l, -14255l,
  115003. -14448l, -14634l, -14810l, -14977l,
  115004. -15136l, -15285l, -15425l, -15556l,
  115005. -15678l, -15790l, -15892l, -15985l,
  115006. -16068l, -16142l, -16206l, -16260l,
  115007. -16304l, -16339l, -16363l, -16378l,
  115008. -16383l,
  115009. };
  115010. #endif
  115011. #endif
  115012. /*** End of inlined file: lookup_data.h ***/
  115013. #ifdef FLOAT_LOOKUP
  115014. /* interpolated lookup based cos function, domain 0 to PI only */
  115015. float vorbis_coslook(float a){
  115016. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  115017. int i=vorbis_ftoi(d-.5);
  115018. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  115019. }
  115020. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115021. float vorbis_invsqlook(float a){
  115022. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  115023. int i=vorbis_ftoi(d-.5f);
  115024. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  115025. }
  115026. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115027. float vorbis_invsq2explook(int a){
  115028. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  115029. }
  115030. #include <stdio.h>
  115031. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115032. float vorbis_fromdBlook(float a){
  115033. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  115034. return (i<0)?1.f:
  115035. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115036. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115037. }
  115038. #endif
  115039. #ifdef INT_LOOKUP
  115040. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  115041. 16.16 format
  115042. returns in m.8 format */
  115043. long vorbis_invsqlook_i(long a,long e){
  115044. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  115045. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  115046. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  115047. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  115048. d)>>16); /* result 1.16 */
  115049. e+=32;
  115050. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  115051. e=(e>>1)-8;
  115052. return(val>>e);
  115053. }
  115054. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115055. /* a is in n.12 format */
  115056. float vorbis_fromdBlook_i(long a){
  115057. int i=(-a)>>(12-FROMdB2_SHIFT);
  115058. return (i<0)?1.f:
  115059. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115060. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115061. }
  115062. /* interpolated lookup based cos function, domain 0 to PI only */
  115063. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  115064. long vorbis_coslook_i(long a){
  115065. int i=a>>COS_LOOKUP_I_SHIFT;
  115066. int d=a&COS_LOOKUP_I_MASK;
  115067. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  115068. COS_LOOKUP_I_SHIFT);
  115069. }
  115070. #endif
  115071. #endif
  115072. /*** End of inlined file: lookup.c ***/
  115073. /* catch this in the build system; we #include for
  115074. compilers (like gcc) that can't inline across
  115075. modules */
  115076. static int MLOOP_1[64]={
  115077. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  115078. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  115079. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115080. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115081. };
  115082. static int MLOOP_2[64]={
  115083. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  115084. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  115085. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115086. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115087. };
  115088. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  115089. /* side effect: changes *lsp to cosines of lsp */
  115090. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115091. float amp,float ampoffset){
  115092. /* 0 <= m < 256 */
  115093. /* set up for using all int later */
  115094. int i;
  115095. int ampoffseti=rint(ampoffset*4096.f);
  115096. int ampi=rint(amp*16.f);
  115097. long *ilsp=alloca(m*sizeof(*ilsp));
  115098. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  115099. i=0;
  115100. while(i<n){
  115101. int j,k=map[i];
  115102. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  115103. unsigned long qi=46341;
  115104. int qexp=0,shift;
  115105. long wi=vorbis_coslook_i(k*65536/ln);
  115106. qi*=labs(ilsp[0]-wi);
  115107. pi*=labs(ilsp[1]-wi);
  115108. for(j=3;j<m;j+=2){
  115109. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115110. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115111. shift=MLOOP_3[(pi|qi)>>16];
  115112. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115113. pi=(pi>>shift)*labs(ilsp[j]-wi);
  115114. qexp+=shift;
  115115. }
  115116. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115117. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115118. shift=MLOOP_3[(pi|qi)>>16];
  115119. /* pi,qi normalized collectively, both tracked using qexp */
  115120. if(m&1){
  115121. /* odd order filter; slightly assymetric */
  115122. /* the last coefficient */
  115123. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115124. pi=(pi>>shift)<<14;
  115125. qexp+=shift;
  115126. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115127. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115128. shift=MLOOP_3[(pi|qi)>>16];
  115129. pi>>=shift;
  115130. qi>>=shift;
  115131. qexp+=shift-14*((m+1)>>1);
  115132. pi=((pi*pi)>>16);
  115133. qi=((qi*qi)>>16);
  115134. qexp=qexp*2+m;
  115135. pi*=(1<<14)-((wi*wi)>>14);
  115136. qi+=pi>>14;
  115137. }else{
  115138. /* even order filter; still symmetric */
  115139. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  115140. worth tracking step by step */
  115141. pi>>=shift;
  115142. qi>>=shift;
  115143. qexp+=shift-7*m;
  115144. pi=((pi*pi)>>16);
  115145. qi=((qi*qi)>>16);
  115146. qexp=qexp*2+m;
  115147. pi*=(1<<14)-wi;
  115148. qi*=(1<<14)+wi;
  115149. qi=(qi+pi)>>14;
  115150. }
  115151. /* we've let the normalization drift because it wasn't important;
  115152. however, for the lookup, things must be normalized again. We
  115153. need at most one right shift or a number of left shifts */
  115154. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115155. qi>>=1; qexp++;
  115156. }else
  115157. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115158. qi<<=1; qexp--;
  115159. }
  115160. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115161. vorbis_invsqlook_i(qi,qexp)-
  115162. /* m.8, m+n<=8 */
  115163. ampoffseti); /* 8.12[0] */
  115164. curve[i]*=amp;
  115165. while(map[++i]==k)curve[i]*=amp;
  115166. }
  115167. }
  115168. #else
  115169. /* old, nonoptimized but simple version for any poor sap who needs to
  115170. figure out what the hell this code does, or wants the other
  115171. fraction of a dB precision */
  115172. /* side effect: changes *lsp to cosines of lsp */
  115173. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115174. float amp,float ampoffset){
  115175. int i;
  115176. float wdel=M_PI/ln;
  115177. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115178. i=0;
  115179. while(i<n){
  115180. int j,k=map[i];
  115181. float p=.5f;
  115182. float q=.5f;
  115183. float w=2.f*cos(wdel*k);
  115184. for(j=1;j<m;j+=2){
  115185. q *= w-lsp[j-1];
  115186. p *= w-lsp[j];
  115187. }
  115188. if(j==m){
  115189. /* odd order filter; slightly assymetric */
  115190. /* the last coefficient */
  115191. q*=w-lsp[j-1];
  115192. p*=p*(4.f-w*w);
  115193. q*=q;
  115194. }else{
  115195. /* even order filter; still symmetric */
  115196. p*=p*(2.f-w);
  115197. q*=q*(2.f+w);
  115198. }
  115199. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115200. curve[i]*=q;
  115201. while(map[++i]==k)curve[i]*=q;
  115202. }
  115203. }
  115204. #endif
  115205. #endif
  115206. static void cheby(float *g, int ord) {
  115207. int i, j;
  115208. g[0] *= .5f;
  115209. for(i=2; i<= ord; i++) {
  115210. for(j=ord; j >= i; j--) {
  115211. g[j-2] -= g[j];
  115212. g[j] += g[j];
  115213. }
  115214. }
  115215. }
  115216. static int comp(const void *a,const void *b){
  115217. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115218. }
  115219. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115220. but there are root sets for which it gets into limit cycles
  115221. (exacerbated by zero suppression) and fails. We can't afford to
  115222. fail, even if the failure is 1 in 100,000,000, so we now use
  115223. Laguerre and later polish with Newton-Raphson (which can then
  115224. afford to fail) */
  115225. #define EPSILON 10e-7
  115226. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115227. int i,m;
  115228. double lastdelta=0.f;
  115229. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115230. for(i=0;i<=ord;i++)defl[i]=a[i];
  115231. for(m=ord;m>0;m--){
  115232. double newx=0.f,delta;
  115233. /* iterate a root */
  115234. while(1){
  115235. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115236. /* eval the polynomial and its first two derivatives */
  115237. for(i=m;i>0;i--){
  115238. ppp = newx*ppp + pp;
  115239. pp = newx*pp + p;
  115240. p = newx*p + defl[i-1];
  115241. }
  115242. /* Laguerre's method */
  115243. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115244. if(denom<0)
  115245. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115246. if(pp>0){
  115247. denom = pp + sqrt(denom);
  115248. if(denom<EPSILON)denom=EPSILON;
  115249. }else{
  115250. denom = pp - sqrt(denom);
  115251. if(denom>-(EPSILON))denom=-(EPSILON);
  115252. }
  115253. delta = m*p/denom;
  115254. newx -= delta;
  115255. if(delta<0.f)delta*=-1;
  115256. if(fabs(delta/newx)<10e-12)break;
  115257. lastdelta=delta;
  115258. }
  115259. r[m-1]=newx;
  115260. /* forward deflation */
  115261. for(i=m;i>0;i--)
  115262. defl[i-1]+=newx*defl[i];
  115263. defl++;
  115264. }
  115265. return(0);
  115266. }
  115267. /* for spit-and-polish only */
  115268. static int Newton_Raphson(float *a,int ord,float *r){
  115269. int i, k, count=0;
  115270. double error=1.f;
  115271. double *root=(double*)alloca(ord*sizeof(*root));
  115272. for(i=0; i<ord;i++) root[i] = r[i];
  115273. while(error>1e-20){
  115274. error=0;
  115275. for(i=0; i<ord; i++) { /* Update each point. */
  115276. double pp=0.,delta;
  115277. double rooti=root[i];
  115278. double p=a[ord];
  115279. for(k=ord-1; k>= 0; k--) {
  115280. pp= pp* rooti + p;
  115281. p = p * rooti + a[k];
  115282. }
  115283. delta = p/pp;
  115284. root[i] -= delta;
  115285. error+= delta*delta;
  115286. }
  115287. if(count>40)return(-1);
  115288. count++;
  115289. }
  115290. /* Replaced the original bubble sort with a real sort. With your
  115291. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115292. for(i=0; i<ord;i++) r[i] = root[i];
  115293. return(0);
  115294. }
  115295. /* Convert lpc coefficients to lsp coefficients */
  115296. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115297. int order2=(m+1)>>1;
  115298. int g1_order,g2_order;
  115299. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115300. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115301. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115302. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115303. int i;
  115304. /* even and odd are slightly different base cases */
  115305. g1_order=(m+1)>>1;
  115306. g2_order=(m) >>1;
  115307. /* Compute the lengths of the x polynomials. */
  115308. /* Compute the first half of K & R F1 & F2 polynomials. */
  115309. /* Compute half of the symmetric and antisymmetric polynomials. */
  115310. /* Remove the roots at +1 and -1. */
  115311. g1[g1_order] = 1.f;
  115312. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115313. g2[g2_order] = 1.f;
  115314. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115315. if(g1_order>g2_order){
  115316. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115317. }else{
  115318. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115319. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115320. }
  115321. /* Convert into polynomials in cos(alpha) */
  115322. cheby(g1,g1_order);
  115323. cheby(g2,g2_order);
  115324. /* Find the roots of the 2 even polynomials.*/
  115325. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115326. Laguerre_With_Deflation(g2,g2_order,g2r))
  115327. return(-1);
  115328. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115329. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115330. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115331. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115332. for(i=0;i<g1_order;i++)
  115333. lsp[i*2] = acos(g1r[i]);
  115334. for(i=0;i<g2_order;i++)
  115335. lsp[i*2+1] = acos(g2r[i]);
  115336. return(0);
  115337. }
  115338. #endif
  115339. /*** End of inlined file: lsp.c ***/
  115340. /*** Start of inlined file: mapping0.c ***/
  115341. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115342. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115343. // tasks..
  115344. #if JUCE_MSVC
  115345. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115346. #endif
  115347. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115348. #if JUCE_USE_OGGVORBIS
  115349. #include <stdlib.h>
  115350. #include <stdio.h>
  115351. #include <string.h>
  115352. #include <math.h>
  115353. /* simplistic, wasteful way of doing this (unique lookup for each
  115354. mode/submapping); there should be a central repository for
  115355. identical lookups. That will require minor work, so I'm putting it
  115356. off as low priority.
  115357. Why a lookup for each backend in a given mode? Because the
  115358. blocksize is set by the mode, and low backend lookups may require
  115359. parameters from other areas of the mode/mapping */
  115360. static void mapping0_free_info(vorbis_info_mapping *i){
  115361. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115362. if(info){
  115363. memset(info,0,sizeof(*info));
  115364. _ogg_free(info);
  115365. }
  115366. }
  115367. static int ilog3(unsigned int v){
  115368. int ret=0;
  115369. if(v)--v;
  115370. while(v){
  115371. ret++;
  115372. v>>=1;
  115373. }
  115374. return(ret);
  115375. }
  115376. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115377. oggpack_buffer *opb){
  115378. int i;
  115379. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115380. /* another 'we meant to do it this way' hack... up to beta 4, we
  115381. packed 4 binary zeros here to signify one submapping in use. We
  115382. now redefine that to mean four bitflags that indicate use of
  115383. deeper features; bit0:submappings, bit1:coupling,
  115384. bit2,3:reserved. This is backward compatable with all actual uses
  115385. of the beta code. */
  115386. if(info->submaps>1){
  115387. oggpack_write(opb,1,1);
  115388. oggpack_write(opb,info->submaps-1,4);
  115389. }else
  115390. oggpack_write(opb,0,1);
  115391. if(info->coupling_steps>0){
  115392. oggpack_write(opb,1,1);
  115393. oggpack_write(opb,info->coupling_steps-1,8);
  115394. for(i=0;i<info->coupling_steps;i++){
  115395. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115396. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115397. }
  115398. }else
  115399. oggpack_write(opb,0,1);
  115400. oggpack_write(opb,0,2); /* 2,3:reserved */
  115401. /* we don't write the channel submappings if we only have one... */
  115402. if(info->submaps>1){
  115403. for(i=0;i<vi->channels;i++)
  115404. oggpack_write(opb,info->chmuxlist[i],4);
  115405. }
  115406. for(i=0;i<info->submaps;i++){
  115407. oggpack_write(opb,0,8); /* time submap unused */
  115408. oggpack_write(opb,info->floorsubmap[i],8);
  115409. oggpack_write(opb,info->residuesubmap[i],8);
  115410. }
  115411. }
  115412. /* also responsible for range checking */
  115413. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115414. int i;
  115415. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115416. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115417. memset(info,0,sizeof(*info));
  115418. if(oggpack_read(opb,1))
  115419. info->submaps=oggpack_read(opb,4)+1;
  115420. else
  115421. info->submaps=1;
  115422. if(oggpack_read(opb,1)){
  115423. info->coupling_steps=oggpack_read(opb,8)+1;
  115424. for(i=0;i<info->coupling_steps;i++){
  115425. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115426. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115427. if(testM<0 ||
  115428. testA<0 ||
  115429. testM==testA ||
  115430. testM>=vi->channels ||
  115431. testA>=vi->channels) goto err_out;
  115432. }
  115433. }
  115434. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115435. if(info->submaps>1){
  115436. for(i=0;i<vi->channels;i++){
  115437. info->chmuxlist[i]=oggpack_read(opb,4);
  115438. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115439. }
  115440. }
  115441. for(i=0;i<info->submaps;i++){
  115442. oggpack_read(opb,8); /* time submap unused */
  115443. info->floorsubmap[i]=oggpack_read(opb,8);
  115444. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115445. info->residuesubmap[i]=oggpack_read(opb,8);
  115446. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115447. }
  115448. return info;
  115449. err_out:
  115450. mapping0_free_info(info);
  115451. return(NULL);
  115452. }
  115453. #if 0
  115454. static long seq=0;
  115455. static ogg_int64_t total=0;
  115456. static float FLOOR1_fromdB_LOOKUP[256]={
  115457. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115458. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115459. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115460. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115461. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115462. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115463. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115464. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115465. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115466. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115467. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115468. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115469. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115470. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115471. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115472. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115473. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115474. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115475. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115476. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115477. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115478. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115479. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115480. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115481. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115482. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115483. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115484. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115485. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115486. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115487. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115488. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115489. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115490. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115491. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115492. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115493. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115494. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115495. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115496. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115497. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115498. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115499. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115500. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115501. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115502. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115503. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115504. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115505. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115506. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115507. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115508. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115509. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115510. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115511. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115512. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115513. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115514. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115515. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115516. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115517. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115518. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115519. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115520. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115521. };
  115522. #endif
  115523. extern int *floor1_fit(vorbis_block *vb,void *look,
  115524. const float *logmdct, /* in */
  115525. const float *logmask);
  115526. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115527. int *A,int *B,
  115528. int del);
  115529. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115530. void*look,
  115531. int *post,int *ilogmask);
  115532. static int mapping0_forward(vorbis_block *vb){
  115533. vorbis_dsp_state *vd=vb->vd;
  115534. vorbis_info *vi=vd->vi;
  115535. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115536. private_state *b=(private_state*)vb->vd->backend_state;
  115537. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115538. int n=vb->pcmend;
  115539. int i,j,k;
  115540. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115541. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115542. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115543. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115544. float global_ampmax=vbi->ampmax;
  115545. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115546. int blocktype=vbi->blocktype;
  115547. int modenumber=vb->W;
  115548. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115549. vorbis_look_psy *psy_look=
  115550. b->psy+blocktype+(vb->W?2:0);
  115551. vb->mode=modenumber;
  115552. for(i=0;i<vi->channels;i++){
  115553. float scale=4.f/n;
  115554. float scale_dB;
  115555. float *pcm =vb->pcm[i];
  115556. float *logfft =pcm;
  115557. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115558. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115559. todB estimation used on IEEE 754
  115560. compliant machines had a bug that
  115561. returned dB values about a third
  115562. of a decibel too high. The bug
  115563. was harmless because tunings
  115564. implicitly took that into
  115565. account. However, fixing the bug
  115566. in the estimator requires
  115567. changing all the tunings as well.
  115568. For now, it's easier to sync
  115569. things back up here, and
  115570. recalibrate the tunings in the
  115571. next major model upgrade. */
  115572. #if 0
  115573. if(vi->channels==2)
  115574. if(i==0)
  115575. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115576. else
  115577. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115578. #endif
  115579. /* window the PCM data */
  115580. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115581. #if 0
  115582. if(vi->channels==2)
  115583. if(i==0)
  115584. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115585. else
  115586. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115587. #endif
  115588. /* transform the PCM data */
  115589. /* only MDCT right now.... */
  115590. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115591. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115592. drft_forward(&b->fft_look[vb->W],pcm);
  115593. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115594. original todB estimation used on
  115595. IEEE 754 compliant machines had a
  115596. bug that returned dB values about
  115597. a third of a decibel too high.
  115598. The bug was harmless because
  115599. tunings implicitly took that into
  115600. account. However, fixing the bug
  115601. in the estimator requires
  115602. changing all the tunings as well.
  115603. For now, it's easier to sync
  115604. things back up here, and
  115605. recalibrate the tunings in the
  115606. next major model upgrade. */
  115607. local_ampmax[i]=logfft[0];
  115608. for(j=1;j<n-1;j+=2){
  115609. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115610. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115611. .345 is a hack; the original todB
  115612. estimation used on IEEE 754
  115613. compliant machines had a bug that
  115614. returned dB values about a third
  115615. of a decibel too high. The bug
  115616. was harmless because tunings
  115617. implicitly took that into
  115618. account. However, fixing the bug
  115619. in the estimator requires
  115620. changing all the tunings as well.
  115621. For now, it's easier to sync
  115622. things back up here, and
  115623. recalibrate the tunings in the
  115624. next major model upgrade. */
  115625. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115626. }
  115627. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115628. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115629. #if 0
  115630. if(vi->channels==2){
  115631. if(i==0){
  115632. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115633. }else{
  115634. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115635. }
  115636. }
  115637. #endif
  115638. }
  115639. {
  115640. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115641. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115642. for(i=0;i<vi->channels;i++){
  115643. /* the encoder setup assumes that all the modes used by any
  115644. specific bitrate tweaking use the same floor */
  115645. int submap=info->chmuxlist[i];
  115646. /* the following makes things clearer to *me* anyway */
  115647. float *mdct =gmdct[i];
  115648. float *logfft =vb->pcm[i];
  115649. float *logmdct =logfft+n/2;
  115650. float *logmask =logfft;
  115651. vb->mode=modenumber;
  115652. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115653. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115654. for(j=0;j<n/2;j++)
  115655. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115656. todB estimation used on IEEE 754
  115657. compliant machines had a bug that
  115658. returned dB values about a third
  115659. of a decibel too high. The bug
  115660. was harmless because tunings
  115661. implicitly took that into
  115662. account. However, fixing the bug
  115663. in the estimator requires
  115664. changing all the tunings as well.
  115665. For now, it's easier to sync
  115666. things back up here, and
  115667. recalibrate the tunings in the
  115668. next major model upgrade. */
  115669. #if 0
  115670. if(vi->channels==2){
  115671. if(i==0)
  115672. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115673. else
  115674. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115675. }else{
  115676. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115677. }
  115678. #endif
  115679. /* first step; noise masking. Not only does 'noise masking'
  115680. give us curves from which we can decide how much resolution
  115681. to give noise parts of the spectrum, it also implicitly hands
  115682. us a tonality estimate (the larger the value in the
  115683. 'noise_depth' vector, the more tonal that area is) */
  115684. _vp_noisemask(psy_look,
  115685. logmdct,
  115686. noise); /* noise does not have by-frequency offset
  115687. bias applied yet */
  115688. #if 0
  115689. if(vi->channels==2){
  115690. if(i==0)
  115691. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115692. else
  115693. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115694. }
  115695. #endif
  115696. /* second step: 'all the other crap'; all the stuff that isn't
  115697. computed/fit for bitrate management goes in the second psy
  115698. vector. This includes tone masking, peak limiting and ATH */
  115699. _vp_tonemask(psy_look,
  115700. logfft,
  115701. tone,
  115702. global_ampmax,
  115703. local_ampmax[i]);
  115704. #if 0
  115705. if(vi->channels==2){
  115706. if(i==0)
  115707. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115708. else
  115709. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115710. }
  115711. #endif
  115712. /* third step; we offset the noise vectors, overlay tone
  115713. masking. We then do a floor1-specific line fit. If we're
  115714. performing bitrate management, the line fit is performed
  115715. multiple times for up/down tweakage on demand. */
  115716. #if 0
  115717. {
  115718. float aotuv[psy_look->n];
  115719. #endif
  115720. _vp_offset_and_mix(psy_look,
  115721. noise,
  115722. tone,
  115723. 1,
  115724. logmask,
  115725. mdct,
  115726. logmdct);
  115727. #if 0
  115728. if(vi->channels==2){
  115729. if(i==0)
  115730. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115731. else
  115732. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115733. }
  115734. }
  115735. #endif
  115736. #if 0
  115737. if(vi->channels==2){
  115738. if(i==0)
  115739. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115740. else
  115741. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115742. }
  115743. #endif
  115744. /* this algorithm is hardwired to floor 1 for now; abort out if
  115745. we're *not* floor1. This won't happen unless someone has
  115746. broken the encode setup lib. Guard it anyway. */
  115747. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115748. floor_posts[i][PACKETBLOBS/2]=
  115749. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115750. logmdct,
  115751. logmask);
  115752. /* are we managing bitrate? If so, perform two more fits for
  115753. later rate tweaking (fits represent hi/lo) */
  115754. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115755. /* higher rate by way of lower noise curve */
  115756. _vp_offset_and_mix(psy_look,
  115757. noise,
  115758. tone,
  115759. 2,
  115760. logmask,
  115761. mdct,
  115762. logmdct);
  115763. #if 0
  115764. if(vi->channels==2){
  115765. if(i==0)
  115766. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115767. else
  115768. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115769. }
  115770. #endif
  115771. floor_posts[i][PACKETBLOBS-1]=
  115772. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115773. logmdct,
  115774. logmask);
  115775. /* lower rate by way of higher noise curve */
  115776. _vp_offset_and_mix(psy_look,
  115777. noise,
  115778. tone,
  115779. 0,
  115780. logmask,
  115781. mdct,
  115782. logmdct);
  115783. #if 0
  115784. if(vi->channels==2)
  115785. if(i==0)
  115786. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115787. else
  115788. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115789. #endif
  115790. floor_posts[i][0]=
  115791. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115792. logmdct,
  115793. logmask);
  115794. /* we also interpolate a range of intermediate curves for
  115795. intermediate rates */
  115796. for(k=1;k<PACKETBLOBS/2;k++)
  115797. floor_posts[i][k]=
  115798. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115799. floor_posts[i][0],
  115800. floor_posts[i][PACKETBLOBS/2],
  115801. k*65536/(PACKETBLOBS/2));
  115802. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115803. floor_posts[i][k]=
  115804. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115805. floor_posts[i][PACKETBLOBS/2],
  115806. floor_posts[i][PACKETBLOBS-1],
  115807. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115808. }
  115809. }
  115810. }
  115811. vbi->ampmax=global_ampmax;
  115812. /*
  115813. the next phases are performed once for vbr-only and PACKETBLOB
  115814. times for bitrate managed modes.
  115815. 1) encode actual mode being used
  115816. 2) encode the floor for each channel, compute coded mask curve/res
  115817. 3) normalize and couple.
  115818. 4) encode residue
  115819. 5) save packet bytes to the packetblob vector
  115820. */
  115821. /* iterate over the many masking curve fits we've created */
  115822. {
  115823. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115824. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115825. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115826. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115827. float **mag_memo;
  115828. int **mag_sort;
  115829. if(info->coupling_steps){
  115830. mag_memo=_vp_quantize_couple_memo(vb,
  115831. &ci->psy_g_param,
  115832. psy_look,
  115833. info,
  115834. gmdct);
  115835. mag_sort=_vp_quantize_couple_sort(vb,
  115836. psy_look,
  115837. info,
  115838. mag_memo);
  115839. hf_reduction(&ci->psy_g_param,
  115840. psy_look,
  115841. info,
  115842. mag_memo);
  115843. }
  115844. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115845. if(psy_look->vi->normal_channel_p){
  115846. for(i=0;i<vi->channels;i++){
  115847. float *mdct =gmdct[i];
  115848. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115849. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115850. }
  115851. }
  115852. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115853. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115854. k++){
  115855. oggpack_buffer *opb=vbi->packetblob[k];
  115856. /* start out our new packet blob with packet type and mode */
  115857. /* Encode the packet type */
  115858. oggpack_write(opb,0,1);
  115859. /* Encode the modenumber */
  115860. /* Encode frame mode, pre,post windowsize, then dispatch */
  115861. oggpack_write(opb,modenumber,b->modebits);
  115862. if(vb->W){
  115863. oggpack_write(opb,vb->lW,1);
  115864. oggpack_write(opb,vb->nW,1);
  115865. }
  115866. /* encode floor, compute masking curve, sep out residue */
  115867. for(i=0;i<vi->channels;i++){
  115868. int submap=info->chmuxlist[i];
  115869. float *mdct =gmdct[i];
  115870. float *res =vb->pcm[i];
  115871. int *ilogmask=ilogmaskch[i]=
  115872. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115873. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115874. floor_posts[i][k],
  115875. ilogmask);
  115876. #if 0
  115877. {
  115878. char buf[80];
  115879. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115880. float work[n/2];
  115881. for(j=0;j<n/2;j++)
  115882. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115883. _analysis_output(buf,seq,work,n/2,1,1,0);
  115884. }
  115885. #endif
  115886. _vp_remove_floor(psy_look,
  115887. mdct,
  115888. ilogmask,
  115889. res,
  115890. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115891. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115892. #if 0
  115893. {
  115894. char buf[80];
  115895. float work[n/2];
  115896. for(j=0;j<n/2;j++)
  115897. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115898. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115899. _analysis_output(buf,seq,work,n/2,1,1,0);
  115900. }
  115901. #endif
  115902. }
  115903. /* our iteration is now based on masking curve, not prequant and
  115904. coupling. Only one prequant/coupling step */
  115905. /* quantize/couple */
  115906. /* incomplete implementation that assumes the tree is all depth
  115907. one, or no tree at all */
  115908. if(info->coupling_steps){
  115909. _vp_couple(k,
  115910. &ci->psy_g_param,
  115911. psy_look,
  115912. info,
  115913. vb->pcm,
  115914. mag_memo,
  115915. mag_sort,
  115916. ilogmaskch,
  115917. nonzero,
  115918. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115919. }
  115920. /* classify and encode by submap */
  115921. for(i=0;i<info->submaps;i++){
  115922. int ch_in_bundle=0;
  115923. long **classifications;
  115924. int resnum=info->residuesubmap[i];
  115925. for(j=0;j<vi->channels;j++){
  115926. if(info->chmuxlist[j]==i){
  115927. zerobundle[ch_in_bundle]=0;
  115928. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115929. res_bundle[ch_in_bundle]=vb->pcm[j];
  115930. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115931. }
  115932. }
  115933. classifications=_residue_P[ci->residue_type[resnum]]->
  115934. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115935. _residue_P[ci->residue_type[resnum]]->
  115936. forward(opb,vb,b->residue[resnum],
  115937. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115938. }
  115939. /* ok, done encoding. Next protopacket. */
  115940. }
  115941. }
  115942. #if 0
  115943. seq++;
  115944. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115945. #endif
  115946. return(0);
  115947. }
  115948. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115949. vorbis_dsp_state *vd=vb->vd;
  115950. vorbis_info *vi=vd->vi;
  115951. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115952. private_state *b=(private_state*)vd->backend_state;
  115953. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115954. int i,j;
  115955. long n=vb->pcmend=ci->blocksizes[vb->W];
  115956. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115957. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115958. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115959. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115960. /* recover the spectral envelope; store it in the PCM vector for now */
  115961. for(i=0;i<vi->channels;i++){
  115962. int submap=info->chmuxlist[i];
  115963. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115964. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115965. if(floormemo[i])
  115966. nonzero[i]=1;
  115967. else
  115968. nonzero[i]=0;
  115969. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115970. }
  115971. /* channel coupling can 'dirty' the nonzero listing */
  115972. for(i=0;i<info->coupling_steps;i++){
  115973. if(nonzero[info->coupling_mag[i]] ||
  115974. nonzero[info->coupling_ang[i]]){
  115975. nonzero[info->coupling_mag[i]]=1;
  115976. nonzero[info->coupling_ang[i]]=1;
  115977. }
  115978. }
  115979. /* recover the residue into our working vectors */
  115980. for(i=0;i<info->submaps;i++){
  115981. int ch_in_bundle=0;
  115982. for(j=0;j<vi->channels;j++){
  115983. if(info->chmuxlist[j]==i){
  115984. if(nonzero[j])
  115985. zerobundle[ch_in_bundle]=1;
  115986. else
  115987. zerobundle[ch_in_bundle]=0;
  115988. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115989. }
  115990. }
  115991. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115992. inverse(vb,b->residue[info->residuesubmap[i]],
  115993. pcmbundle,zerobundle,ch_in_bundle);
  115994. }
  115995. /* channel coupling */
  115996. for(i=info->coupling_steps-1;i>=0;i--){
  115997. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115998. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115999. for(j=0;j<n/2;j++){
  116000. float mag=pcmM[j];
  116001. float ang=pcmA[j];
  116002. if(mag>0)
  116003. if(ang>0){
  116004. pcmM[j]=mag;
  116005. pcmA[j]=mag-ang;
  116006. }else{
  116007. pcmA[j]=mag;
  116008. pcmM[j]=mag+ang;
  116009. }
  116010. else
  116011. if(ang>0){
  116012. pcmM[j]=mag;
  116013. pcmA[j]=mag+ang;
  116014. }else{
  116015. pcmA[j]=mag;
  116016. pcmM[j]=mag-ang;
  116017. }
  116018. }
  116019. }
  116020. /* compute and apply spectral envelope */
  116021. for(i=0;i<vi->channels;i++){
  116022. float *pcm=vb->pcm[i];
  116023. int submap=info->chmuxlist[i];
  116024. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  116025. inverse2(vb,b->flr[info->floorsubmap[submap]],
  116026. floormemo[i],pcm);
  116027. }
  116028. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  116029. /* only MDCT right now.... */
  116030. for(i=0;i<vi->channels;i++){
  116031. float *pcm=vb->pcm[i];
  116032. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  116033. }
  116034. /* all done! */
  116035. return(0);
  116036. }
  116037. /* export hooks */
  116038. vorbis_func_mapping mapping0_exportbundle={
  116039. &mapping0_pack,
  116040. &mapping0_unpack,
  116041. &mapping0_free_info,
  116042. &mapping0_forward,
  116043. &mapping0_inverse
  116044. };
  116045. #endif
  116046. /*** End of inlined file: mapping0.c ***/
  116047. /*** Start of inlined file: mdct.c ***/
  116048. /* this can also be run as an integer transform by uncommenting a
  116049. define in mdct.h; the integerization is a first pass and although
  116050. it's likely stable for Vorbis, the dynamic range is constrained and
  116051. roundoff isn't done (so it's noisy). Consider it functional, but
  116052. only a starting point. There's no point on a machine with an FPU */
  116053. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116054. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116055. // tasks..
  116056. #if JUCE_MSVC
  116057. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116058. #endif
  116059. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116060. #if JUCE_USE_OGGVORBIS
  116061. #include <stdio.h>
  116062. #include <stdlib.h>
  116063. #include <string.h>
  116064. #include <math.h>
  116065. /* build lookups for trig functions; also pre-figure scaling and
  116066. some window function algebra. */
  116067. void mdct_init(mdct_lookup *lookup,int n){
  116068. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  116069. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  116070. int i;
  116071. int n2=n>>1;
  116072. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  116073. lookup->n=n;
  116074. lookup->trig=T;
  116075. lookup->bitrev=bitrev;
  116076. /* trig lookups... */
  116077. for(i=0;i<n/4;i++){
  116078. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  116079. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  116080. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  116081. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  116082. }
  116083. for(i=0;i<n/8;i++){
  116084. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  116085. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  116086. }
  116087. /* bitreverse lookup... */
  116088. {
  116089. int mask=(1<<(log2n-1))-1,i,j;
  116090. int msb=1<<(log2n-2);
  116091. for(i=0;i<n/8;i++){
  116092. int acc=0;
  116093. for(j=0;msb>>j;j++)
  116094. if((msb>>j)&i)acc|=1<<j;
  116095. bitrev[i*2]=((~acc)&mask)-1;
  116096. bitrev[i*2+1]=acc;
  116097. }
  116098. }
  116099. lookup->scale=FLOAT_CONV(4.f/n);
  116100. }
  116101. /* 8 point butterfly (in place, 4 register) */
  116102. STIN void mdct_butterfly_8(DATA_TYPE *x){
  116103. REG_TYPE r0 = x[6] + x[2];
  116104. REG_TYPE r1 = x[6] - x[2];
  116105. REG_TYPE r2 = x[4] + x[0];
  116106. REG_TYPE r3 = x[4] - x[0];
  116107. x[6] = r0 + r2;
  116108. x[4] = r0 - r2;
  116109. r0 = x[5] - x[1];
  116110. r2 = x[7] - x[3];
  116111. x[0] = r1 + r0;
  116112. x[2] = r1 - r0;
  116113. r0 = x[5] + x[1];
  116114. r1 = x[7] + x[3];
  116115. x[3] = r2 + r3;
  116116. x[1] = r2 - r3;
  116117. x[7] = r1 + r0;
  116118. x[5] = r1 - r0;
  116119. }
  116120. /* 16 point butterfly (in place, 4 register) */
  116121. STIN void mdct_butterfly_16(DATA_TYPE *x){
  116122. REG_TYPE r0 = x[1] - x[9];
  116123. REG_TYPE r1 = x[0] - x[8];
  116124. x[8] += x[0];
  116125. x[9] += x[1];
  116126. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  116127. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  116128. r0 = x[3] - x[11];
  116129. r1 = x[10] - x[2];
  116130. x[10] += x[2];
  116131. x[11] += x[3];
  116132. x[2] = r0;
  116133. x[3] = r1;
  116134. r0 = x[12] - x[4];
  116135. r1 = x[13] - x[5];
  116136. x[12] += x[4];
  116137. x[13] += x[5];
  116138. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  116139. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  116140. r0 = x[14] - x[6];
  116141. r1 = x[15] - x[7];
  116142. x[14] += x[6];
  116143. x[15] += x[7];
  116144. x[6] = r0;
  116145. x[7] = r1;
  116146. mdct_butterfly_8(x);
  116147. mdct_butterfly_8(x+8);
  116148. }
  116149. /* 32 point butterfly (in place, 4 register) */
  116150. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116151. REG_TYPE r0 = x[30] - x[14];
  116152. REG_TYPE r1 = x[31] - x[15];
  116153. x[30] += x[14];
  116154. x[31] += x[15];
  116155. x[14] = r0;
  116156. x[15] = r1;
  116157. r0 = x[28] - x[12];
  116158. r1 = x[29] - x[13];
  116159. x[28] += x[12];
  116160. x[29] += x[13];
  116161. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116162. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116163. r0 = x[26] - x[10];
  116164. r1 = x[27] - x[11];
  116165. x[26] += x[10];
  116166. x[27] += x[11];
  116167. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116168. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116169. r0 = x[24] - x[8];
  116170. r1 = x[25] - x[9];
  116171. x[24] += x[8];
  116172. x[25] += x[9];
  116173. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116174. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116175. r0 = x[22] - x[6];
  116176. r1 = x[7] - x[23];
  116177. x[22] += x[6];
  116178. x[23] += x[7];
  116179. x[6] = r1;
  116180. x[7] = r0;
  116181. r0 = x[4] - x[20];
  116182. r1 = x[5] - x[21];
  116183. x[20] += x[4];
  116184. x[21] += x[5];
  116185. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116186. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116187. r0 = x[2] - x[18];
  116188. r1 = x[3] - x[19];
  116189. x[18] += x[2];
  116190. x[19] += x[3];
  116191. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116192. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116193. r0 = x[0] - x[16];
  116194. r1 = x[1] - x[17];
  116195. x[16] += x[0];
  116196. x[17] += x[1];
  116197. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116198. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116199. mdct_butterfly_16(x);
  116200. mdct_butterfly_16(x+16);
  116201. }
  116202. /* N point first stage butterfly (in place, 2 register) */
  116203. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116204. DATA_TYPE *x,
  116205. int points){
  116206. DATA_TYPE *x1 = x + points - 8;
  116207. DATA_TYPE *x2 = x + (points>>1) - 8;
  116208. REG_TYPE r0;
  116209. REG_TYPE r1;
  116210. do{
  116211. r0 = x1[6] - x2[6];
  116212. r1 = x1[7] - x2[7];
  116213. x1[6] += x2[6];
  116214. x1[7] += x2[7];
  116215. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116216. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116217. r0 = x1[4] - x2[4];
  116218. r1 = x1[5] - x2[5];
  116219. x1[4] += x2[4];
  116220. x1[5] += x2[5];
  116221. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116222. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116223. r0 = x1[2] - x2[2];
  116224. r1 = x1[3] - x2[3];
  116225. x1[2] += x2[2];
  116226. x1[3] += x2[3];
  116227. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116228. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116229. r0 = x1[0] - x2[0];
  116230. r1 = x1[1] - x2[1];
  116231. x1[0] += x2[0];
  116232. x1[1] += x2[1];
  116233. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116234. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116235. x1-=8;
  116236. x2-=8;
  116237. T+=16;
  116238. }while(x2>=x);
  116239. }
  116240. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116241. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116242. DATA_TYPE *x,
  116243. int points,
  116244. int trigint){
  116245. DATA_TYPE *x1 = x + points - 8;
  116246. DATA_TYPE *x2 = x + (points>>1) - 8;
  116247. REG_TYPE r0;
  116248. REG_TYPE r1;
  116249. do{
  116250. r0 = x1[6] - x2[6];
  116251. r1 = x1[7] - x2[7];
  116252. x1[6] += x2[6];
  116253. x1[7] += x2[7];
  116254. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116255. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116256. T+=trigint;
  116257. r0 = x1[4] - x2[4];
  116258. r1 = x1[5] - x2[5];
  116259. x1[4] += x2[4];
  116260. x1[5] += x2[5];
  116261. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116262. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116263. T+=trigint;
  116264. r0 = x1[2] - x2[2];
  116265. r1 = x1[3] - x2[3];
  116266. x1[2] += x2[2];
  116267. x1[3] += x2[3];
  116268. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116269. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116270. T+=trigint;
  116271. r0 = x1[0] - x2[0];
  116272. r1 = x1[1] - x2[1];
  116273. x1[0] += x2[0];
  116274. x1[1] += x2[1];
  116275. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116276. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116277. T+=trigint;
  116278. x1-=8;
  116279. x2-=8;
  116280. }while(x2>=x);
  116281. }
  116282. STIN void mdct_butterflies(mdct_lookup *init,
  116283. DATA_TYPE *x,
  116284. int points){
  116285. DATA_TYPE *T=init->trig;
  116286. int stages=init->log2n-5;
  116287. int i,j;
  116288. if(--stages>0){
  116289. mdct_butterfly_first(T,x,points);
  116290. }
  116291. for(i=1;--stages>0;i++){
  116292. for(j=0;j<(1<<i);j++)
  116293. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116294. }
  116295. for(j=0;j<points;j+=32)
  116296. mdct_butterfly_32(x+j);
  116297. }
  116298. void mdct_clear(mdct_lookup *l){
  116299. if(l){
  116300. if(l->trig)_ogg_free(l->trig);
  116301. if(l->bitrev)_ogg_free(l->bitrev);
  116302. memset(l,0,sizeof(*l));
  116303. }
  116304. }
  116305. STIN void mdct_bitreverse(mdct_lookup *init,
  116306. DATA_TYPE *x){
  116307. int n = init->n;
  116308. int *bit = init->bitrev;
  116309. DATA_TYPE *w0 = x;
  116310. DATA_TYPE *w1 = x = w0+(n>>1);
  116311. DATA_TYPE *T = init->trig+n;
  116312. do{
  116313. DATA_TYPE *x0 = x+bit[0];
  116314. DATA_TYPE *x1 = x+bit[1];
  116315. REG_TYPE r0 = x0[1] - x1[1];
  116316. REG_TYPE r1 = x0[0] + x1[0];
  116317. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116318. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116319. w1 -= 4;
  116320. r0 = HALVE(x0[1] + x1[1]);
  116321. r1 = HALVE(x0[0] - x1[0]);
  116322. w0[0] = r0 + r2;
  116323. w1[2] = r0 - r2;
  116324. w0[1] = r1 + r3;
  116325. w1[3] = r3 - r1;
  116326. x0 = x+bit[2];
  116327. x1 = x+bit[3];
  116328. r0 = x0[1] - x1[1];
  116329. r1 = x0[0] + x1[0];
  116330. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116331. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116332. r0 = HALVE(x0[1] + x1[1]);
  116333. r1 = HALVE(x0[0] - x1[0]);
  116334. w0[2] = r0 + r2;
  116335. w1[0] = r0 - r2;
  116336. w0[3] = r1 + r3;
  116337. w1[1] = r3 - r1;
  116338. T += 4;
  116339. bit += 4;
  116340. w0 += 4;
  116341. }while(w0<w1);
  116342. }
  116343. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116344. int n=init->n;
  116345. int n2=n>>1;
  116346. int n4=n>>2;
  116347. /* rotate */
  116348. DATA_TYPE *iX = in+n2-7;
  116349. DATA_TYPE *oX = out+n2+n4;
  116350. DATA_TYPE *T = init->trig+n4;
  116351. do{
  116352. oX -= 4;
  116353. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116354. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116355. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116356. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116357. iX -= 8;
  116358. T += 4;
  116359. }while(iX>=in);
  116360. iX = in+n2-8;
  116361. oX = out+n2+n4;
  116362. T = init->trig+n4;
  116363. do{
  116364. T -= 4;
  116365. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116366. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116367. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116368. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116369. iX -= 8;
  116370. oX += 4;
  116371. }while(iX>=in);
  116372. mdct_butterflies(init,out+n2,n2);
  116373. mdct_bitreverse(init,out);
  116374. /* roatate + window */
  116375. {
  116376. DATA_TYPE *oX1=out+n2+n4;
  116377. DATA_TYPE *oX2=out+n2+n4;
  116378. DATA_TYPE *iX =out;
  116379. T =init->trig+n2;
  116380. do{
  116381. oX1-=4;
  116382. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116383. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116384. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116385. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116386. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116387. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116388. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116389. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116390. oX2+=4;
  116391. iX += 8;
  116392. T += 8;
  116393. }while(iX<oX1);
  116394. iX=out+n2+n4;
  116395. oX1=out+n4;
  116396. oX2=oX1;
  116397. do{
  116398. oX1-=4;
  116399. iX-=4;
  116400. oX2[0] = -(oX1[3] = iX[3]);
  116401. oX2[1] = -(oX1[2] = iX[2]);
  116402. oX2[2] = -(oX1[1] = iX[1]);
  116403. oX2[3] = -(oX1[0] = iX[0]);
  116404. oX2+=4;
  116405. }while(oX2<iX);
  116406. iX=out+n2+n4;
  116407. oX1=out+n2+n4;
  116408. oX2=out+n2;
  116409. do{
  116410. oX1-=4;
  116411. oX1[0]= iX[3];
  116412. oX1[1]= iX[2];
  116413. oX1[2]= iX[1];
  116414. oX1[3]= iX[0];
  116415. iX+=4;
  116416. }while(oX1>oX2);
  116417. }
  116418. }
  116419. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116420. int n=init->n;
  116421. int n2=n>>1;
  116422. int n4=n>>2;
  116423. int n8=n>>3;
  116424. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116425. DATA_TYPE *w2=w+n2;
  116426. /* rotate */
  116427. /* window + rotate + step 1 */
  116428. REG_TYPE r0;
  116429. REG_TYPE r1;
  116430. DATA_TYPE *x0=in+n2+n4;
  116431. DATA_TYPE *x1=x0+1;
  116432. DATA_TYPE *T=init->trig+n2;
  116433. int i=0;
  116434. for(i=0;i<n8;i+=2){
  116435. x0 -=4;
  116436. T-=2;
  116437. r0= x0[2] + x1[0];
  116438. r1= x0[0] + x1[2];
  116439. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116440. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116441. x1 +=4;
  116442. }
  116443. x1=in+1;
  116444. for(;i<n2-n8;i+=2){
  116445. T-=2;
  116446. x0 -=4;
  116447. r0= x0[2] - x1[0];
  116448. r1= x0[0] - x1[2];
  116449. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116450. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116451. x1 +=4;
  116452. }
  116453. x0=in+n;
  116454. for(;i<n2;i+=2){
  116455. T-=2;
  116456. x0 -=4;
  116457. r0= -x0[2] - x1[0];
  116458. r1= -x0[0] - x1[2];
  116459. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116460. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116461. x1 +=4;
  116462. }
  116463. mdct_butterflies(init,w+n2,n2);
  116464. mdct_bitreverse(init,w);
  116465. /* roatate + window */
  116466. T=init->trig+n2;
  116467. x0=out+n2;
  116468. for(i=0;i<n4;i++){
  116469. x0--;
  116470. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116471. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116472. w+=2;
  116473. T+=2;
  116474. }
  116475. }
  116476. #endif
  116477. /*** End of inlined file: mdct.c ***/
  116478. /*** Start of inlined file: psy.c ***/
  116479. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116480. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116481. // tasks..
  116482. #if JUCE_MSVC
  116483. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116484. #endif
  116485. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116486. #if JUCE_USE_OGGVORBIS
  116487. #include <stdlib.h>
  116488. #include <math.h>
  116489. #include <string.h>
  116490. /*** Start of inlined file: masking.h ***/
  116491. #ifndef _V_MASKING_H_
  116492. #define _V_MASKING_H_
  116493. /* more detailed ATH; the bass if flat to save stressing the floor
  116494. overly for only a bin or two of savings. */
  116495. #define MAX_ATH 88
  116496. static float ATH[]={
  116497. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116498. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116499. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116500. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116501. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116502. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116503. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116504. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116505. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116506. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116507. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116508. };
  116509. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116510. replaced by an empirically collected data set. The previously
  116511. published values were, far too often, simply on crack. */
  116512. #define EHMER_OFFSET 16
  116513. #define EHMER_MAX 56
  116514. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116515. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116516. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116517. for collection of these curves) */
  116518. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116519. /* 62.5 Hz */
  116520. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116521. -60, -60, -60, -60, -62, -62, -65, -73,
  116522. -69, -68, -68, -67, -70, -70, -72, -74,
  116523. -75, -79, -79, -80, -83, -88, -93, -100,
  116524. -110, -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. { -48, -48, -48, -48, -48, -48, -48, -48,
  116528. -48, -48, -48, -48, -48, -53, -61, -66,
  116529. -66, -68, -67, -70, -76, -76, -72, -73,
  116530. -75, -76, -78, -79, -83, -88, -93, -100,
  116531. -110, -999, -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. { -37, -37, -37, -37, -37, -37, -37, -37,
  116535. -38, -40, -42, -46, -48, -53, -55, -62,
  116536. -65, -58, -56, -56, -61, -60, -65, -67,
  116537. -69, -71, -77, -77, -78, -80, -82, -84,
  116538. -88, -93, -98, -106, -112, -999, -999, -999,
  116539. -999, -999, -999, -999, -999, -999, -999, -999,
  116540. -999, -999, -999, -999, -999, -999, -999, -999},
  116541. { -25, -25, -25, -25, -25, -25, -25, -25,
  116542. -25, -26, -27, -29, -32, -38, -48, -52,
  116543. -52, -50, -48, -48, -51, -52, -54, -60,
  116544. -67, -67, -66, -68, -69, -73, -73, -76,
  116545. -80, -81, -81, -85, -85, -86, -88, -93,
  116546. -100, -110, -999, -999, -999, -999, -999, -999,
  116547. -999, -999, -999, -999, -999, -999, -999, -999},
  116548. { -16, -16, -16, -16, -16, -16, -16, -16,
  116549. -17, -19, -20, -22, -26, -28, -31, -40,
  116550. -47, -39, -39, -40, -42, -43, -47, -51,
  116551. -57, -52, -55, -55, -60, -58, -62, -63,
  116552. -70, -67, -69, -72, -73, -77, -80, -82,
  116553. -83, -87, -90, -94, -98, -104, -115, -999,
  116554. -999, -999, -999, -999, -999, -999, -999, -999},
  116555. { -8, -8, -8, -8, -8, -8, -8, -8,
  116556. -8, -8, -10, -11, -15, -19, -25, -30,
  116557. -34, -31, -30, -31, -29, -32, -35, -42,
  116558. -48, -42, -44, -46, -50, -50, -51, -52,
  116559. -59, -54, -55, -55, -58, -62, -63, -66,
  116560. -72, -73, -76, -75, -78, -80, -80, -81,
  116561. -84, -88, -90, -94, -98, -101, -106, -110}},
  116562. /* 88Hz */
  116563. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116564. -66, -66, -66, -66, -66, -67, -67, -67,
  116565. -76, -72, -71, -74, -76, -76, -75, -78,
  116566. -79, -79, -81, -83, -86, -89, -93, -97,
  116567. -100, -105, -110, -999, -999, -999, -999, -999,
  116568. -999, -999, -999, -999, -999, -999, -999, -999,
  116569. -999, -999, -999, -999, -999, -999, -999, -999},
  116570. { -47, -47, -47, -47, -47, -47, -47, -47,
  116571. -47, -47, -47, -48, -51, -55, -59, -66,
  116572. -66, -66, -67, -66, -68, -69, -70, -74,
  116573. -79, -77, -77, -78, -80, -81, -82, -84,
  116574. -86, -88, -91, -95, -100, -108, -116, -999,
  116575. -999, -999, -999, -999, -999, -999, -999, -999,
  116576. -999, -999, -999, -999, -999, -999, -999, -999},
  116577. { -36, -36, -36, -36, -36, -36, -36, -36,
  116578. -36, -37, -37, -41, -44, -48, -51, -58,
  116579. -62, -60, -57, -59, -59, -60, -63, -65,
  116580. -72, -71, -70, -72, -74, -77, -76, -78,
  116581. -81, -81, -80, -83, -86, -91, -96, -100,
  116582. -105, -110, -999, -999, -999, -999, -999, -999,
  116583. -999, -999, -999, -999, -999, -999, -999, -999},
  116584. { -28, -28, -28, -28, -28, -28, -28, -28,
  116585. -28, -30, -32, -32, -33, -35, -41, -49,
  116586. -50, -49, -47, -48, -48, -52, -51, -57,
  116587. -65, -61, -59, -61, -64, -69, -70, -74,
  116588. -77, -77, -78, -81, -84, -85, -87, -90,
  116589. -92, -96, -100, -107, -112, -999, -999, -999,
  116590. -999, -999, -999, -999, -999, -999, -999, -999},
  116591. { -19, -19, -19, -19, -19, -19, -19, -19,
  116592. -20, -21, -23, -27, -30, -35, -36, -41,
  116593. -46, -44, -42, -40, -41, -41, -43, -48,
  116594. -55, -53, -52, -53, -56, -59, -58, -60,
  116595. -67, -66, -69, -71, -72, -75, -79, -81,
  116596. -84, -87, -90, -93, -97, -101, -107, -114,
  116597. -999, -999, -999, -999, -999, -999, -999, -999},
  116598. { -9, -9, -9, -9, -9, -9, -9, -9,
  116599. -11, -12, -12, -15, -16, -20, -23, -30,
  116600. -37, -34, -33, -34, -31, -32, -32, -38,
  116601. -47, -44, -41, -40, -47, -49, -46, -46,
  116602. -58, -50, -50, -54, -58, -62, -64, -67,
  116603. -67, -70, -72, -76, -79, -83, -87, -91,
  116604. -96, -100, -104, -110, -999, -999, -999, -999}},
  116605. /* 125 Hz */
  116606. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116607. -62, -62, -63, -64, -66, -67, -66, -68,
  116608. -75, -72, -76, -75, -76, -78, -79, -82,
  116609. -84, -85, -90, -94, -101, -110, -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. { -59, -59, -59, -59, -59, -59, -59, -59,
  116614. -59, -59, -59, -60, -60, -61, -63, -66,
  116615. -71, -68, -70, -70, -71, -72, -72, -75,
  116616. -81, -78, -79, -82, -83, -86, -90, -97,
  116617. -103, -113, -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. { -53, -53, -53, -53, -53, -53, -53, -53,
  116621. -53, -54, -55, -57, -56, -57, -55, -61,
  116622. -65, -60, -60, -62, -63, -63, -66, -68,
  116623. -74, -73, -75, -75, -78, -80, -80, -82,
  116624. -85, -90, -96, -101, -108, -999, -999, -999,
  116625. -999, -999, -999, -999, -999, -999, -999, -999,
  116626. -999, -999, -999, -999, -999, -999, -999, -999},
  116627. { -46, -46, -46, -46, -46, -46, -46, -46,
  116628. -46, -46, -47, -47, -47, -47, -48, -51,
  116629. -57, -51, -49, -50, -51, -53, -54, -59,
  116630. -66, -60, -62, -67, -67, -70, -72, -75,
  116631. -76, -78, -81, -85, -88, -94, -97, -104,
  116632. -112, -999, -999, -999, -999, -999, -999, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999},
  116634. { -36, -36, -36, -36, -36, -36, -36, -36,
  116635. -39, -41, -42, -42, -39, -38, -41, -43,
  116636. -52, -44, -40, -39, -37, -37, -40, -47,
  116637. -54, -50, -48, -50, -55, -61, -59, -62,
  116638. -66, -66, -66, -69, -69, -73, -74, -74,
  116639. -75, -77, -79, -82, -87, -91, -95, -100,
  116640. -108, -115, -999, -999, -999, -999, -999, -999},
  116641. { -28, -26, -24, -22, -20, -20, -23, -29,
  116642. -30, -31, -28, -27, -28, -28, -28, -35,
  116643. -40, -33, -32, -29, -30, -30, -30, -37,
  116644. -45, -41, -37, -38, -45, -47, -47, -48,
  116645. -53, -49, -48, -50, -49, -49, -51, -52,
  116646. -58, -56, -57, -56, -60, -61, -62, -70,
  116647. -72, -74, -78, -83, -88, -93, -100, -106}},
  116648. /* 177 Hz */
  116649. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116650. -999, -110, -105, -100, -95, -91, -87, -83,
  116651. -80, -78, -76, -78, -78, -81, -83, -85,
  116652. -86, -85, -86, -87, -90, -97, -107, -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, -110, -105, -100, -95, -90,
  116657. -85, -81, -77, -73, -70, -67, -67, -68,
  116658. -75, -73, -70, -69, -70, -72, -75, -79,
  116659. -84, -83, -84, -86, -88, -89, -89, -93,
  116660. -98, -105, -112, -999, -999, -999, -999, -999,
  116661. -999, -999, -999, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999},
  116663. {-105, -100, -95, -90, -85, -80, -76, -71,
  116664. -68, -68, -65, -63, -63, -62, -62, -64,
  116665. -65, -64, -61, -62, -63, -64, -66, -68,
  116666. -73, -73, -74, -75, -76, -81, -83, -85,
  116667. -88, -89, -92, -95, -100, -108, -999, -999,
  116668. -999, -999, -999, -999, -999, -999, -999, -999,
  116669. -999, -999, -999, -999, -999, -999, -999, -999},
  116670. { -80, -75, -71, -68, -65, -63, -62, -61,
  116671. -61, -61, -61, -59, -56, -57, -53, -50,
  116672. -58, -52, -50, -50, -52, -53, -54, -58,
  116673. -67, -63, -67, -68, -72, -75, -78, -80,
  116674. -81, -81, -82, -85, -89, -90, -93, -97,
  116675. -101, -107, -114, -999, -999, -999, -999, -999,
  116676. -999, -999, -999, -999, -999, -999, -999, -999},
  116677. { -65, -61, -59, -57, -56, -55, -55, -56,
  116678. -56, -57, -55, -53, -52, -47, -44, -44,
  116679. -50, -44, -41, -39, -39, -42, -40, -46,
  116680. -51, -49, -50, -53, -54, -63, -60, -61,
  116681. -62, -66, -66, -66, -70, -73, -74, -75,
  116682. -76, -75, -79, -85, -89, -91, -96, -102,
  116683. -110, -999, -999, -999, -999, -999, -999, -999},
  116684. { -52, -50, -49, -49, -48, -48, -48, -49,
  116685. -50, -50, -49, -46, -43, -39, -35, -33,
  116686. -38, -36, -32, -29, -32, -32, -32, -35,
  116687. -44, -39, -38, -38, -46, -50, -45, -46,
  116688. -53, -50, -50, -50, -54, -54, -53, -53,
  116689. -56, -57, -59, -66, -70, -72, -74, -79,
  116690. -83, -85, -90, -97, -114, -999, -999, -999}},
  116691. /* 250 Hz */
  116692. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116693. -100, -95, -90, -86, -80, -75, -75, -79,
  116694. -80, -79, -80, -81, -82, -88, -95, -103,
  116695. -110, -999, -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, -108, -103, -98, -93,
  116700. -88, -83, -79, -78, -75, -71, -67, -68,
  116701. -73, -73, -72, -73, -75, -77, -80, -82,
  116702. -88, -93, -100, -107, -114, -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, -110, -105, -101, -96, -90,
  116707. -86, -81, -77, -73, -69, -66, -61, -62,
  116708. -66, -64, -62, -65, -66, -70, -72, -76,
  116709. -81, -80, -84, -90, -95, -102, -110, -999,
  116710. -999, -999, -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, -107, -103, -97, -92, -88,
  116714. -83, -79, -74, -70, -66, -59, -53, -58,
  116715. -62, -55, -54, -54, -54, -58, -61, -62,
  116716. -72, -70, -72, -75, -78, -80, -81, -80,
  116717. -83, -83, -88, -93, -100, -107, -115, -999,
  116718. -999, -999, -999, -999, -999, -999, -999, -999,
  116719. -999, -999, -999, -999, -999, -999, -999, -999},
  116720. {-999, -999, -999, -105, -100, -95, -90, -85,
  116721. -80, -75, -70, -66, -62, -56, -48, -44,
  116722. -48, -46, -46, -43, -46, -48, -48, -51,
  116723. -58, -58, -59, -60, -62, -62, -61, -61,
  116724. -65, -64, -65, -68, -70, -74, -75, -78,
  116725. -81, -86, -95, -110, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999},
  116727. {-999, -999, -105, -100, -95, -90, -85, -80,
  116728. -75, -70, -65, -61, -55, -49, -39, -33,
  116729. -40, -35, -32, -38, -40, -33, -35, -37,
  116730. -46, -41, -45, -44, -46, -42, -45, -46,
  116731. -52, -50, -50, -50, -54, -54, -55, -57,
  116732. -62, -64, -66, -68, -70, -76, -81, -90,
  116733. -100, -110, -999, -999, -999, -999, -999, -999}},
  116734. /* 354 hz */
  116735. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116736. -105, -98, -90, -85, -82, -83, -80, -78,
  116737. -84, -79, -80, -83, -87, -89, -91, -93,
  116738. -99, -106, -117, -999, -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. -105, -98, -90, -85, -80, -75, -70, -68,
  116744. -74, -72, -74, -77, -80, -82, -85, -87,
  116745. -92, -89, -91, -95, -100, -106, -112, -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. -105, -98, -90, -83, -75, -71, -63, -64,
  116751. -67, -62, -64, -67, -70, -73, -77, -81,
  116752. -84, -83, -85, -89, -90, -93, -98, -104,
  116753. -109, -114, -999, -999, -999, -999, -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. -103, -96, -88, -81, -75, -68, -58, -54,
  116758. -56, -54, -56, -56, -58, -60, -63, -66,
  116759. -74, -69, -72, -72, -75, -74, -77, -81,
  116760. -81, -82, -84, -87, -93, -96, -99, -104,
  116761. -110, -999, -999, -999, -999, -999, -999, -999,
  116762. -999, -999, -999, -999, -999, -999, -999, -999},
  116763. {-999, -999, -999, -999, -999, -108, -102, -96,
  116764. -91, -85, -80, -74, -68, -60, -51, -46,
  116765. -48, -46, -43, -45, -47, -47, -49, -48,
  116766. -56, -53, -55, -58, -57, -63, -58, -60,
  116767. -66, -64, -67, -70, -70, -74, -77, -84,
  116768. -86, -89, -91, -93, -94, -101, -109, -118,
  116769. -999, -999, -999, -999, -999, -999, -999, -999},
  116770. {-999, -999, -999, -108, -103, -98, -93, -88,
  116771. -83, -78, -73, -68, -60, -53, -44, -35,
  116772. -38, -38, -34, -34, -36, -40, -41, -44,
  116773. -51, -45, -46, -47, -46, -54, -50, -49,
  116774. -50, -50, -50, -51, -54, -57, -58, -60,
  116775. -66, -66, -66, -64, -65, -68, -77, -82,
  116776. -87, -95, -110, -999, -999, -999, -999, -999}},
  116777. /* 500 Hz */
  116778. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116779. -107, -102, -97, -92, -87, -83, -78, -75,
  116780. -82, -79, -83, -85, -89, -92, -95, -98,
  116781. -101, -105, -109, -113, -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, -106,
  116786. -100, -95, -90, -86, -81, -78, -74, -69,
  116787. -74, -74, -76, -79, -83, -84, -86, -89,
  116788. -92, -97, -93, -100, -103, -107, -110, -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, -106, -100,
  116793. -95, -90, -87, -83, -80, -75, -69, -60,
  116794. -66, -66, -68, -70, -74, -78, -79, -81,
  116795. -81, -83, -84, -87, -93, -96, -99, -103,
  116796. -107, -110, -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, -108, -103, -98,
  116800. -93, -89, -85, -82, -78, -71, -62, -55,
  116801. -58, -58, -54, -54, -55, -59, -61, -62,
  116802. -70, -66, -66, -67, -70, -72, -75, -78,
  116803. -84, -84, -84, -88, -91, -90, -95, -98,
  116804. -102, -103, -106, -110, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999},
  116806. {-999, -999, -999, -999, -108, -103, -98, -94,
  116807. -90, -87, -82, -79, -73, -67, -58, -47,
  116808. -50, -45, -41, -45, -48, -44, -44, -49,
  116809. -54, -51, -48, -47, -49, -50, -51, -57,
  116810. -58, -60, -63, -69, -70, -69, -71, -74,
  116811. -78, -82, -90, -95, -101, -105, -110, -999,
  116812. -999, -999, -999, -999, -999, -999, -999, -999},
  116813. {-999, -999, -999, -105, -101, -97, -93, -90,
  116814. -85, -80, -77, -72, -65, -56, -48, -37,
  116815. -40, -36, -34, -40, -50, -47, -38, -41,
  116816. -47, -38, -35, -39, -38, -43, -40, -45,
  116817. -50, -45, -44, -47, -50, -55, -48, -48,
  116818. -52, -66, -70, -76, -82, -90, -97, -105,
  116819. -110, -999, -999, -999, -999, -999, -999, -999}},
  116820. /* 707 Hz */
  116821. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116822. -999, -108, -103, -98, -93, -86, -79, -76,
  116823. -83, -81, -85, -87, -89, -93, -98, -102,
  116824. -107, -112, -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, -108, -103, -98, -93, -86, -79, -71,
  116830. -77, -74, -77, -79, -81, -84, -85, -90,
  116831. -92, -93, -92, -98, -101, -108, -112, -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. -108, -103, -98, -93, -87, -78, -68, -65,
  116837. -66, -62, -65, -67, -70, -73, -75, -78,
  116838. -82, -82, -83, -84, -91, -93, -98, -102,
  116839. -106, -110, -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. -105, -100, -95, -90, -82, -74, -62, -57,
  116844. -58, -56, -51, -52, -52, -54, -54, -58,
  116845. -66, -59, -60, -63, -66, -69, -73, -79,
  116846. -83, -84, -80, -81, -81, -82, -88, -92,
  116847. -98, -105, -113, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -999, -999, -999, -999},
  116849. {-999, -999, -999, -999, -999, -999, -999, -107,
  116850. -102, -97, -92, -84, -79, -69, -57, -47,
  116851. -52, -47, -44, -45, -50, -52, -42, -42,
  116852. -53, -43, -43, -48, -51, -56, -55, -52,
  116853. -57, -59, -61, -62, -67, -71, -78, -83,
  116854. -86, -94, -98, -103, -110, -999, -999, -999,
  116855. -999, -999, -999, -999, -999, -999, -999, -999},
  116856. {-999, -999, -999, -999, -999, -999, -105, -100,
  116857. -95, -90, -84, -78, -70, -61, -51, -41,
  116858. -40, -38, -40, -46, -52, -51, -41, -40,
  116859. -46, -40, -38, -38, -41, -46, -41, -46,
  116860. -47, -43, -43, -45, -41, -45, -56, -67,
  116861. -68, -83, -87, -90, -95, -102, -107, -113,
  116862. -999, -999, -999, -999, -999, -999, -999, -999}},
  116863. /* 1000 Hz */
  116864. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116865. -999, -109, -105, -101, -96, -91, -84, -77,
  116866. -82, -82, -85, -89, -94, -100, -106, -110,
  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, -106, -103, -98, -92, -85, -80, -71,
  116873. -75, -72, -76, -80, -84, -86, -89, -93,
  116874. -100, -107, -113, -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, -107,
  116879. -104, -101, -97, -92, -88, -84, -80, -64,
  116880. -66, -63, -64, -66, -69, -73, -77, -83,
  116881. -83, -86, -91, -98, -104, -111, -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, -107,
  116886. -104, -101, -97, -92, -90, -84, -74, -57,
  116887. -58, -52, -55, -54, -50, -52, -50, -52,
  116888. -63, -62, -69, -76, -77, -78, -78, -79,
  116889. -82, -88, -94, -100, -106, -111, -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, -106, -102,
  116893. -98, -95, -90, -85, -83, -78, -70, -50,
  116894. -50, -41, -44, -49, -47, -50, -50, -44,
  116895. -55, -46, -47, -48, -48, -54, -49, -49,
  116896. -58, -62, -71, -81, -87, -92, -97, -102,
  116897. -108, -114, -999, -999, -999, -999, -999, -999,
  116898. -999, -999, -999, -999, -999, -999, -999, -999},
  116899. {-999, -999, -999, -999, -999, -999, -106, -102,
  116900. -98, -95, -90, -85, -83, -78, -70, -45,
  116901. -43, -41, -47, -50, -51, -50, -49, -45,
  116902. -47, -41, -44, -41, -39, -43, -38, -37,
  116903. -40, -41, -44, -50, -58, -65, -73, -79,
  116904. -85, -92, -97, -101, -105, -109, -113, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999}},
  116906. /* 1414 Hz */
  116907. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116908. -999, -999, -999, -107, -100, -95, -87, -81,
  116909. -85, -83, -88, -93, -100, -107, -114, -999,
  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, -107, -101, -95, -88, -83, -76,
  116916. -73, -72, -79, -84, -90, -95, -100, -105,
  116917. -110, -115, -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, -104, -98, -92, -87, -81, -70,
  116923. -65, -62, -67, -71, -74, -80, -85, -91,
  116924. -95, -99, -103, -108, -111, -114, -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, -103, -97, -90, -85, -76, -60,
  116930. -56, -54, -60, -62, -61, -56, -63, -65,
  116931. -73, -74, -77, -75, -78, -81, -86, -87,
  116932. -88, -91, -94, -98, -103, -110, -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, -105,
  116936. -100, -97, -92, -86, -81, -79, -70, -57,
  116937. -51, -47, -51, -58, -60, -56, -53, -50,
  116938. -58, -52, -50, -50, -53, -55, -64, -69,
  116939. -71, -85, -82, -78, -81, -85, -95, -102,
  116940. -112, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -999, -999, -999, -999, -999, -999},
  116942. {-999, -999, -999, -999, -999, -999, -999, -105,
  116943. -100, -97, -92, -85, -83, -79, -72, -49,
  116944. -40, -43, -43, -54, -56, -51, -50, -40,
  116945. -43, -38, -36, -35, -37, -38, -37, -44,
  116946. -54, -60, -57, -60, -70, -75, -84, -92,
  116947. -103, -112, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999}},
  116949. /* 2000 Hz */
  116950. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116951. -999, -999, -999, -110, -102, -95, -89, -82,
  116952. -83, -84, -90, -92, -99, -107, -113, -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, -107, -101, -95, -89, -83, -72,
  116959. -74, -78, -85, -88, -88, -90, -92, -98,
  116960. -105, -111, -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, -109, -103, -97, -93, -87, -81, -70,
  116966. -70, -67, -75, -73, -76, -79, -81, -83,
  116967. -88, -89, -97, -103, -110, -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, -107, -100, -94, -88, -83, -75, -63,
  116973. -59, -59, -63, -66, -60, -62, -67, -67,
  116974. -77, -76, -81, -88, -86, -92, -96, -102,
  116975. -109, -116, -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, -105, -98, -92, -86, -81, -73, -56,
  116980. -52, -47, -55, -60, -58, -52, -51, -45,
  116981. -49, -50, -53, -54, -61, -71, -70, -69,
  116982. -78, -79, -87, -90, -96, -104, -112, -999,
  116983. -999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -999, -999, -999, -999, -999, -999},
  116985. {-999, -999, -999, -999, -999, -999, -999, -999,
  116986. -999, -103, -96, -90, -86, -78, -70, -51,
  116987. -42, -47, -48, -55, -54, -54, -53, -42,
  116988. -35, -28, -33, -38, -37, -44, -47, -49,
  116989. -54, -63, -68, -78, -82, -89, -94, -99,
  116990. -104, -109, -114, -999, -999, -999, -999, -999,
  116991. -999, -999, -999, -999, -999, -999, -999, -999}},
  116992. /* 2828 Hz */
  116993. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116994. -999, -999, -999, -999, -110, -100, -90, -79,
  116995. -85, -81, -82, -82, -89, -94, -99, -103,
  116996. -109, -115, -999, -999, -999, -999, -999, -999,
  116997. -999, -999, -999, -999, -999, -999, -999, -999,
  116998. -999, -999, -999, -999, -999, -999, -999, -999,
  116999. -999, -999, -999, -999, -999, -999, -999, -999},
  117000. {-999, -999, -999, -999, -999, -999, -999, -999,
  117001. -999, -999, -999, -999, -105, -97, -85, -72,
  117002. -74, -70, -70, -70, -76, -85, -91, -93,
  117003. -97, -103, -109, -115, -999, -999, -999, -999,
  117004. -999, -999, -999, -999, -999, -999, -999, -999,
  117005. -999, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -999, -999, -999, -999, -999, -999, -999},
  117007. {-999, -999, -999, -999, -999, -999, -999, -999,
  117008. -999, -999, -999, -999, -112, -93, -81, -68,
  117009. -62, -60, -60, -57, -63, -70, -77, -82,
  117010. -90, -93, -98, -104, -109, -113, -999, -999,
  117011. -999, -999, -999, -999, -999, -999, -999, -999,
  117012. -999, -999, -999, -999, -999, -999, -999, -999,
  117013. -999, -999, -999, -999, -999, -999, -999, -999},
  117014. {-999, -999, -999, -999, -999, -999, -999, -999,
  117015. -999, -999, -999, -113, -100, -93, -84, -63,
  117016. -58, -48, -53, -54, -52, -52, -57, -64,
  117017. -66, -76, -83, -81, -85, -85, -90, -95,
  117018. -98, -101, -103, -106, -108, -111, -999, -999,
  117019. -999, -999, -999, -999, -999, -999, -999, -999,
  117020. -999, -999, -999, -999, -999, -999, -999, -999},
  117021. {-999, -999, -999, -999, -999, -999, -999, -999,
  117022. -999, -999, -999, -105, -95, -86, -74, -53,
  117023. -50, -38, -43, -49, -43, -42, -39, -39,
  117024. -46, -52, -57, -56, -72, -69, -74, -81,
  117025. -87, -92, -94, -97, -99, -102, -105, -108,
  117026. -999, -999, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -999, -999, -999, -999, -999},
  117028. {-999, -999, -999, -999, -999, -999, -999, -999,
  117029. -999, -999, -108, -99, -90, -76, -66, -45,
  117030. -43, -41, -44, -47, -43, -47, -40, -30,
  117031. -31, -31, -39, -33, -40, -41, -43, -53,
  117032. -59, -70, -73, -77, -79, -82, -84, -87,
  117033. -999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -999, -999, -999, -999, -999, -999}},
  117035. /* 4000 Hz */
  117036. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117037. -999, -999, -999, -999, -999, -110, -91, -76,
  117038. -75, -85, -93, -98, -104, -110, -999, -999,
  117039. -999, -999, -999, -999, -999, -999, -999, -999,
  117040. -999, -999, -999, -999, -999, -999, -999, -999,
  117041. -999, -999, -999, -999, -999, -999, -999, -999,
  117042. -999, -999, -999, -999, -999, -999, -999, -999},
  117043. {-999, -999, -999, -999, -999, -999, -999, -999,
  117044. -999, -999, -999, -999, -999, -110, -91, -70,
  117045. -70, -75, -86, -89, -94, -98, -101, -106,
  117046. -110, -999, -999, -999, -999, -999, -999, -999,
  117047. -999, -999, -999, -999, -999, -999, -999, -999,
  117048. -999, -999, -999, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -999, -999, -999, -999, -999},
  117050. {-999, -999, -999, -999, -999, -999, -999, -999,
  117051. -999, -999, -999, -999, -110, -95, -80, -60,
  117052. -65, -64, -74, -83, -88, -91, -95, -99,
  117053. -103, -107, -110, -999, -999, -999, -999, -999,
  117054. -999, -999, -999, -999, -999, -999, -999, -999,
  117055. -999, -999, -999, -999, -999, -999, -999, -999,
  117056. -999, -999, -999, -999, -999, -999, -999, -999},
  117057. {-999, -999, -999, -999, -999, -999, -999, -999,
  117058. -999, -999, -999, -999, -110, -95, -80, -58,
  117059. -55, -49, -66, -68, -71, -78, -78, -80,
  117060. -88, -85, -89, -97, -100, -105, -110, -999,
  117061. -999, -999, -999, -999, -999, -999, -999, -999,
  117062. -999, -999, -999, -999, -999, -999, -999, -999,
  117063. -999, -999, -999, -999, -999, -999, -999, -999},
  117064. {-999, -999, -999, -999, -999, -999, -999, -999,
  117065. -999, -999, -999, -999, -110, -95, -80, -53,
  117066. -52, -41, -59, -59, -49, -58, -56, -63,
  117067. -86, -79, -90, -93, -98, -103, -107, -112,
  117068. -999, -999, -999, -999, -999, -999, -999, -999,
  117069. -999, -999, -999, -999, -999, -999, -999, -999,
  117070. -999, -999, -999, -999, -999, -999, -999, -999},
  117071. {-999, -999, -999, -999, -999, -999, -999, -999,
  117072. -999, -999, -999, -110, -97, -91, -73, -45,
  117073. -40, -33, -53, -61, -49, -54, -50, -50,
  117074. -60, -52, -67, -74, -81, -92, -96, -100,
  117075. -105, -110, -999, -999, -999, -999, -999, -999,
  117076. -999, -999, -999, -999, -999, -999, -999, -999,
  117077. -999, -999, -999, -999, -999, -999, -999, -999}},
  117078. /* 5657 Hz */
  117079. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117080. -999, -999, -999, -113, -106, -99, -92, -77,
  117081. -80, -88, -97, -106, -115, -999, -999, -999,
  117082. -999, -999, -999, -999, -999, -999, -999, -999,
  117083. -999, -999, -999, -999, -999, -999, -999, -999,
  117084. -999, -999, -999, -999, -999, -999, -999, -999,
  117085. -999, -999, -999, -999, -999, -999, -999, -999},
  117086. {-999, -999, -999, -999, -999, -999, -999, -999,
  117087. -999, -999, -116, -109, -102, -95, -89, -74,
  117088. -72, -88, -87, -95, -102, -109, -116, -999,
  117089. -999, -999, -999, -999, -999, -999, -999, -999,
  117090. -999, -999, -999, -999, -999, -999, -999, -999,
  117091. -999, -999, -999, -999, -999, -999, -999, -999,
  117092. -999, -999, -999, -999, -999, -999, -999, -999},
  117093. {-999, -999, -999, -999, -999, -999, -999, -999,
  117094. -999, -999, -116, -109, -102, -95, -89, -75,
  117095. -66, -74, -77, -78, -86, -87, -90, -96,
  117096. -105, -115, -999, -999, -999, -999, -999, -999,
  117097. -999, -999, -999, -999, -999, -999, -999, -999,
  117098. -999, -999, -999, -999, -999, -999, -999, -999,
  117099. -999, -999, -999, -999, -999, -999, -999, -999},
  117100. {-999, -999, -999, -999, -999, -999, -999, -999,
  117101. -999, -999, -115, -108, -101, -94, -88, -66,
  117102. -56, -61, -70, -65, -78, -72, -83, -84,
  117103. -93, -98, -105, -110, -999, -999, -999, -999,
  117104. -999, -999, -999, -999, -999, -999, -999, -999,
  117105. -999, -999, -999, -999, -999, -999, -999, -999,
  117106. -999, -999, -999, -999, -999, -999, -999, -999},
  117107. {-999, -999, -999, -999, -999, -999, -999, -999,
  117108. -999, -999, -110, -105, -95, -89, -82, -57,
  117109. -52, -52, -59, -56, -59, -58, -69, -67,
  117110. -88, -82, -82, -89, -94, -100, -108, -999,
  117111. -999, -999, -999, -999, -999, -999, -999, -999,
  117112. -999, -999, -999, -999, -999, -999, -999, -999,
  117113. -999, -999, -999, -999, -999, -999, -999, -999},
  117114. {-999, -999, -999, -999, -999, -999, -999, -999,
  117115. -999, -110, -101, -96, -90, -83, -77, -54,
  117116. -43, -38, -50, -48, -52, -48, -42, -42,
  117117. -51, -52, -53, -59, -65, -71, -78, -85,
  117118. -95, -999, -999, -999, -999, -999, -999, -999,
  117119. -999, -999, -999, -999, -999, -999, -999, -999,
  117120. -999, -999, -999, -999, -999, -999, -999, -999}},
  117121. /* 8000 Hz */
  117122. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117123. -999, -999, -999, -999, -120, -105, -86, -68,
  117124. -78, -79, -90, -100, -110, -999, -999, -999,
  117125. -999, -999, -999, -999, -999, -999, -999, -999,
  117126. -999, -999, -999, -999, -999, -999, -999, -999,
  117127. -999, -999, -999, -999, -999, -999, -999, -999,
  117128. -999, -999, -999, -999, -999, -999, -999, -999},
  117129. {-999, -999, -999, -999, -999, -999, -999, -999,
  117130. -999, -999, -999, -999, -120, -105, -86, -66,
  117131. -73, -77, -88, -96, -105, -115, -999, -999,
  117132. -999, -999, -999, -999, -999, -999, -999, -999,
  117133. -999, -999, -999, -999, -999, -999, -999, -999,
  117134. -999, -999, -999, -999, -999, -999, -999, -999,
  117135. -999, -999, -999, -999, -999, -999, -999, -999},
  117136. {-999, -999, -999, -999, -999, -999, -999, -999,
  117137. -999, -999, -999, -120, -105, -92, -80, -61,
  117138. -64, -68, -80, -87, -92, -100, -110, -999,
  117139. -999, -999, -999, -999, -999, -999, -999, -999,
  117140. -999, -999, -999, -999, -999, -999, -999, -999,
  117141. -999, -999, -999, -999, -999, -999, -999, -999,
  117142. -999, -999, -999, -999, -999, -999, -999, -999},
  117143. {-999, -999, -999, -999, -999, -999, -999, -999,
  117144. -999, -999, -999, -120, -104, -91, -79, -52,
  117145. -60, -54, -64, -69, -77, -80, -82, -84,
  117146. -85, -87, -88, -90, -999, -999, -999, -999,
  117147. -999, -999, -999, -999, -999, -999, -999, -999,
  117148. -999, -999, -999, -999, -999, -999, -999, -999,
  117149. -999, -999, -999, -999, -999, -999, -999, -999},
  117150. {-999, -999, -999, -999, -999, -999, -999, -999,
  117151. -999, -999, -999, -118, -100, -87, -77, -49,
  117152. -50, -44, -58, -61, -61, -67, -65, -62,
  117153. -62, -62, -65, -68, -999, -999, -999, -999,
  117154. -999, -999, -999, -999, -999, -999, -999, -999,
  117155. -999, -999, -999, -999, -999, -999, -999, -999,
  117156. -999, -999, -999, -999, -999, -999, -999, -999},
  117157. {-999, -999, -999, -999, -999, -999, -999, -999,
  117158. -999, -999, -999, -115, -98, -84, -62, -49,
  117159. -44, -38, -46, -49, -49, -46, -39, -37,
  117160. -39, -40, -42, -43, -999, -999, -999, -999,
  117161. -999, -999, -999, -999, -999, -999, -999, -999,
  117162. -999, -999, -999, -999, -999, -999, -999, -999,
  117163. -999, -999, -999, -999, -999, -999, -999, -999}},
  117164. /* 11314 Hz */
  117165. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117166. -999, -999, -999, -999, -999, -110, -88, -74,
  117167. -77, -82, -82, -85, -90, -94, -99, -104,
  117168. -999, -999, -999, -999, -999, -999, -999, -999,
  117169. -999, -999, -999, -999, -999, -999, -999, -999,
  117170. -999, -999, -999, -999, -999, -999, -999, -999,
  117171. -999, -999, -999, -999, -999, -999, -999, -999},
  117172. {-999, -999, -999, -999, -999, -999, -999, -999,
  117173. -999, -999, -999, -999, -999, -110, -88, -66,
  117174. -70, -81, -80, -81, -84, -88, -91, -93,
  117175. -999, -999, -999, -999, -999, -999, -999, -999,
  117176. -999, -999, -999, -999, -999, -999, -999, -999,
  117177. -999, -999, -999, -999, -999, -999, -999, -999,
  117178. -999, -999, -999, -999, -999, -999, -999, -999},
  117179. {-999, -999, -999, -999, -999, -999, -999, -999,
  117180. -999, -999, -999, -999, -999, -110, -88, -61,
  117181. -63, -70, -71, -74, -77, -80, -83, -85,
  117182. -999, -999, -999, -999, -999, -999, -999, -999,
  117183. -999, -999, -999, -999, -999, -999, -999, -999,
  117184. -999, -999, -999, -999, -999, -999, -999, -999,
  117185. -999, -999, -999, -999, -999, -999, -999, -999},
  117186. {-999, -999, -999, -999, -999, -999, -999, -999,
  117187. -999, -999, -999, -999, -999, -110, -86, -62,
  117188. -63, -62, -62, -58, -52, -50, -50, -52,
  117189. -54, -999, -999, -999, -999, -999, -999, -999,
  117190. -999, -999, -999, -999, -999, -999, -999, -999,
  117191. -999, -999, -999, -999, -999, -999, -999, -999,
  117192. -999, -999, -999, -999, -999, -999, -999, -999},
  117193. {-999, -999, -999, -999, -999, -999, -999, -999,
  117194. -999, -999, -999, -999, -118, -108, -84, -53,
  117195. -50, -50, -50, -55, -47, -45, -40, -40,
  117196. -40, -999, -999, -999, -999, -999, -999, -999,
  117197. -999, -999, -999, -999, -999, -999, -999, -999,
  117198. -999, -999, -999, -999, -999, -999, -999, -999,
  117199. -999, -999, -999, -999, -999, -999, -999, -999},
  117200. {-999, -999, -999, -999, -999, -999, -999, -999,
  117201. -999, -999, -999, -999, -118, -100, -73, -43,
  117202. -37, -42, -43, -53, -38, -37, -35, -35,
  117203. -38, -999, -999, -999, -999, -999, -999, -999,
  117204. -999, -999, -999, -999, -999, -999, -999, -999,
  117205. -999, -999, -999, -999, -999, -999, -999, -999,
  117206. -999, -999, -999, -999, -999, -999, -999, -999}},
  117207. /* 16000 Hz */
  117208. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117209. -999, -999, -999, -110, -100, -91, -84, -74,
  117210. -80, -80, -80, -80, -80, -999, -999, -999,
  117211. -999, -999, -999, -999, -999, -999, -999, -999,
  117212. -999, -999, -999, -999, -999, -999, -999, -999,
  117213. -999, -999, -999, -999, -999, -999, -999, -999,
  117214. -999, -999, -999, -999, -999, -999, -999, -999},
  117215. {-999, -999, -999, -999, -999, -999, -999, -999,
  117216. -999, -999, -999, -110, -100, -91, -84, -74,
  117217. -68, -68, -68, -68, -68, -999, -999, -999,
  117218. -999, -999, -999, -999, -999, -999, -999, -999,
  117219. -999, -999, -999, -999, -999, -999, -999, -999,
  117220. -999, -999, -999, -999, -999, -999, -999, -999,
  117221. -999, -999, -999, -999, -999, -999, -999, -999},
  117222. {-999, -999, -999, -999, -999, -999, -999, -999,
  117223. -999, -999, -999, -110, -100, -86, -78, -70,
  117224. -60, -45, -30, -21, -999, -999, -999, -999,
  117225. -999, -999, -999, -999, -999, -999, -999, -999,
  117226. -999, -999, -999, -999, -999, -999, -999, -999,
  117227. -999, -999, -999, -999, -999, -999, -999, -999,
  117228. -999, -999, -999, -999, -999, -999, -999, -999},
  117229. {-999, -999, -999, -999, -999, -999, -999, -999,
  117230. -999, -999, -999, -110, -100, -87, -78, -67,
  117231. -48, -38, -29, -21, -999, -999, -999, -999,
  117232. -999, -999, -999, -999, -999, -999, -999, -999,
  117233. -999, -999, -999, -999, -999, -999, -999, -999,
  117234. -999, -999, -999, -999, -999, -999, -999, -999,
  117235. -999, -999, -999, -999, -999, -999, -999, -999},
  117236. {-999, -999, -999, -999, -999, -999, -999, -999,
  117237. -999, -999, -999, -110, -100, -86, -69, -56,
  117238. -45, -35, -33, -29, -999, -999, -999, -999,
  117239. -999, -999, -999, -999, -999, -999, -999, -999,
  117240. -999, -999, -999, -999, -999, -999, -999, -999,
  117241. -999, -999, -999, -999, -999, -999, -999, -999,
  117242. -999, -999, -999, -999, -999, -999, -999, -999},
  117243. {-999, -999, -999, -999, -999, -999, -999, -999,
  117244. -999, -999, -999, -110, -100, -83, -71, -48,
  117245. -27, -38, -37, -34, -999, -999, -999, -999,
  117246. -999, -999, -999, -999, -999, -999, -999, -999,
  117247. -999, -999, -999, -999, -999, -999, -999, -999,
  117248. -999, -999, -999, -999, -999, -999, -999, -999,
  117249. -999, -999, -999, -999, -999, -999, -999, -999}}
  117250. };
  117251. #endif
  117252. /*** End of inlined file: masking.h ***/
  117253. #define NEGINF -9999.f
  117254. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117255. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117256. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117257. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117258. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117259. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117260. look->channels=vi->channels;
  117261. look->ampmax=-9999.;
  117262. look->gi=gi;
  117263. return(look);
  117264. }
  117265. void _vp_global_free(vorbis_look_psy_global *look){
  117266. if(look){
  117267. memset(look,0,sizeof(*look));
  117268. _ogg_free(look);
  117269. }
  117270. }
  117271. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117272. if(i){
  117273. memset(i,0,sizeof(*i));
  117274. _ogg_free(i);
  117275. }
  117276. }
  117277. void _vi_psy_free(vorbis_info_psy *i){
  117278. if(i){
  117279. memset(i,0,sizeof(*i));
  117280. _ogg_free(i);
  117281. }
  117282. }
  117283. static void min_curve(float *c,
  117284. float *c2){
  117285. int i;
  117286. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117287. }
  117288. static void max_curve(float *c,
  117289. float *c2){
  117290. int i;
  117291. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117292. }
  117293. static void attenuate_curve(float *c,float att){
  117294. int i;
  117295. for(i=0;i<EHMER_MAX;i++)
  117296. c[i]+=att;
  117297. }
  117298. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117299. float center_boost, float center_decay_rate){
  117300. int i,j,k,m;
  117301. float ath[EHMER_MAX];
  117302. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117303. float athc[P_LEVELS][EHMER_MAX];
  117304. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117305. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117306. memset(workc,0,sizeof(workc));
  117307. for(i=0;i<P_BANDS;i++){
  117308. /* we add back in the ATH to avoid low level curves falling off to
  117309. -infinity and unnecessarily cutting off high level curves in the
  117310. curve limiting (last step). */
  117311. /* A half-band's settings must be valid over the whole band, and
  117312. it's better to mask too little than too much */
  117313. int ath_offset=i*4;
  117314. for(j=0;j<EHMER_MAX;j++){
  117315. float min=999.;
  117316. for(k=0;k<4;k++)
  117317. if(j+k+ath_offset<MAX_ATH){
  117318. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117319. }else{
  117320. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117321. }
  117322. ath[j]=min;
  117323. }
  117324. /* copy curves into working space, replicate the 50dB curve to 30
  117325. and 40, replicate the 100dB curve to 110 */
  117326. for(j=0;j<6;j++)
  117327. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117328. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117329. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117330. /* apply centered curve boost/decay */
  117331. for(j=0;j<P_LEVELS;j++){
  117332. for(k=0;k<EHMER_MAX;k++){
  117333. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117334. if(adj<0. && center_boost>0)adj=0.;
  117335. if(adj>0. && center_boost<0)adj=0.;
  117336. workc[i][j][k]+=adj;
  117337. }
  117338. }
  117339. /* normalize curves so the driving amplitude is 0dB */
  117340. /* make temp curves with the ATH overlayed */
  117341. for(j=0;j<P_LEVELS;j++){
  117342. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117343. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117344. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117345. max_curve(athc[j],workc[i][j]);
  117346. }
  117347. /* Now limit the louder curves.
  117348. the idea is this: We don't know what the playback attenuation
  117349. will be; 0dB SL moves every time the user twiddles the volume
  117350. knob. So that means we have to use a single 'most pessimal' curve
  117351. for all masking amplitudes, right? Wrong. The *loudest* sound
  117352. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117353. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117354. etc... */
  117355. for(j=1;j<P_LEVELS;j++){
  117356. min_curve(athc[j],athc[j-1]);
  117357. min_curve(workc[i][j],athc[j]);
  117358. }
  117359. }
  117360. for(i=0;i<P_BANDS;i++){
  117361. int hi_curve,lo_curve,bin;
  117362. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117363. /* low frequency curves are measured with greater resolution than
  117364. the MDCT/FFT will actually give us; we want the curve applied
  117365. to the tone data to be pessimistic and thus apply the minimum
  117366. masking possible for a given bin. That means that a single bin
  117367. could span more than one octave and that the curve will be a
  117368. composite of multiple octaves. It also may mean that a single
  117369. bin may span > an eighth of an octave and that the eighth
  117370. octave values may also be composited. */
  117371. /* which octave curves will we be compositing? */
  117372. bin=floor(fromOC(i*.5)/binHz);
  117373. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117374. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117375. if(lo_curve>i)lo_curve=i;
  117376. if(lo_curve<0)lo_curve=0;
  117377. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117378. for(m=0;m<P_LEVELS;m++){
  117379. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117380. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117381. /* render the curve into bins, then pull values back into curve.
  117382. The point is that any inherent subsampling aliasing results in
  117383. a safe minimum */
  117384. for(k=lo_curve;k<=hi_curve;k++){
  117385. int l=0;
  117386. for(j=0;j<EHMER_MAX;j++){
  117387. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117388. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117389. if(lo_bin<0)lo_bin=0;
  117390. if(lo_bin>n)lo_bin=n;
  117391. if(lo_bin<l)l=lo_bin;
  117392. if(hi_bin<0)hi_bin=0;
  117393. if(hi_bin>n)hi_bin=n;
  117394. for(;l<hi_bin && l<n;l++)
  117395. if(brute_buffer[l]>workc[k][m][j])
  117396. brute_buffer[l]=workc[k][m][j];
  117397. }
  117398. for(;l<n;l++)
  117399. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117400. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117401. }
  117402. /* be equally paranoid about being valid up to next half ocatve */
  117403. if(i+1<P_BANDS){
  117404. int l=0;
  117405. k=i+1;
  117406. for(j=0;j<EHMER_MAX;j++){
  117407. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117408. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117409. if(lo_bin<0)lo_bin=0;
  117410. if(lo_bin>n)lo_bin=n;
  117411. if(lo_bin<l)l=lo_bin;
  117412. if(hi_bin<0)hi_bin=0;
  117413. if(hi_bin>n)hi_bin=n;
  117414. for(;l<hi_bin && l<n;l++)
  117415. if(brute_buffer[l]>workc[k][m][j])
  117416. brute_buffer[l]=workc[k][m][j];
  117417. }
  117418. for(;l<n;l++)
  117419. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117420. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117421. }
  117422. for(j=0;j<EHMER_MAX;j++){
  117423. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117424. if(bin<0){
  117425. ret[i][m][j+2]=-999.;
  117426. }else{
  117427. if(bin>=n){
  117428. ret[i][m][j+2]=-999.;
  117429. }else{
  117430. ret[i][m][j+2]=brute_buffer[bin];
  117431. }
  117432. }
  117433. }
  117434. /* add fenceposts */
  117435. for(j=0;j<EHMER_OFFSET;j++)
  117436. if(ret[i][m][j+2]>-200.f)break;
  117437. ret[i][m][0]=j;
  117438. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117439. if(ret[i][m][j+2]>-200.f)
  117440. break;
  117441. ret[i][m][1]=j;
  117442. }
  117443. }
  117444. return(ret);
  117445. }
  117446. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117447. vorbis_info_psy_global *gi,int n,long rate){
  117448. long i,j,lo=-99,hi=1;
  117449. long maxoc;
  117450. memset(p,0,sizeof(*p));
  117451. p->eighth_octave_lines=gi->eighth_octave_lines;
  117452. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117453. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117454. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117455. p->total_octave_lines=maxoc-p->firstoc+1;
  117456. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117457. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117458. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117459. p->vi=vi;
  117460. p->n=n;
  117461. p->rate=rate;
  117462. /* AoTuV HF weighting */
  117463. p->m_val = 1.;
  117464. if(rate < 26000) p->m_val = 0;
  117465. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117466. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117467. /* set up the lookups for a given blocksize and sample rate */
  117468. for(i=0,j=0;i<MAX_ATH-1;i++){
  117469. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117470. float base=ATH[i];
  117471. if(j<endpos){
  117472. float delta=(ATH[i+1]-base)/(endpos-j);
  117473. for(;j<endpos && j<n;j++){
  117474. p->ath[j]=base+100.;
  117475. base+=delta;
  117476. }
  117477. }
  117478. }
  117479. for(i=0;i<n;i++){
  117480. float bark=toBARK(rate/(2*n)*i);
  117481. for(;lo+vi->noisewindowlomin<i &&
  117482. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117483. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117484. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117485. p->bark[i]=((lo-1)<<16)+(hi-1);
  117486. }
  117487. for(i=0;i<n;i++)
  117488. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117489. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117490. vi->tone_centerboost,vi->tone_decay);
  117491. /* set up rolling noise median */
  117492. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117493. for(i=0;i<P_NOISECURVES;i++)
  117494. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117495. for(i=0;i<n;i++){
  117496. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117497. int inthalfoc;
  117498. float del;
  117499. if(halfoc<0)halfoc=0;
  117500. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117501. inthalfoc=(int)halfoc;
  117502. del=halfoc-inthalfoc;
  117503. for(j=0;j<P_NOISECURVES;j++)
  117504. p->noiseoffset[j][i]=
  117505. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117506. p->vi->noiseoff[j][inthalfoc+1]*del;
  117507. }
  117508. #if 0
  117509. {
  117510. static int ls=0;
  117511. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117512. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117513. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117514. }
  117515. #endif
  117516. }
  117517. void _vp_psy_clear(vorbis_look_psy *p){
  117518. int i,j;
  117519. if(p){
  117520. if(p->ath)_ogg_free(p->ath);
  117521. if(p->octave)_ogg_free(p->octave);
  117522. if(p->bark)_ogg_free(p->bark);
  117523. if(p->tonecurves){
  117524. for(i=0;i<P_BANDS;i++){
  117525. for(j=0;j<P_LEVELS;j++){
  117526. _ogg_free(p->tonecurves[i][j]);
  117527. }
  117528. _ogg_free(p->tonecurves[i]);
  117529. }
  117530. _ogg_free(p->tonecurves);
  117531. }
  117532. if(p->noiseoffset){
  117533. for(i=0;i<P_NOISECURVES;i++){
  117534. _ogg_free(p->noiseoffset[i]);
  117535. }
  117536. _ogg_free(p->noiseoffset);
  117537. }
  117538. memset(p,0,sizeof(*p));
  117539. }
  117540. }
  117541. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117542. static void seed_curve(float *seed,
  117543. const float **curves,
  117544. float amp,
  117545. int oc, int n,
  117546. int linesper,float dBoffset){
  117547. int i,post1;
  117548. int seedptr;
  117549. const float *posts,*curve;
  117550. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117551. choice=max(choice,0);
  117552. choice=min(choice,P_LEVELS-1);
  117553. posts=curves[choice];
  117554. curve=posts+2;
  117555. post1=(int)posts[1];
  117556. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117557. for(i=posts[0];i<post1;i++){
  117558. if(seedptr>0){
  117559. float lin=amp+curve[i];
  117560. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117561. }
  117562. seedptr+=linesper;
  117563. if(seedptr>=n)break;
  117564. }
  117565. }
  117566. static void seed_loop(vorbis_look_psy *p,
  117567. const float ***curves,
  117568. const float *f,
  117569. const float *flr,
  117570. float *seed,
  117571. float specmax){
  117572. vorbis_info_psy *vi=p->vi;
  117573. long n=p->n,i;
  117574. float dBoffset=vi->max_curve_dB-specmax;
  117575. /* prime the working vector with peak values */
  117576. for(i=0;i<n;i++){
  117577. float max=f[i];
  117578. long oc=p->octave[i];
  117579. while(i+1<n && p->octave[i+1]==oc){
  117580. i++;
  117581. if(f[i]>max)max=f[i];
  117582. }
  117583. if(max+6.f>flr[i]){
  117584. oc=oc>>p->shiftoc;
  117585. if(oc>=P_BANDS)oc=P_BANDS-1;
  117586. if(oc<0)oc=0;
  117587. seed_curve(seed,
  117588. curves[oc],
  117589. max,
  117590. p->octave[i]-p->firstoc,
  117591. p->total_octave_lines,
  117592. p->eighth_octave_lines,
  117593. dBoffset);
  117594. }
  117595. }
  117596. }
  117597. static void seed_chase(float *seeds, int linesper, long n){
  117598. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117599. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117600. long stack=0;
  117601. long pos=0;
  117602. long i;
  117603. for(i=0;i<n;i++){
  117604. if(stack<2){
  117605. posstack[stack]=i;
  117606. ampstack[stack++]=seeds[i];
  117607. }else{
  117608. while(1){
  117609. if(seeds[i]<ampstack[stack-1]){
  117610. posstack[stack]=i;
  117611. ampstack[stack++]=seeds[i];
  117612. break;
  117613. }else{
  117614. if(i<posstack[stack-1]+linesper){
  117615. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117616. i<posstack[stack-2]+linesper){
  117617. /* we completely overlap, making stack-1 irrelevant. pop it */
  117618. stack--;
  117619. continue;
  117620. }
  117621. }
  117622. posstack[stack]=i;
  117623. ampstack[stack++]=seeds[i];
  117624. break;
  117625. }
  117626. }
  117627. }
  117628. }
  117629. /* the stack now contains only the positions that are relevant. Scan
  117630. 'em straight through */
  117631. for(i=0;i<stack;i++){
  117632. long endpos;
  117633. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117634. endpos=posstack[i+1];
  117635. }else{
  117636. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117637. discarded in short frames */
  117638. }
  117639. if(endpos>n)endpos=n;
  117640. for(;pos<endpos;pos++)
  117641. seeds[pos]=ampstack[i];
  117642. }
  117643. /* there. Linear time. I now remember this was on a problem set I
  117644. had in Grad Skool... I didn't solve it at the time ;-) */
  117645. }
  117646. /* bleaugh, this is more complicated than it needs to be */
  117647. #include<stdio.h>
  117648. static void max_seeds(vorbis_look_psy *p,
  117649. float *seed,
  117650. float *flr){
  117651. long n=p->total_octave_lines;
  117652. int linesper=p->eighth_octave_lines;
  117653. long linpos=0;
  117654. long pos;
  117655. seed_chase(seed,linesper,n); /* for masking */
  117656. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117657. while(linpos+1<p->n){
  117658. float minV=seed[pos];
  117659. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117660. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117661. while(pos+1<=end){
  117662. pos++;
  117663. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117664. minV=seed[pos];
  117665. }
  117666. end=pos+p->firstoc;
  117667. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117668. if(flr[linpos]<minV)flr[linpos]=minV;
  117669. }
  117670. {
  117671. float minV=seed[p->total_octave_lines-1];
  117672. for(;linpos<p->n;linpos++)
  117673. if(flr[linpos]<minV)flr[linpos]=minV;
  117674. }
  117675. }
  117676. static void bark_noise_hybridmp(int n,const long *b,
  117677. const float *f,
  117678. float *noise,
  117679. const float offset,
  117680. const int fixed){
  117681. float *N=(float*) alloca(n*sizeof(*N));
  117682. float *X=(float*) alloca(n*sizeof(*N));
  117683. float *XX=(float*) alloca(n*sizeof(*N));
  117684. float *Y=(float*) alloca(n*sizeof(*N));
  117685. float *XY=(float*) alloca(n*sizeof(*N));
  117686. float tN, tX, tXX, tY, tXY;
  117687. int i;
  117688. int lo, hi;
  117689. float R, A, B, D;
  117690. float w, x, y;
  117691. tN = tX = tXX = tY = tXY = 0.f;
  117692. y = f[0] + offset;
  117693. if (y < 1.f) y = 1.f;
  117694. w = y * y * .5;
  117695. tN += w;
  117696. tX += w;
  117697. tY += w * y;
  117698. N[0] = tN;
  117699. X[0] = tX;
  117700. XX[0] = tXX;
  117701. Y[0] = tY;
  117702. XY[0] = tXY;
  117703. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117704. y = f[i] + offset;
  117705. if (y < 1.f) y = 1.f;
  117706. w = y * y;
  117707. tN += w;
  117708. tX += w * x;
  117709. tXX += w * x * x;
  117710. tY += w * y;
  117711. tXY += w * x * y;
  117712. N[i] = tN;
  117713. X[i] = tX;
  117714. XX[i] = tXX;
  117715. Y[i] = tY;
  117716. XY[i] = tXY;
  117717. }
  117718. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117719. lo = b[i] >> 16;
  117720. if( lo>=0 ) break;
  117721. hi = b[i] & 0xffff;
  117722. tN = N[hi] + N[-lo];
  117723. tX = X[hi] - X[-lo];
  117724. tXX = XX[hi] + XX[-lo];
  117725. tY = Y[hi] + Y[-lo];
  117726. tXY = XY[hi] - XY[-lo];
  117727. A = tY * tXX - tX * tXY;
  117728. B = tN * tXY - tX * tY;
  117729. D = tN * tXX - tX * tX;
  117730. R = (A + x * B) / D;
  117731. if (R < 0.f)
  117732. R = 0.f;
  117733. noise[i] = R - offset;
  117734. }
  117735. for ( ;; i++, x += 1.f) {
  117736. lo = b[i] >> 16;
  117737. hi = b[i] & 0xffff;
  117738. if(hi>=n)break;
  117739. tN = N[hi] - N[lo];
  117740. tX = X[hi] - X[lo];
  117741. tXX = XX[hi] - XX[lo];
  117742. tY = Y[hi] - Y[lo];
  117743. tXY = XY[hi] - XY[lo];
  117744. A = tY * tXX - tX * tXY;
  117745. B = tN * tXY - tX * tY;
  117746. D = tN * tXX - tX * tX;
  117747. R = (A + x * B) / D;
  117748. if (R < 0.f) R = 0.f;
  117749. noise[i] = R - offset;
  117750. }
  117751. for ( ; i < n; i++, x += 1.f) {
  117752. R = (A + x * B) / D;
  117753. if (R < 0.f) R = 0.f;
  117754. noise[i] = R - offset;
  117755. }
  117756. if (fixed <= 0) return;
  117757. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117758. hi = i + fixed / 2;
  117759. lo = hi - fixed;
  117760. if(lo>=0)break;
  117761. tN = N[hi] + N[-lo];
  117762. tX = X[hi] - X[-lo];
  117763. tXX = XX[hi] + XX[-lo];
  117764. tY = Y[hi] + Y[-lo];
  117765. tXY = XY[hi] - XY[-lo];
  117766. A = tY * tXX - tX * tXY;
  117767. B = tN * tXY - tX * tY;
  117768. D = tN * tXX - tX * tX;
  117769. R = (A + x * B) / D;
  117770. if (R - offset < noise[i]) noise[i] = R - offset;
  117771. }
  117772. for ( ;; i++, x += 1.f) {
  117773. hi = i + fixed / 2;
  117774. lo = hi - fixed;
  117775. if(hi>=n)break;
  117776. tN = N[hi] - N[lo];
  117777. tX = X[hi] - X[lo];
  117778. tXX = XX[hi] - XX[lo];
  117779. tY = Y[hi] - Y[lo];
  117780. tXY = XY[hi] - XY[lo];
  117781. A = tY * tXX - tX * tXY;
  117782. B = tN * tXY - tX * tY;
  117783. D = tN * tXX - tX * tX;
  117784. R = (A + x * B) / D;
  117785. if (R - offset < noise[i]) noise[i] = R - offset;
  117786. }
  117787. for ( ; i < n; i++, x += 1.f) {
  117788. R = (A + x * B) / D;
  117789. if (R - offset < noise[i]) noise[i] = R - offset;
  117790. }
  117791. }
  117792. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117793. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117794. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117795. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117796. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117797. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117798. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117799. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117800. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117801. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117802. 973377.F, 913981.F, 858210.F, 805842.F,
  117803. 756669.F, 710497.F, 667142.F, 626433.F,
  117804. 588208.F, 552316.F, 518613.F, 486967.F,
  117805. 457252.F, 429351.F, 403152.F, 378551.F,
  117806. 355452.F, 333762.F, 313396.F, 294273.F,
  117807. 276316.F, 259455.F, 243623.F, 228757.F,
  117808. 214798.F, 201691.F, 189384.F, 177828.F,
  117809. 166977.F, 156788.F, 147221.F, 138237.F,
  117810. 129802.F, 121881.F, 114444.F, 107461.F,
  117811. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117812. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117813. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117814. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117815. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117816. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117817. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117818. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117819. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117820. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117821. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117822. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117823. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117824. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117825. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117826. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117827. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117828. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117829. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117830. 842.910F, 791.475F, 743.179F, 697.830F,
  117831. 655.249F, 615.265F, 577.722F, 542.469F,
  117832. 509.367F, 478.286F, 449.101F, 421.696F,
  117833. 395.964F, 371.803F, 349.115F, 327.812F,
  117834. 307.809F, 289.026F, 271.390F, 254.830F,
  117835. 239.280F, 224.679F, 210.969F, 198.096F,
  117836. 186.008F, 174.658F, 164.000F, 153.993F,
  117837. 144.596F, 135.773F, 127.488F, 119.708F,
  117838. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117839. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117840. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117841. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117842. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117843. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117844. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117845. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117846. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117847. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117848. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117849. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117850. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117851. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117852. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117853. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117854. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117855. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117856. 1.20790F, 1.13419F, 1.06499F, 1.F
  117857. };
  117858. void _vp_remove_floor(vorbis_look_psy *p,
  117859. float *mdct,
  117860. int *codedflr,
  117861. float *residue,
  117862. int sliding_lowpass){
  117863. int i,n=p->n;
  117864. if(sliding_lowpass>n)sliding_lowpass=n;
  117865. for(i=0;i<sliding_lowpass;i++){
  117866. residue[i]=
  117867. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117868. }
  117869. for(;i<n;i++)
  117870. residue[i]=0.;
  117871. }
  117872. void _vp_noisemask(vorbis_look_psy *p,
  117873. float *logmdct,
  117874. float *logmask){
  117875. int i,n=p->n;
  117876. float *work=(float*) alloca(n*sizeof(*work));
  117877. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117878. 140.,-1);
  117879. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117880. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117881. p->vi->noisewindowfixed);
  117882. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117883. #if 0
  117884. {
  117885. static int seq=0;
  117886. float work2[n];
  117887. for(i=0;i<n;i++){
  117888. work2[i]=logmask[i]+work[i];
  117889. }
  117890. if(seq&1)
  117891. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117892. else
  117893. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117894. if(seq&1)
  117895. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117896. else
  117897. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117898. seq++;
  117899. }
  117900. #endif
  117901. for(i=0;i<n;i++){
  117902. int dB=logmask[i]+.5;
  117903. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117904. if(dB<0)dB=0;
  117905. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117906. }
  117907. }
  117908. void _vp_tonemask(vorbis_look_psy *p,
  117909. float *logfft,
  117910. float *logmask,
  117911. float global_specmax,
  117912. float local_specmax){
  117913. int i,n=p->n;
  117914. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117915. float att=local_specmax+p->vi->ath_adjatt;
  117916. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117917. /* set the ATH (floating below localmax, not global max by a
  117918. specified att) */
  117919. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117920. for(i=0;i<n;i++)
  117921. logmask[i]=p->ath[i]+att;
  117922. /* tone masking */
  117923. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117924. max_seeds(p,seed,logmask);
  117925. }
  117926. void _vp_offset_and_mix(vorbis_look_psy *p,
  117927. float *noise,
  117928. float *tone,
  117929. int offset_select,
  117930. float *logmask,
  117931. float *mdct,
  117932. float *logmdct){
  117933. int i,n=p->n;
  117934. float de, coeffi, cx;/* AoTuV */
  117935. float toneatt=p->vi->tone_masteratt[offset_select];
  117936. cx = p->m_val;
  117937. for(i=0;i<n;i++){
  117938. float val= noise[i]+p->noiseoffset[offset_select][i];
  117939. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117940. logmask[i]=max(val,tone[i]+toneatt);
  117941. /* AoTuV */
  117942. /** @ M1 **
  117943. The following codes improve a noise problem.
  117944. A fundamental idea uses the value of masking and carries out
  117945. the relative compensation of the MDCT.
  117946. However, this code is not perfect and all noise problems cannot be solved.
  117947. by Aoyumi @ 2004/04/18
  117948. */
  117949. if(offset_select == 1) {
  117950. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117951. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117952. if(val > coeffi){
  117953. /* mdct value is > -17.2 dB below floor */
  117954. de = 1.0-((val-coeffi)*0.005*cx);
  117955. /* pro-rated attenuation:
  117956. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117957. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117958. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117959. etc... */
  117960. if(de < 0) de = 0.0001;
  117961. }else
  117962. /* mdct value is <= -17.2 dB below floor */
  117963. de = 1.0-((val-coeffi)*0.0003*cx);
  117964. /* pro-rated attenuation:
  117965. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117966. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117967. etc... */
  117968. mdct[i] *= de;
  117969. }
  117970. }
  117971. }
  117972. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117973. vorbis_info *vi=vd->vi;
  117974. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117975. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117976. int n=ci->blocksizes[vd->W]/2;
  117977. float secs=(float)n/vi->rate;
  117978. amp+=secs*gi->ampmax_att_per_sec;
  117979. if(amp<-9999)amp=-9999;
  117980. return(amp);
  117981. }
  117982. static void couple_lossless(float A, float B,
  117983. float *qA, float *qB){
  117984. int test1=fabs(*qA)>fabs(*qB);
  117985. test1-= fabs(*qA)<fabs(*qB);
  117986. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117987. if(test1==1){
  117988. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117989. }else{
  117990. float temp=*qB;
  117991. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117992. *qA=temp;
  117993. }
  117994. if(*qB>fabs(*qA)*1.9999f){
  117995. *qB= -fabs(*qA)*2.f;
  117996. *qA= -*qA;
  117997. }
  117998. }
  117999. static float hypot_lookup[32]={
  118000. -0.009935, -0.011245, -0.012726, -0.014397,
  118001. -0.016282, -0.018407, -0.020800, -0.023494,
  118002. -0.026522, -0.029923, -0.033737, -0.038010,
  118003. -0.042787, -0.048121, -0.054064, -0.060671,
  118004. -0.068000, -0.076109, -0.085054, -0.094892,
  118005. -0.105675, -0.117451, -0.130260, -0.144134,
  118006. -0.159093, -0.175146, -0.192286, -0.210490,
  118007. -0.229718, -0.249913, -0.271001, -0.292893};
  118008. static void precomputed_couple_point(float premag,
  118009. int floorA,int floorB,
  118010. float *mag, float *ang){
  118011. int test=(floorA>floorB)-1;
  118012. int offset=31-abs(floorA-floorB);
  118013. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  118014. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  118015. *mag=premag*floormag;
  118016. *ang=0.f;
  118017. }
  118018. /* just like below, this is currently set up to only do
  118019. single-step-depth coupling. Otherwise, we'd have to do more
  118020. copying (which will be inevitable later) */
  118021. /* doing the real circular magnitude calculation is audibly superior
  118022. to (A+B)/sqrt(2) */
  118023. static float dipole_hypot(float a, float b){
  118024. if(a>0.){
  118025. if(b>0.)return sqrt(a*a+b*b);
  118026. if(a>-b)return sqrt(a*a-b*b);
  118027. return -sqrt(b*b-a*a);
  118028. }
  118029. if(b<0.)return -sqrt(a*a+b*b);
  118030. if(-a>b)return -sqrt(a*a-b*b);
  118031. return sqrt(b*b-a*a);
  118032. }
  118033. static float round_hypot(float a, float b){
  118034. if(a>0.){
  118035. if(b>0.)return sqrt(a*a+b*b);
  118036. if(a>-b)return sqrt(a*a+b*b);
  118037. return -sqrt(b*b+a*a);
  118038. }
  118039. if(b<0.)return -sqrt(a*a+b*b);
  118040. if(-a>b)return -sqrt(a*a+b*b);
  118041. return sqrt(b*b+a*a);
  118042. }
  118043. /* revert to round hypot for now */
  118044. float **_vp_quantize_couple_memo(vorbis_block *vb,
  118045. vorbis_info_psy_global *g,
  118046. vorbis_look_psy *p,
  118047. vorbis_info_mapping0 *vi,
  118048. float **mdct){
  118049. int i,j,n=p->n;
  118050. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118051. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118052. for(i=0;i<vi->coupling_steps;i++){
  118053. float *mdctM=mdct[vi->coupling_mag[i]];
  118054. float *mdctA=mdct[vi->coupling_ang[i]];
  118055. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118056. for(j=0;j<limit;j++)
  118057. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  118058. for(;j<n;j++)
  118059. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  118060. }
  118061. return(ret);
  118062. }
  118063. /* this is for per-channel noise normalization */
  118064. static int apsort(const void *a, const void *b){
  118065. float f1=fabs(**(float**)a);
  118066. float f2=fabs(**(float**)b);
  118067. return (f1<f2)-(f1>f2);
  118068. }
  118069. int **_vp_quantize_couple_sort(vorbis_block *vb,
  118070. vorbis_look_psy *p,
  118071. vorbis_info_mapping0 *vi,
  118072. float **mags){
  118073. if(p->vi->normal_point_p){
  118074. int i,j,k,n=p->n;
  118075. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118076. int partition=p->vi->normal_partition;
  118077. float **work=(float**) alloca(sizeof(*work)*partition);
  118078. for(i=0;i<vi->coupling_steps;i++){
  118079. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118080. for(j=0;j<n;j+=partition){
  118081. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  118082. qsort(work,partition,sizeof(*work),apsort);
  118083. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  118084. }
  118085. }
  118086. return(ret);
  118087. }
  118088. return(NULL);
  118089. }
  118090. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  118091. float *magnitudes,int *sortedindex){
  118092. int i,j,n=p->n;
  118093. vorbis_info_psy *vi=p->vi;
  118094. int partition=vi->normal_partition;
  118095. float **work=(float**) alloca(sizeof(*work)*partition);
  118096. int start=vi->normal_start;
  118097. for(j=start;j<n;j+=partition){
  118098. if(j+partition>n)partition=n-j;
  118099. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  118100. qsort(work,partition,sizeof(*work),apsort);
  118101. for(i=0;i<partition;i++){
  118102. sortedindex[i+j-start]=work[i]-magnitudes;
  118103. }
  118104. }
  118105. }
  118106. void _vp_noise_normalize(vorbis_look_psy *p,
  118107. float *in,float *out,int *sortedindex){
  118108. int flag=0,i,j=0,n=p->n;
  118109. vorbis_info_psy *vi=p->vi;
  118110. int partition=vi->normal_partition;
  118111. int start=vi->normal_start;
  118112. if(start>n)start=n;
  118113. if(vi->normal_channel_p){
  118114. for(;j<start;j++)
  118115. out[j]=rint(in[j]);
  118116. for(;j+partition<=n;j+=partition){
  118117. float acc=0.;
  118118. int k;
  118119. for(i=j;i<j+partition;i++)
  118120. acc+=in[i]*in[i];
  118121. for(i=0;i<partition;i++){
  118122. k=sortedindex[i+j-start];
  118123. if(in[k]*in[k]>=.25f){
  118124. out[k]=rint(in[k]);
  118125. acc-=in[k]*in[k];
  118126. flag=1;
  118127. }else{
  118128. if(acc<vi->normal_thresh)break;
  118129. out[k]=unitnorm(in[k]);
  118130. acc-=1.;
  118131. }
  118132. }
  118133. for(;i<partition;i++){
  118134. k=sortedindex[i+j-start];
  118135. out[k]=0.;
  118136. }
  118137. }
  118138. }
  118139. for(;j<n;j++)
  118140. out[j]=rint(in[j]);
  118141. }
  118142. void _vp_couple(int blobno,
  118143. vorbis_info_psy_global *g,
  118144. vorbis_look_psy *p,
  118145. vorbis_info_mapping0 *vi,
  118146. float **res,
  118147. float **mag_memo,
  118148. int **mag_sort,
  118149. int **ifloor,
  118150. int *nonzero,
  118151. int sliding_lowpass){
  118152. int i,j,k,n=p->n;
  118153. /* perform any requested channel coupling */
  118154. /* point stereo can only be used in a first stage (in this encoder)
  118155. because of the dependency on floor lookups */
  118156. for(i=0;i<vi->coupling_steps;i++){
  118157. /* once we're doing multistage coupling in which a channel goes
  118158. through more than one coupling step, the floor vector
  118159. magnitudes will also have to be recalculated an propogated
  118160. along with PCM. Right now, we're not (that will wait until 5.1
  118161. most likely), so the code isn't here yet. The memory management
  118162. here is all assuming single depth couplings anyway. */
  118163. /* make sure coupling a zero and a nonzero channel results in two
  118164. nonzero channels. */
  118165. if(nonzero[vi->coupling_mag[i]] ||
  118166. nonzero[vi->coupling_ang[i]]){
  118167. float *rM=res[vi->coupling_mag[i]];
  118168. float *rA=res[vi->coupling_ang[i]];
  118169. float *qM=rM+n;
  118170. float *qA=rA+n;
  118171. int *floorM=ifloor[vi->coupling_mag[i]];
  118172. int *floorA=ifloor[vi->coupling_ang[i]];
  118173. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118174. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118175. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118176. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118177. int pointlimit=limit;
  118178. nonzero[vi->coupling_mag[i]]=1;
  118179. nonzero[vi->coupling_ang[i]]=1;
  118180. /* The threshold of a stereo is changed with the size of n */
  118181. if(n > 1000)
  118182. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118183. for(j=0;j<p->n;j+=partition){
  118184. float acc=0.f;
  118185. for(k=0;k<partition;k++){
  118186. int l=k+j;
  118187. if(l<sliding_lowpass){
  118188. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118189. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118190. precomputed_couple_point(mag_memo[i][l],
  118191. floorM[l],floorA[l],
  118192. qM+l,qA+l);
  118193. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118194. }else{
  118195. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118196. }
  118197. }else{
  118198. qM[l]=0.;
  118199. qA[l]=0.;
  118200. }
  118201. }
  118202. if(p->vi->normal_point_p){
  118203. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118204. int l=mag_sort[i][j+k];
  118205. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118206. qM[l]=unitnorm(qM[l]);
  118207. acc-=1.f;
  118208. }
  118209. }
  118210. }
  118211. }
  118212. }
  118213. }
  118214. }
  118215. /* AoTuV */
  118216. /** @ M2 **
  118217. The boost problem by the combination of noise normalization and point stereo is eased.
  118218. However, this is a temporary patch.
  118219. by Aoyumi @ 2004/04/18
  118220. */
  118221. void hf_reduction(vorbis_info_psy_global *g,
  118222. vorbis_look_psy *p,
  118223. vorbis_info_mapping0 *vi,
  118224. float **mdct){
  118225. int i,j,n=p->n, de=0.3*p->m_val;
  118226. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118227. for(i=0; i<vi->coupling_steps; i++){
  118228. /* for(j=start; j<limit; j++){} // ???*/
  118229. for(j=limit; j<n; j++)
  118230. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118231. }
  118232. }
  118233. #endif
  118234. /*** End of inlined file: psy.c ***/
  118235. /*** Start of inlined file: registry.c ***/
  118236. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118237. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118238. // tasks..
  118239. #if JUCE_MSVC
  118240. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118241. #endif
  118242. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118243. #if JUCE_USE_OGGVORBIS
  118244. /* seems like major overkill now; the backend numbers will grow into
  118245. the infrastructure soon enough */
  118246. extern vorbis_func_floor floor0_exportbundle;
  118247. extern vorbis_func_floor floor1_exportbundle;
  118248. extern vorbis_func_residue residue0_exportbundle;
  118249. extern vorbis_func_residue residue1_exportbundle;
  118250. extern vorbis_func_residue residue2_exportbundle;
  118251. extern vorbis_func_mapping mapping0_exportbundle;
  118252. vorbis_func_floor *_floor_P[]={
  118253. &floor0_exportbundle,
  118254. &floor1_exportbundle,
  118255. };
  118256. vorbis_func_residue *_residue_P[]={
  118257. &residue0_exportbundle,
  118258. &residue1_exportbundle,
  118259. &residue2_exportbundle,
  118260. };
  118261. vorbis_func_mapping *_mapping_P[]={
  118262. &mapping0_exportbundle,
  118263. };
  118264. #endif
  118265. /*** End of inlined file: registry.c ***/
  118266. /*** Start of inlined file: res0.c ***/
  118267. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118268. encode/decode loops are coded for clarity and performance is not
  118269. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118270. it's slow. */
  118271. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118272. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118273. // tasks..
  118274. #if JUCE_MSVC
  118275. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118276. #endif
  118277. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118278. #if JUCE_USE_OGGVORBIS
  118279. #include <stdlib.h>
  118280. #include <string.h>
  118281. #include <math.h>
  118282. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118283. #include <stdio.h>
  118284. #endif
  118285. typedef struct {
  118286. vorbis_info_residue0 *info;
  118287. int parts;
  118288. int stages;
  118289. codebook *fullbooks;
  118290. codebook *phrasebook;
  118291. codebook ***partbooks;
  118292. int partvals;
  118293. int **decodemap;
  118294. long postbits;
  118295. long phrasebits;
  118296. long frames;
  118297. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118298. int train_seq;
  118299. long *training_data[8][64];
  118300. float training_max[8][64];
  118301. float training_min[8][64];
  118302. float tmin;
  118303. float tmax;
  118304. #endif
  118305. } vorbis_look_residue0;
  118306. void res0_free_info(vorbis_info_residue *i){
  118307. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118308. if(info){
  118309. memset(info,0,sizeof(*info));
  118310. _ogg_free(info);
  118311. }
  118312. }
  118313. void res0_free_look(vorbis_look_residue *i){
  118314. int j;
  118315. if(i){
  118316. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118317. #ifdef TRAIN_RES
  118318. {
  118319. int j,k,l;
  118320. for(j=0;j<look->parts;j++){
  118321. /*fprintf(stderr,"partition %d: ",j);*/
  118322. for(k=0;k<8;k++)
  118323. if(look->training_data[k][j]){
  118324. char buffer[80];
  118325. FILE *of;
  118326. codebook *statebook=look->partbooks[j][k];
  118327. /* long and short into the same bucket by current convention */
  118328. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118329. of=fopen(buffer,"a");
  118330. for(l=0;l<statebook->entries;l++)
  118331. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118332. fclose(of);
  118333. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118334. look->training_min[k][j],look->training_max[k][j]);*/
  118335. _ogg_free(look->training_data[k][j]);
  118336. look->training_data[k][j]=NULL;
  118337. }
  118338. /*fprintf(stderr,"\n");*/
  118339. }
  118340. }
  118341. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118342. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118343. (float)look->phrasebits/look->frames,
  118344. (float)look->postbits/look->frames,
  118345. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118346. #endif
  118347. /*vorbis_info_residue0 *info=look->info;
  118348. fprintf(stderr,
  118349. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118350. "(%g/frame) \n",look->frames,look->phrasebits,
  118351. look->resbitsflat,
  118352. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118353. for(j=0;j<look->parts;j++){
  118354. long acc=0;
  118355. fprintf(stderr,"\t[%d] == ",j);
  118356. for(k=0;k<look->stages;k++)
  118357. if((info->secondstages[j]>>k)&1){
  118358. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118359. acc+=look->resbits[j][k];
  118360. }
  118361. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118362. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118363. }
  118364. fprintf(stderr,"\n");*/
  118365. for(j=0;j<look->parts;j++)
  118366. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118367. _ogg_free(look->partbooks);
  118368. for(j=0;j<look->partvals;j++)
  118369. _ogg_free(look->decodemap[j]);
  118370. _ogg_free(look->decodemap);
  118371. memset(look,0,sizeof(*look));
  118372. _ogg_free(look);
  118373. }
  118374. }
  118375. static int icount(unsigned int v){
  118376. int ret=0;
  118377. while(v){
  118378. ret+=v&1;
  118379. v>>=1;
  118380. }
  118381. return(ret);
  118382. }
  118383. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118384. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118385. int j,acc=0;
  118386. oggpack_write(opb,info->begin,24);
  118387. oggpack_write(opb,info->end,24);
  118388. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118389. code with a partitioned book */
  118390. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118391. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118392. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118393. bitmask of one indicates this partition class has bits to write
  118394. this pass */
  118395. for(j=0;j<info->partitions;j++){
  118396. if(ilog(info->secondstages[j])>3){
  118397. /* yes, this is a minor hack due to not thinking ahead */
  118398. oggpack_write(opb,info->secondstages[j],3);
  118399. oggpack_write(opb,1,1);
  118400. oggpack_write(opb,info->secondstages[j]>>3,5);
  118401. }else
  118402. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118403. acc+=icount(info->secondstages[j]);
  118404. }
  118405. for(j=0;j<acc;j++)
  118406. oggpack_write(opb,info->booklist[j],8);
  118407. }
  118408. /* vorbis_info is for range checking */
  118409. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118410. int j,acc=0;
  118411. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118412. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118413. info->begin=oggpack_read(opb,24);
  118414. info->end=oggpack_read(opb,24);
  118415. info->grouping=oggpack_read(opb,24)+1;
  118416. info->partitions=oggpack_read(opb,6)+1;
  118417. info->groupbook=oggpack_read(opb,8);
  118418. for(j=0;j<info->partitions;j++){
  118419. int cascade=oggpack_read(opb,3);
  118420. if(oggpack_read(opb,1))
  118421. cascade|=(oggpack_read(opb,5)<<3);
  118422. info->secondstages[j]=cascade;
  118423. acc+=icount(cascade);
  118424. }
  118425. for(j=0;j<acc;j++)
  118426. info->booklist[j]=oggpack_read(opb,8);
  118427. if(info->groupbook>=ci->books)goto errout;
  118428. for(j=0;j<acc;j++)
  118429. if(info->booklist[j]>=ci->books)goto errout;
  118430. return(info);
  118431. errout:
  118432. res0_free_info(info);
  118433. return(NULL);
  118434. }
  118435. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118436. vorbis_info_residue *vr){
  118437. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118438. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118439. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118440. int j,k,acc=0;
  118441. int dim;
  118442. int maxstage=0;
  118443. look->info=info;
  118444. look->parts=info->partitions;
  118445. look->fullbooks=ci->fullbooks;
  118446. look->phrasebook=ci->fullbooks+info->groupbook;
  118447. dim=look->phrasebook->dim;
  118448. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118449. for(j=0;j<look->parts;j++){
  118450. int stages=ilog(info->secondstages[j]);
  118451. if(stages){
  118452. if(stages>maxstage)maxstage=stages;
  118453. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118454. for(k=0;k<stages;k++)
  118455. if(info->secondstages[j]&(1<<k)){
  118456. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118457. #ifdef TRAIN_RES
  118458. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118459. sizeof(***look->training_data));
  118460. #endif
  118461. }
  118462. }
  118463. }
  118464. look->partvals=rint(pow((float)look->parts,(float)dim));
  118465. look->stages=maxstage;
  118466. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118467. for(j=0;j<look->partvals;j++){
  118468. long val=j;
  118469. long mult=look->partvals/look->parts;
  118470. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118471. for(k=0;k<dim;k++){
  118472. long deco=val/mult;
  118473. val-=deco*mult;
  118474. mult/=look->parts;
  118475. look->decodemap[j][k]=deco;
  118476. }
  118477. }
  118478. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118479. {
  118480. static int train_seq=0;
  118481. look->train_seq=train_seq++;
  118482. }
  118483. #endif
  118484. return(look);
  118485. }
  118486. /* break an abstraction and copy some code for performance purposes */
  118487. static int local_book_besterror(codebook *book,float *a){
  118488. int dim=book->dim,i,k,o;
  118489. int best=0;
  118490. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118491. /* find the quant val of each scalar */
  118492. for(k=0,o=dim;k<dim;++k){
  118493. float val=a[--o];
  118494. i=tt->threshvals>>1;
  118495. if(val<tt->quantthresh[i]){
  118496. if(val<tt->quantthresh[i-1]){
  118497. for(--i;i>0;--i)
  118498. if(val>=tt->quantthresh[i-1])
  118499. break;
  118500. }
  118501. }else{
  118502. for(++i;i<tt->threshvals-1;++i)
  118503. if(val<tt->quantthresh[i])break;
  118504. }
  118505. best=(best*tt->quantvals)+tt->quantmap[i];
  118506. }
  118507. /* regular lattices are easy :-) */
  118508. if(book->c->lengthlist[best]<=0){
  118509. const static_codebook *c=book->c;
  118510. int i,j;
  118511. float bestf=0.f;
  118512. float *e=book->valuelist;
  118513. best=-1;
  118514. for(i=0;i<book->entries;i++){
  118515. if(c->lengthlist[i]>0){
  118516. float thisx=0.f;
  118517. for(j=0;j<dim;j++){
  118518. float val=(e[j]-a[j]);
  118519. thisx+=val*val;
  118520. }
  118521. if(best==-1 || thisx<bestf){
  118522. bestf=thisx;
  118523. best=i;
  118524. }
  118525. }
  118526. e+=dim;
  118527. }
  118528. }
  118529. {
  118530. float *ptr=book->valuelist+best*dim;
  118531. for(i=0;i<dim;i++)
  118532. *a++ -= *ptr++;
  118533. }
  118534. return(best);
  118535. }
  118536. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118537. codebook *book,long *acc){
  118538. int i,bits=0;
  118539. int dim=book->dim;
  118540. int step=n/dim;
  118541. for(i=0;i<step;i++){
  118542. int entry=local_book_besterror(book,vec+i*dim);
  118543. #ifdef TRAIN_RES
  118544. acc[entry]++;
  118545. #endif
  118546. bits+=vorbis_book_encode(book,entry,opb);
  118547. }
  118548. return(bits);
  118549. }
  118550. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118551. float **in,int ch){
  118552. long i,j,k;
  118553. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118554. vorbis_info_residue0 *info=look->info;
  118555. /* move all this setup out later */
  118556. int samples_per_partition=info->grouping;
  118557. int possible_partitions=info->partitions;
  118558. int n=info->end-info->begin;
  118559. int partvals=n/samples_per_partition;
  118560. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118561. float scale=100./samples_per_partition;
  118562. /* we find the partition type for each partition of each
  118563. channel. We'll go back and do the interleaved encoding in a
  118564. bit. For now, clarity */
  118565. for(i=0;i<ch;i++){
  118566. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118567. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118568. }
  118569. for(i=0;i<partvals;i++){
  118570. int offset=i*samples_per_partition+info->begin;
  118571. for(j=0;j<ch;j++){
  118572. float max=0.;
  118573. float ent=0.;
  118574. for(k=0;k<samples_per_partition;k++){
  118575. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118576. ent+=fabs(rint(in[j][offset+k]));
  118577. }
  118578. ent*=scale;
  118579. for(k=0;k<possible_partitions-1;k++)
  118580. if(max<=info->classmetric1[k] &&
  118581. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118582. break;
  118583. partword[j][i]=k;
  118584. }
  118585. }
  118586. #ifdef TRAIN_RESAUX
  118587. {
  118588. FILE *of;
  118589. char buffer[80];
  118590. for(i=0;i<ch;i++){
  118591. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118592. of=fopen(buffer,"a");
  118593. for(j=0;j<partvals;j++)
  118594. fprintf(of,"%ld, ",partword[i][j]);
  118595. fprintf(of,"\n");
  118596. fclose(of);
  118597. }
  118598. }
  118599. #endif
  118600. look->frames++;
  118601. return(partword);
  118602. }
  118603. /* designed for stereo or other modes where the partition size is an
  118604. integer multiple of the number of channels encoded in the current
  118605. submap */
  118606. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118607. int ch){
  118608. long i,j,k,l;
  118609. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118610. vorbis_info_residue0 *info=look->info;
  118611. /* move all this setup out later */
  118612. int samples_per_partition=info->grouping;
  118613. int possible_partitions=info->partitions;
  118614. int n=info->end-info->begin;
  118615. int partvals=n/samples_per_partition;
  118616. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118617. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118618. FILE *of;
  118619. char buffer[80];
  118620. #endif
  118621. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118622. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118623. for(i=0,l=info->begin/ch;i<partvals;i++){
  118624. float magmax=0.f;
  118625. float angmax=0.f;
  118626. for(j=0;j<samples_per_partition;j+=ch){
  118627. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118628. for(k=1;k<ch;k++)
  118629. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118630. l++;
  118631. }
  118632. for(j=0;j<possible_partitions-1;j++)
  118633. if(magmax<=info->classmetric1[j] &&
  118634. angmax<=info->classmetric2[j])
  118635. break;
  118636. partword[0][i]=j;
  118637. }
  118638. #ifdef TRAIN_RESAUX
  118639. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118640. of=fopen(buffer,"a");
  118641. for(i=0;i<partvals;i++)
  118642. fprintf(of,"%ld, ",partword[0][i]);
  118643. fprintf(of,"\n");
  118644. fclose(of);
  118645. #endif
  118646. look->frames++;
  118647. return(partword);
  118648. }
  118649. static int _01forward(oggpack_buffer *opb,
  118650. vorbis_block *vb,vorbis_look_residue *vl,
  118651. float **in,int ch,
  118652. long **partword,
  118653. int (*encode)(oggpack_buffer *,float *,int,
  118654. codebook *,long *)){
  118655. long i,j,k,s;
  118656. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118657. vorbis_info_residue0 *info=look->info;
  118658. /* move all this setup out later */
  118659. int samples_per_partition=info->grouping;
  118660. int possible_partitions=info->partitions;
  118661. int partitions_per_word=look->phrasebook->dim;
  118662. int n=info->end-info->begin;
  118663. int partvals=n/samples_per_partition;
  118664. long resbits[128];
  118665. long resvals[128];
  118666. #ifdef TRAIN_RES
  118667. for(i=0;i<ch;i++)
  118668. for(j=info->begin;j<info->end;j++){
  118669. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118670. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118671. }
  118672. #endif
  118673. memset(resbits,0,sizeof(resbits));
  118674. memset(resvals,0,sizeof(resvals));
  118675. /* we code the partition words for each channel, then the residual
  118676. words for a partition per channel until we've written all the
  118677. residual words for that partition word. Then write the next
  118678. partition channel words... */
  118679. for(s=0;s<look->stages;s++){
  118680. for(i=0;i<partvals;){
  118681. /* first we encode a partition codeword for each channel */
  118682. if(s==0){
  118683. for(j=0;j<ch;j++){
  118684. long val=partword[j][i];
  118685. for(k=1;k<partitions_per_word;k++){
  118686. val*=possible_partitions;
  118687. if(i+k<partvals)
  118688. val+=partword[j][i+k];
  118689. }
  118690. /* training hack */
  118691. if(val<look->phrasebook->entries)
  118692. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118693. #if 0 /*def TRAIN_RES*/
  118694. else
  118695. fprintf(stderr,"!");
  118696. #endif
  118697. }
  118698. }
  118699. /* now we encode interleaved residual values for the partitions */
  118700. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118701. long offset=i*samples_per_partition+info->begin;
  118702. for(j=0;j<ch;j++){
  118703. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118704. if(info->secondstages[partword[j][i]]&(1<<s)){
  118705. codebook *statebook=look->partbooks[partword[j][i]][s];
  118706. if(statebook){
  118707. int ret;
  118708. long *accumulator=NULL;
  118709. #ifdef TRAIN_RES
  118710. accumulator=look->training_data[s][partword[j][i]];
  118711. {
  118712. int l;
  118713. float *samples=in[j]+offset;
  118714. for(l=0;l<samples_per_partition;l++){
  118715. if(samples[l]<look->training_min[s][partword[j][i]])
  118716. look->training_min[s][partword[j][i]]=samples[l];
  118717. if(samples[l]>look->training_max[s][partword[j][i]])
  118718. look->training_max[s][partword[j][i]]=samples[l];
  118719. }
  118720. }
  118721. #endif
  118722. ret=encode(opb,in[j]+offset,samples_per_partition,
  118723. statebook,accumulator);
  118724. look->postbits+=ret;
  118725. resbits[partword[j][i]]+=ret;
  118726. }
  118727. }
  118728. }
  118729. }
  118730. }
  118731. }
  118732. /*{
  118733. long total=0;
  118734. long totalbits=0;
  118735. fprintf(stderr,"%d :: ",vb->mode);
  118736. for(k=0;k<possible_partitions;k++){
  118737. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118738. total+=resvals[k];
  118739. totalbits+=resbits[k];
  118740. }
  118741. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118742. }*/
  118743. return(0);
  118744. }
  118745. /* a truncated packet here just means 'stop working'; it's not an error */
  118746. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118747. float **in,int ch,
  118748. long (*decodepart)(codebook *, float *,
  118749. oggpack_buffer *,int)){
  118750. long i,j,k,l,s;
  118751. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118752. vorbis_info_residue0 *info=look->info;
  118753. /* move all this setup out later */
  118754. int samples_per_partition=info->grouping;
  118755. int partitions_per_word=look->phrasebook->dim;
  118756. int n=info->end-info->begin;
  118757. int partvals=n/samples_per_partition;
  118758. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118759. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118760. for(j=0;j<ch;j++)
  118761. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118762. for(s=0;s<look->stages;s++){
  118763. /* each loop decodes on partition codeword containing
  118764. partitions_pre_word partitions */
  118765. for(i=0,l=0;i<partvals;l++){
  118766. if(s==0){
  118767. /* fetch the partition word for each channel */
  118768. for(j=0;j<ch;j++){
  118769. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118770. if(temp==-1)goto eopbreak;
  118771. partword[j][l]=look->decodemap[temp];
  118772. if(partword[j][l]==NULL)goto errout;
  118773. }
  118774. }
  118775. /* now we decode residual values for the partitions */
  118776. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118777. for(j=0;j<ch;j++){
  118778. long offset=info->begin+i*samples_per_partition;
  118779. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118780. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118781. if(stagebook){
  118782. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118783. samples_per_partition)==-1)goto eopbreak;
  118784. }
  118785. }
  118786. }
  118787. }
  118788. }
  118789. errout:
  118790. eopbreak:
  118791. return(0);
  118792. }
  118793. #if 0
  118794. /* residue 0 and 1 are just slight variants of one another. 0 is
  118795. interleaved, 1 is not */
  118796. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118797. float **in,int *nonzero,int ch){
  118798. /* we encode only the nonzero parts of a bundle */
  118799. int i,used=0;
  118800. for(i=0;i<ch;i++)
  118801. if(nonzero[i])
  118802. in[used++]=in[i];
  118803. if(used)
  118804. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118805. return(_01class(vb,vl,in,used));
  118806. else
  118807. return(0);
  118808. }
  118809. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118810. float **in,float **out,int *nonzero,int ch,
  118811. long **partword){
  118812. /* we encode only the nonzero parts of a bundle */
  118813. int i,j,used=0,n=vb->pcmend/2;
  118814. for(i=0;i<ch;i++)
  118815. if(nonzero[i]){
  118816. if(out)
  118817. for(j=0;j<n;j++)
  118818. out[i][j]+=in[i][j];
  118819. in[used++]=in[i];
  118820. }
  118821. if(used){
  118822. int ret=_01forward(vb,vl,in,used,partword,
  118823. _interleaved_encodepart);
  118824. if(out){
  118825. used=0;
  118826. for(i=0;i<ch;i++)
  118827. if(nonzero[i]){
  118828. for(j=0;j<n;j++)
  118829. out[i][j]-=in[used][j];
  118830. used++;
  118831. }
  118832. }
  118833. return(ret);
  118834. }else{
  118835. return(0);
  118836. }
  118837. }
  118838. #endif
  118839. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118840. float **in,int *nonzero,int ch){
  118841. int i,used=0;
  118842. for(i=0;i<ch;i++)
  118843. if(nonzero[i])
  118844. in[used++]=in[i];
  118845. if(used)
  118846. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118847. else
  118848. return(0);
  118849. }
  118850. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118851. float **in,float **out,int *nonzero,int ch,
  118852. long **partword){
  118853. int i,j,used=0,n=vb->pcmend/2;
  118854. for(i=0;i<ch;i++)
  118855. if(nonzero[i]){
  118856. if(out)
  118857. for(j=0;j<n;j++)
  118858. out[i][j]+=in[i][j];
  118859. in[used++]=in[i];
  118860. }
  118861. if(used){
  118862. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118863. if(out){
  118864. used=0;
  118865. for(i=0;i<ch;i++)
  118866. if(nonzero[i]){
  118867. for(j=0;j<n;j++)
  118868. out[i][j]-=in[used][j];
  118869. used++;
  118870. }
  118871. }
  118872. return(ret);
  118873. }else{
  118874. return(0);
  118875. }
  118876. }
  118877. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118878. float **in,int *nonzero,int ch){
  118879. int i,used=0;
  118880. for(i=0;i<ch;i++)
  118881. if(nonzero[i])
  118882. in[used++]=in[i];
  118883. if(used)
  118884. return(_01class(vb,vl,in,used));
  118885. else
  118886. return(0);
  118887. }
  118888. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118889. float **in,int *nonzero,int ch){
  118890. int i,used=0;
  118891. for(i=0;i<ch;i++)
  118892. if(nonzero[i])
  118893. in[used++]=in[i];
  118894. if(used)
  118895. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118896. else
  118897. return(0);
  118898. }
  118899. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118900. float **in,int *nonzero,int ch){
  118901. int i,used=0;
  118902. for(i=0;i<ch;i++)
  118903. if(nonzero[i])used++;
  118904. if(used)
  118905. return(_2class(vb,vl,in,ch));
  118906. else
  118907. return(0);
  118908. }
  118909. /* res2 is slightly more different; all the channels are interleaved
  118910. into a single vector and encoded. */
  118911. int res2_forward(oggpack_buffer *opb,
  118912. vorbis_block *vb,vorbis_look_residue *vl,
  118913. float **in,float **out,int *nonzero,int ch,
  118914. long **partword){
  118915. long i,j,k,n=vb->pcmend/2,used=0;
  118916. /* don't duplicate the code; use a working vector hack for now and
  118917. reshape ourselves into a single channel res1 */
  118918. /* ugly; reallocs for each coupling pass :-( */
  118919. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118920. for(i=0;i<ch;i++){
  118921. float *pcm=in[i];
  118922. if(nonzero[i])used++;
  118923. for(j=0,k=i;j<n;j++,k+=ch)
  118924. work[k]=pcm[j];
  118925. }
  118926. if(used){
  118927. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118928. /* update the sofar vector */
  118929. if(out){
  118930. for(i=0;i<ch;i++){
  118931. float *pcm=in[i];
  118932. float *sofar=out[i];
  118933. for(j=0,k=i;j<n;j++,k+=ch)
  118934. sofar[j]+=pcm[j]-work[k];
  118935. }
  118936. }
  118937. return(ret);
  118938. }else{
  118939. return(0);
  118940. }
  118941. }
  118942. /* duplicate code here as speed is somewhat more important */
  118943. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118944. float **in,int *nonzero,int ch){
  118945. long i,k,l,s;
  118946. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118947. vorbis_info_residue0 *info=look->info;
  118948. /* move all this setup out later */
  118949. int samples_per_partition=info->grouping;
  118950. int partitions_per_word=look->phrasebook->dim;
  118951. int n=info->end-info->begin;
  118952. int partvals=n/samples_per_partition;
  118953. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118954. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118955. for(i=0;i<ch;i++)if(nonzero[i])break;
  118956. if(i==ch)return(0); /* no nonzero vectors */
  118957. for(s=0;s<look->stages;s++){
  118958. for(i=0,l=0;i<partvals;l++){
  118959. if(s==0){
  118960. /* fetch the partition word */
  118961. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118962. if(temp==-1)goto eopbreak;
  118963. partword[l]=look->decodemap[temp];
  118964. if(partword[l]==NULL)goto errout;
  118965. }
  118966. /* now we decode residual values for the partitions */
  118967. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118968. if(info->secondstages[partword[l][k]]&(1<<s)){
  118969. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118970. if(stagebook){
  118971. if(vorbis_book_decodevv_add(stagebook,in,
  118972. i*samples_per_partition+info->begin,ch,
  118973. &vb->opb,samples_per_partition)==-1)
  118974. goto eopbreak;
  118975. }
  118976. }
  118977. }
  118978. }
  118979. errout:
  118980. eopbreak:
  118981. return(0);
  118982. }
  118983. vorbis_func_residue residue0_exportbundle={
  118984. NULL,
  118985. &res0_unpack,
  118986. &res0_look,
  118987. &res0_free_info,
  118988. &res0_free_look,
  118989. NULL,
  118990. NULL,
  118991. &res0_inverse
  118992. };
  118993. vorbis_func_residue residue1_exportbundle={
  118994. &res0_pack,
  118995. &res0_unpack,
  118996. &res0_look,
  118997. &res0_free_info,
  118998. &res0_free_look,
  118999. &res1_class,
  119000. &res1_forward,
  119001. &res1_inverse
  119002. };
  119003. vorbis_func_residue residue2_exportbundle={
  119004. &res0_pack,
  119005. &res0_unpack,
  119006. &res0_look,
  119007. &res0_free_info,
  119008. &res0_free_look,
  119009. &res2_class,
  119010. &res2_forward,
  119011. &res2_inverse
  119012. };
  119013. #endif
  119014. /*** End of inlined file: res0.c ***/
  119015. /*** Start of inlined file: sharedbook.c ***/
  119016. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119017. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119018. // tasks..
  119019. #if JUCE_MSVC
  119020. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119021. #endif
  119022. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119023. #if JUCE_USE_OGGVORBIS
  119024. #include <stdlib.h>
  119025. #include <math.h>
  119026. #include <string.h>
  119027. /**** pack/unpack helpers ******************************************/
  119028. int _ilog(unsigned int v){
  119029. int ret=0;
  119030. while(v){
  119031. ret++;
  119032. v>>=1;
  119033. }
  119034. return(ret);
  119035. }
  119036. /* 32 bit float (not IEEE; nonnormalized mantissa +
  119037. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  119038. Why not IEEE? It's just not that important here. */
  119039. #define VQ_FEXP 10
  119040. #define VQ_FMAN 21
  119041. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  119042. /* doesn't currently guard under/overflow */
  119043. long _float32_pack(float val){
  119044. int sign=0;
  119045. long exp;
  119046. long mant;
  119047. if(val<0){
  119048. sign=0x80000000;
  119049. val= -val;
  119050. }
  119051. exp= floor(log(val)/log(2.f));
  119052. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  119053. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  119054. return(sign|exp|mant);
  119055. }
  119056. float _float32_unpack(long val){
  119057. double mant=val&0x1fffff;
  119058. int sign=val&0x80000000;
  119059. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  119060. if(sign)mant= -mant;
  119061. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  119062. }
  119063. /* given a list of word lengths, generate a list of codewords. Works
  119064. for length ordered or unordered, always assigns the lowest valued
  119065. codewords first. Extended to handle unused entries (length 0) */
  119066. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  119067. long i,j,count=0;
  119068. ogg_uint32_t marker[33];
  119069. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  119070. memset(marker,0,sizeof(marker));
  119071. for(i=0;i<n;i++){
  119072. long length=l[i];
  119073. if(length>0){
  119074. ogg_uint32_t entry=marker[length];
  119075. /* when we claim a node for an entry, we also claim the nodes
  119076. below it (pruning off the imagined tree that may have dangled
  119077. from it) as well as blocking the use of any nodes directly
  119078. above for leaves */
  119079. /* update ourself */
  119080. if(length<32 && (entry>>length)){
  119081. /* error condition; the lengths must specify an overpopulated tree */
  119082. _ogg_free(r);
  119083. return(NULL);
  119084. }
  119085. r[count++]=entry;
  119086. /* Look to see if the next shorter marker points to the node
  119087. above. if so, update it and repeat. */
  119088. {
  119089. for(j=length;j>0;j--){
  119090. if(marker[j]&1){
  119091. /* have to jump branches */
  119092. if(j==1)
  119093. marker[1]++;
  119094. else
  119095. marker[j]=marker[j-1]<<1;
  119096. break; /* invariant says next upper marker would already
  119097. have been moved if it was on the same path */
  119098. }
  119099. marker[j]++;
  119100. }
  119101. }
  119102. /* prune the tree; the implicit invariant says all the longer
  119103. markers were dangling from our just-taken node. Dangle them
  119104. from our *new* node. */
  119105. for(j=length+1;j<33;j++)
  119106. if((marker[j]>>1) == entry){
  119107. entry=marker[j];
  119108. marker[j]=marker[j-1]<<1;
  119109. }else
  119110. break;
  119111. }else
  119112. if(sparsecount==0)count++;
  119113. }
  119114. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119115. endian */
  119116. for(i=0,count=0;i<n;i++){
  119117. ogg_uint32_t temp=0;
  119118. for(j=0;j<l[i];j++){
  119119. temp<<=1;
  119120. temp|=(r[count]>>j)&1;
  119121. }
  119122. if(sparsecount){
  119123. if(l[i])
  119124. r[count++]=temp;
  119125. }else
  119126. r[count++]=temp;
  119127. }
  119128. return(r);
  119129. }
  119130. /* there might be a straightforward one-line way to do the below
  119131. that's portable and totally safe against roundoff, but I haven't
  119132. thought of it. Therefore, we opt on the side of caution */
  119133. long _book_maptype1_quantvals(const static_codebook *b){
  119134. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119135. /* the above *should* be reliable, but we'll not assume that FP is
  119136. ever reliable when bitstream sync is at stake; verify via integer
  119137. means that vals really is the greatest value of dim for which
  119138. vals^b->bim <= b->entries */
  119139. /* treat the above as an initial guess */
  119140. while(1){
  119141. long acc=1;
  119142. long acc1=1;
  119143. int i;
  119144. for(i=0;i<b->dim;i++){
  119145. acc*=vals;
  119146. acc1*=vals+1;
  119147. }
  119148. if(acc<=b->entries && acc1>b->entries){
  119149. return(vals);
  119150. }else{
  119151. if(acc>b->entries){
  119152. vals--;
  119153. }else{
  119154. vals++;
  119155. }
  119156. }
  119157. }
  119158. }
  119159. /* unpack the quantized list of values for encode/decode ***********/
  119160. /* we need to deal with two map types: in map type 1, the values are
  119161. generated algorithmically (each column of the vector counts through
  119162. the values in the quant vector). in map type 2, all the values came
  119163. in in an explicit list. Both value lists must be unpacked */
  119164. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119165. long j,k,count=0;
  119166. if(b->maptype==1 || b->maptype==2){
  119167. int quantvals;
  119168. float mindel=_float32_unpack(b->q_min);
  119169. float delta=_float32_unpack(b->q_delta);
  119170. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119171. /* maptype 1 and 2 both use a quantized value vector, but
  119172. different sizes */
  119173. switch(b->maptype){
  119174. case 1:
  119175. /* most of the time, entries%dimensions == 0, but we need to be
  119176. well defined. We define that the possible vales at each
  119177. scalar is values == entries/dim. If entries%dim != 0, we'll
  119178. have 'too few' values (values*dim<entries), which means that
  119179. we'll have 'left over' entries; left over entries use zeroed
  119180. values (and are wasted). So don't generate codebooks like
  119181. that */
  119182. quantvals=_book_maptype1_quantvals(b);
  119183. for(j=0;j<b->entries;j++){
  119184. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119185. float last=0.f;
  119186. int indexdiv=1;
  119187. for(k=0;k<b->dim;k++){
  119188. int index= (j/indexdiv)%quantvals;
  119189. float val=b->quantlist[index];
  119190. val=fabs(val)*delta+mindel+last;
  119191. if(b->q_sequencep)last=val;
  119192. if(sparsemap)
  119193. r[sparsemap[count]*b->dim+k]=val;
  119194. else
  119195. r[count*b->dim+k]=val;
  119196. indexdiv*=quantvals;
  119197. }
  119198. count++;
  119199. }
  119200. }
  119201. break;
  119202. case 2:
  119203. for(j=0;j<b->entries;j++){
  119204. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119205. float last=0.f;
  119206. for(k=0;k<b->dim;k++){
  119207. float val=b->quantlist[j*b->dim+k];
  119208. val=fabs(val)*delta+mindel+last;
  119209. if(b->q_sequencep)last=val;
  119210. if(sparsemap)
  119211. r[sparsemap[count]*b->dim+k]=val;
  119212. else
  119213. r[count*b->dim+k]=val;
  119214. }
  119215. count++;
  119216. }
  119217. }
  119218. break;
  119219. }
  119220. return(r);
  119221. }
  119222. return(NULL);
  119223. }
  119224. void vorbis_staticbook_clear(static_codebook *b){
  119225. if(b->allocedp){
  119226. if(b->quantlist)_ogg_free(b->quantlist);
  119227. if(b->lengthlist)_ogg_free(b->lengthlist);
  119228. if(b->nearest_tree){
  119229. _ogg_free(b->nearest_tree->ptr0);
  119230. _ogg_free(b->nearest_tree->ptr1);
  119231. _ogg_free(b->nearest_tree->p);
  119232. _ogg_free(b->nearest_tree->q);
  119233. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119234. _ogg_free(b->nearest_tree);
  119235. }
  119236. if(b->thresh_tree){
  119237. _ogg_free(b->thresh_tree->quantthresh);
  119238. _ogg_free(b->thresh_tree->quantmap);
  119239. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119240. _ogg_free(b->thresh_tree);
  119241. }
  119242. memset(b,0,sizeof(*b));
  119243. }
  119244. }
  119245. void vorbis_staticbook_destroy(static_codebook *b){
  119246. if(b->allocedp){
  119247. vorbis_staticbook_clear(b);
  119248. _ogg_free(b);
  119249. }
  119250. }
  119251. void vorbis_book_clear(codebook *b){
  119252. /* static book is not cleared; we're likely called on the lookup and
  119253. the static codebook belongs to the info struct */
  119254. if(b->valuelist)_ogg_free(b->valuelist);
  119255. if(b->codelist)_ogg_free(b->codelist);
  119256. if(b->dec_index)_ogg_free(b->dec_index);
  119257. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119258. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119259. memset(b,0,sizeof(*b));
  119260. }
  119261. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119262. memset(c,0,sizeof(*c));
  119263. c->c=s;
  119264. c->entries=s->entries;
  119265. c->used_entries=s->entries;
  119266. c->dim=s->dim;
  119267. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119268. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119269. return(0);
  119270. }
  119271. static int sort32a(const void *a,const void *b){
  119272. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119273. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119274. }
  119275. /* decode codebook arrangement is more heavily optimized than encode */
  119276. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119277. int i,j,n=0,tabn;
  119278. int *sortindex;
  119279. memset(c,0,sizeof(*c));
  119280. /* count actually used entries */
  119281. for(i=0;i<s->entries;i++)
  119282. if(s->lengthlist[i]>0)
  119283. n++;
  119284. c->entries=s->entries;
  119285. c->used_entries=n;
  119286. c->dim=s->dim;
  119287. /* two different remappings go on here.
  119288. First, we collapse the likely sparse codebook down only to
  119289. actually represented values/words. This collapsing needs to be
  119290. indexed as map-valueless books are used to encode original entry
  119291. positions as integers.
  119292. Second, we reorder all vectors, including the entry index above,
  119293. by sorted bitreversed codeword to allow treeless decode. */
  119294. {
  119295. /* perform sort */
  119296. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119297. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119298. if(codes==NULL)goto err_out;
  119299. for(i=0;i<n;i++){
  119300. codes[i]=ogg_bitreverse(codes[i]);
  119301. codep[i]=codes+i;
  119302. }
  119303. qsort(codep,n,sizeof(*codep),sort32a);
  119304. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119305. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119306. /* the index is a reverse index */
  119307. for(i=0;i<n;i++){
  119308. int position=codep[i]-codes;
  119309. sortindex[position]=i;
  119310. }
  119311. for(i=0;i<n;i++)
  119312. c->codelist[sortindex[i]]=codes[i];
  119313. _ogg_free(codes);
  119314. }
  119315. c->valuelist=_book_unquantize(s,n,sortindex);
  119316. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119317. for(n=0,i=0;i<s->entries;i++)
  119318. if(s->lengthlist[i]>0)
  119319. c->dec_index[sortindex[n++]]=i;
  119320. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119321. for(n=0,i=0;i<s->entries;i++)
  119322. if(s->lengthlist[i]>0)
  119323. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119324. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119325. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119326. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119327. tabn=1<<c->dec_firsttablen;
  119328. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119329. c->dec_maxlength=0;
  119330. for(i=0;i<n;i++){
  119331. if(c->dec_maxlength<c->dec_codelengths[i])
  119332. c->dec_maxlength=c->dec_codelengths[i];
  119333. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119334. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119335. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119336. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119337. }
  119338. }
  119339. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119340. hints for the non-direct-hits */
  119341. {
  119342. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119343. long lo=0,hi=0;
  119344. for(i=0;i<tabn;i++){
  119345. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119346. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119347. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119348. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119349. /* we only actually have 15 bits per hint to play with here.
  119350. In order to overflow gracefully (nothing breaks, efficiency
  119351. just drops), encode as the difference from the extremes. */
  119352. {
  119353. unsigned long loval=lo;
  119354. unsigned long hival=n-hi;
  119355. if(loval>0x7fff)loval=0x7fff;
  119356. if(hival>0x7fff)hival=0x7fff;
  119357. c->dec_firsttable[ogg_bitreverse(word)]=
  119358. 0x80000000UL | (loval<<15) | hival;
  119359. }
  119360. }
  119361. }
  119362. }
  119363. return(0);
  119364. err_out:
  119365. vorbis_book_clear(c);
  119366. return(-1);
  119367. }
  119368. static float _dist(int el,float *ref, float *b,int step){
  119369. int i;
  119370. float acc=0.f;
  119371. for(i=0;i<el;i++){
  119372. float val=(ref[i]-b[i*step]);
  119373. acc+=val*val;
  119374. }
  119375. return(acc);
  119376. }
  119377. int _best(codebook *book, float *a, int step){
  119378. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119379. #if 0
  119380. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119381. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119382. #endif
  119383. int dim=book->dim;
  119384. int k,o;
  119385. /*int savebest=-1;
  119386. float saverr;*/
  119387. /* do we have a threshhold encode hint? */
  119388. if(tt){
  119389. int index=0,i;
  119390. /* find the quant val of each scalar */
  119391. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119392. i=tt->threshvals>>1;
  119393. if(a[o]<tt->quantthresh[i]){
  119394. for(;i>0;i--)
  119395. if(a[o]>=tt->quantthresh[i-1])
  119396. break;
  119397. }else{
  119398. for(i++;i<tt->threshvals-1;i++)
  119399. if(a[o]<tt->quantthresh[i])break;
  119400. }
  119401. index=(index*tt->quantvals)+tt->quantmap[i];
  119402. }
  119403. /* regular lattices are easy :-) */
  119404. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119405. use a decision tree after all
  119406. and fall through*/
  119407. return(index);
  119408. }
  119409. #if 0
  119410. /* do we have a pigeonhole encode hint? */
  119411. if(pt){
  119412. const static_codebook *c=book->c;
  119413. int i,besti=-1;
  119414. float best=0.f;
  119415. int entry=0;
  119416. /* dealing with sequentialness is a pain in the ass */
  119417. if(c->q_sequencep){
  119418. int pv;
  119419. long mul=1;
  119420. float qlast=0;
  119421. for(k=0,o=0;k<dim;k++,o+=step){
  119422. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119423. if(pv<0 || pv>=pt->mapentries)break;
  119424. entry+=pt->pigeonmap[pv]*mul;
  119425. mul*=pt->quantvals;
  119426. qlast+=pv*pt->del+pt->min;
  119427. }
  119428. }else{
  119429. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119430. int pv=(int)((a[o]-pt->min)/pt->del);
  119431. if(pv<0 || pv>=pt->mapentries)break;
  119432. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119433. }
  119434. }
  119435. /* must be within the pigeonholable range; if we quant outside (or
  119436. in an entry that we define no list for), brute force it */
  119437. if(k==dim && pt->fitlength[entry]){
  119438. /* search the abbreviated list */
  119439. long *list=pt->fitlist+pt->fitmap[entry];
  119440. for(i=0;i<pt->fitlength[entry];i++){
  119441. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119442. if(besti==-1 || this<best){
  119443. best=this;
  119444. besti=list[i];
  119445. }
  119446. }
  119447. return(besti);
  119448. }
  119449. }
  119450. if(nt){
  119451. /* optimized using the decision tree */
  119452. while(1){
  119453. float c=0.f;
  119454. float *p=book->valuelist+nt->p[ptr];
  119455. float *q=book->valuelist+nt->q[ptr];
  119456. for(k=0,o=0;k<dim;k++,o+=step)
  119457. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119458. if(c>0.f) /* in A */
  119459. ptr= -nt->ptr0[ptr];
  119460. else /* in B */
  119461. ptr= -nt->ptr1[ptr];
  119462. if(ptr<=0)break;
  119463. }
  119464. return(-ptr);
  119465. }
  119466. #endif
  119467. /* brute force it! */
  119468. {
  119469. const static_codebook *c=book->c;
  119470. int i,besti=-1;
  119471. float best=0.f;
  119472. float *e=book->valuelist;
  119473. for(i=0;i<book->entries;i++){
  119474. if(c->lengthlist[i]>0){
  119475. float thisx=_dist(dim,e,a,step);
  119476. if(besti==-1 || thisx<best){
  119477. best=thisx;
  119478. besti=i;
  119479. }
  119480. }
  119481. e+=dim;
  119482. }
  119483. /*if(savebest!=-1 && savebest!=besti){
  119484. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119485. "original:");
  119486. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119487. fprintf(stderr,"\n"
  119488. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119489. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119490. (book->valuelist+savebest*dim)[i]);
  119491. fprintf(stderr,"\n"
  119492. "bruteforce (entry %d, err %g):",besti,best);
  119493. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119494. (book->valuelist+besti*dim)[i]);
  119495. fprintf(stderr,"\n");
  119496. }*/
  119497. return(besti);
  119498. }
  119499. }
  119500. long vorbis_book_codeword(codebook *book,int entry){
  119501. if(book->c) /* only use with encode; decode optimizations are
  119502. allowed to break this */
  119503. return book->codelist[entry];
  119504. return -1;
  119505. }
  119506. long vorbis_book_codelen(codebook *book,int entry){
  119507. if(book->c) /* only use with encode; decode optimizations are
  119508. allowed to break this */
  119509. return book->c->lengthlist[entry];
  119510. return -1;
  119511. }
  119512. #ifdef _V_SELFTEST
  119513. /* Unit tests of the dequantizer; this stuff will be OK
  119514. cross-platform, I simply want to be sure that special mapping cases
  119515. actually work properly; a bug could go unnoticed for a while */
  119516. #include <stdio.h>
  119517. /* cases:
  119518. no mapping
  119519. full, explicit mapping
  119520. algorithmic mapping
  119521. nonsequential
  119522. sequential
  119523. */
  119524. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119525. static long partial_quantlist1[]={0,7,2};
  119526. /* no mapping */
  119527. static_codebook test1={
  119528. 4,16,
  119529. NULL,
  119530. 0,
  119531. 0,0,0,0,
  119532. NULL,
  119533. NULL,NULL
  119534. };
  119535. static float *test1_result=NULL;
  119536. /* linear, full mapping, nonsequential */
  119537. static_codebook test2={
  119538. 4,3,
  119539. NULL,
  119540. 2,
  119541. -533200896,1611661312,4,0,
  119542. full_quantlist1,
  119543. NULL,NULL
  119544. };
  119545. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119546. /* linear, full mapping, sequential */
  119547. static_codebook test3={
  119548. 4,3,
  119549. NULL,
  119550. 2,
  119551. -533200896,1611661312,4,1,
  119552. full_quantlist1,
  119553. NULL,NULL
  119554. };
  119555. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119556. /* linear, algorithmic mapping, nonsequential */
  119557. static_codebook test4={
  119558. 3,27,
  119559. NULL,
  119560. 1,
  119561. -533200896,1611661312,4,0,
  119562. partial_quantlist1,
  119563. NULL,NULL
  119564. };
  119565. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119566. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119567. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119568. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119569. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119570. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119571. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119572. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119573. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119574. /* linear, algorithmic mapping, sequential */
  119575. static_codebook test5={
  119576. 3,27,
  119577. NULL,
  119578. 1,
  119579. -533200896,1611661312,4,1,
  119580. partial_quantlist1,
  119581. NULL,NULL
  119582. };
  119583. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119584. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119585. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119586. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119587. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119588. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119589. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119590. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119591. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119592. void run_test(static_codebook *b,float *comp){
  119593. float *out=_book_unquantize(b,b->entries,NULL);
  119594. int i;
  119595. if(comp){
  119596. if(!out){
  119597. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119598. exit(1);
  119599. }
  119600. for(i=0;i<b->entries*b->dim;i++)
  119601. if(fabs(out[i]-comp[i])>.0001){
  119602. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119603. "position %d, %g != %g\n",i,out[i],comp[i]);
  119604. exit(1);
  119605. }
  119606. }else{
  119607. if(out){
  119608. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119609. " correct result should have been NULL\n");
  119610. exit(1);
  119611. }
  119612. }
  119613. }
  119614. int main(){
  119615. /* run the nine dequant tests, and compare to the hand-rolled results */
  119616. fprintf(stderr,"Dequant test 1... ");
  119617. run_test(&test1,test1_result);
  119618. fprintf(stderr,"OK\nDequant test 2... ");
  119619. run_test(&test2,test2_result);
  119620. fprintf(stderr,"OK\nDequant test 3... ");
  119621. run_test(&test3,test3_result);
  119622. fprintf(stderr,"OK\nDequant test 4... ");
  119623. run_test(&test4,test4_result);
  119624. fprintf(stderr,"OK\nDequant test 5... ");
  119625. run_test(&test5,test5_result);
  119626. fprintf(stderr,"OK\n\n");
  119627. return(0);
  119628. }
  119629. #endif
  119630. #endif
  119631. /*** End of inlined file: sharedbook.c ***/
  119632. /*** Start of inlined file: smallft.c ***/
  119633. /* FFT implementation from OggSquish, minus cosine transforms,
  119634. * minus all but radix 2/4 case. In Vorbis we only need this
  119635. * cut-down version.
  119636. *
  119637. * To do more than just power-of-two sized vectors, see the full
  119638. * version I wrote for NetLib.
  119639. *
  119640. * Note that the packing is a little strange; rather than the FFT r/i
  119641. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119642. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119643. * FORTRAN version
  119644. */
  119645. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119646. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119647. // tasks..
  119648. #if JUCE_MSVC
  119649. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119650. #endif
  119651. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119652. #if JUCE_USE_OGGVORBIS
  119653. #include <stdlib.h>
  119654. #include <string.h>
  119655. #include <math.h>
  119656. static void drfti1(int n, float *wa, int *ifac){
  119657. static int ntryh[4] = { 4,2,3,5 };
  119658. static float tpi = 6.28318530717958648f;
  119659. float arg,argh,argld,fi;
  119660. int ntry=0,i,j=-1;
  119661. int k1, l1, l2, ib;
  119662. int ld, ii, ip, is, nq, nr;
  119663. int ido, ipm, nfm1;
  119664. int nl=n;
  119665. int nf=0;
  119666. L101:
  119667. j++;
  119668. if (j < 4)
  119669. ntry=ntryh[j];
  119670. else
  119671. ntry+=2;
  119672. L104:
  119673. nq=nl/ntry;
  119674. nr=nl-ntry*nq;
  119675. if (nr!=0) goto L101;
  119676. nf++;
  119677. ifac[nf+1]=ntry;
  119678. nl=nq;
  119679. if(ntry!=2)goto L107;
  119680. if(nf==1)goto L107;
  119681. for (i=1;i<nf;i++){
  119682. ib=nf-i+1;
  119683. ifac[ib+1]=ifac[ib];
  119684. }
  119685. ifac[2] = 2;
  119686. L107:
  119687. if(nl!=1)goto L104;
  119688. ifac[0]=n;
  119689. ifac[1]=nf;
  119690. argh=tpi/n;
  119691. is=0;
  119692. nfm1=nf-1;
  119693. l1=1;
  119694. if(nfm1==0)return;
  119695. for (k1=0;k1<nfm1;k1++){
  119696. ip=ifac[k1+2];
  119697. ld=0;
  119698. l2=l1*ip;
  119699. ido=n/l2;
  119700. ipm=ip-1;
  119701. for (j=0;j<ipm;j++){
  119702. ld+=l1;
  119703. i=is;
  119704. argld=(float)ld*argh;
  119705. fi=0.f;
  119706. for (ii=2;ii<ido;ii+=2){
  119707. fi+=1.f;
  119708. arg=fi*argld;
  119709. wa[i++]=cos(arg);
  119710. wa[i++]=sin(arg);
  119711. }
  119712. is+=ido;
  119713. }
  119714. l1=l2;
  119715. }
  119716. }
  119717. static void fdrffti(int n, float *wsave, int *ifac){
  119718. if (n == 1) return;
  119719. drfti1(n, wsave+n, ifac);
  119720. }
  119721. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119722. int i,k;
  119723. float ti2,tr2;
  119724. int t0,t1,t2,t3,t4,t5,t6;
  119725. t1=0;
  119726. t0=(t2=l1*ido);
  119727. t3=ido<<1;
  119728. for(k=0;k<l1;k++){
  119729. ch[t1<<1]=cc[t1]+cc[t2];
  119730. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119731. t1+=ido;
  119732. t2+=ido;
  119733. }
  119734. if(ido<2)return;
  119735. if(ido==2)goto L105;
  119736. t1=0;
  119737. t2=t0;
  119738. for(k=0;k<l1;k++){
  119739. t3=t2;
  119740. t4=(t1<<1)+(ido<<1);
  119741. t5=t1;
  119742. t6=t1+t1;
  119743. for(i=2;i<ido;i+=2){
  119744. t3+=2;
  119745. t4-=2;
  119746. t5+=2;
  119747. t6+=2;
  119748. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119749. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119750. ch[t6]=cc[t5]+ti2;
  119751. ch[t4]=ti2-cc[t5];
  119752. ch[t6-1]=cc[t5-1]+tr2;
  119753. ch[t4-1]=cc[t5-1]-tr2;
  119754. }
  119755. t1+=ido;
  119756. t2+=ido;
  119757. }
  119758. if(ido%2==1)return;
  119759. L105:
  119760. t3=(t2=(t1=ido)-1);
  119761. t2+=t0;
  119762. for(k=0;k<l1;k++){
  119763. ch[t1]=-cc[t2];
  119764. ch[t1-1]=cc[t3];
  119765. t1+=ido<<1;
  119766. t2+=ido;
  119767. t3+=ido;
  119768. }
  119769. }
  119770. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119771. float *wa2,float *wa3){
  119772. static float hsqt2 = .70710678118654752f;
  119773. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119774. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119775. t0=l1*ido;
  119776. t1=t0;
  119777. t4=t1<<1;
  119778. t2=t1+(t1<<1);
  119779. t3=0;
  119780. for(k=0;k<l1;k++){
  119781. tr1=cc[t1]+cc[t2];
  119782. tr2=cc[t3]+cc[t4];
  119783. ch[t5=t3<<2]=tr1+tr2;
  119784. ch[(ido<<2)+t5-1]=tr2-tr1;
  119785. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119786. ch[t5]=cc[t2]-cc[t1];
  119787. t1+=ido;
  119788. t2+=ido;
  119789. t3+=ido;
  119790. t4+=ido;
  119791. }
  119792. if(ido<2)return;
  119793. if(ido==2)goto L105;
  119794. t1=0;
  119795. for(k=0;k<l1;k++){
  119796. t2=t1;
  119797. t4=t1<<2;
  119798. t5=(t6=ido<<1)+t4;
  119799. for(i=2;i<ido;i+=2){
  119800. t3=(t2+=2);
  119801. t4+=2;
  119802. t5-=2;
  119803. t3+=t0;
  119804. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119805. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119806. t3+=t0;
  119807. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119808. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119809. t3+=t0;
  119810. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119811. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119812. tr1=cr2+cr4;
  119813. tr4=cr4-cr2;
  119814. ti1=ci2+ci4;
  119815. ti4=ci2-ci4;
  119816. ti2=cc[t2]+ci3;
  119817. ti3=cc[t2]-ci3;
  119818. tr2=cc[t2-1]+cr3;
  119819. tr3=cc[t2-1]-cr3;
  119820. ch[t4-1]=tr1+tr2;
  119821. ch[t4]=ti1+ti2;
  119822. ch[t5-1]=tr3-ti4;
  119823. ch[t5]=tr4-ti3;
  119824. ch[t4+t6-1]=ti4+tr3;
  119825. ch[t4+t6]=tr4+ti3;
  119826. ch[t5+t6-1]=tr2-tr1;
  119827. ch[t5+t6]=ti1-ti2;
  119828. }
  119829. t1+=ido;
  119830. }
  119831. if(ido&1)return;
  119832. L105:
  119833. t2=(t1=t0+ido-1)+(t0<<1);
  119834. t3=ido<<2;
  119835. t4=ido;
  119836. t5=ido<<1;
  119837. t6=ido;
  119838. for(k=0;k<l1;k++){
  119839. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119840. tr1=hsqt2*(cc[t1]-cc[t2]);
  119841. ch[t4-1]=tr1+cc[t6-1];
  119842. ch[t4+t5-1]=cc[t6-1]-tr1;
  119843. ch[t4]=ti1-cc[t1+t0];
  119844. ch[t4+t5]=ti1+cc[t1+t0];
  119845. t1+=ido;
  119846. t2+=ido;
  119847. t4+=t3;
  119848. t6+=ido;
  119849. }
  119850. }
  119851. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119852. float *c2,float *ch,float *ch2,float *wa){
  119853. static float tpi=6.283185307179586f;
  119854. int idij,ipph,i,j,k,l,ic,ik,is;
  119855. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119856. float dc2,ai1,ai2,ar1,ar2,ds2;
  119857. int nbd;
  119858. float dcp,arg,dsp,ar1h,ar2h;
  119859. int idp2,ipp2;
  119860. arg=tpi/(float)ip;
  119861. dcp=cos(arg);
  119862. dsp=sin(arg);
  119863. ipph=(ip+1)>>1;
  119864. ipp2=ip;
  119865. idp2=ido;
  119866. nbd=(ido-1)>>1;
  119867. t0=l1*ido;
  119868. t10=ip*ido;
  119869. if(ido==1)goto L119;
  119870. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119871. t1=0;
  119872. for(j=1;j<ip;j++){
  119873. t1+=t0;
  119874. t2=t1;
  119875. for(k=0;k<l1;k++){
  119876. ch[t2]=c1[t2];
  119877. t2+=ido;
  119878. }
  119879. }
  119880. is=-ido;
  119881. t1=0;
  119882. if(nbd>l1){
  119883. for(j=1;j<ip;j++){
  119884. t1+=t0;
  119885. is+=ido;
  119886. t2= -ido+t1;
  119887. for(k=0;k<l1;k++){
  119888. idij=is-1;
  119889. t2+=ido;
  119890. t3=t2;
  119891. for(i=2;i<ido;i+=2){
  119892. idij+=2;
  119893. t3+=2;
  119894. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119895. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119896. }
  119897. }
  119898. }
  119899. }else{
  119900. for(j=1;j<ip;j++){
  119901. is+=ido;
  119902. idij=is-1;
  119903. t1+=t0;
  119904. t2=t1;
  119905. for(i=2;i<ido;i+=2){
  119906. idij+=2;
  119907. t2+=2;
  119908. t3=t2;
  119909. for(k=0;k<l1;k++){
  119910. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119911. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119912. t3+=ido;
  119913. }
  119914. }
  119915. }
  119916. }
  119917. t1=0;
  119918. t2=ipp2*t0;
  119919. if(nbd<l1){
  119920. for(j=1;j<ipph;j++){
  119921. t1+=t0;
  119922. t2-=t0;
  119923. t3=t1;
  119924. t4=t2;
  119925. for(i=2;i<ido;i+=2){
  119926. t3+=2;
  119927. t4+=2;
  119928. t5=t3-ido;
  119929. t6=t4-ido;
  119930. for(k=0;k<l1;k++){
  119931. t5+=ido;
  119932. t6+=ido;
  119933. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119934. c1[t6-1]=ch[t5]-ch[t6];
  119935. c1[t5]=ch[t5]+ch[t6];
  119936. c1[t6]=ch[t6-1]-ch[t5-1];
  119937. }
  119938. }
  119939. }
  119940. }else{
  119941. for(j=1;j<ipph;j++){
  119942. t1+=t0;
  119943. t2-=t0;
  119944. t3=t1;
  119945. t4=t2;
  119946. for(k=0;k<l1;k++){
  119947. t5=t3;
  119948. t6=t4;
  119949. for(i=2;i<ido;i+=2){
  119950. t5+=2;
  119951. t6+=2;
  119952. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119953. c1[t6-1]=ch[t5]-ch[t6];
  119954. c1[t5]=ch[t5]+ch[t6];
  119955. c1[t6]=ch[t6-1]-ch[t5-1];
  119956. }
  119957. t3+=ido;
  119958. t4+=ido;
  119959. }
  119960. }
  119961. }
  119962. L119:
  119963. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119964. t1=0;
  119965. t2=ipp2*idl1;
  119966. for(j=1;j<ipph;j++){
  119967. t1+=t0;
  119968. t2-=t0;
  119969. t3=t1-ido;
  119970. t4=t2-ido;
  119971. for(k=0;k<l1;k++){
  119972. t3+=ido;
  119973. t4+=ido;
  119974. c1[t3]=ch[t3]+ch[t4];
  119975. c1[t4]=ch[t4]-ch[t3];
  119976. }
  119977. }
  119978. ar1=1.f;
  119979. ai1=0.f;
  119980. t1=0;
  119981. t2=ipp2*idl1;
  119982. t3=(ip-1)*idl1;
  119983. for(l=1;l<ipph;l++){
  119984. t1+=idl1;
  119985. t2-=idl1;
  119986. ar1h=dcp*ar1-dsp*ai1;
  119987. ai1=dcp*ai1+dsp*ar1;
  119988. ar1=ar1h;
  119989. t4=t1;
  119990. t5=t2;
  119991. t6=t3;
  119992. t7=idl1;
  119993. for(ik=0;ik<idl1;ik++){
  119994. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119995. ch2[t5++]=ai1*c2[t6++];
  119996. }
  119997. dc2=ar1;
  119998. ds2=ai1;
  119999. ar2=ar1;
  120000. ai2=ai1;
  120001. t4=idl1;
  120002. t5=(ipp2-1)*idl1;
  120003. for(j=2;j<ipph;j++){
  120004. t4+=idl1;
  120005. t5-=idl1;
  120006. ar2h=dc2*ar2-ds2*ai2;
  120007. ai2=dc2*ai2+ds2*ar2;
  120008. ar2=ar2h;
  120009. t6=t1;
  120010. t7=t2;
  120011. t8=t4;
  120012. t9=t5;
  120013. for(ik=0;ik<idl1;ik++){
  120014. ch2[t6++]+=ar2*c2[t8++];
  120015. ch2[t7++]+=ai2*c2[t9++];
  120016. }
  120017. }
  120018. }
  120019. t1=0;
  120020. for(j=1;j<ipph;j++){
  120021. t1+=idl1;
  120022. t2=t1;
  120023. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  120024. }
  120025. if(ido<l1)goto L132;
  120026. t1=0;
  120027. t2=0;
  120028. for(k=0;k<l1;k++){
  120029. t3=t1;
  120030. t4=t2;
  120031. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  120032. t1+=ido;
  120033. t2+=t10;
  120034. }
  120035. goto L135;
  120036. L132:
  120037. for(i=0;i<ido;i++){
  120038. t1=i;
  120039. t2=i;
  120040. for(k=0;k<l1;k++){
  120041. cc[t2]=ch[t1];
  120042. t1+=ido;
  120043. t2+=t10;
  120044. }
  120045. }
  120046. L135:
  120047. t1=0;
  120048. t2=ido<<1;
  120049. t3=0;
  120050. t4=ipp2*t0;
  120051. for(j=1;j<ipph;j++){
  120052. t1+=t2;
  120053. t3+=t0;
  120054. t4-=t0;
  120055. t5=t1;
  120056. t6=t3;
  120057. t7=t4;
  120058. for(k=0;k<l1;k++){
  120059. cc[t5-1]=ch[t6];
  120060. cc[t5]=ch[t7];
  120061. t5+=t10;
  120062. t6+=ido;
  120063. t7+=ido;
  120064. }
  120065. }
  120066. if(ido==1)return;
  120067. if(nbd<l1)goto L141;
  120068. t1=-ido;
  120069. t3=0;
  120070. t4=0;
  120071. t5=ipp2*t0;
  120072. for(j=1;j<ipph;j++){
  120073. t1+=t2;
  120074. t3+=t2;
  120075. t4+=t0;
  120076. t5-=t0;
  120077. t6=t1;
  120078. t7=t3;
  120079. t8=t4;
  120080. t9=t5;
  120081. for(k=0;k<l1;k++){
  120082. for(i=2;i<ido;i+=2){
  120083. ic=idp2-i;
  120084. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  120085. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  120086. cc[i+t7]=ch[i+t8]+ch[i+t9];
  120087. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  120088. }
  120089. t6+=t10;
  120090. t7+=t10;
  120091. t8+=ido;
  120092. t9+=ido;
  120093. }
  120094. }
  120095. return;
  120096. L141:
  120097. t1=-ido;
  120098. t3=0;
  120099. t4=0;
  120100. t5=ipp2*t0;
  120101. for(j=1;j<ipph;j++){
  120102. t1+=t2;
  120103. t3+=t2;
  120104. t4+=t0;
  120105. t5-=t0;
  120106. for(i=2;i<ido;i+=2){
  120107. t6=idp2+t1-i;
  120108. t7=i+t3;
  120109. t8=i+t4;
  120110. t9=i+t5;
  120111. for(k=0;k<l1;k++){
  120112. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120113. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120114. cc[t7]=ch[t8]+ch[t9];
  120115. cc[t6]=ch[t9]-ch[t8];
  120116. t6+=t10;
  120117. t7+=t10;
  120118. t8+=ido;
  120119. t9+=ido;
  120120. }
  120121. }
  120122. }
  120123. }
  120124. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120125. int i,k1,l1,l2;
  120126. int na,kh,nf;
  120127. int ip,iw,ido,idl1,ix2,ix3;
  120128. nf=ifac[1];
  120129. na=1;
  120130. l2=n;
  120131. iw=n;
  120132. for(k1=0;k1<nf;k1++){
  120133. kh=nf-k1;
  120134. ip=ifac[kh+1];
  120135. l1=l2/ip;
  120136. ido=n/l2;
  120137. idl1=ido*l1;
  120138. iw-=(ip-1)*ido;
  120139. na=1-na;
  120140. if(ip!=4)goto L102;
  120141. ix2=iw+ido;
  120142. ix3=ix2+ido;
  120143. if(na!=0)
  120144. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120145. else
  120146. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120147. goto L110;
  120148. L102:
  120149. if(ip!=2)goto L104;
  120150. if(na!=0)goto L103;
  120151. dradf2(ido,l1,c,ch,wa+iw-1);
  120152. goto L110;
  120153. L103:
  120154. dradf2(ido,l1,ch,c,wa+iw-1);
  120155. goto L110;
  120156. L104:
  120157. if(ido==1)na=1-na;
  120158. if(na!=0)goto L109;
  120159. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120160. na=1;
  120161. goto L110;
  120162. L109:
  120163. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120164. na=0;
  120165. L110:
  120166. l2=l1;
  120167. }
  120168. if(na==1)return;
  120169. for(i=0;i<n;i++)c[i]=ch[i];
  120170. }
  120171. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120172. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120173. float ti2,tr2;
  120174. t0=l1*ido;
  120175. t1=0;
  120176. t2=0;
  120177. t3=(ido<<1)-1;
  120178. for(k=0;k<l1;k++){
  120179. ch[t1]=cc[t2]+cc[t3+t2];
  120180. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120181. t2=(t1+=ido)<<1;
  120182. }
  120183. if(ido<2)return;
  120184. if(ido==2)goto L105;
  120185. t1=0;
  120186. t2=0;
  120187. for(k=0;k<l1;k++){
  120188. t3=t1;
  120189. t5=(t4=t2)+(ido<<1);
  120190. t6=t0+t1;
  120191. for(i=2;i<ido;i+=2){
  120192. t3+=2;
  120193. t4+=2;
  120194. t5-=2;
  120195. t6+=2;
  120196. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120197. tr2=cc[t4-1]-cc[t5-1];
  120198. ch[t3]=cc[t4]-cc[t5];
  120199. ti2=cc[t4]+cc[t5];
  120200. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120201. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120202. }
  120203. t2=(t1+=ido)<<1;
  120204. }
  120205. if(ido%2==1)return;
  120206. L105:
  120207. t1=ido-1;
  120208. t2=ido-1;
  120209. for(k=0;k<l1;k++){
  120210. ch[t1]=cc[t2]+cc[t2];
  120211. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120212. t1+=ido;
  120213. t2+=ido<<1;
  120214. }
  120215. }
  120216. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120217. float *wa2){
  120218. static float taur = -.5f;
  120219. static float taui = .8660254037844386f;
  120220. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120221. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120222. t0=l1*ido;
  120223. t1=0;
  120224. t2=t0<<1;
  120225. t3=ido<<1;
  120226. t4=ido+(ido<<1);
  120227. t5=0;
  120228. for(k=0;k<l1;k++){
  120229. tr2=cc[t3-1]+cc[t3-1];
  120230. cr2=cc[t5]+(taur*tr2);
  120231. ch[t1]=cc[t5]+tr2;
  120232. ci3=taui*(cc[t3]+cc[t3]);
  120233. ch[t1+t0]=cr2-ci3;
  120234. ch[t1+t2]=cr2+ci3;
  120235. t1+=ido;
  120236. t3+=t4;
  120237. t5+=t4;
  120238. }
  120239. if(ido==1)return;
  120240. t1=0;
  120241. t3=ido<<1;
  120242. for(k=0;k<l1;k++){
  120243. t7=t1+(t1<<1);
  120244. t6=(t5=t7+t3);
  120245. t8=t1;
  120246. t10=(t9=t1+t0)+t0;
  120247. for(i=2;i<ido;i+=2){
  120248. t5+=2;
  120249. t6-=2;
  120250. t7+=2;
  120251. t8+=2;
  120252. t9+=2;
  120253. t10+=2;
  120254. tr2=cc[t5-1]+cc[t6-1];
  120255. cr2=cc[t7-1]+(taur*tr2);
  120256. ch[t8-1]=cc[t7-1]+tr2;
  120257. ti2=cc[t5]-cc[t6];
  120258. ci2=cc[t7]+(taur*ti2);
  120259. ch[t8]=cc[t7]+ti2;
  120260. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120261. ci3=taui*(cc[t5]+cc[t6]);
  120262. dr2=cr2-ci3;
  120263. dr3=cr2+ci3;
  120264. di2=ci2+cr3;
  120265. di3=ci2-cr3;
  120266. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120267. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120268. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120269. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120270. }
  120271. t1+=ido;
  120272. }
  120273. }
  120274. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120275. float *wa2,float *wa3){
  120276. static float sqrt2=1.414213562373095f;
  120277. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120278. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120279. t0=l1*ido;
  120280. t1=0;
  120281. t2=ido<<2;
  120282. t3=0;
  120283. t6=ido<<1;
  120284. for(k=0;k<l1;k++){
  120285. t4=t3+t6;
  120286. t5=t1;
  120287. tr3=cc[t4-1]+cc[t4-1];
  120288. tr4=cc[t4]+cc[t4];
  120289. tr1=cc[t3]-cc[(t4+=t6)-1];
  120290. tr2=cc[t3]+cc[t4-1];
  120291. ch[t5]=tr2+tr3;
  120292. ch[t5+=t0]=tr1-tr4;
  120293. ch[t5+=t0]=tr2-tr3;
  120294. ch[t5+=t0]=tr1+tr4;
  120295. t1+=ido;
  120296. t3+=t2;
  120297. }
  120298. if(ido<2)return;
  120299. if(ido==2)goto L105;
  120300. t1=0;
  120301. for(k=0;k<l1;k++){
  120302. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120303. t7=t1;
  120304. for(i=2;i<ido;i+=2){
  120305. t2+=2;
  120306. t3+=2;
  120307. t4-=2;
  120308. t5-=2;
  120309. t7+=2;
  120310. ti1=cc[t2]+cc[t5];
  120311. ti2=cc[t2]-cc[t5];
  120312. ti3=cc[t3]-cc[t4];
  120313. tr4=cc[t3]+cc[t4];
  120314. tr1=cc[t2-1]-cc[t5-1];
  120315. tr2=cc[t2-1]+cc[t5-1];
  120316. ti4=cc[t3-1]-cc[t4-1];
  120317. tr3=cc[t3-1]+cc[t4-1];
  120318. ch[t7-1]=tr2+tr3;
  120319. cr3=tr2-tr3;
  120320. ch[t7]=ti2+ti3;
  120321. ci3=ti2-ti3;
  120322. cr2=tr1-tr4;
  120323. cr4=tr1+tr4;
  120324. ci2=ti1+ti4;
  120325. ci4=ti1-ti4;
  120326. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120327. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120328. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120329. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120330. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120331. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120332. }
  120333. t1+=ido;
  120334. }
  120335. if(ido%2 == 1)return;
  120336. L105:
  120337. t1=ido;
  120338. t2=ido<<2;
  120339. t3=ido-1;
  120340. t4=ido+(ido<<1);
  120341. for(k=0;k<l1;k++){
  120342. t5=t3;
  120343. ti1=cc[t1]+cc[t4];
  120344. ti2=cc[t4]-cc[t1];
  120345. tr1=cc[t1-1]-cc[t4-1];
  120346. tr2=cc[t1-1]+cc[t4-1];
  120347. ch[t5]=tr2+tr2;
  120348. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120349. ch[t5+=t0]=ti2+ti2;
  120350. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120351. t3+=ido;
  120352. t1+=t2;
  120353. t4+=t2;
  120354. }
  120355. }
  120356. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120357. float *c2,float *ch,float *ch2,float *wa){
  120358. static float tpi=6.283185307179586f;
  120359. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120360. t11,t12;
  120361. float dc2,ai1,ai2,ar1,ar2,ds2;
  120362. int nbd;
  120363. float dcp,arg,dsp,ar1h,ar2h;
  120364. int ipp2;
  120365. t10=ip*ido;
  120366. t0=l1*ido;
  120367. arg=tpi/(float)ip;
  120368. dcp=cos(arg);
  120369. dsp=sin(arg);
  120370. nbd=(ido-1)>>1;
  120371. ipp2=ip;
  120372. ipph=(ip+1)>>1;
  120373. if(ido<l1)goto L103;
  120374. t1=0;
  120375. t2=0;
  120376. for(k=0;k<l1;k++){
  120377. t3=t1;
  120378. t4=t2;
  120379. for(i=0;i<ido;i++){
  120380. ch[t3]=cc[t4];
  120381. t3++;
  120382. t4++;
  120383. }
  120384. t1+=ido;
  120385. t2+=t10;
  120386. }
  120387. goto L106;
  120388. L103:
  120389. t1=0;
  120390. for(i=0;i<ido;i++){
  120391. t2=t1;
  120392. t3=t1;
  120393. for(k=0;k<l1;k++){
  120394. ch[t2]=cc[t3];
  120395. t2+=ido;
  120396. t3+=t10;
  120397. }
  120398. t1++;
  120399. }
  120400. L106:
  120401. t1=0;
  120402. t2=ipp2*t0;
  120403. t7=(t5=ido<<1);
  120404. for(j=1;j<ipph;j++){
  120405. t1+=t0;
  120406. t2-=t0;
  120407. t3=t1;
  120408. t4=t2;
  120409. t6=t5;
  120410. for(k=0;k<l1;k++){
  120411. ch[t3]=cc[t6-1]+cc[t6-1];
  120412. ch[t4]=cc[t6]+cc[t6];
  120413. t3+=ido;
  120414. t4+=ido;
  120415. t6+=t10;
  120416. }
  120417. t5+=t7;
  120418. }
  120419. if (ido == 1)goto L116;
  120420. if(nbd<l1)goto L112;
  120421. t1=0;
  120422. t2=ipp2*t0;
  120423. t7=0;
  120424. for(j=1;j<ipph;j++){
  120425. t1+=t0;
  120426. t2-=t0;
  120427. t3=t1;
  120428. t4=t2;
  120429. t7+=(ido<<1);
  120430. t8=t7;
  120431. for(k=0;k<l1;k++){
  120432. t5=t3;
  120433. t6=t4;
  120434. t9=t8;
  120435. t11=t8;
  120436. for(i=2;i<ido;i+=2){
  120437. t5+=2;
  120438. t6+=2;
  120439. t9+=2;
  120440. t11-=2;
  120441. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120442. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120443. ch[t5]=cc[t9]-cc[t11];
  120444. ch[t6]=cc[t9]+cc[t11];
  120445. }
  120446. t3+=ido;
  120447. t4+=ido;
  120448. t8+=t10;
  120449. }
  120450. }
  120451. goto L116;
  120452. L112:
  120453. t1=0;
  120454. t2=ipp2*t0;
  120455. t7=0;
  120456. for(j=1;j<ipph;j++){
  120457. t1+=t0;
  120458. t2-=t0;
  120459. t3=t1;
  120460. t4=t2;
  120461. t7+=(ido<<1);
  120462. t8=t7;
  120463. t9=t7;
  120464. for(i=2;i<ido;i+=2){
  120465. t3+=2;
  120466. t4+=2;
  120467. t8+=2;
  120468. t9-=2;
  120469. t5=t3;
  120470. t6=t4;
  120471. t11=t8;
  120472. t12=t9;
  120473. for(k=0;k<l1;k++){
  120474. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120475. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120476. ch[t5]=cc[t11]-cc[t12];
  120477. ch[t6]=cc[t11]+cc[t12];
  120478. t5+=ido;
  120479. t6+=ido;
  120480. t11+=t10;
  120481. t12+=t10;
  120482. }
  120483. }
  120484. }
  120485. L116:
  120486. ar1=1.f;
  120487. ai1=0.f;
  120488. t1=0;
  120489. t9=(t2=ipp2*idl1);
  120490. t3=(ip-1)*idl1;
  120491. for(l=1;l<ipph;l++){
  120492. t1+=idl1;
  120493. t2-=idl1;
  120494. ar1h=dcp*ar1-dsp*ai1;
  120495. ai1=dcp*ai1+dsp*ar1;
  120496. ar1=ar1h;
  120497. t4=t1;
  120498. t5=t2;
  120499. t6=0;
  120500. t7=idl1;
  120501. t8=t3;
  120502. for(ik=0;ik<idl1;ik++){
  120503. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120504. c2[t5++]=ai1*ch2[t8++];
  120505. }
  120506. dc2=ar1;
  120507. ds2=ai1;
  120508. ar2=ar1;
  120509. ai2=ai1;
  120510. t6=idl1;
  120511. t7=t9-idl1;
  120512. for(j=2;j<ipph;j++){
  120513. t6+=idl1;
  120514. t7-=idl1;
  120515. ar2h=dc2*ar2-ds2*ai2;
  120516. ai2=dc2*ai2+ds2*ar2;
  120517. ar2=ar2h;
  120518. t4=t1;
  120519. t5=t2;
  120520. t11=t6;
  120521. t12=t7;
  120522. for(ik=0;ik<idl1;ik++){
  120523. c2[t4++]+=ar2*ch2[t11++];
  120524. c2[t5++]+=ai2*ch2[t12++];
  120525. }
  120526. }
  120527. }
  120528. t1=0;
  120529. for(j=1;j<ipph;j++){
  120530. t1+=idl1;
  120531. t2=t1;
  120532. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120533. }
  120534. t1=0;
  120535. t2=ipp2*t0;
  120536. for(j=1;j<ipph;j++){
  120537. t1+=t0;
  120538. t2-=t0;
  120539. t3=t1;
  120540. t4=t2;
  120541. for(k=0;k<l1;k++){
  120542. ch[t3]=c1[t3]-c1[t4];
  120543. ch[t4]=c1[t3]+c1[t4];
  120544. t3+=ido;
  120545. t4+=ido;
  120546. }
  120547. }
  120548. if(ido==1)goto L132;
  120549. if(nbd<l1)goto L128;
  120550. t1=0;
  120551. t2=ipp2*t0;
  120552. for(j=1;j<ipph;j++){
  120553. t1+=t0;
  120554. t2-=t0;
  120555. t3=t1;
  120556. t4=t2;
  120557. for(k=0;k<l1;k++){
  120558. t5=t3;
  120559. t6=t4;
  120560. for(i=2;i<ido;i+=2){
  120561. t5+=2;
  120562. t6+=2;
  120563. ch[t5-1]=c1[t5-1]-c1[t6];
  120564. ch[t6-1]=c1[t5-1]+c1[t6];
  120565. ch[t5]=c1[t5]+c1[t6-1];
  120566. ch[t6]=c1[t5]-c1[t6-1];
  120567. }
  120568. t3+=ido;
  120569. t4+=ido;
  120570. }
  120571. }
  120572. goto L132;
  120573. L128:
  120574. t1=0;
  120575. t2=ipp2*t0;
  120576. for(j=1;j<ipph;j++){
  120577. t1+=t0;
  120578. t2-=t0;
  120579. t3=t1;
  120580. t4=t2;
  120581. for(i=2;i<ido;i+=2){
  120582. t3+=2;
  120583. t4+=2;
  120584. t5=t3;
  120585. t6=t4;
  120586. for(k=0;k<l1;k++){
  120587. ch[t5-1]=c1[t5-1]-c1[t6];
  120588. ch[t6-1]=c1[t5-1]+c1[t6];
  120589. ch[t5]=c1[t5]+c1[t6-1];
  120590. ch[t6]=c1[t5]-c1[t6-1];
  120591. t5+=ido;
  120592. t6+=ido;
  120593. }
  120594. }
  120595. }
  120596. L132:
  120597. if(ido==1)return;
  120598. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120599. t1=0;
  120600. for(j=1;j<ip;j++){
  120601. t2=(t1+=t0);
  120602. for(k=0;k<l1;k++){
  120603. c1[t2]=ch[t2];
  120604. t2+=ido;
  120605. }
  120606. }
  120607. if(nbd>l1)goto L139;
  120608. is= -ido-1;
  120609. t1=0;
  120610. for(j=1;j<ip;j++){
  120611. is+=ido;
  120612. t1+=t0;
  120613. idij=is;
  120614. t2=t1;
  120615. for(i=2;i<ido;i+=2){
  120616. t2+=2;
  120617. idij+=2;
  120618. t3=t2;
  120619. for(k=0;k<l1;k++){
  120620. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120621. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120622. t3+=ido;
  120623. }
  120624. }
  120625. }
  120626. return;
  120627. L139:
  120628. is= -ido-1;
  120629. t1=0;
  120630. for(j=1;j<ip;j++){
  120631. is+=ido;
  120632. t1+=t0;
  120633. t2=t1;
  120634. for(k=0;k<l1;k++){
  120635. idij=is;
  120636. t3=t2;
  120637. for(i=2;i<ido;i+=2){
  120638. idij+=2;
  120639. t3+=2;
  120640. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120641. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120642. }
  120643. t2+=ido;
  120644. }
  120645. }
  120646. }
  120647. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120648. int i,k1,l1,l2;
  120649. int na;
  120650. int nf,ip,iw,ix2,ix3,ido,idl1;
  120651. nf=ifac[1];
  120652. na=0;
  120653. l1=1;
  120654. iw=1;
  120655. for(k1=0;k1<nf;k1++){
  120656. ip=ifac[k1 + 2];
  120657. l2=ip*l1;
  120658. ido=n/l2;
  120659. idl1=ido*l1;
  120660. if(ip!=4)goto L103;
  120661. ix2=iw+ido;
  120662. ix3=ix2+ido;
  120663. if(na!=0)
  120664. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120665. else
  120666. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120667. na=1-na;
  120668. goto L115;
  120669. L103:
  120670. if(ip!=2)goto L106;
  120671. if(na!=0)
  120672. dradb2(ido,l1,ch,c,wa+iw-1);
  120673. else
  120674. dradb2(ido,l1,c,ch,wa+iw-1);
  120675. na=1-na;
  120676. goto L115;
  120677. L106:
  120678. if(ip!=3)goto L109;
  120679. ix2=iw+ido;
  120680. if(na!=0)
  120681. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120682. else
  120683. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120684. na=1-na;
  120685. goto L115;
  120686. L109:
  120687. /* The radix five case can be translated later..... */
  120688. /* if(ip!=5)goto L112;
  120689. ix2=iw+ido;
  120690. ix3=ix2+ido;
  120691. ix4=ix3+ido;
  120692. if(na!=0)
  120693. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120694. else
  120695. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120696. na=1-na;
  120697. goto L115;
  120698. L112:*/
  120699. if(na!=0)
  120700. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120701. else
  120702. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120703. if(ido==1)na=1-na;
  120704. L115:
  120705. l1=l2;
  120706. iw+=(ip-1)*ido;
  120707. }
  120708. if(na==0)return;
  120709. for(i=0;i<n;i++)c[i]=ch[i];
  120710. }
  120711. void drft_forward(drft_lookup *l,float *data){
  120712. if(l->n==1)return;
  120713. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120714. }
  120715. void drft_backward(drft_lookup *l,float *data){
  120716. if (l->n==1)return;
  120717. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120718. }
  120719. void drft_init(drft_lookup *l,int n){
  120720. l->n=n;
  120721. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120722. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120723. fdrffti(n, l->trigcache, l->splitcache);
  120724. }
  120725. void drft_clear(drft_lookup *l){
  120726. if(l){
  120727. if(l->trigcache)_ogg_free(l->trigcache);
  120728. if(l->splitcache)_ogg_free(l->splitcache);
  120729. memset(l,0,sizeof(*l));
  120730. }
  120731. }
  120732. #endif
  120733. /*** End of inlined file: smallft.c ***/
  120734. /*** Start of inlined file: synthesis.c ***/
  120735. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120736. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120737. // tasks..
  120738. #if JUCE_MSVC
  120739. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120740. #endif
  120741. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120742. #if JUCE_USE_OGGVORBIS
  120743. #include <stdio.h>
  120744. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120745. vorbis_dsp_state *vd=vb->vd;
  120746. private_state *b=(private_state*)vd->backend_state;
  120747. vorbis_info *vi=vd->vi;
  120748. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120749. oggpack_buffer *opb=&vb->opb;
  120750. int type,mode,i;
  120751. /* first things first. Make sure decode is ready */
  120752. _vorbis_block_ripcord(vb);
  120753. oggpack_readinit(opb,op->packet,op->bytes);
  120754. /* Check the packet type */
  120755. if(oggpack_read(opb,1)!=0){
  120756. /* Oops. This is not an audio data packet */
  120757. return(OV_ENOTAUDIO);
  120758. }
  120759. /* read our mode and pre/post windowsize */
  120760. mode=oggpack_read(opb,b->modebits);
  120761. if(mode==-1)return(OV_EBADPACKET);
  120762. vb->mode=mode;
  120763. vb->W=ci->mode_param[mode]->blockflag;
  120764. if(vb->W){
  120765. /* this doesn;t get mapped through mode selection as it's used
  120766. only for window selection */
  120767. vb->lW=oggpack_read(opb,1);
  120768. vb->nW=oggpack_read(opb,1);
  120769. if(vb->nW==-1) return(OV_EBADPACKET);
  120770. }else{
  120771. vb->lW=0;
  120772. vb->nW=0;
  120773. }
  120774. /* more setup */
  120775. vb->granulepos=op->granulepos;
  120776. vb->sequence=op->packetno;
  120777. vb->eofflag=op->e_o_s;
  120778. /* alloc pcm passback storage */
  120779. vb->pcmend=ci->blocksizes[vb->W];
  120780. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120781. for(i=0;i<vi->channels;i++)
  120782. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120783. /* unpack_header enforces range checking */
  120784. type=ci->map_type[ci->mode_param[mode]->mapping];
  120785. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120786. mapping]));
  120787. }
  120788. /* used to track pcm position without actually performing decode.
  120789. Useful for sequential 'fast forward' */
  120790. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120791. vorbis_dsp_state *vd=vb->vd;
  120792. private_state *b=(private_state*)vd->backend_state;
  120793. vorbis_info *vi=vd->vi;
  120794. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120795. oggpack_buffer *opb=&vb->opb;
  120796. int mode;
  120797. /* first things first. Make sure decode is ready */
  120798. _vorbis_block_ripcord(vb);
  120799. oggpack_readinit(opb,op->packet,op->bytes);
  120800. /* Check the packet type */
  120801. if(oggpack_read(opb,1)!=0){
  120802. /* Oops. This is not an audio data packet */
  120803. return(OV_ENOTAUDIO);
  120804. }
  120805. /* read our mode and pre/post windowsize */
  120806. mode=oggpack_read(opb,b->modebits);
  120807. if(mode==-1)return(OV_EBADPACKET);
  120808. vb->mode=mode;
  120809. vb->W=ci->mode_param[mode]->blockflag;
  120810. if(vb->W){
  120811. vb->lW=oggpack_read(opb,1);
  120812. vb->nW=oggpack_read(opb,1);
  120813. if(vb->nW==-1) return(OV_EBADPACKET);
  120814. }else{
  120815. vb->lW=0;
  120816. vb->nW=0;
  120817. }
  120818. /* more setup */
  120819. vb->granulepos=op->granulepos;
  120820. vb->sequence=op->packetno;
  120821. vb->eofflag=op->e_o_s;
  120822. /* no pcm */
  120823. vb->pcmend=0;
  120824. vb->pcm=NULL;
  120825. return(0);
  120826. }
  120827. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120828. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120829. oggpack_buffer opb;
  120830. int mode;
  120831. oggpack_readinit(&opb,op->packet,op->bytes);
  120832. /* Check the packet type */
  120833. if(oggpack_read(&opb,1)!=0){
  120834. /* Oops. This is not an audio data packet */
  120835. return(OV_ENOTAUDIO);
  120836. }
  120837. {
  120838. int modebits=0;
  120839. int v=ci->modes;
  120840. while(v>1){
  120841. modebits++;
  120842. v>>=1;
  120843. }
  120844. /* read our mode and pre/post windowsize */
  120845. mode=oggpack_read(&opb,modebits);
  120846. }
  120847. if(mode==-1)return(OV_EBADPACKET);
  120848. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120849. }
  120850. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120851. /* set / clear half-sample-rate mode */
  120852. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120853. /* right now, our MDCT can't handle < 64 sample windows. */
  120854. if(ci->blocksizes[0]<=64 && flag)return -1;
  120855. ci->halfrate_flag=(flag?1:0);
  120856. return 0;
  120857. }
  120858. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120859. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120860. return ci->halfrate_flag;
  120861. }
  120862. #endif
  120863. /*** End of inlined file: synthesis.c ***/
  120864. /*** Start of inlined file: vorbisenc.c ***/
  120865. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120866. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120867. // tasks..
  120868. #if JUCE_MSVC
  120869. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120870. #endif
  120871. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120872. #if JUCE_USE_OGGVORBIS
  120873. #include <stdlib.h>
  120874. #include <string.h>
  120875. #include <math.h>
  120876. /* careful with this; it's using static array sizing to make managing
  120877. all the modes a little less annoying. If we use a residue backend
  120878. with > 12 partition types, or a different division of iteration,
  120879. this needs to be updated. */
  120880. typedef struct {
  120881. static_codebook *books[12][3];
  120882. } static_bookblock;
  120883. typedef struct {
  120884. int res_type;
  120885. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120886. vorbis_info_residue0 *res;
  120887. static_codebook *book_aux;
  120888. static_codebook *book_aux_managed;
  120889. static_bookblock *books_base;
  120890. static_bookblock *books_base_managed;
  120891. } vorbis_residue_template;
  120892. typedef struct {
  120893. vorbis_info_mapping0 *map;
  120894. vorbis_residue_template *res;
  120895. } vorbis_mapping_template;
  120896. typedef struct vp_adjblock{
  120897. int block[P_BANDS];
  120898. } vp_adjblock;
  120899. typedef struct {
  120900. int data[NOISE_COMPAND_LEVELS];
  120901. } compandblock;
  120902. /* high level configuration information for setting things up
  120903. step-by-step with the detailed vorbis_encode_ctl interface.
  120904. There's a fair amount of redundancy such that interactive setup
  120905. does not directly deal with any vorbis_info or codec_setup_info
  120906. initialization; it's all stored (until full init) in this highlevel
  120907. setup, then flushed out to the real codec setup structs later. */
  120908. typedef struct {
  120909. int att[P_NOISECURVES];
  120910. float boost;
  120911. float decay;
  120912. } att3;
  120913. typedef struct { int data[P_NOISECURVES]; } adj3;
  120914. typedef struct {
  120915. int pre[PACKETBLOBS];
  120916. int post[PACKETBLOBS];
  120917. float kHz[PACKETBLOBS];
  120918. float lowpasskHz[PACKETBLOBS];
  120919. } adj_stereo;
  120920. typedef struct {
  120921. int lo;
  120922. int hi;
  120923. int fixed;
  120924. } noiseguard;
  120925. typedef struct {
  120926. int data[P_NOISECURVES][17];
  120927. } noise3;
  120928. typedef struct {
  120929. int mappings;
  120930. double *rate_mapping;
  120931. double *quality_mapping;
  120932. int coupling_restriction;
  120933. long samplerate_min_restriction;
  120934. long samplerate_max_restriction;
  120935. int *blocksize_short;
  120936. int *blocksize_long;
  120937. att3 *psy_tone_masteratt;
  120938. int *psy_tone_0dB;
  120939. int *psy_tone_dBsuppress;
  120940. vp_adjblock *psy_tone_adj_impulse;
  120941. vp_adjblock *psy_tone_adj_long;
  120942. vp_adjblock *psy_tone_adj_other;
  120943. noiseguard *psy_noiseguards;
  120944. noise3 *psy_noise_bias_impulse;
  120945. noise3 *psy_noise_bias_padding;
  120946. noise3 *psy_noise_bias_trans;
  120947. noise3 *psy_noise_bias_long;
  120948. int *psy_noise_dBsuppress;
  120949. compandblock *psy_noise_compand;
  120950. double *psy_noise_compand_short_mapping;
  120951. double *psy_noise_compand_long_mapping;
  120952. int *psy_noise_normal_start[2];
  120953. int *psy_noise_normal_partition[2];
  120954. double *psy_noise_normal_thresh;
  120955. int *psy_ath_float;
  120956. int *psy_ath_abs;
  120957. double *psy_lowpass;
  120958. vorbis_info_psy_global *global_params;
  120959. double *global_mapping;
  120960. adj_stereo *stereo_modes;
  120961. static_codebook ***floor_books;
  120962. vorbis_info_floor1 *floor_params;
  120963. int *floor_short_mapping;
  120964. int *floor_long_mapping;
  120965. vorbis_mapping_template *maps;
  120966. } ve_setup_data_template;
  120967. /* a few static coder conventions */
  120968. static vorbis_info_mode _mode_template[2]={
  120969. {0,0,0,0},
  120970. {1,0,0,1}
  120971. };
  120972. static vorbis_info_mapping0 _map_nominal[2]={
  120973. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120974. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120975. };
  120976. /*** Start of inlined file: setup_44.h ***/
  120977. /*** Start of inlined file: floor_all.h ***/
  120978. /*** Start of inlined file: floor_books.h ***/
  120979. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120980. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120981. };
  120982. static static_codebook _huff_book_line_256x7_0sub1 = {
  120983. 1, 9,
  120984. _huff_lengthlist_line_256x7_0sub1,
  120985. 0, 0, 0, 0, 0,
  120986. NULL,
  120987. NULL,
  120988. NULL,
  120989. NULL,
  120990. 0
  120991. };
  120992. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120994. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120995. };
  120996. static static_codebook _huff_book_line_256x7_0sub2 = {
  120997. 1, 25,
  120998. _huff_lengthlist_line_256x7_0sub2,
  120999. 0, 0, 0, 0, 0,
  121000. NULL,
  121001. NULL,
  121002. NULL,
  121003. NULL,
  121004. 0
  121005. };
  121006. static long _huff_lengthlist_line_256x7_0sub3[] = {
  121007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  121009. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  121010. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  121011. };
  121012. static static_codebook _huff_book_line_256x7_0sub3 = {
  121013. 1, 64,
  121014. _huff_lengthlist_line_256x7_0sub3,
  121015. 0, 0, 0, 0, 0,
  121016. NULL,
  121017. NULL,
  121018. NULL,
  121019. NULL,
  121020. 0
  121021. };
  121022. static long _huff_lengthlist_line_256x7_1sub1[] = {
  121023. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  121024. };
  121025. static static_codebook _huff_book_line_256x7_1sub1 = {
  121026. 1, 9,
  121027. _huff_lengthlist_line_256x7_1sub1,
  121028. 0, 0, 0, 0, 0,
  121029. NULL,
  121030. NULL,
  121031. NULL,
  121032. NULL,
  121033. 0
  121034. };
  121035. static long _huff_lengthlist_line_256x7_1sub2[] = {
  121036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  121037. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  121038. };
  121039. static static_codebook _huff_book_line_256x7_1sub2 = {
  121040. 1, 25,
  121041. _huff_lengthlist_line_256x7_1sub2,
  121042. 0, 0, 0, 0, 0,
  121043. NULL,
  121044. NULL,
  121045. NULL,
  121046. NULL,
  121047. 0
  121048. };
  121049. static long _huff_lengthlist_line_256x7_1sub3[] = {
  121050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  121052. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121053. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  121054. };
  121055. static static_codebook _huff_book_line_256x7_1sub3 = {
  121056. 1, 64,
  121057. _huff_lengthlist_line_256x7_1sub3,
  121058. 0, 0, 0, 0, 0,
  121059. NULL,
  121060. NULL,
  121061. NULL,
  121062. NULL,
  121063. 0
  121064. };
  121065. static long _huff_lengthlist_line_256x7_class0[] = {
  121066. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  121067. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  121068. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  121069. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  121070. };
  121071. static static_codebook _huff_book_line_256x7_class0 = {
  121072. 1, 64,
  121073. _huff_lengthlist_line_256x7_class0,
  121074. 0, 0, 0, 0, 0,
  121075. NULL,
  121076. NULL,
  121077. NULL,
  121078. NULL,
  121079. 0
  121080. };
  121081. static long _huff_lengthlist_line_256x7_class1[] = {
  121082. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  121083. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  121084. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  121085. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  121086. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  121087. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  121088. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  121089. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  121090. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  121091. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  121092. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  121093. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  121094. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121095. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121096. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  121097. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  121098. };
  121099. static static_codebook _huff_book_line_256x7_class1 = {
  121100. 1, 256,
  121101. _huff_lengthlist_line_256x7_class1,
  121102. 0, 0, 0, 0, 0,
  121103. NULL,
  121104. NULL,
  121105. NULL,
  121106. NULL,
  121107. 0
  121108. };
  121109. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121110. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121111. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121112. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121113. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121114. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121115. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121116. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121117. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121118. };
  121119. static static_codebook _huff_book_line_512x17_0sub0 = {
  121120. 1, 128,
  121121. _huff_lengthlist_line_512x17_0sub0,
  121122. 0, 0, 0, 0, 0,
  121123. NULL,
  121124. NULL,
  121125. NULL,
  121126. NULL,
  121127. 0
  121128. };
  121129. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121130. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121131. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121132. };
  121133. static static_codebook _huff_book_line_512x17_1sub0 = {
  121134. 1, 32,
  121135. _huff_lengthlist_line_512x17_1sub0,
  121136. 0, 0, 0, 0, 0,
  121137. NULL,
  121138. NULL,
  121139. NULL,
  121140. NULL,
  121141. 0
  121142. };
  121143. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121146. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121147. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121148. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121149. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121150. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121151. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121152. };
  121153. static static_codebook _huff_book_line_512x17_1sub1 = {
  121154. 1, 128,
  121155. _huff_lengthlist_line_512x17_1sub1,
  121156. 0, 0, 0, 0, 0,
  121157. NULL,
  121158. NULL,
  121159. NULL,
  121160. NULL,
  121161. 0
  121162. };
  121163. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121164. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121165. 5, 3,
  121166. };
  121167. static static_codebook _huff_book_line_512x17_2sub1 = {
  121168. 1, 18,
  121169. _huff_lengthlist_line_512x17_2sub1,
  121170. 0, 0, 0, 0, 0,
  121171. NULL,
  121172. NULL,
  121173. NULL,
  121174. NULL,
  121175. 0
  121176. };
  121177. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121179. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121180. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121181. 9, 8,
  121182. };
  121183. static static_codebook _huff_book_line_512x17_2sub2 = {
  121184. 1, 50,
  121185. _huff_lengthlist_line_512x17_2sub2,
  121186. 0, 0, 0, 0, 0,
  121187. NULL,
  121188. NULL,
  121189. NULL,
  121190. NULL,
  121191. 0
  121192. };
  121193. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121197. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121198. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121199. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121200. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121201. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121202. };
  121203. static static_codebook _huff_book_line_512x17_2sub3 = {
  121204. 1, 128,
  121205. _huff_lengthlist_line_512x17_2sub3,
  121206. 0, 0, 0, 0, 0,
  121207. NULL,
  121208. NULL,
  121209. NULL,
  121210. NULL,
  121211. 0
  121212. };
  121213. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121214. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121215. 5, 5,
  121216. };
  121217. static static_codebook _huff_book_line_512x17_3sub1 = {
  121218. 1, 18,
  121219. _huff_lengthlist_line_512x17_3sub1,
  121220. 0, 0, 0, 0, 0,
  121221. NULL,
  121222. NULL,
  121223. NULL,
  121224. NULL,
  121225. 0
  121226. };
  121227. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121229. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121230. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121231. 11,14,
  121232. };
  121233. static static_codebook _huff_book_line_512x17_3sub2 = {
  121234. 1, 50,
  121235. _huff_lengthlist_line_512x17_3sub2,
  121236. 0, 0, 0, 0, 0,
  121237. NULL,
  121238. NULL,
  121239. NULL,
  121240. NULL,
  121241. 0
  121242. };
  121243. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121247. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121248. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121249. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121250. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121251. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121252. };
  121253. static static_codebook _huff_book_line_512x17_3sub3 = {
  121254. 1, 128,
  121255. _huff_lengthlist_line_512x17_3sub3,
  121256. 0, 0, 0, 0, 0,
  121257. NULL,
  121258. NULL,
  121259. NULL,
  121260. NULL,
  121261. 0
  121262. };
  121263. static long _huff_lengthlist_line_512x17_class1[] = {
  121264. 1, 2, 3, 6, 5, 4, 7, 7,
  121265. };
  121266. static static_codebook _huff_book_line_512x17_class1 = {
  121267. 1, 8,
  121268. _huff_lengthlist_line_512x17_class1,
  121269. 0, 0, 0, 0, 0,
  121270. NULL,
  121271. NULL,
  121272. NULL,
  121273. NULL,
  121274. 0
  121275. };
  121276. static long _huff_lengthlist_line_512x17_class2[] = {
  121277. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121278. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121279. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121280. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121281. };
  121282. static static_codebook _huff_book_line_512x17_class2 = {
  121283. 1, 64,
  121284. _huff_lengthlist_line_512x17_class2,
  121285. 0, 0, 0, 0, 0,
  121286. NULL,
  121287. NULL,
  121288. NULL,
  121289. NULL,
  121290. 0
  121291. };
  121292. static long _huff_lengthlist_line_512x17_class3[] = {
  121293. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121294. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121295. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121296. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121297. };
  121298. static static_codebook _huff_book_line_512x17_class3 = {
  121299. 1, 64,
  121300. _huff_lengthlist_line_512x17_class3,
  121301. 0, 0, 0, 0, 0,
  121302. NULL,
  121303. NULL,
  121304. NULL,
  121305. NULL,
  121306. 0
  121307. };
  121308. static long _huff_lengthlist_line_128x4_class0[] = {
  121309. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121310. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121311. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121312. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121313. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121314. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121315. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121316. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121317. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121318. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121319. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121320. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121321. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121322. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121323. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121324. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121325. };
  121326. static static_codebook _huff_book_line_128x4_class0 = {
  121327. 1, 256,
  121328. _huff_lengthlist_line_128x4_class0,
  121329. 0, 0, 0, 0, 0,
  121330. NULL,
  121331. NULL,
  121332. NULL,
  121333. NULL,
  121334. 0
  121335. };
  121336. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121337. 2, 2, 2, 2,
  121338. };
  121339. static static_codebook _huff_book_line_128x4_0sub0 = {
  121340. 1, 4,
  121341. _huff_lengthlist_line_128x4_0sub0,
  121342. 0, 0, 0, 0, 0,
  121343. NULL,
  121344. NULL,
  121345. NULL,
  121346. NULL,
  121347. 0
  121348. };
  121349. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121350. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121351. };
  121352. static static_codebook _huff_book_line_128x4_0sub1 = {
  121353. 1, 10,
  121354. _huff_lengthlist_line_128x4_0sub1,
  121355. 0, 0, 0, 0, 0,
  121356. NULL,
  121357. NULL,
  121358. NULL,
  121359. NULL,
  121360. 0
  121361. };
  121362. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121364. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121365. };
  121366. static static_codebook _huff_book_line_128x4_0sub2 = {
  121367. 1, 25,
  121368. _huff_lengthlist_line_128x4_0sub2,
  121369. 0, 0, 0, 0, 0,
  121370. NULL,
  121371. NULL,
  121372. NULL,
  121373. NULL,
  121374. 0
  121375. };
  121376. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121379. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121380. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121381. };
  121382. static static_codebook _huff_book_line_128x4_0sub3 = {
  121383. 1, 64,
  121384. _huff_lengthlist_line_128x4_0sub3,
  121385. 0, 0, 0, 0, 0,
  121386. NULL,
  121387. NULL,
  121388. NULL,
  121389. NULL,
  121390. 0
  121391. };
  121392. static long _huff_lengthlist_line_256x4_class0[] = {
  121393. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121394. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121395. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121396. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121397. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121398. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121399. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121400. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121401. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121402. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121403. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121404. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121405. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121406. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121407. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121408. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121409. };
  121410. static static_codebook _huff_book_line_256x4_class0 = {
  121411. 1, 256,
  121412. _huff_lengthlist_line_256x4_class0,
  121413. 0, 0, 0, 0, 0,
  121414. NULL,
  121415. NULL,
  121416. NULL,
  121417. NULL,
  121418. 0
  121419. };
  121420. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121421. 2, 2, 2, 2,
  121422. };
  121423. static static_codebook _huff_book_line_256x4_0sub0 = {
  121424. 1, 4,
  121425. _huff_lengthlist_line_256x4_0sub0,
  121426. 0, 0, 0, 0, 0,
  121427. NULL,
  121428. NULL,
  121429. NULL,
  121430. NULL,
  121431. 0
  121432. };
  121433. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121434. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121435. };
  121436. static static_codebook _huff_book_line_256x4_0sub1 = {
  121437. 1, 10,
  121438. _huff_lengthlist_line_256x4_0sub1,
  121439. 0, 0, 0, 0, 0,
  121440. NULL,
  121441. NULL,
  121442. NULL,
  121443. NULL,
  121444. 0
  121445. };
  121446. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121448. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121449. };
  121450. static static_codebook _huff_book_line_256x4_0sub2 = {
  121451. 1, 25,
  121452. _huff_lengthlist_line_256x4_0sub2,
  121453. 0, 0, 0, 0, 0,
  121454. NULL,
  121455. NULL,
  121456. NULL,
  121457. NULL,
  121458. 0
  121459. };
  121460. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121463. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121464. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121465. };
  121466. static static_codebook _huff_book_line_256x4_0sub3 = {
  121467. 1, 64,
  121468. _huff_lengthlist_line_256x4_0sub3,
  121469. 0, 0, 0, 0, 0,
  121470. NULL,
  121471. NULL,
  121472. NULL,
  121473. NULL,
  121474. 0
  121475. };
  121476. static long _huff_lengthlist_line_128x7_class0[] = {
  121477. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121478. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121479. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121480. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121481. };
  121482. static static_codebook _huff_book_line_128x7_class0 = {
  121483. 1, 64,
  121484. _huff_lengthlist_line_128x7_class0,
  121485. 0, 0, 0, 0, 0,
  121486. NULL,
  121487. NULL,
  121488. NULL,
  121489. NULL,
  121490. 0
  121491. };
  121492. static long _huff_lengthlist_line_128x7_class1[] = {
  121493. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121494. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121495. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121496. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121497. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121498. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121499. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121500. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121501. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121502. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121503. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121504. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121505. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121506. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121507. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121508. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121509. };
  121510. static static_codebook _huff_book_line_128x7_class1 = {
  121511. 1, 256,
  121512. _huff_lengthlist_line_128x7_class1,
  121513. 0, 0, 0, 0, 0,
  121514. NULL,
  121515. NULL,
  121516. NULL,
  121517. NULL,
  121518. 0
  121519. };
  121520. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121521. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121522. };
  121523. static static_codebook _huff_book_line_128x7_0sub1 = {
  121524. 1, 9,
  121525. _huff_lengthlist_line_128x7_0sub1,
  121526. 0, 0, 0, 0, 0,
  121527. NULL,
  121528. NULL,
  121529. NULL,
  121530. NULL,
  121531. 0
  121532. };
  121533. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121535. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121536. };
  121537. static static_codebook _huff_book_line_128x7_0sub2 = {
  121538. 1, 25,
  121539. _huff_lengthlist_line_128x7_0sub2,
  121540. 0, 0, 0, 0, 0,
  121541. NULL,
  121542. NULL,
  121543. NULL,
  121544. NULL,
  121545. 0
  121546. };
  121547. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121550. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121551. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121552. };
  121553. static static_codebook _huff_book_line_128x7_0sub3 = {
  121554. 1, 64,
  121555. _huff_lengthlist_line_128x7_0sub3,
  121556. 0, 0, 0, 0, 0,
  121557. NULL,
  121558. NULL,
  121559. NULL,
  121560. NULL,
  121561. 0
  121562. };
  121563. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121564. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121565. };
  121566. static static_codebook _huff_book_line_128x7_1sub1 = {
  121567. 1, 9,
  121568. _huff_lengthlist_line_128x7_1sub1,
  121569. 0, 0, 0, 0, 0,
  121570. NULL,
  121571. NULL,
  121572. NULL,
  121573. NULL,
  121574. 0
  121575. };
  121576. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121578. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121579. };
  121580. static static_codebook _huff_book_line_128x7_1sub2 = {
  121581. 1, 25,
  121582. _huff_lengthlist_line_128x7_1sub2,
  121583. 0, 0, 0, 0, 0,
  121584. NULL,
  121585. NULL,
  121586. NULL,
  121587. NULL,
  121588. 0
  121589. };
  121590. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121593. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121594. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121595. };
  121596. static static_codebook _huff_book_line_128x7_1sub3 = {
  121597. 1, 64,
  121598. _huff_lengthlist_line_128x7_1sub3,
  121599. 0, 0, 0, 0, 0,
  121600. NULL,
  121601. NULL,
  121602. NULL,
  121603. NULL,
  121604. 0
  121605. };
  121606. static long _huff_lengthlist_line_128x11_class1[] = {
  121607. 1, 6, 3, 7, 2, 4, 5, 7,
  121608. };
  121609. static static_codebook _huff_book_line_128x11_class1 = {
  121610. 1, 8,
  121611. _huff_lengthlist_line_128x11_class1,
  121612. 0, 0, 0, 0, 0,
  121613. NULL,
  121614. NULL,
  121615. NULL,
  121616. NULL,
  121617. 0
  121618. };
  121619. static long _huff_lengthlist_line_128x11_class2[] = {
  121620. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121621. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121622. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121623. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121624. };
  121625. static static_codebook _huff_book_line_128x11_class2 = {
  121626. 1, 64,
  121627. _huff_lengthlist_line_128x11_class2,
  121628. 0, 0, 0, 0, 0,
  121629. NULL,
  121630. NULL,
  121631. NULL,
  121632. NULL,
  121633. 0
  121634. };
  121635. static long _huff_lengthlist_line_128x11_class3[] = {
  121636. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121637. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121638. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121639. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121640. };
  121641. static static_codebook _huff_book_line_128x11_class3 = {
  121642. 1, 64,
  121643. _huff_lengthlist_line_128x11_class3,
  121644. 0, 0, 0, 0, 0,
  121645. NULL,
  121646. NULL,
  121647. NULL,
  121648. NULL,
  121649. 0
  121650. };
  121651. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121652. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121653. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121654. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121655. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121656. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121657. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121658. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121659. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121660. };
  121661. static static_codebook _huff_book_line_128x11_0sub0 = {
  121662. 1, 128,
  121663. _huff_lengthlist_line_128x11_0sub0,
  121664. 0, 0, 0, 0, 0,
  121665. NULL,
  121666. NULL,
  121667. NULL,
  121668. NULL,
  121669. 0
  121670. };
  121671. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121672. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121673. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121674. };
  121675. static static_codebook _huff_book_line_128x11_1sub0 = {
  121676. 1, 32,
  121677. _huff_lengthlist_line_128x11_1sub0,
  121678. 0, 0, 0, 0, 0,
  121679. NULL,
  121680. NULL,
  121681. NULL,
  121682. NULL,
  121683. 0
  121684. };
  121685. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121688. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121689. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121690. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121691. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121692. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121693. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121694. };
  121695. static static_codebook _huff_book_line_128x11_1sub1 = {
  121696. 1, 128,
  121697. _huff_lengthlist_line_128x11_1sub1,
  121698. 0, 0, 0, 0, 0,
  121699. NULL,
  121700. NULL,
  121701. NULL,
  121702. NULL,
  121703. 0
  121704. };
  121705. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121706. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121707. 5, 5,
  121708. };
  121709. static static_codebook _huff_book_line_128x11_2sub1 = {
  121710. 1, 18,
  121711. _huff_lengthlist_line_128x11_2sub1,
  121712. 0, 0, 0, 0, 0,
  121713. NULL,
  121714. NULL,
  121715. NULL,
  121716. NULL,
  121717. 0
  121718. };
  121719. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121721. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121722. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121723. 8,11,
  121724. };
  121725. static static_codebook _huff_book_line_128x11_2sub2 = {
  121726. 1, 50,
  121727. _huff_lengthlist_line_128x11_2sub2,
  121728. 0, 0, 0, 0, 0,
  121729. NULL,
  121730. NULL,
  121731. NULL,
  121732. NULL,
  121733. 0
  121734. };
  121735. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121739. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121740. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121741. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121742. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121743. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121744. };
  121745. static static_codebook _huff_book_line_128x11_2sub3 = {
  121746. 1, 128,
  121747. _huff_lengthlist_line_128x11_2sub3,
  121748. 0, 0, 0, 0, 0,
  121749. NULL,
  121750. NULL,
  121751. NULL,
  121752. NULL,
  121753. 0
  121754. };
  121755. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121756. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121757. 5, 4,
  121758. };
  121759. static static_codebook _huff_book_line_128x11_3sub1 = {
  121760. 1, 18,
  121761. _huff_lengthlist_line_128x11_3sub1,
  121762. 0, 0, 0, 0, 0,
  121763. NULL,
  121764. NULL,
  121765. NULL,
  121766. NULL,
  121767. 0
  121768. };
  121769. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121771. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121772. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121773. 12, 6,
  121774. };
  121775. static static_codebook _huff_book_line_128x11_3sub2 = {
  121776. 1, 50,
  121777. _huff_lengthlist_line_128x11_3sub2,
  121778. 0, 0, 0, 0, 0,
  121779. NULL,
  121780. NULL,
  121781. NULL,
  121782. NULL,
  121783. 0
  121784. };
  121785. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121789. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121790. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121793. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121794. };
  121795. static static_codebook _huff_book_line_128x11_3sub3 = {
  121796. 1, 128,
  121797. _huff_lengthlist_line_128x11_3sub3,
  121798. 0, 0, 0, 0, 0,
  121799. NULL,
  121800. NULL,
  121801. NULL,
  121802. NULL,
  121803. 0
  121804. };
  121805. static long _huff_lengthlist_line_128x17_class1[] = {
  121806. 1, 3, 4, 7, 2, 5, 6, 7,
  121807. };
  121808. static static_codebook _huff_book_line_128x17_class1 = {
  121809. 1, 8,
  121810. _huff_lengthlist_line_128x17_class1,
  121811. 0, 0, 0, 0, 0,
  121812. NULL,
  121813. NULL,
  121814. NULL,
  121815. NULL,
  121816. 0
  121817. };
  121818. static long _huff_lengthlist_line_128x17_class2[] = {
  121819. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121820. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121821. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121822. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121823. };
  121824. static static_codebook _huff_book_line_128x17_class2 = {
  121825. 1, 64,
  121826. _huff_lengthlist_line_128x17_class2,
  121827. 0, 0, 0, 0, 0,
  121828. NULL,
  121829. NULL,
  121830. NULL,
  121831. NULL,
  121832. 0
  121833. };
  121834. static long _huff_lengthlist_line_128x17_class3[] = {
  121835. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121836. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121837. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121838. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121839. };
  121840. static static_codebook _huff_book_line_128x17_class3 = {
  121841. 1, 64,
  121842. _huff_lengthlist_line_128x17_class3,
  121843. 0, 0, 0, 0, 0,
  121844. NULL,
  121845. NULL,
  121846. NULL,
  121847. NULL,
  121848. 0
  121849. };
  121850. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121851. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121852. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121853. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121854. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121855. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121856. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121857. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121858. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121859. };
  121860. static static_codebook _huff_book_line_128x17_0sub0 = {
  121861. 1, 128,
  121862. _huff_lengthlist_line_128x17_0sub0,
  121863. 0, 0, 0, 0, 0,
  121864. NULL,
  121865. NULL,
  121866. NULL,
  121867. NULL,
  121868. 0
  121869. };
  121870. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121871. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121872. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121873. };
  121874. static static_codebook _huff_book_line_128x17_1sub0 = {
  121875. 1, 32,
  121876. _huff_lengthlist_line_128x17_1sub0,
  121877. 0, 0, 0, 0, 0,
  121878. NULL,
  121879. NULL,
  121880. NULL,
  121881. NULL,
  121882. 0
  121883. };
  121884. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121887. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121888. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121889. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121890. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121891. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121892. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121893. };
  121894. static static_codebook _huff_book_line_128x17_1sub1 = {
  121895. 1, 128,
  121896. _huff_lengthlist_line_128x17_1sub1,
  121897. 0, 0, 0, 0, 0,
  121898. NULL,
  121899. NULL,
  121900. NULL,
  121901. NULL,
  121902. 0
  121903. };
  121904. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121905. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121906. 9, 4,
  121907. };
  121908. static static_codebook _huff_book_line_128x17_2sub1 = {
  121909. 1, 18,
  121910. _huff_lengthlist_line_128x17_2sub1,
  121911. 0, 0, 0, 0, 0,
  121912. NULL,
  121913. NULL,
  121914. NULL,
  121915. NULL,
  121916. 0
  121917. };
  121918. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121920. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121921. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121922. 13,13,
  121923. };
  121924. static static_codebook _huff_book_line_128x17_2sub2 = {
  121925. 1, 50,
  121926. _huff_lengthlist_line_128x17_2sub2,
  121927. 0, 0, 0, 0, 0,
  121928. NULL,
  121929. NULL,
  121930. NULL,
  121931. NULL,
  121932. 0
  121933. };
  121934. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121938. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121939. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121940. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121941. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121942. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121943. };
  121944. static static_codebook _huff_book_line_128x17_2sub3 = {
  121945. 1, 128,
  121946. _huff_lengthlist_line_128x17_2sub3,
  121947. 0, 0, 0, 0, 0,
  121948. NULL,
  121949. NULL,
  121950. NULL,
  121951. NULL,
  121952. 0
  121953. };
  121954. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121955. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121956. 6, 4,
  121957. };
  121958. static static_codebook _huff_book_line_128x17_3sub1 = {
  121959. 1, 18,
  121960. _huff_lengthlist_line_128x17_3sub1,
  121961. 0, 0, 0, 0, 0,
  121962. NULL,
  121963. NULL,
  121964. NULL,
  121965. NULL,
  121966. 0
  121967. };
  121968. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121970. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121971. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121972. 10, 8,
  121973. };
  121974. static static_codebook _huff_book_line_128x17_3sub2 = {
  121975. 1, 50,
  121976. _huff_lengthlist_line_128x17_3sub2,
  121977. 0, 0, 0, 0, 0,
  121978. NULL,
  121979. NULL,
  121980. NULL,
  121981. NULL,
  121982. 0
  121983. };
  121984. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121988. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121989. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121990. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121991. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121992. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121993. };
  121994. static static_codebook _huff_book_line_128x17_3sub3 = {
  121995. 1, 128,
  121996. _huff_lengthlist_line_128x17_3sub3,
  121997. 0, 0, 0, 0, 0,
  121998. NULL,
  121999. NULL,
  122000. NULL,
  122001. NULL,
  122002. 0
  122003. };
  122004. static long _huff_lengthlist_line_1024x27_class1[] = {
  122005. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  122006. };
  122007. static static_codebook _huff_book_line_1024x27_class1 = {
  122008. 1, 16,
  122009. _huff_lengthlist_line_1024x27_class1,
  122010. 0, 0, 0, 0, 0,
  122011. NULL,
  122012. NULL,
  122013. NULL,
  122014. NULL,
  122015. 0
  122016. };
  122017. static long _huff_lengthlist_line_1024x27_class2[] = {
  122018. 1, 4, 2, 6, 3, 7, 5, 7,
  122019. };
  122020. static static_codebook _huff_book_line_1024x27_class2 = {
  122021. 1, 8,
  122022. _huff_lengthlist_line_1024x27_class2,
  122023. 0, 0, 0, 0, 0,
  122024. NULL,
  122025. NULL,
  122026. NULL,
  122027. NULL,
  122028. 0
  122029. };
  122030. static long _huff_lengthlist_line_1024x27_class3[] = {
  122031. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  122032. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  122033. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  122034. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  122035. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  122036. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  122037. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  122038. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  122039. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  122040. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  122041. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  122042. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122043. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  122044. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  122045. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  122046. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122047. };
  122048. static static_codebook _huff_book_line_1024x27_class3 = {
  122049. 1, 256,
  122050. _huff_lengthlist_line_1024x27_class3,
  122051. 0, 0, 0, 0, 0,
  122052. NULL,
  122053. NULL,
  122054. NULL,
  122055. NULL,
  122056. 0
  122057. };
  122058. static long _huff_lengthlist_line_1024x27_class4[] = {
  122059. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  122060. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  122061. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  122062. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  122063. };
  122064. static static_codebook _huff_book_line_1024x27_class4 = {
  122065. 1, 64,
  122066. _huff_lengthlist_line_1024x27_class4,
  122067. 0, 0, 0, 0, 0,
  122068. NULL,
  122069. NULL,
  122070. NULL,
  122071. NULL,
  122072. 0
  122073. };
  122074. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  122075. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122076. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  122077. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  122078. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  122079. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  122080. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  122081. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  122082. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  122083. };
  122084. static static_codebook _huff_book_line_1024x27_0sub0 = {
  122085. 1, 128,
  122086. _huff_lengthlist_line_1024x27_0sub0,
  122087. 0, 0, 0, 0, 0,
  122088. NULL,
  122089. NULL,
  122090. NULL,
  122091. NULL,
  122092. 0
  122093. };
  122094. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  122095. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  122096. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  122097. };
  122098. static static_codebook _huff_book_line_1024x27_1sub0 = {
  122099. 1, 32,
  122100. _huff_lengthlist_line_1024x27_1sub0,
  122101. 0, 0, 0, 0, 0,
  122102. NULL,
  122103. NULL,
  122104. NULL,
  122105. NULL,
  122106. 0
  122107. };
  122108. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  122109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122111. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122112. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122113. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122114. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122115. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122116. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122117. };
  122118. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122119. 1, 128,
  122120. _huff_lengthlist_line_1024x27_1sub1,
  122121. 0, 0, 0, 0, 0,
  122122. NULL,
  122123. NULL,
  122124. NULL,
  122125. NULL,
  122126. 0
  122127. };
  122128. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122129. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122130. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122131. };
  122132. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122133. 1, 32,
  122134. _huff_lengthlist_line_1024x27_2sub0,
  122135. 0, 0, 0, 0, 0,
  122136. NULL,
  122137. NULL,
  122138. NULL,
  122139. NULL,
  122140. 0
  122141. };
  122142. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  122143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122145. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122146. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122147. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122148. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122149. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122150. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122151. };
  122152. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122153. 1, 128,
  122154. _huff_lengthlist_line_1024x27_2sub1,
  122155. 0, 0, 0, 0, 0,
  122156. NULL,
  122157. NULL,
  122158. NULL,
  122159. NULL,
  122160. 0
  122161. };
  122162. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122163. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122164. 5, 5,
  122165. };
  122166. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122167. 1, 18,
  122168. _huff_lengthlist_line_1024x27_3sub1,
  122169. 0, 0, 0, 0, 0,
  122170. NULL,
  122171. NULL,
  122172. NULL,
  122173. NULL,
  122174. 0
  122175. };
  122176. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122178. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122179. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122180. 9,11,
  122181. };
  122182. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122183. 1, 50,
  122184. _huff_lengthlist_line_1024x27_3sub2,
  122185. 0, 0, 0, 0, 0,
  122186. NULL,
  122187. NULL,
  122188. NULL,
  122189. NULL,
  122190. 0
  122191. };
  122192. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122196. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122197. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122198. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122199. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122200. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122201. };
  122202. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122203. 1, 128,
  122204. _huff_lengthlist_line_1024x27_3sub3,
  122205. 0, 0, 0, 0, 0,
  122206. NULL,
  122207. NULL,
  122208. NULL,
  122209. NULL,
  122210. 0
  122211. };
  122212. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122213. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122214. 5, 4,
  122215. };
  122216. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122217. 1, 18,
  122218. _huff_lengthlist_line_1024x27_4sub1,
  122219. 0, 0, 0, 0, 0,
  122220. NULL,
  122221. NULL,
  122222. NULL,
  122223. NULL,
  122224. 0
  122225. };
  122226. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122228. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122229. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122230. 9,12,
  122231. };
  122232. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122233. 1, 50,
  122234. _huff_lengthlist_line_1024x27_4sub2,
  122235. 0, 0, 0, 0, 0,
  122236. NULL,
  122237. NULL,
  122238. NULL,
  122239. NULL,
  122240. 0
  122241. };
  122242. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122246. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122247. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122249. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122250. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122251. };
  122252. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122253. 1, 128,
  122254. _huff_lengthlist_line_1024x27_4sub3,
  122255. 0, 0, 0, 0, 0,
  122256. NULL,
  122257. NULL,
  122258. NULL,
  122259. NULL,
  122260. 0
  122261. };
  122262. static long _huff_lengthlist_line_2048x27_class1[] = {
  122263. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122264. };
  122265. static static_codebook _huff_book_line_2048x27_class1 = {
  122266. 1, 16,
  122267. _huff_lengthlist_line_2048x27_class1,
  122268. 0, 0, 0, 0, 0,
  122269. NULL,
  122270. NULL,
  122271. NULL,
  122272. NULL,
  122273. 0
  122274. };
  122275. static long _huff_lengthlist_line_2048x27_class2[] = {
  122276. 1, 2, 3, 6, 4, 7, 5, 7,
  122277. };
  122278. static static_codebook _huff_book_line_2048x27_class2 = {
  122279. 1, 8,
  122280. _huff_lengthlist_line_2048x27_class2,
  122281. 0, 0, 0, 0, 0,
  122282. NULL,
  122283. NULL,
  122284. NULL,
  122285. NULL,
  122286. 0
  122287. };
  122288. static long _huff_lengthlist_line_2048x27_class3[] = {
  122289. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122290. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122291. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122292. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122293. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122294. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122295. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122296. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122297. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122298. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122299. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122300. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122301. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122302. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122303. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122304. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122305. };
  122306. static static_codebook _huff_book_line_2048x27_class3 = {
  122307. 1, 256,
  122308. _huff_lengthlist_line_2048x27_class3,
  122309. 0, 0, 0, 0, 0,
  122310. NULL,
  122311. NULL,
  122312. NULL,
  122313. NULL,
  122314. 0
  122315. };
  122316. static long _huff_lengthlist_line_2048x27_class4[] = {
  122317. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122318. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122319. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122320. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122321. };
  122322. static static_codebook _huff_book_line_2048x27_class4 = {
  122323. 1, 64,
  122324. _huff_lengthlist_line_2048x27_class4,
  122325. 0, 0, 0, 0, 0,
  122326. NULL,
  122327. NULL,
  122328. NULL,
  122329. NULL,
  122330. 0
  122331. };
  122332. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122333. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122334. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122335. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122336. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122337. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122338. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122339. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122340. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122341. };
  122342. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122343. 1, 128,
  122344. _huff_lengthlist_line_2048x27_0sub0,
  122345. 0, 0, 0, 0, 0,
  122346. NULL,
  122347. NULL,
  122348. NULL,
  122349. NULL,
  122350. 0
  122351. };
  122352. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122353. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122354. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122355. };
  122356. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122357. 1, 32,
  122358. _huff_lengthlist_line_2048x27_1sub0,
  122359. 0, 0, 0, 0, 0,
  122360. NULL,
  122361. NULL,
  122362. NULL,
  122363. NULL,
  122364. 0
  122365. };
  122366. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122370. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122371. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122372. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122373. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122374. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122375. };
  122376. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122377. 1, 128,
  122378. _huff_lengthlist_line_2048x27_1sub1,
  122379. 0, 0, 0, 0, 0,
  122380. NULL,
  122381. NULL,
  122382. NULL,
  122383. NULL,
  122384. 0
  122385. };
  122386. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122387. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122388. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122389. };
  122390. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122391. 1, 32,
  122392. _huff_lengthlist_line_2048x27_2sub0,
  122393. 0, 0, 0, 0, 0,
  122394. NULL,
  122395. NULL,
  122396. NULL,
  122397. NULL,
  122398. 0
  122399. };
  122400. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122404. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122405. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122406. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122407. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122408. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122409. };
  122410. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122411. 1, 128,
  122412. _huff_lengthlist_line_2048x27_2sub1,
  122413. 0, 0, 0, 0, 0,
  122414. NULL,
  122415. NULL,
  122416. NULL,
  122417. NULL,
  122418. 0
  122419. };
  122420. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122421. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122422. 5, 5,
  122423. };
  122424. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122425. 1, 18,
  122426. _huff_lengthlist_line_2048x27_3sub1,
  122427. 0, 0, 0, 0, 0,
  122428. NULL,
  122429. NULL,
  122430. NULL,
  122431. NULL,
  122432. 0
  122433. };
  122434. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122437. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122438. 10,12,
  122439. };
  122440. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122441. 1, 50,
  122442. _huff_lengthlist_line_2048x27_3sub2,
  122443. 0, 0, 0, 0, 0,
  122444. NULL,
  122445. NULL,
  122446. NULL,
  122447. NULL,
  122448. 0
  122449. };
  122450. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122455. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122456. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122457. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122458. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122459. };
  122460. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122461. 1, 128,
  122462. _huff_lengthlist_line_2048x27_3sub3,
  122463. 0, 0, 0, 0, 0,
  122464. NULL,
  122465. NULL,
  122466. NULL,
  122467. NULL,
  122468. 0
  122469. };
  122470. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122471. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122472. 4, 5,
  122473. };
  122474. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122475. 1, 18,
  122476. _huff_lengthlist_line_2048x27_4sub1,
  122477. 0, 0, 0, 0, 0,
  122478. NULL,
  122479. NULL,
  122480. NULL,
  122481. NULL,
  122482. 0
  122483. };
  122484. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122487. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122488. 10,10,
  122489. };
  122490. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122491. 1, 50,
  122492. _huff_lengthlist_line_2048x27_4sub2,
  122493. 0, 0, 0, 0, 0,
  122494. NULL,
  122495. NULL,
  122496. NULL,
  122497. NULL,
  122498. 0
  122499. };
  122500. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122505. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122506. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122507. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122508. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122509. };
  122510. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122511. 1, 128,
  122512. _huff_lengthlist_line_2048x27_4sub3,
  122513. 0, 0, 0, 0, 0,
  122514. NULL,
  122515. NULL,
  122516. NULL,
  122517. NULL,
  122518. 0
  122519. };
  122520. static long _huff_lengthlist_line_256x4low_class0[] = {
  122521. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122522. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122523. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122524. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122525. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122526. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122527. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122528. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122529. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122530. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122531. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122532. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122533. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122534. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122535. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122536. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122537. };
  122538. static static_codebook _huff_book_line_256x4low_class0 = {
  122539. 1, 256,
  122540. _huff_lengthlist_line_256x4low_class0,
  122541. 0, 0, 0, 0, 0,
  122542. NULL,
  122543. NULL,
  122544. NULL,
  122545. NULL,
  122546. 0
  122547. };
  122548. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122549. 1, 3, 2, 3,
  122550. };
  122551. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122552. 1, 4,
  122553. _huff_lengthlist_line_256x4low_0sub0,
  122554. 0, 0, 0, 0, 0,
  122555. NULL,
  122556. NULL,
  122557. NULL,
  122558. NULL,
  122559. 0
  122560. };
  122561. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122562. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122563. };
  122564. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122565. 1, 10,
  122566. _huff_lengthlist_line_256x4low_0sub1,
  122567. 0, 0, 0, 0, 0,
  122568. NULL,
  122569. NULL,
  122570. NULL,
  122571. NULL,
  122572. 0
  122573. };
  122574. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122576. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122577. };
  122578. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122579. 1, 25,
  122580. _huff_lengthlist_line_256x4low_0sub2,
  122581. 0, 0, 0, 0, 0,
  122582. NULL,
  122583. NULL,
  122584. NULL,
  122585. NULL,
  122586. 0
  122587. };
  122588. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  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, 3, 4, 2, 4, 3, 5, 4,
  122591. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122592. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122593. };
  122594. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122595. 1, 64,
  122596. _huff_lengthlist_line_256x4low_0sub3,
  122597. 0, 0, 0, 0, 0,
  122598. NULL,
  122599. NULL,
  122600. NULL,
  122601. NULL,
  122602. 0
  122603. };
  122604. /*** End of inlined file: floor_books.h ***/
  122605. static static_codebook *_floor_128x4_books[]={
  122606. &_huff_book_line_128x4_class0,
  122607. &_huff_book_line_128x4_0sub0,
  122608. &_huff_book_line_128x4_0sub1,
  122609. &_huff_book_line_128x4_0sub2,
  122610. &_huff_book_line_128x4_0sub3,
  122611. };
  122612. static static_codebook *_floor_256x4_books[]={
  122613. &_huff_book_line_256x4_class0,
  122614. &_huff_book_line_256x4_0sub0,
  122615. &_huff_book_line_256x4_0sub1,
  122616. &_huff_book_line_256x4_0sub2,
  122617. &_huff_book_line_256x4_0sub3,
  122618. };
  122619. static static_codebook *_floor_128x7_books[]={
  122620. &_huff_book_line_128x7_class0,
  122621. &_huff_book_line_128x7_class1,
  122622. &_huff_book_line_128x7_0sub1,
  122623. &_huff_book_line_128x7_0sub2,
  122624. &_huff_book_line_128x7_0sub3,
  122625. &_huff_book_line_128x7_1sub1,
  122626. &_huff_book_line_128x7_1sub2,
  122627. &_huff_book_line_128x7_1sub3,
  122628. };
  122629. static static_codebook *_floor_256x7_books[]={
  122630. &_huff_book_line_256x7_class0,
  122631. &_huff_book_line_256x7_class1,
  122632. &_huff_book_line_256x7_0sub1,
  122633. &_huff_book_line_256x7_0sub2,
  122634. &_huff_book_line_256x7_0sub3,
  122635. &_huff_book_line_256x7_1sub1,
  122636. &_huff_book_line_256x7_1sub2,
  122637. &_huff_book_line_256x7_1sub3,
  122638. };
  122639. static static_codebook *_floor_128x11_books[]={
  122640. &_huff_book_line_128x11_class1,
  122641. &_huff_book_line_128x11_class2,
  122642. &_huff_book_line_128x11_class3,
  122643. &_huff_book_line_128x11_0sub0,
  122644. &_huff_book_line_128x11_1sub0,
  122645. &_huff_book_line_128x11_1sub1,
  122646. &_huff_book_line_128x11_2sub1,
  122647. &_huff_book_line_128x11_2sub2,
  122648. &_huff_book_line_128x11_2sub3,
  122649. &_huff_book_line_128x11_3sub1,
  122650. &_huff_book_line_128x11_3sub2,
  122651. &_huff_book_line_128x11_3sub3,
  122652. };
  122653. static static_codebook *_floor_128x17_books[]={
  122654. &_huff_book_line_128x17_class1,
  122655. &_huff_book_line_128x17_class2,
  122656. &_huff_book_line_128x17_class3,
  122657. &_huff_book_line_128x17_0sub0,
  122658. &_huff_book_line_128x17_1sub0,
  122659. &_huff_book_line_128x17_1sub1,
  122660. &_huff_book_line_128x17_2sub1,
  122661. &_huff_book_line_128x17_2sub2,
  122662. &_huff_book_line_128x17_2sub3,
  122663. &_huff_book_line_128x17_3sub1,
  122664. &_huff_book_line_128x17_3sub2,
  122665. &_huff_book_line_128x17_3sub3,
  122666. };
  122667. static static_codebook *_floor_256x4low_books[]={
  122668. &_huff_book_line_256x4low_class0,
  122669. &_huff_book_line_256x4low_0sub0,
  122670. &_huff_book_line_256x4low_0sub1,
  122671. &_huff_book_line_256x4low_0sub2,
  122672. &_huff_book_line_256x4low_0sub3,
  122673. };
  122674. static static_codebook *_floor_1024x27_books[]={
  122675. &_huff_book_line_1024x27_class1,
  122676. &_huff_book_line_1024x27_class2,
  122677. &_huff_book_line_1024x27_class3,
  122678. &_huff_book_line_1024x27_class4,
  122679. &_huff_book_line_1024x27_0sub0,
  122680. &_huff_book_line_1024x27_1sub0,
  122681. &_huff_book_line_1024x27_1sub1,
  122682. &_huff_book_line_1024x27_2sub0,
  122683. &_huff_book_line_1024x27_2sub1,
  122684. &_huff_book_line_1024x27_3sub1,
  122685. &_huff_book_line_1024x27_3sub2,
  122686. &_huff_book_line_1024x27_3sub3,
  122687. &_huff_book_line_1024x27_4sub1,
  122688. &_huff_book_line_1024x27_4sub2,
  122689. &_huff_book_line_1024x27_4sub3,
  122690. };
  122691. static static_codebook *_floor_2048x27_books[]={
  122692. &_huff_book_line_2048x27_class1,
  122693. &_huff_book_line_2048x27_class2,
  122694. &_huff_book_line_2048x27_class3,
  122695. &_huff_book_line_2048x27_class4,
  122696. &_huff_book_line_2048x27_0sub0,
  122697. &_huff_book_line_2048x27_1sub0,
  122698. &_huff_book_line_2048x27_1sub1,
  122699. &_huff_book_line_2048x27_2sub0,
  122700. &_huff_book_line_2048x27_2sub1,
  122701. &_huff_book_line_2048x27_3sub1,
  122702. &_huff_book_line_2048x27_3sub2,
  122703. &_huff_book_line_2048x27_3sub3,
  122704. &_huff_book_line_2048x27_4sub1,
  122705. &_huff_book_line_2048x27_4sub2,
  122706. &_huff_book_line_2048x27_4sub3,
  122707. };
  122708. static static_codebook *_floor_512x17_books[]={
  122709. &_huff_book_line_512x17_class1,
  122710. &_huff_book_line_512x17_class2,
  122711. &_huff_book_line_512x17_class3,
  122712. &_huff_book_line_512x17_0sub0,
  122713. &_huff_book_line_512x17_1sub0,
  122714. &_huff_book_line_512x17_1sub1,
  122715. &_huff_book_line_512x17_2sub1,
  122716. &_huff_book_line_512x17_2sub2,
  122717. &_huff_book_line_512x17_2sub3,
  122718. &_huff_book_line_512x17_3sub1,
  122719. &_huff_book_line_512x17_3sub2,
  122720. &_huff_book_line_512x17_3sub3,
  122721. };
  122722. static static_codebook **_floor_books[10]={
  122723. _floor_128x4_books,
  122724. _floor_256x4_books,
  122725. _floor_128x7_books,
  122726. _floor_256x7_books,
  122727. _floor_128x11_books,
  122728. _floor_128x17_books,
  122729. _floor_256x4low_books,
  122730. _floor_1024x27_books,
  122731. _floor_2048x27_books,
  122732. _floor_512x17_books,
  122733. };
  122734. static vorbis_info_floor1 _floor[10]={
  122735. /* 128 x 4 */
  122736. {
  122737. 1,{0},{4},{2},{0},
  122738. {{1,2,3,4}},
  122739. 4,{0,128, 33,8,16,70},
  122740. 60,30,500, 1.,18., -1
  122741. },
  122742. /* 256 x 4 */
  122743. {
  122744. 1,{0},{4},{2},{0},
  122745. {{1,2,3,4}},
  122746. 4,{0,256, 66,16,32,140},
  122747. 60,30,500, 1.,18., -1
  122748. },
  122749. /* 128 x 7 */
  122750. {
  122751. 2,{0,1},{3,4},{2,2},{0,1},
  122752. {{-1,2,3,4},{-1,5,6,7}},
  122753. 4,{0,128, 14,4,58, 2,8,28,90},
  122754. 60,30,500, 1.,18., -1
  122755. },
  122756. /* 256 x 7 */
  122757. {
  122758. 2,{0,1},{3,4},{2,2},{0,1},
  122759. {{-1,2,3,4},{-1,5,6,7}},
  122760. 4,{0,256, 28,8,116, 4,16,56,180},
  122761. 60,30,500, 1.,18., -1
  122762. },
  122763. /* 128 x 11 */
  122764. {
  122765. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122766. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122767. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122768. 60,30,500, 1,18., -1
  122769. },
  122770. /* 128 x 17 */
  122771. {
  122772. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122773. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122774. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122775. 60,30,500, 1,18., -1
  122776. },
  122777. /* 256 x 4 (low bitrate version) */
  122778. {
  122779. 1,{0},{4},{2},{0},
  122780. {{1,2,3,4}},
  122781. 4,{0,256, 66,16,32,140},
  122782. 60,30,500, 1.,18., -1
  122783. },
  122784. /* 1024 x 27 */
  122785. {
  122786. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122787. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122788. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122789. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122790. 60,30,500, 3,18., -1 /* lowpass */
  122791. },
  122792. /* 2048 x 27 */
  122793. {
  122794. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122795. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122796. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122797. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122798. 60,30,500, 3,18., -1 /* lowpass */
  122799. },
  122800. /* 512 x 17 */
  122801. {
  122802. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122803. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122804. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122805. 7,23,39, 55,79,110, 156,232,360},
  122806. 60,30,500, 1,18., -1 /* lowpass! */
  122807. },
  122808. };
  122809. /*** End of inlined file: floor_all.h ***/
  122810. /*** Start of inlined file: residue_44.h ***/
  122811. /*** Start of inlined file: res_books_stereo.h ***/
  122812. static long _vq_quantlist__16c0_s_p1_0[] = {
  122813. 1,
  122814. 0,
  122815. 2,
  122816. };
  122817. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122818. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122819. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122824. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122829. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  122864. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122869. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122874. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122910. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122915. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122920. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0,
  123229. };
  123230. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123231. -0.5, 0.5,
  123232. };
  123233. static long _vq_quantmap__16c0_s_p1_0[] = {
  123234. 1, 0, 2,
  123235. };
  123236. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123237. _vq_quantthresh__16c0_s_p1_0,
  123238. _vq_quantmap__16c0_s_p1_0,
  123239. 3,
  123240. 3
  123241. };
  123242. static static_codebook _16c0_s_p1_0 = {
  123243. 8, 6561,
  123244. _vq_lengthlist__16c0_s_p1_0,
  123245. 1, -535822336, 1611661312, 2, 0,
  123246. _vq_quantlist__16c0_s_p1_0,
  123247. NULL,
  123248. &_vq_auxt__16c0_s_p1_0,
  123249. NULL,
  123250. 0
  123251. };
  123252. static long _vq_quantlist__16c0_s_p2_0[] = {
  123253. 2,
  123254. 1,
  123255. 3,
  123256. 0,
  123257. 4,
  123258. };
  123259. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0,
  123300. };
  123301. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123302. -1.5, -0.5, 0.5, 1.5,
  123303. };
  123304. static long _vq_quantmap__16c0_s_p2_0[] = {
  123305. 3, 1, 0, 2, 4,
  123306. };
  123307. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123308. _vq_quantthresh__16c0_s_p2_0,
  123309. _vq_quantmap__16c0_s_p2_0,
  123310. 5,
  123311. 5
  123312. };
  123313. static static_codebook _16c0_s_p2_0 = {
  123314. 4, 625,
  123315. _vq_lengthlist__16c0_s_p2_0,
  123316. 1, -533725184, 1611661312, 3, 0,
  123317. _vq_quantlist__16c0_s_p2_0,
  123318. NULL,
  123319. &_vq_auxt__16c0_s_p2_0,
  123320. NULL,
  123321. 0
  123322. };
  123323. static long _vq_quantlist__16c0_s_p3_0[] = {
  123324. 2,
  123325. 1,
  123326. 3,
  123327. 0,
  123328. 4,
  123329. };
  123330. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123331. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0,
  123371. };
  123372. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123373. -1.5, -0.5, 0.5, 1.5,
  123374. };
  123375. static long _vq_quantmap__16c0_s_p3_0[] = {
  123376. 3, 1, 0, 2, 4,
  123377. };
  123378. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123379. _vq_quantthresh__16c0_s_p3_0,
  123380. _vq_quantmap__16c0_s_p3_0,
  123381. 5,
  123382. 5
  123383. };
  123384. static static_codebook _16c0_s_p3_0 = {
  123385. 4, 625,
  123386. _vq_lengthlist__16c0_s_p3_0,
  123387. 1, -533725184, 1611661312, 3, 0,
  123388. _vq_quantlist__16c0_s_p3_0,
  123389. NULL,
  123390. &_vq_auxt__16c0_s_p3_0,
  123391. NULL,
  123392. 0
  123393. };
  123394. static long _vq_quantlist__16c0_s_p4_0[] = {
  123395. 4,
  123396. 3,
  123397. 5,
  123398. 2,
  123399. 6,
  123400. 1,
  123401. 7,
  123402. 0,
  123403. 8,
  123404. };
  123405. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123406. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123407. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123408. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123409. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123410. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0,
  123412. };
  123413. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123414. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123415. };
  123416. static long _vq_quantmap__16c0_s_p4_0[] = {
  123417. 7, 5, 3, 1, 0, 2, 4, 6,
  123418. 8,
  123419. };
  123420. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123421. _vq_quantthresh__16c0_s_p4_0,
  123422. _vq_quantmap__16c0_s_p4_0,
  123423. 9,
  123424. 9
  123425. };
  123426. static static_codebook _16c0_s_p4_0 = {
  123427. 2, 81,
  123428. _vq_lengthlist__16c0_s_p4_0,
  123429. 1, -531628032, 1611661312, 4, 0,
  123430. _vq_quantlist__16c0_s_p4_0,
  123431. NULL,
  123432. &_vq_auxt__16c0_s_p4_0,
  123433. NULL,
  123434. 0
  123435. };
  123436. static long _vq_quantlist__16c0_s_p5_0[] = {
  123437. 4,
  123438. 3,
  123439. 5,
  123440. 2,
  123441. 6,
  123442. 1,
  123443. 7,
  123444. 0,
  123445. 8,
  123446. };
  123447. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123448. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123449. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123450. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123451. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123452. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123453. 10,
  123454. };
  123455. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123456. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123457. };
  123458. static long _vq_quantmap__16c0_s_p5_0[] = {
  123459. 7, 5, 3, 1, 0, 2, 4, 6,
  123460. 8,
  123461. };
  123462. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123463. _vq_quantthresh__16c0_s_p5_0,
  123464. _vq_quantmap__16c0_s_p5_0,
  123465. 9,
  123466. 9
  123467. };
  123468. static static_codebook _16c0_s_p5_0 = {
  123469. 2, 81,
  123470. _vq_lengthlist__16c0_s_p5_0,
  123471. 1, -531628032, 1611661312, 4, 0,
  123472. _vq_quantlist__16c0_s_p5_0,
  123473. NULL,
  123474. &_vq_auxt__16c0_s_p5_0,
  123475. NULL,
  123476. 0
  123477. };
  123478. static long _vq_quantlist__16c0_s_p6_0[] = {
  123479. 8,
  123480. 7,
  123481. 9,
  123482. 6,
  123483. 10,
  123484. 5,
  123485. 11,
  123486. 4,
  123487. 12,
  123488. 3,
  123489. 13,
  123490. 2,
  123491. 14,
  123492. 1,
  123493. 15,
  123494. 0,
  123495. 16,
  123496. };
  123497. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123498. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123499. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123500. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123501. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123502. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123503. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123504. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123505. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123506. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123507. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123508. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123509. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123510. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123511. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123512. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123513. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123514. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123516. 14,
  123517. };
  123518. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123519. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123520. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123521. };
  123522. static long _vq_quantmap__16c0_s_p6_0[] = {
  123523. 15, 13, 11, 9, 7, 5, 3, 1,
  123524. 0, 2, 4, 6, 8, 10, 12, 14,
  123525. 16,
  123526. };
  123527. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123528. _vq_quantthresh__16c0_s_p6_0,
  123529. _vq_quantmap__16c0_s_p6_0,
  123530. 17,
  123531. 17
  123532. };
  123533. static static_codebook _16c0_s_p6_0 = {
  123534. 2, 289,
  123535. _vq_lengthlist__16c0_s_p6_0,
  123536. 1, -529530880, 1611661312, 5, 0,
  123537. _vq_quantlist__16c0_s_p6_0,
  123538. NULL,
  123539. &_vq_auxt__16c0_s_p6_0,
  123540. NULL,
  123541. 0
  123542. };
  123543. static long _vq_quantlist__16c0_s_p7_0[] = {
  123544. 1,
  123545. 0,
  123546. 2,
  123547. };
  123548. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123549. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123550. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123551. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123552. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123553. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123554. 13,
  123555. };
  123556. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123557. -5.5, 5.5,
  123558. };
  123559. static long _vq_quantmap__16c0_s_p7_0[] = {
  123560. 1, 0, 2,
  123561. };
  123562. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123563. _vq_quantthresh__16c0_s_p7_0,
  123564. _vq_quantmap__16c0_s_p7_0,
  123565. 3,
  123566. 3
  123567. };
  123568. static static_codebook _16c0_s_p7_0 = {
  123569. 4, 81,
  123570. _vq_lengthlist__16c0_s_p7_0,
  123571. 1, -529137664, 1618345984, 2, 0,
  123572. _vq_quantlist__16c0_s_p7_0,
  123573. NULL,
  123574. &_vq_auxt__16c0_s_p7_0,
  123575. NULL,
  123576. 0
  123577. };
  123578. static long _vq_quantlist__16c0_s_p7_1[] = {
  123579. 5,
  123580. 4,
  123581. 6,
  123582. 3,
  123583. 7,
  123584. 2,
  123585. 8,
  123586. 1,
  123587. 9,
  123588. 0,
  123589. 10,
  123590. };
  123591. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123592. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123593. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123594. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123595. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123596. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123597. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123598. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123599. 11,11,11, 9, 9, 9, 9,10,10,
  123600. };
  123601. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123602. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123603. 3.5, 4.5,
  123604. };
  123605. static long _vq_quantmap__16c0_s_p7_1[] = {
  123606. 9, 7, 5, 3, 1, 0, 2, 4,
  123607. 6, 8, 10,
  123608. };
  123609. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123610. _vq_quantthresh__16c0_s_p7_1,
  123611. _vq_quantmap__16c0_s_p7_1,
  123612. 11,
  123613. 11
  123614. };
  123615. static static_codebook _16c0_s_p7_1 = {
  123616. 2, 121,
  123617. _vq_lengthlist__16c0_s_p7_1,
  123618. 1, -531365888, 1611661312, 4, 0,
  123619. _vq_quantlist__16c0_s_p7_1,
  123620. NULL,
  123621. &_vq_auxt__16c0_s_p7_1,
  123622. NULL,
  123623. 0
  123624. };
  123625. static long _vq_quantlist__16c0_s_p8_0[] = {
  123626. 6,
  123627. 5,
  123628. 7,
  123629. 4,
  123630. 8,
  123631. 3,
  123632. 9,
  123633. 2,
  123634. 10,
  123635. 1,
  123636. 11,
  123637. 0,
  123638. 12,
  123639. };
  123640. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123641. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123642. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123643. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123644. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123645. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123646. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123647. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123648. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123649. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123650. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123651. 0,12,13,13,12,13,14,14,14,
  123652. };
  123653. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123654. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123655. 12.5, 17.5, 22.5, 27.5,
  123656. };
  123657. static long _vq_quantmap__16c0_s_p8_0[] = {
  123658. 11, 9, 7, 5, 3, 1, 0, 2,
  123659. 4, 6, 8, 10, 12,
  123660. };
  123661. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123662. _vq_quantthresh__16c0_s_p8_0,
  123663. _vq_quantmap__16c0_s_p8_0,
  123664. 13,
  123665. 13
  123666. };
  123667. static static_codebook _16c0_s_p8_0 = {
  123668. 2, 169,
  123669. _vq_lengthlist__16c0_s_p8_0,
  123670. 1, -526516224, 1616117760, 4, 0,
  123671. _vq_quantlist__16c0_s_p8_0,
  123672. NULL,
  123673. &_vq_auxt__16c0_s_p8_0,
  123674. NULL,
  123675. 0
  123676. };
  123677. static long _vq_quantlist__16c0_s_p8_1[] = {
  123678. 2,
  123679. 1,
  123680. 3,
  123681. 0,
  123682. 4,
  123683. };
  123684. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123685. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123686. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123687. };
  123688. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123689. -1.5, -0.5, 0.5, 1.5,
  123690. };
  123691. static long _vq_quantmap__16c0_s_p8_1[] = {
  123692. 3, 1, 0, 2, 4,
  123693. };
  123694. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123695. _vq_quantthresh__16c0_s_p8_1,
  123696. _vq_quantmap__16c0_s_p8_1,
  123697. 5,
  123698. 5
  123699. };
  123700. static static_codebook _16c0_s_p8_1 = {
  123701. 2, 25,
  123702. _vq_lengthlist__16c0_s_p8_1,
  123703. 1, -533725184, 1611661312, 3, 0,
  123704. _vq_quantlist__16c0_s_p8_1,
  123705. NULL,
  123706. &_vq_auxt__16c0_s_p8_1,
  123707. NULL,
  123708. 0
  123709. };
  123710. static long _vq_quantlist__16c0_s_p9_0[] = {
  123711. 1,
  123712. 0,
  123713. 2,
  123714. };
  123715. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123716. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123717. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123718. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123719. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123720. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123721. 7,
  123722. };
  123723. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123724. -157.5, 157.5,
  123725. };
  123726. static long _vq_quantmap__16c0_s_p9_0[] = {
  123727. 1, 0, 2,
  123728. };
  123729. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123730. _vq_quantthresh__16c0_s_p9_0,
  123731. _vq_quantmap__16c0_s_p9_0,
  123732. 3,
  123733. 3
  123734. };
  123735. static static_codebook _16c0_s_p9_0 = {
  123736. 4, 81,
  123737. _vq_lengthlist__16c0_s_p9_0,
  123738. 1, -518803456, 1628680192, 2, 0,
  123739. _vq_quantlist__16c0_s_p9_0,
  123740. NULL,
  123741. &_vq_auxt__16c0_s_p9_0,
  123742. NULL,
  123743. 0
  123744. };
  123745. static long _vq_quantlist__16c0_s_p9_1[] = {
  123746. 7,
  123747. 6,
  123748. 8,
  123749. 5,
  123750. 9,
  123751. 4,
  123752. 10,
  123753. 3,
  123754. 11,
  123755. 2,
  123756. 12,
  123757. 1,
  123758. 13,
  123759. 0,
  123760. 14,
  123761. };
  123762. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123763. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123764. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123765. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123766. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123767. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123768. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123769. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123770. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123777. 10,
  123778. };
  123779. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123780. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123781. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123782. };
  123783. static long _vq_quantmap__16c0_s_p9_1[] = {
  123784. 13, 11, 9, 7, 5, 3, 1, 0,
  123785. 2, 4, 6, 8, 10, 12, 14,
  123786. };
  123787. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123788. _vq_quantthresh__16c0_s_p9_1,
  123789. _vq_quantmap__16c0_s_p9_1,
  123790. 15,
  123791. 15
  123792. };
  123793. static static_codebook _16c0_s_p9_1 = {
  123794. 2, 225,
  123795. _vq_lengthlist__16c0_s_p9_1,
  123796. 1, -520986624, 1620377600, 4, 0,
  123797. _vq_quantlist__16c0_s_p9_1,
  123798. NULL,
  123799. &_vq_auxt__16c0_s_p9_1,
  123800. NULL,
  123801. 0
  123802. };
  123803. static long _vq_quantlist__16c0_s_p9_2[] = {
  123804. 10,
  123805. 9,
  123806. 11,
  123807. 8,
  123808. 12,
  123809. 7,
  123810. 13,
  123811. 6,
  123812. 14,
  123813. 5,
  123814. 15,
  123815. 4,
  123816. 16,
  123817. 3,
  123818. 17,
  123819. 2,
  123820. 18,
  123821. 1,
  123822. 19,
  123823. 0,
  123824. 20,
  123825. };
  123826. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123827. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123828. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123829. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123830. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123831. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123832. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123833. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123834. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123835. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123836. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123837. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123838. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123839. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123840. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123841. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123842. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123843. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123844. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123845. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123846. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123847. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123848. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123849. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123850. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123851. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123852. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123853. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123854. 10,11,10,10,11, 9,10,10,10,
  123855. };
  123856. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123857. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123858. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123859. 6.5, 7.5, 8.5, 9.5,
  123860. };
  123861. static long _vq_quantmap__16c0_s_p9_2[] = {
  123862. 19, 17, 15, 13, 11, 9, 7, 5,
  123863. 3, 1, 0, 2, 4, 6, 8, 10,
  123864. 12, 14, 16, 18, 20,
  123865. };
  123866. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123867. _vq_quantthresh__16c0_s_p9_2,
  123868. _vq_quantmap__16c0_s_p9_2,
  123869. 21,
  123870. 21
  123871. };
  123872. static static_codebook _16c0_s_p9_2 = {
  123873. 2, 441,
  123874. _vq_lengthlist__16c0_s_p9_2,
  123875. 1, -529268736, 1611661312, 5, 0,
  123876. _vq_quantlist__16c0_s_p9_2,
  123877. NULL,
  123878. &_vq_auxt__16c0_s_p9_2,
  123879. NULL,
  123880. 0
  123881. };
  123882. static long _huff_lengthlist__16c0_s_single[] = {
  123883. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123884. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123885. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123886. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123887. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123888. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123889. 16,16,18,18,
  123890. };
  123891. static static_codebook _huff_book__16c0_s_single = {
  123892. 2, 100,
  123893. _huff_lengthlist__16c0_s_single,
  123894. 0, 0, 0, 0, 0,
  123895. NULL,
  123896. NULL,
  123897. NULL,
  123898. NULL,
  123899. 0
  123900. };
  123901. static long _huff_lengthlist__16c1_s_long[] = {
  123902. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123903. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123904. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123905. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123906. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123907. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123908. 12,11,11,13,
  123909. };
  123910. static static_codebook _huff_book__16c1_s_long = {
  123911. 2, 100,
  123912. _huff_lengthlist__16c1_s_long,
  123913. 0, 0, 0, 0, 0,
  123914. NULL,
  123915. NULL,
  123916. NULL,
  123917. NULL,
  123918. 0
  123919. };
  123920. static long _vq_quantlist__16c1_s_p1_0[] = {
  123921. 1,
  123922. 0,
  123923. 2,
  123924. };
  123925. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123926. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123927. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123932. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123937. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  123972. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  123977. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  123982. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124018. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124023. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124028. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0,
  124337. };
  124338. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124339. -0.5, 0.5,
  124340. };
  124341. static long _vq_quantmap__16c1_s_p1_0[] = {
  124342. 1, 0, 2,
  124343. };
  124344. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124345. _vq_quantthresh__16c1_s_p1_0,
  124346. _vq_quantmap__16c1_s_p1_0,
  124347. 3,
  124348. 3
  124349. };
  124350. static static_codebook _16c1_s_p1_0 = {
  124351. 8, 6561,
  124352. _vq_lengthlist__16c1_s_p1_0,
  124353. 1, -535822336, 1611661312, 2, 0,
  124354. _vq_quantlist__16c1_s_p1_0,
  124355. NULL,
  124356. &_vq_auxt__16c1_s_p1_0,
  124357. NULL,
  124358. 0
  124359. };
  124360. static long _vq_quantlist__16c1_s_p2_0[] = {
  124361. 2,
  124362. 1,
  124363. 3,
  124364. 0,
  124365. 4,
  124366. };
  124367. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0,
  124408. };
  124409. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124410. -1.5, -0.5, 0.5, 1.5,
  124411. };
  124412. static long _vq_quantmap__16c1_s_p2_0[] = {
  124413. 3, 1, 0, 2, 4,
  124414. };
  124415. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124416. _vq_quantthresh__16c1_s_p2_0,
  124417. _vq_quantmap__16c1_s_p2_0,
  124418. 5,
  124419. 5
  124420. };
  124421. static static_codebook _16c1_s_p2_0 = {
  124422. 4, 625,
  124423. _vq_lengthlist__16c1_s_p2_0,
  124424. 1, -533725184, 1611661312, 3, 0,
  124425. _vq_quantlist__16c1_s_p2_0,
  124426. NULL,
  124427. &_vq_auxt__16c1_s_p2_0,
  124428. NULL,
  124429. 0
  124430. };
  124431. static long _vq_quantlist__16c1_s_p3_0[] = {
  124432. 2,
  124433. 1,
  124434. 3,
  124435. 0,
  124436. 4,
  124437. };
  124438. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124439. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124442. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124445. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124478. 0,
  124479. };
  124480. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124481. -1.5, -0.5, 0.5, 1.5,
  124482. };
  124483. static long _vq_quantmap__16c1_s_p3_0[] = {
  124484. 3, 1, 0, 2, 4,
  124485. };
  124486. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124487. _vq_quantthresh__16c1_s_p3_0,
  124488. _vq_quantmap__16c1_s_p3_0,
  124489. 5,
  124490. 5
  124491. };
  124492. static static_codebook _16c1_s_p3_0 = {
  124493. 4, 625,
  124494. _vq_lengthlist__16c1_s_p3_0,
  124495. 1, -533725184, 1611661312, 3, 0,
  124496. _vq_quantlist__16c1_s_p3_0,
  124497. NULL,
  124498. &_vq_auxt__16c1_s_p3_0,
  124499. NULL,
  124500. 0
  124501. };
  124502. static long _vq_quantlist__16c1_s_p4_0[] = {
  124503. 4,
  124504. 3,
  124505. 5,
  124506. 2,
  124507. 6,
  124508. 1,
  124509. 7,
  124510. 0,
  124511. 8,
  124512. };
  124513. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124514. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124515. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124516. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124517. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124518. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124519. 0,
  124520. };
  124521. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124522. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124523. };
  124524. static long _vq_quantmap__16c1_s_p4_0[] = {
  124525. 7, 5, 3, 1, 0, 2, 4, 6,
  124526. 8,
  124527. };
  124528. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124529. _vq_quantthresh__16c1_s_p4_0,
  124530. _vq_quantmap__16c1_s_p4_0,
  124531. 9,
  124532. 9
  124533. };
  124534. static static_codebook _16c1_s_p4_0 = {
  124535. 2, 81,
  124536. _vq_lengthlist__16c1_s_p4_0,
  124537. 1, -531628032, 1611661312, 4, 0,
  124538. _vq_quantlist__16c1_s_p4_0,
  124539. NULL,
  124540. &_vq_auxt__16c1_s_p4_0,
  124541. NULL,
  124542. 0
  124543. };
  124544. static long _vq_quantlist__16c1_s_p5_0[] = {
  124545. 4,
  124546. 3,
  124547. 5,
  124548. 2,
  124549. 6,
  124550. 1,
  124551. 7,
  124552. 0,
  124553. 8,
  124554. };
  124555. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124556. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124557. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124558. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124559. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124560. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124561. 10,
  124562. };
  124563. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124564. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124565. };
  124566. static long _vq_quantmap__16c1_s_p5_0[] = {
  124567. 7, 5, 3, 1, 0, 2, 4, 6,
  124568. 8,
  124569. };
  124570. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124571. _vq_quantthresh__16c1_s_p5_0,
  124572. _vq_quantmap__16c1_s_p5_0,
  124573. 9,
  124574. 9
  124575. };
  124576. static static_codebook _16c1_s_p5_0 = {
  124577. 2, 81,
  124578. _vq_lengthlist__16c1_s_p5_0,
  124579. 1, -531628032, 1611661312, 4, 0,
  124580. _vq_quantlist__16c1_s_p5_0,
  124581. NULL,
  124582. &_vq_auxt__16c1_s_p5_0,
  124583. NULL,
  124584. 0
  124585. };
  124586. static long _vq_quantlist__16c1_s_p6_0[] = {
  124587. 8,
  124588. 7,
  124589. 9,
  124590. 6,
  124591. 10,
  124592. 5,
  124593. 11,
  124594. 4,
  124595. 12,
  124596. 3,
  124597. 13,
  124598. 2,
  124599. 14,
  124600. 1,
  124601. 15,
  124602. 0,
  124603. 16,
  124604. };
  124605. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124606. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124607. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124608. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124609. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124610. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124611. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124612. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124613. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124614. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124615. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124616. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124617. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124618. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124619. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124620. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124621. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124622. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124623. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124624. 14,
  124625. };
  124626. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124627. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124628. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124629. };
  124630. static long _vq_quantmap__16c1_s_p6_0[] = {
  124631. 15, 13, 11, 9, 7, 5, 3, 1,
  124632. 0, 2, 4, 6, 8, 10, 12, 14,
  124633. 16,
  124634. };
  124635. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124636. _vq_quantthresh__16c1_s_p6_0,
  124637. _vq_quantmap__16c1_s_p6_0,
  124638. 17,
  124639. 17
  124640. };
  124641. static static_codebook _16c1_s_p6_0 = {
  124642. 2, 289,
  124643. _vq_lengthlist__16c1_s_p6_0,
  124644. 1, -529530880, 1611661312, 5, 0,
  124645. _vq_quantlist__16c1_s_p6_0,
  124646. NULL,
  124647. &_vq_auxt__16c1_s_p6_0,
  124648. NULL,
  124649. 0
  124650. };
  124651. static long _vq_quantlist__16c1_s_p7_0[] = {
  124652. 1,
  124653. 0,
  124654. 2,
  124655. };
  124656. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124657. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124658. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124659. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124660. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124661. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124662. 11,
  124663. };
  124664. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124665. -5.5, 5.5,
  124666. };
  124667. static long _vq_quantmap__16c1_s_p7_0[] = {
  124668. 1, 0, 2,
  124669. };
  124670. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124671. _vq_quantthresh__16c1_s_p7_0,
  124672. _vq_quantmap__16c1_s_p7_0,
  124673. 3,
  124674. 3
  124675. };
  124676. static static_codebook _16c1_s_p7_0 = {
  124677. 4, 81,
  124678. _vq_lengthlist__16c1_s_p7_0,
  124679. 1, -529137664, 1618345984, 2, 0,
  124680. _vq_quantlist__16c1_s_p7_0,
  124681. NULL,
  124682. &_vq_auxt__16c1_s_p7_0,
  124683. NULL,
  124684. 0
  124685. };
  124686. static long _vq_quantlist__16c1_s_p7_1[] = {
  124687. 5,
  124688. 4,
  124689. 6,
  124690. 3,
  124691. 7,
  124692. 2,
  124693. 8,
  124694. 1,
  124695. 9,
  124696. 0,
  124697. 10,
  124698. };
  124699. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124700. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124701. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124702. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124703. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124704. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124705. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124706. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124707. 10,10,10, 8, 8, 8, 8, 9, 9,
  124708. };
  124709. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124710. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124711. 3.5, 4.5,
  124712. };
  124713. static long _vq_quantmap__16c1_s_p7_1[] = {
  124714. 9, 7, 5, 3, 1, 0, 2, 4,
  124715. 6, 8, 10,
  124716. };
  124717. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124718. _vq_quantthresh__16c1_s_p7_1,
  124719. _vq_quantmap__16c1_s_p7_1,
  124720. 11,
  124721. 11
  124722. };
  124723. static static_codebook _16c1_s_p7_1 = {
  124724. 2, 121,
  124725. _vq_lengthlist__16c1_s_p7_1,
  124726. 1, -531365888, 1611661312, 4, 0,
  124727. _vq_quantlist__16c1_s_p7_1,
  124728. NULL,
  124729. &_vq_auxt__16c1_s_p7_1,
  124730. NULL,
  124731. 0
  124732. };
  124733. static long _vq_quantlist__16c1_s_p8_0[] = {
  124734. 6,
  124735. 5,
  124736. 7,
  124737. 4,
  124738. 8,
  124739. 3,
  124740. 9,
  124741. 2,
  124742. 10,
  124743. 1,
  124744. 11,
  124745. 0,
  124746. 12,
  124747. };
  124748. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124749. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124750. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124751. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124752. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124753. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124754. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124755. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124756. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124757. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124758. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124759. 0,12,12,12,12,13,13,14,15,
  124760. };
  124761. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124762. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124763. 12.5, 17.5, 22.5, 27.5,
  124764. };
  124765. static long _vq_quantmap__16c1_s_p8_0[] = {
  124766. 11, 9, 7, 5, 3, 1, 0, 2,
  124767. 4, 6, 8, 10, 12,
  124768. };
  124769. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124770. _vq_quantthresh__16c1_s_p8_0,
  124771. _vq_quantmap__16c1_s_p8_0,
  124772. 13,
  124773. 13
  124774. };
  124775. static static_codebook _16c1_s_p8_0 = {
  124776. 2, 169,
  124777. _vq_lengthlist__16c1_s_p8_0,
  124778. 1, -526516224, 1616117760, 4, 0,
  124779. _vq_quantlist__16c1_s_p8_0,
  124780. NULL,
  124781. &_vq_auxt__16c1_s_p8_0,
  124782. NULL,
  124783. 0
  124784. };
  124785. static long _vq_quantlist__16c1_s_p8_1[] = {
  124786. 2,
  124787. 1,
  124788. 3,
  124789. 0,
  124790. 4,
  124791. };
  124792. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124793. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124794. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124795. };
  124796. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124797. -1.5, -0.5, 0.5, 1.5,
  124798. };
  124799. static long _vq_quantmap__16c1_s_p8_1[] = {
  124800. 3, 1, 0, 2, 4,
  124801. };
  124802. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124803. _vq_quantthresh__16c1_s_p8_1,
  124804. _vq_quantmap__16c1_s_p8_1,
  124805. 5,
  124806. 5
  124807. };
  124808. static static_codebook _16c1_s_p8_1 = {
  124809. 2, 25,
  124810. _vq_lengthlist__16c1_s_p8_1,
  124811. 1, -533725184, 1611661312, 3, 0,
  124812. _vq_quantlist__16c1_s_p8_1,
  124813. NULL,
  124814. &_vq_auxt__16c1_s_p8_1,
  124815. NULL,
  124816. 0
  124817. };
  124818. static long _vq_quantlist__16c1_s_p9_0[] = {
  124819. 6,
  124820. 5,
  124821. 7,
  124822. 4,
  124823. 8,
  124824. 3,
  124825. 9,
  124826. 2,
  124827. 10,
  124828. 1,
  124829. 11,
  124830. 0,
  124831. 12,
  124832. };
  124833. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124834. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124835. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124836. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124837. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124838. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124839. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124840. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124841. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124842. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124843. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124844. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124845. };
  124846. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124847. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124848. 787.5, 1102.5, 1417.5, 1732.5,
  124849. };
  124850. static long _vq_quantmap__16c1_s_p9_0[] = {
  124851. 11, 9, 7, 5, 3, 1, 0, 2,
  124852. 4, 6, 8, 10, 12,
  124853. };
  124854. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124855. _vq_quantthresh__16c1_s_p9_0,
  124856. _vq_quantmap__16c1_s_p9_0,
  124857. 13,
  124858. 13
  124859. };
  124860. static static_codebook _16c1_s_p9_0 = {
  124861. 2, 169,
  124862. _vq_lengthlist__16c1_s_p9_0,
  124863. 1, -513964032, 1628680192, 4, 0,
  124864. _vq_quantlist__16c1_s_p9_0,
  124865. NULL,
  124866. &_vq_auxt__16c1_s_p9_0,
  124867. NULL,
  124868. 0
  124869. };
  124870. static long _vq_quantlist__16c1_s_p9_1[] = {
  124871. 7,
  124872. 6,
  124873. 8,
  124874. 5,
  124875. 9,
  124876. 4,
  124877. 10,
  124878. 3,
  124879. 11,
  124880. 2,
  124881. 12,
  124882. 1,
  124883. 13,
  124884. 0,
  124885. 14,
  124886. };
  124887. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124888. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124889. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124890. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124891. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124892. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124893. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124894. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124895. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124896. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124897. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124898. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124899. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124900. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124901. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124902. 13,
  124903. };
  124904. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124905. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124906. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124907. };
  124908. static long _vq_quantmap__16c1_s_p9_1[] = {
  124909. 13, 11, 9, 7, 5, 3, 1, 0,
  124910. 2, 4, 6, 8, 10, 12, 14,
  124911. };
  124912. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124913. _vq_quantthresh__16c1_s_p9_1,
  124914. _vq_quantmap__16c1_s_p9_1,
  124915. 15,
  124916. 15
  124917. };
  124918. static static_codebook _16c1_s_p9_1 = {
  124919. 2, 225,
  124920. _vq_lengthlist__16c1_s_p9_1,
  124921. 1, -520986624, 1620377600, 4, 0,
  124922. _vq_quantlist__16c1_s_p9_1,
  124923. NULL,
  124924. &_vq_auxt__16c1_s_p9_1,
  124925. NULL,
  124926. 0
  124927. };
  124928. static long _vq_quantlist__16c1_s_p9_2[] = {
  124929. 10,
  124930. 9,
  124931. 11,
  124932. 8,
  124933. 12,
  124934. 7,
  124935. 13,
  124936. 6,
  124937. 14,
  124938. 5,
  124939. 15,
  124940. 4,
  124941. 16,
  124942. 3,
  124943. 17,
  124944. 2,
  124945. 18,
  124946. 1,
  124947. 19,
  124948. 0,
  124949. 20,
  124950. };
  124951. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124952. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124953. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124954. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124955. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124956. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124957. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124958. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124959. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124960. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124961. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124962. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124963. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124964. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124965. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124966. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124967. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124968. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124969. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124970. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124971. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124972. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124973. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124974. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124975. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124976. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124977. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124978. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124979. 11,11,11,11,12,11,11,12,11,
  124980. };
  124981. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124982. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124983. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124984. 6.5, 7.5, 8.5, 9.5,
  124985. };
  124986. static long _vq_quantmap__16c1_s_p9_2[] = {
  124987. 19, 17, 15, 13, 11, 9, 7, 5,
  124988. 3, 1, 0, 2, 4, 6, 8, 10,
  124989. 12, 14, 16, 18, 20,
  124990. };
  124991. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124992. _vq_quantthresh__16c1_s_p9_2,
  124993. _vq_quantmap__16c1_s_p9_2,
  124994. 21,
  124995. 21
  124996. };
  124997. static static_codebook _16c1_s_p9_2 = {
  124998. 2, 441,
  124999. _vq_lengthlist__16c1_s_p9_2,
  125000. 1, -529268736, 1611661312, 5, 0,
  125001. _vq_quantlist__16c1_s_p9_2,
  125002. NULL,
  125003. &_vq_auxt__16c1_s_p9_2,
  125004. NULL,
  125005. 0
  125006. };
  125007. static long _huff_lengthlist__16c1_s_short[] = {
  125008. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  125009. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  125010. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  125011. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  125012. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  125013. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  125014. 9, 9,10,13,
  125015. };
  125016. static static_codebook _huff_book__16c1_s_short = {
  125017. 2, 100,
  125018. _huff_lengthlist__16c1_s_short,
  125019. 0, 0, 0, 0, 0,
  125020. NULL,
  125021. NULL,
  125022. NULL,
  125023. NULL,
  125024. 0
  125025. };
  125026. static long _huff_lengthlist__16c2_s_long[] = {
  125027. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  125028. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  125029. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  125030. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  125031. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  125032. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  125033. 14,14,16,18,
  125034. };
  125035. static static_codebook _huff_book__16c2_s_long = {
  125036. 2, 100,
  125037. _huff_lengthlist__16c2_s_long,
  125038. 0, 0, 0, 0, 0,
  125039. NULL,
  125040. NULL,
  125041. NULL,
  125042. NULL,
  125043. 0
  125044. };
  125045. static long _vq_quantlist__16c2_s_p1_0[] = {
  125046. 1,
  125047. 0,
  125048. 2,
  125049. };
  125050. static long _vq_lengthlist__16c2_s_p1_0[] = {
  125051. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  125052. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125056. 0,
  125057. };
  125058. static float _vq_quantthresh__16c2_s_p1_0[] = {
  125059. -0.5, 0.5,
  125060. };
  125061. static long _vq_quantmap__16c2_s_p1_0[] = {
  125062. 1, 0, 2,
  125063. };
  125064. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  125065. _vq_quantthresh__16c2_s_p1_0,
  125066. _vq_quantmap__16c2_s_p1_0,
  125067. 3,
  125068. 3
  125069. };
  125070. static static_codebook _16c2_s_p1_0 = {
  125071. 4, 81,
  125072. _vq_lengthlist__16c2_s_p1_0,
  125073. 1, -535822336, 1611661312, 2, 0,
  125074. _vq_quantlist__16c2_s_p1_0,
  125075. NULL,
  125076. &_vq_auxt__16c2_s_p1_0,
  125077. NULL,
  125078. 0
  125079. };
  125080. static long _vq_quantlist__16c2_s_p2_0[] = {
  125081. 2,
  125082. 1,
  125083. 3,
  125084. 0,
  125085. 4,
  125086. };
  125087. static long _vq_lengthlist__16c2_s_p2_0[] = {
  125088. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  125089. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  125090. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  125091. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  125092. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  125093. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  125094. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  125095. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8, 8, 8,11,11, 0, 0, 0,
  125101. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  125102. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  125103. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125109. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125110. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125111. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125116. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125117. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125118. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125119. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  125124. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125125. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125126. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125127. 13,
  125128. };
  125129. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125130. -1.5, -0.5, 0.5, 1.5,
  125131. };
  125132. static long _vq_quantmap__16c2_s_p2_0[] = {
  125133. 3, 1, 0, 2, 4,
  125134. };
  125135. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125136. _vq_quantthresh__16c2_s_p2_0,
  125137. _vq_quantmap__16c2_s_p2_0,
  125138. 5,
  125139. 5
  125140. };
  125141. static static_codebook _16c2_s_p2_0 = {
  125142. 4, 625,
  125143. _vq_lengthlist__16c2_s_p2_0,
  125144. 1, -533725184, 1611661312, 3, 0,
  125145. _vq_quantlist__16c2_s_p2_0,
  125146. NULL,
  125147. &_vq_auxt__16c2_s_p2_0,
  125148. NULL,
  125149. 0
  125150. };
  125151. static long _vq_quantlist__16c2_s_p3_0[] = {
  125152. 4,
  125153. 3,
  125154. 5,
  125155. 2,
  125156. 6,
  125157. 1,
  125158. 7,
  125159. 0,
  125160. 8,
  125161. };
  125162. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125163. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125164. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125165. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125166. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125168. 0,
  125169. };
  125170. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125171. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125172. };
  125173. static long _vq_quantmap__16c2_s_p3_0[] = {
  125174. 7, 5, 3, 1, 0, 2, 4, 6,
  125175. 8,
  125176. };
  125177. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125178. _vq_quantthresh__16c2_s_p3_0,
  125179. _vq_quantmap__16c2_s_p3_0,
  125180. 9,
  125181. 9
  125182. };
  125183. static static_codebook _16c2_s_p3_0 = {
  125184. 2, 81,
  125185. _vq_lengthlist__16c2_s_p3_0,
  125186. 1, -531628032, 1611661312, 4, 0,
  125187. _vq_quantlist__16c2_s_p3_0,
  125188. NULL,
  125189. &_vq_auxt__16c2_s_p3_0,
  125190. NULL,
  125191. 0
  125192. };
  125193. static long _vq_quantlist__16c2_s_p4_0[] = {
  125194. 8,
  125195. 7,
  125196. 9,
  125197. 6,
  125198. 10,
  125199. 5,
  125200. 11,
  125201. 4,
  125202. 12,
  125203. 3,
  125204. 13,
  125205. 2,
  125206. 14,
  125207. 1,
  125208. 15,
  125209. 0,
  125210. 16,
  125211. };
  125212. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125213. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125214. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125215. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125216. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125217. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125218. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125219. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125220. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125221. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125222. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0,
  125232. };
  125233. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125234. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125235. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125236. };
  125237. static long _vq_quantmap__16c2_s_p4_0[] = {
  125238. 15, 13, 11, 9, 7, 5, 3, 1,
  125239. 0, 2, 4, 6, 8, 10, 12, 14,
  125240. 16,
  125241. };
  125242. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125243. _vq_quantthresh__16c2_s_p4_0,
  125244. _vq_quantmap__16c2_s_p4_0,
  125245. 17,
  125246. 17
  125247. };
  125248. static static_codebook _16c2_s_p4_0 = {
  125249. 2, 289,
  125250. _vq_lengthlist__16c2_s_p4_0,
  125251. 1, -529530880, 1611661312, 5, 0,
  125252. _vq_quantlist__16c2_s_p4_0,
  125253. NULL,
  125254. &_vq_auxt__16c2_s_p4_0,
  125255. NULL,
  125256. 0
  125257. };
  125258. static long _vq_quantlist__16c2_s_p5_0[] = {
  125259. 1,
  125260. 0,
  125261. 2,
  125262. };
  125263. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125264. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125265. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125266. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125267. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125268. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125269. 12,
  125270. };
  125271. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125272. -5.5, 5.5,
  125273. };
  125274. static long _vq_quantmap__16c2_s_p5_0[] = {
  125275. 1, 0, 2,
  125276. };
  125277. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125278. _vq_quantthresh__16c2_s_p5_0,
  125279. _vq_quantmap__16c2_s_p5_0,
  125280. 3,
  125281. 3
  125282. };
  125283. static static_codebook _16c2_s_p5_0 = {
  125284. 4, 81,
  125285. _vq_lengthlist__16c2_s_p5_0,
  125286. 1, -529137664, 1618345984, 2, 0,
  125287. _vq_quantlist__16c2_s_p5_0,
  125288. NULL,
  125289. &_vq_auxt__16c2_s_p5_0,
  125290. NULL,
  125291. 0
  125292. };
  125293. static long _vq_quantlist__16c2_s_p5_1[] = {
  125294. 5,
  125295. 4,
  125296. 6,
  125297. 3,
  125298. 7,
  125299. 2,
  125300. 8,
  125301. 1,
  125302. 9,
  125303. 0,
  125304. 10,
  125305. };
  125306. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125307. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125308. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125309. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125310. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125311. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125312. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125313. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125314. 11,11,11, 7, 7, 8, 8, 8, 8,
  125315. };
  125316. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125317. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125318. 3.5, 4.5,
  125319. };
  125320. static long _vq_quantmap__16c2_s_p5_1[] = {
  125321. 9, 7, 5, 3, 1, 0, 2, 4,
  125322. 6, 8, 10,
  125323. };
  125324. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125325. _vq_quantthresh__16c2_s_p5_1,
  125326. _vq_quantmap__16c2_s_p5_1,
  125327. 11,
  125328. 11
  125329. };
  125330. static static_codebook _16c2_s_p5_1 = {
  125331. 2, 121,
  125332. _vq_lengthlist__16c2_s_p5_1,
  125333. 1, -531365888, 1611661312, 4, 0,
  125334. _vq_quantlist__16c2_s_p5_1,
  125335. NULL,
  125336. &_vq_auxt__16c2_s_p5_1,
  125337. NULL,
  125338. 0
  125339. };
  125340. static long _vq_quantlist__16c2_s_p6_0[] = {
  125341. 6,
  125342. 5,
  125343. 7,
  125344. 4,
  125345. 8,
  125346. 3,
  125347. 9,
  125348. 2,
  125349. 10,
  125350. 1,
  125351. 11,
  125352. 0,
  125353. 12,
  125354. };
  125355. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125356. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125357. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125358. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125359. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125360. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125361. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. };
  125368. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125369. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125370. 12.5, 17.5, 22.5, 27.5,
  125371. };
  125372. static long _vq_quantmap__16c2_s_p6_0[] = {
  125373. 11, 9, 7, 5, 3, 1, 0, 2,
  125374. 4, 6, 8, 10, 12,
  125375. };
  125376. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125377. _vq_quantthresh__16c2_s_p6_0,
  125378. _vq_quantmap__16c2_s_p6_0,
  125379. 13,
  125380. 13
  125381. };
  125382. static static_codebook _16c2_s_p6_0 = {
  125383. 2, 169,
  125384. _vq_lengthlist__16c2_s_p6_0,
  125385. 1, -526516224, 1616117760, 4, 0,
  125386. _vq_quantlist__16c2_s_p6_0,
  125387. NULL,
  125388. &_vq_auxt__16c2_s_p6_0,
  125389. NULL,
  125390. 0
  125391. };
  125392. static long _vq_quantlist__16c2_s_p6_1[] = {
  125393. 2,
  125394. 1,
  125395. 3,
  125396. 0,
  125397. 4,
  125398. };
  125399. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125400. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125401. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125402. };
  125403. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125404. -1.5, -0.5, 0.5, 1.5,
  125405. };
  125406. static long _vq_quantmap__16c2_s_p6_1[] = {
  125407. 3, 1, 0, 2, 4,
  125408. };
  125409. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125410. _vq_quantthresh__16c2_s_p6_1,
  125411. _vq_quantmap__16c2_s_p6_1,
  125412. 5,
  125413. 5
  125414. };
  125415. static static_codebook _16c2_s_p6_1 = {
  125416. 2, 25,
  125417. _vq_lengthlist__16c2_s_p6_1,
  125418. 1, -533725184, 1611661312, 3, 0,
  125419. _vq_quantlist__16c2_s_p6_1,
  125420. NULL,
  125421. &_vq_auxt__16c2_s_p6_1,
  125422. NULL,
  125423. 0
  125424. };
  125425. static long _vq_quantlist__16c2_s_p7_0[] = {
  125426. 6,
  125427. 5,
  125428. 7,
  125429. 4,
  125430. 8,
  125431. 3,
  125432. 9,
  125433. 2,
  125434. 10,
  125435. 1,
  125436. 11,
  125437. 0,
  125438. 12,
  125439. };
  125440. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125441. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125442. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125443. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125444. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125445. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125446. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125447. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125448. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125449. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125450. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125451. 18,13,14,13,13,14,13,15,14,
  125452. };
  125453. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125454. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125455. 27.5, 38.5, 49.5, 60.5,
  125456. };
  125457. static long _vq_quantmap__16c2_s_p7_0[] = {
  125458. 11, 9, 7, 5, 3, 1, 0, 2,
  125459. 4, 6, 8, 10, 12,
  125460. };
  125461. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125462. _vq_quantthresh__16c2_s_p7_0,
  125463. _vq_quantmap__16c2_s_p7_0,
  125464. 13,
  125465. 13
  125466. };
  125467. static static_codebook _16c2_s_p7_0 = {
  125468. 2, 169,
  125469. _vq_lengthlist__16c2_s_p7_0,
  125470. 1, -523206656, 1618345984, 4, 0,
  125471. _vq_quantlist__16c2_s_p7_0,
  125472. NULL,
  125473. &_vq_auxt__16c2_s_p7_0,
  125474. NULL,
  125475. 0
  125476. };
  125477. static long _vq_quantlist__16c2_s_p7_1[] = {
  125478. 5,
  125479. 4,
  125480. 6,
  125481. 3,
  125482. 7,
  125483. 2,
  125484. 8,
  125485. 1,
  125486. 9,
  125487. 0,
  125488. 10,
  125489. };
  125490. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125491. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125492. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125493. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125494. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125495. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125496. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125497. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125498. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125499. };
  125500. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125501. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125502. 3.5, 4.5,
  125503. };
  125504. static long _vq_quantmap__16c2_s_p7_1[] = {
  125505. 9, 7, 5, 3, 1, 0, 2, 4,
  125506. 6, 8, 10,
  125507. };
  125508. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125509. _vq_quantthresh__16c2_s_p7_1,
  125510. _vq_quantmap__16c2_s_p7_1,
  125511. 11,
  125512. 11
  125513. };
  125514. static static_codebook _16c2_s_p7_1 = {
  125515. 2, 121,
  125516. _vq_lengthlist__16c2_s_p7_1,
  125517. 1, -531365888, 1611661312, 4, 0,
  125518. _vq_quantlist__16c2_s_p7_1,
  125519. NULL,
  125520. &_vq_auxt__16c2_s_p7_1,
  125521. NULL,
  125522. 0
  125523. };
  125524. static long _vq_quantlist__16c2_s_p8_0[] = {
  125525. 7,
  125526. 6,
  125527. 8,
  125528. 5,
  125529. 9,
  125530. 4,
  125531. 10,
  125532. 3,
  125533. 11,
  125534. 2,
  125535. 12,
  125536. 1,
  125537. 13,
  125538. 0,
  125539. 14,
  125540. };
  125541. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125542. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125543. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125544. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125545. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125546. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125547. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125548. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125549. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125550. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125551. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125552. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125553. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125554. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125555. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125556. 13,
  125557. };
  125558. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125559. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125560. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125561. };
  125562. static long _vq_quantmap__16c2_s_p8_0[] = {
  125563. 13, 11, 9, 7, 5, 3, 1, 0,
  125564. 2, 4, 6, 8, 10, 12, 14,
  125565. };
  125566. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125567. _vq_quantthresh__16c2_s_p8_0,
  125568. _vq_quantmap__16c2_s_p8_0,
  125569. 15,
  125570. 15
  125571. };
  125572. static static_codebook _16c2_s_p8_0 = {
  125573. 2, 225,
  125574. _vq_lengthlist__16c2_s_p8_0,
  125575. 1, -520986624, 1620377600, 4, 0,
  125576. _vq_quantlist__16c2_s_p8_0,
  125577. NULL,
  125578. &_vq_auxt__16c2_s_p8_0,
  125579. NULL,
  125580. 0
  125581. };
  125582. static long _vq_quantlist__16c2_s_p8_1[] = {
  125583. 10,
  125584. 9,
  125585. 11,
  125586. 8,
  125587. 12,
  125588. 7,
  125589. 13,
  125590. 6,
  125591. 14,
  125592. 5,
  125593. 15,
  125594. 4,
  125595. 16,
  125596. 3,
  125597. 17,
  125598. 2,
  125599. 18,
  125600. 1,
  125601. 19,
  125602. 0,
  125603. 20,
  125604. };
  125605. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125606. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125607. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125608. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125609. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125610. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125611. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125612. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125613. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125614. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125615. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125616. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125617. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125618. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125619. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125620. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125621. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125622. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125623. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125624. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125625. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125626. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125627. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125628. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125629. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125630. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125631. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125632. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125633. 10,11,10,10,10,10,10,10,10,
  125634. };
  125635. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125636. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125637. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125638. 6.5, 7.5, 8.5, 9.5,
  125639. };
  125640. static long _vq_quantmap__16c2_s_p8_1[] = {
  125641. 19, 17, 15, 13, 11, 9, 7, 5,
  125642. 3, 1, 0, 2, 4, 6, 8, 10,
  125643. 12, 14, 16, 18, 20,
  125644. };
  125645. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125646. _vq_quantthresh__16c2_s_p8_1,
  125647. _vq_quantmap__16c2_s_p8_1,
  125648. 21,
  125649. 21
  125650. };
  125651. static static_codebook _16c2_s_p8_1 = {
  125652. 2, 441,
  125653. _vq_lengthlist__16c2_s_p8_1,
  125654. 1, -529268736, 1611661312, 5, 0,
  125655. _vq_quantlist__16c2_s_p8_1,
  125656. NULL,
  125657. &_vq_auxt__16c2_s_p8_1,
  125658. NULL,
  125659. 0
  125660. };
  125661. static long _vq_quantlist__16c2_s_p9_0[] = {
  125662. 6,
  125663. 5,
  125664. 7,
  125665. 4,
  125666. 8,
  125667. 3,
  125668. 9,
  125669. 2,
  125670. 10,
  125671. 1,
  125672. 11,
  125673. 0,
  125674. 12,
  125675. };
  125676. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125677. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125678. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125679. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125680. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125681. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125682. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125683. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125684. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125685. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125686. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125687. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125688. };
  125689. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125690. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125691. 2327.5, 3258.5, 4189.5, 5120.5,
  125692. };
  125693. static long _vq_quantmap__16c2_s_p9_0[] = {
  125694. 11, 9, 7, 5, 3, 1, 0, 2,
  125695. 4, 6, 8, 10, 12,
  125696. };
  125697. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125698. _vq_quantthresh__16c2_s_p9_0,
  125699. _vq_quantmap__16c2_s_p9_0,
  125700. 13,
  125701. 13
  125702. };
  125703. static static_codebook _16c2_s_p9_0 = {
  125704. 2, 169,
  125705. _vq_lengthlist__16c2_s_p9_0,
  125706. 1, -510275072, 1631393792, 4, 0,
  125707. _vq_quantlist__16c2_s_p9_0,
  125708. NULL,
  125709. &_vq_auxt__16c2_s_p9_0,
  125710. NULL,
  125711. 0
  125712. };
  125713. static long _vq_quantlist__16c2_s_p9_1[] = {
  125714. 8,
  125715. 7,
  125716. 9,
  125717. 6,
  125718. 10,
  125719. 5,
  125720. 11,
  125721. 4,
  125722. 12,
  125723. 3,
  125724. 13,
  125725. 2,
  125726. 14,
  125727. 1,
  125728. 15,
  125729. 0,
  125730. 16,
  125731. };
  125732. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125733. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125734. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125735. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125736. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125737. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125738. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125739. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125740. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125741. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125742. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125743. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125744. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125745. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125746. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125748. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125749. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125751. 10,
  125752. };
  125753. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125754. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125755. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125756. };
  125757. static long _vq_quantmap__16c2_s_p9_1[] = {
  125758. 15, 13, 11, 9, 7, 5, 3, 1,
  125759. 0, 2, 4, 6, 8, 10, 12, 14,
  125760. 16,
  125761. };
  125762. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125763. _vq_quantthresh__16c2_s_p9_1,
  125764. _vq_quantmap__16c2_s_p9_1,
  125765. 17,
  125766. 17
  125767. };
  125768. static static_codebook _16c2_s_p9_1 = {
  125769. 2, 289,
  125770. _vq_lengthlist__16c2_s_p9_1,
  125771. 1, -518488064, 1622704128, 5, 0,
  125772. _vq_quantlist__16c2_s_p9_1,
  125773. NULL,
  125774. &_vq_auxt__16c2_s_p9_1,
  125775. NULL,
  125776. 0
  125777. };
  125778. static long _vq_quantlist__16c2_s_p9_2[] = {
  125779. 13,
  125780. 12,
  125781. 14,
  125782. 11,
  125783. 15,
  125784. 10,
  125785. 16,
  125786. 9,
  125787. 17,
  125788. 8,
  125789. 18,
  125790. 7,
  125791. 19,
  125792. 6,
  125793. 20,
  125794. 5,
  125795. 21,
  125796. 4,
  125797. 22,
  125798. 3,
  125799. 23,
  125800. 2,
  125801. 24,
  125802. 1,
  125803. 25,
  125804. 0,
  125805. 26,
  125806. };
  125807. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125808. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125809. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125810. };
  125811. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125812. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125813. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125814. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125815. 11.5, 12.5,
  125816. };
  125817. static long _vq_quantmap__16c2_s_p9_2[] = {
  125818. 25, 23, 21, 19, 17, 15, 13, 11,
  125819. 9, 7, 5, 3, 1, 0, 2, 4,
  125820. 6, 8, 10, 12, 14, 16, 18, 20,
  125821. 22, 24, 26,
  125822. };
  125823. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125824. _vq_quantthresh__16c2_s_p9_2,
  125825. _vq_quantmap__16c2_s_p9_2,
  125826. 27,
  125827. 27
  125828. };
  125829. static static_codebook _16c2_s_p9_2 = {
  125830. 1, 27,
  125831. _vq_lengthlist__16c2_s_p9_2,
  125832. 1, -528875520, 1611661312, 5, 0,
  125833. _vq_quantlist__16c2_s_p9_2,
  125834. NULL,
  125835. &_vq_auxt__16c2_s_p9_2,
  125836. NULL,
  125837. 0
  125838. };
  125839. static long _huff_lengthlist__16c2_s_short[] = {
  125840. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125841. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125842. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125843. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125844. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125845. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125846. 15,12,14,14,
  125847. };
  125848. static static_codebook _huff_book__16c2_s_short = {
  125849. 2, 100,
  125850. _huff_lengthlist__16c2_s_short,
  125851. 0, 0, 0, 0, 0,
  125852. NULL,
  125853. NULL,
  125854. NULL,
  125855. NULL,
  125856. 0
  125857. };
  125858. static long _vq_quantlist__8c0_s_p1_0[] = {
  125859. 1,
  125860. 0,
  125861. 2,
  125862. };
  125863. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125864. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125865. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125870. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125875. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  125910. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125915. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125920. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125956. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125961. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125966. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0,
  126275. };
  126276. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126277. -0.5, 0.5,
  126278. };
  126279. static long _vq_quantmap__8c0_s_p1_0[] = {
  126280. 1, 0, 2,
  126281. };
  126282. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126283. _vq_quantthresh__8c0_s_p1_0,
  126284. _vq_quantmap__8c0_s_p1_0,
  126285. 3,
  126286. 3
  126287. };
  126288. static static_codebook _8c0_s_p1_0 = {
  126289. 8, 6561,
  126290. _vq_lengthlist__8c0_s_p1_0,
  126291. 1, -535822336, 1611661312, 2, 0,
  126292. _vq_quantlist__8c0_s_p1_0,
  126293. NULL,
  126294. &_vq_auxt__8c0_s_p1_0,
  126295. NULL,
  126296. 0
  126297. };
  126298. static long _vq_quantlist__8c0_s_p2_0[] = {
  126299. 2,
  126300. 1,
  126301. 3,
  126302. 0,
  126303. 4,
  126304. };
  126305. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0,
  126346. };
  126347. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126348. -1.5, -0.5, 0.5, 1.5,
  126349. };
  126350. static long _vq_quantmap__8c0_s_p2_0[] = {
  126351. 3, 1, 0, 2, 4,
  126352. };
  126353. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126354. _vq_quantthresh__8c0_s_p2_0,
  126355. _vq_quantmap__8c0_s_p2_0,
  126356. 5,
  126357. 5
  126358. };
  126359. static static_codebook _8c0_s_p2_0 = {
  126360. 4, 625,
  126361. _vq_lengthlist__8c0_s_p2_0,
  126362. 1, -533725184, 1611661312, 3, 0,
  126363. _vq_quantlist__8c0_s_p2_0,
  126364. NULL,
  126365. &_vq_auxt__8c0_s_p2_0,
  126366. NULL,
  126367. 0
  126368. };
  126369. static long _vq_quantlist__8c0_s_p3_0[] = {
  126370. 2,
  126371. 1,
  126372. 3,
  126373. 0,
  126374. 4,
  126375. };
  126376. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126377. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0,
  126417. };
  126418. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126419. -1.5, -0.5, 0.5, 1.5,
  126420. };
  126421. static long _vq_quantmap__8c0_s_p3_0[] = {
  126422. 3, 1, 0, 2, 4,
  126423. };
  126424. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126425. _vq_quantthresh__8c0_s_p3_0,
  126426. _vq_quantmap__8c0_s_p3_0,
  126427. 5,
  126428. 5
  126429. };
  126430. static static_codebook _8c0_s_p3_0 = {
  126431. 4, 625,
  126432. _vq_lengthlist__8c0_s_p3_0,
  126433. 1, -533725184, 1611661312, 3, 0,
  126434. _vq_quantlist__8c0_s_p3_0,
  126435. NULL,
  126436. &_vq_auxt__8c0_s_p3_0,
  126437. NULL,
  126438. 0
  126439. };
  126440. static long _vq_quantlist__8c0_s_p4_0[] = {
  126441. 4,
  126442. 3,
  126443. 5,
  126444. 2,
  126445. 6,
  126446. 1,
  126447. 7,
  126448. 0,
  126449. 8,
  126450. };
  126451. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126452. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126453. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126454. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126455. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126456. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0,
  126458. };
  126459. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126460. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126461. };
  126462. static long _vq_quantmap__8c0_s_p4_0[] = {
  126463. 7, 5, 3, 1, 0, 2, 4, 6,
  126464. 8,
  126465. };
  126466. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126467. _vq_quantthresh__8c0_s_p4_0,
  126468. _vq_quantmap__8c0_s_p4_0,
  126469. 9,
  126470. 9
  126471. };
  126472. static static_codebook _8c0_s_p4_0 = {
  126473. 2, 81,
  126474. _vq_lengthlist__8c0_s_p4_0,
  126475. 1, -531628032, 1611661312, 4, 0,
  126476. _vq_quantlist__8c0_s_p4_0,
  126477. NULL,
  126478. &_vq_auxt__8c0_s_p4_0,
  126479. NULL,
  126480. 0
  126481. };
  126482. static long _vq_quantlist__8c0_s_p5_0[] = {
  126483. 4,
  126484. 3,
  126485. 5,
  126486. 2,
  126487. 6,
  126488. 1,
  126489. 7,
  126490. 0,
  126491. 8,
  126492. };
  126493. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126494. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126495. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126496. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126497. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126498. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126499. 10,
  126500. };
  126501. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126502. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126503. };
  126504. static long _vq_quantmap__8c0_s_p5_0[] = {
  126505. 7, 5, 3, 1, 0, 2, 4, 6,
  126506. 8,
  126507. };
  126508. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126509. _vq_quantthresh__8c0_s_p5_0,
  126510. _vq_quantmap__8c0_s_p5_0,
  126511. 9,
  126512. 9
  126513. };
  126514. static static_codebook _8c0_s_p5_0 = {
  126515. 2, 81,
  126516. _vq_lengthlist__8c0_s_p5_0,
  126517. 1, -531628032, 1611661312, 4, 0,
  126518. _vq_quantlist__8c0_s_p5_0,
  126519. NULL,
  126520. &_vq_auxt__8c0_s_p5_0,
  126521. NULL,
  126522. 0
  126523. };
  126524. static long _vq_quantlist__8c0_s_p6_0[] = {
  126525. 8,
  126526. 7,
  126527. 9,
  126528. 6,
  126529. 10,
  126530. 5,
  126531. 11,
  126532. 4,
  126533. 12,
  126534. 3,
  126535. 13,
  126536. 2,
  126537. 14,
  126538. 1,
  126539. 15,
  126540. 0,
  126541. 16,
  126542. };
  126543. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126544. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126545. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126546. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126547. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126548. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126549. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126550. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126551. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126552. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126553. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126554. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126555. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126556. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126557. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126558. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126559. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126560. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126562. 14,
  126563. };
  126564. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126565. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126566. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126567. };
  126568. static long _vq_quantmap__8c0_s_p6_0[] = {
  126569. 15, 13, 11, 9, 7, 5, 3, 1,
  126570. 0, 2, 4, 6, 8, 10, 12, 14,
  126571. 16,
  126572. };
  126573. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126574. _vq_quantthresh__8c0_s_p6_0,
  126575. _vq_quantmap__8c0_s_p6_0,
  126576. 17,
  126577. 17
  126578. };
  126579. static static_codebook _8c0_s_p6_0 = {
  126580. 2, 289,
  126581. _vq_lengthlist__8c0_s_p6_0,
  126582. 1, -529530880, 1611661312, 5, 0,
  126583. _vq_quantlist__8c0_s_p6_0,
  126584. NULL,
  126585. &_vq_auxt__8c0_s_p6_0,
  126586. NULL,
  126587. 0
  126588. };
  126589. static long _vq_quantlist__8c0_s_p7_0[] = {
  126590. 1,
  126591. 0,
  126592. 2,
  126593. };
  126594. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126595. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126596. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126597. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126598. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126599. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126600. 10,
  126601. };
  126602. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126603. -5.5, 5.5,
  126604. };
  126605. static long _vq_quantmap__8c0_s_p7_0[] = {
  126606. 1, 0, 2,
  126607. };
  126608. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126609. _vq_quantthresh__8c0_s_p7_0,
  126610. _vq_quantmap__8c0_s_p7_0,
  126611. 3,
  126612. 3
  126613. };
  126614. static static_codebook _8c0_s_p7_0 = {
  126615. 4, 81,
  126616. _vq_lengthlist__8c0_s_p7_0,
  126617. 1, -529137664, 1618345984, 2, 0,
  126618. _vq_quantlist__8c0_s_p7_0,
  126619. NULL,
  126620. &_vq_auxt__8c0_s_p7_0,
  126621. NULL,
  126622. 0
  126623. };
  126624. static long _vq_quantlist__8c0_s_p7_1[] = {
  126625. 5,
  126626. 4,
  126627. 6,
  126628. 3,
  126629. 7,
  126630. 2,
  126631. 8,
  126632. 1,
  126633. 9,
  126634. 0,
  126635. 10,
  126636. };
  126637. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126638. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126639. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126640. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126641. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126642. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126643. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126644. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126645. 10,10,10, 9, 9, 9,10,10,10,
  126646. };
  126647. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126648. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126649. 3.5, 4.5,
  126650. };
  126651. static long _vq_quantmap__8c0_s_p7_1[] = {
  126652. 9, 7, 5, 3, 1, 0, 2, 4,
  126653. 6, 8, 10,
  126654. };
  126655. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126656. _vq_quantthresh__8c0_s_p7_1,
  126657. _vq_quantmap__8c0_s_p7_1,
  126658. 11,
  126659. 11
  126660. };
  126661. static static_codebook _8c0_s_p7_1 = {
  126662. 2, 121,
  126663. _vq_lengthlist__8c0_s_p7_1,
  126664. 1, -531365888, 1611661312, 4, 0,
  126665. _vq_quantlist__8c0_s_p7_1,
  126666. NULL,
  126667. &_vq_auxt__8c0_s_p7_1,
  126668. NULL,
  126669. 0
  126670. };
  126671. static long _vq_quantlist__8c0_s_p8_0[] = {
  126672. 6,
  126673. 5,
  126674. 7,
  126675. 4,
  126676. 8,
  126677. 3,
  126678. 9,
  126679. 2,
  126680. 10,
  126681. 1,
  126682. 11,
  126683. 0,
  126684. 12,
  126685. };
  126686. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126687. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126688. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126689. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126690. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126691. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126692. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126693. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126694. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126695. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126696. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126697. 0, 0,13,13,11,13,13,11,12,
  126698. };
  126699. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126700. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126701. 12.5, 17.5, 22.5, 27.5,
  126702. };
  126703. static long _vq_quantmap__8c0_s_p8_0[] = {
  126704. 11, 9, 7, 5, 3, 1, 0, 2,
  126705. 4, 6, 8, 10, 12,
  126706. };
  126707. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126708. _vq_quantthresh__8c0_s_p8_0,
  126709. _vq_quantmap__8c0_s_p8_0,
  126710. 13,
  126711. 13
  126712. };
  126713. static static_codebook _8c0_s_p8_0 = {
  126714. 2, 169,
  126715. _vq_lengthlist__8c0_s_p8_0,
  126716. 1, -526516224, 1616117760, 4, 0,
  126717. _vq_quantlist__8c0_s_p8_0,
  126718. NULL,
  126719. &_vq_auxt__8c0_s_p8_0,
  126720. NULL,
  126721. 0
  126722. };
  126723. static long _vq_quantlist__8c0_s_p8_1[] = {
  126724. 2,
  126725. 1,
  126726. 3,
  126727. 0,
  126728. 4,
  126729. };
  126730. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126731. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126732. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126733. };
  126734. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126735. -1.5, -0.5, 0.5, 1.5,
  126736. };
  126737. static long _vq_quantmap__8c0_s_p8_1[] = {
  126738. 3, 1, 0, 2, 4,
  126739. };
  126740. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126741. _vq_quantthresh__8c0_s_p8_1,
  126742. _vq_quantmap__8c0_s_p8_1,
  126743. 5,
  126744. 5
  126745. };
  126746. static static_codebook _8c0_s_p8_1 = {
  126747. 2, 25,
  126748. _vq_lengthlist__8c0_s_p8_1,
  126749. 1, -533725184, 1611661312, 3, 0,
  126750. _vq_quantlist__8c0_s_p8_1,
  126751. NULL,
  126752. &_vq_auxt__8c0_s_p8_1,
  126753. NULL,
  126754. 0
  126755. };
  126756. static long _vq_quantlist__8c0_s_p9_0[] = {
  126757. 1,
  126758. 0,
  126759. 2,
  126760. };
  126761. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126762. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126763. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126764. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126765. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126766. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126767. 7,
  126768. };
  126769. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126770. -157.5, 157.5,
  126771. };
  126772. static long _vq_quantmap__8c0_s_p9_0[] = {
  126773. 1, 0, 2,
  126774. };
  126775. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126776. _vq_quantthresh__8c0_s_p9_0,
  126777. _vq_quantmap__8c0_s_p9_0,
  126778. 3,
  126779. 3
  126780. };
  126781. static static_codebook _8c0_s_p9_0 = {
  126782. 4, 81,
  126783. _vq_lengthlist__8c0_s_p9_0,
  126784. 1, -518803456, 1628680192, 2, 0,
  126785. _vq_quantlist__8c0_s_p9_0,
  126786. NULL,
  126787. &_vq_auxt__8c0_s_p9_0,
  126788. NULL,
  126789. 0
  126790. };
  126791. static long _vq_quantlist__8c0_s_p9_1[] = {
  126792. 7,
  126793. 6,
  126794. 8,
  126795. 5,
  126796. 9,
  126797. 4,
  126798. 10,
  126799. 3,
  126800. 11,
  126801. 2,
  126802. 12,
  126803. 1,
  126804. 13,
  126805. 0,
  126806. 14,
  126807. };
  126808. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126809. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126810. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126811. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126812. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126813. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126814. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126816. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126820. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126821. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126822. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126823. 11,
  126824. };
  126825. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126826. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126827. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126828. };
  126829. static long _vq_quantmap__8c0_s_p9_1[] = {
  126830. 13, 11, 9, 7, 5, 3, 1, 0,
  126831. 2, 4, 6, 8, 10, 12, 14,
  126832. };
  126833. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126834. _vq_quantthresh__8c0_s_p9_1,
  126835. _vq_quantmap__8c0_s_p9_1,
  126836. 15,
  126837. 15
  126838. };
  126839. static static_codebook _8c0_s_p9_1 = {
  126840. 2, 225,
  126841. _vq_lengthlist__8c0_s_p9_1,
  126842. 1, -520986624, 1620377600, 4, 0,
  126843. _vq_quantlist__8c0_s_p9_1,
  126844. NULL,
  126845. &_vq_auxt__8c0_s_p9_1,
  126846. NULL,
  126847. 0
  126848. };
  126849. static long _vq_quantlist__8c0_s_p9_2[] = {
  126850. 10,
  126851. 9,
  126852. 11,
  126853. 8,
  126854. 12,
  126855. 7,
  126856. 13,
  126857. 6,
  126858. 14,
  126859. 5,
  126860. 15,
  126861. 4,
  126862. 16,
  126863. 3,
  126864. 17,
  126865. 2,
  126866. 18,
  126867. 1,
  126868. 19,
  126869. 0,
  126870. 20,
  126871. };
  126872. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126873. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126874. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126875. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126876. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126877. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126878. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126879. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126880. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126881. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126882. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126883. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126884. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126885. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126886. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126887. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126888. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126889. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126890. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126891. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126892. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126893. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126894. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126895. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126896. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126897. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126898. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126899. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126900. 10,11, 9,11,10, 9,10, 9,10,
  126901. };
  126902. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126903. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126904. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126905. 6.5, 7.5, 8.5, 9.5,
  126906. };
  126907. static long _vq_quantmap__8c0_s_p9_2[] = {
  126908. 19, 17, 15, 13, 11, 9, 7, 5,
  126909. 3, 1, 0, 2, 4, 6, 8, 10,
  126910. 12, 14, 16, 18, 20,
  126911. };
  126912. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126913. _vq_quantthresh__8c0_s_p9_2,
  126914. _vq_quantmap__8c0_s_p9_2,
  126915. 21,
  126916. 21
  126917. };
  126918. static static_codebook _8c0_s_p9_2 = {
  126919. 2, 441,
  126920. _vq_lengthlist__8c0_s_p9_2,
  126921. 1, -529268736, 1611661312, 5, 0,
  126922. _vq_quantlist__8c0_s_p9_2,
  126923. NULL,
  126924. &_vq_auxt__8c0_s_p9_2,
  126925. NULL,
  126926. 0
  126927. };
  126928. static long _huff_lengthlist__8c0_s_single[] = {
  126929. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126930. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126931. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126932. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126933. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126934. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126935. 17,16,17,17,
  126936. };
  126937. static static_codebook _huff_book__8c0_s_single = {
  126938. 2, 100,
  126939. _huff_lengthlist__8c0_s_single,
  126940. 0, 0, 0, 0, 0,
  126941. NULL,
  126942. NULL,
  126943. NULL,
  126944. NULL,
  126945. 0
  126946. };
  126947. static long _vq_quantlist__8c1_s_p1_0[] = {
  126948. 1,
  126949. 0,
  126950. 2,
  126951. };
  126952. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126953. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126954. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126959. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126964. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  126999. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  127004. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  127009. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127045. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127050. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127055. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0,
  127364. };
  127365. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127366. -0.5, 0.5,
  127367. };
  127368. static long _vq_quantmap__8c1_s_p1_0[] = {
  127369. 1, 0, 2,
  127370. };
  127371. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127372. _vq_quantthresh__8c1_s_p1_0,
  127373. _vq_quantmap__8c1_s_p1_0,
  127374. 3,
  127375. 3
  127376. };
  127377. static static_codebook _8c1_s_p1_0 = {
  127378. 8, 6561,
  127379. _vq_lengthlist__8c1_s_p1_0,
  127380. 1, -535822336, 1611661312, 2, 0,
  127381. _vq_quantlist__8c1_s_p1_0,
  127382. NULL,
  127383. &_vq_auxt__8c1_s_p1_0,
  127384. NULL,
  127385. 0
  127386. };
  127387. static long _vq_quantlist__8c1_s_p2_0[] = {
  127388. 2,
  127389. 1,
  127390. 3,
  127391. 0,
  127392. 4,
  127393. };
  127394. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0,
  127435. };
  127436. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127437. -1.5, -0.5, 0.5, 1.5,
  127438. };
  127439. static long _vq_quantmap__8c1_s_p2_0[] = {
  127440. 3, 1, 0, 2, 4,
  127441. };
  127442. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127443. _vq_quantthresh__8c1_s_p2_0,
  127444. _vq_quantmap__8c1_s_p2_0,
  127445. 5,
  127446. 5
  127447. };
  127448. static static_codebook _8c1_s_p2_0 = {
  127449. 4, 625,
  127450. _vq_lengthlist__8c1_s_p2_0,
  127451. 1, -533725184, 1611661312, 3, 0,
  127452. _vq_quantlist__8c1_s_p2_0,
  127453. NULL,
  127454. &_vq_auxt__8c1_s_p2_0,
  127455. NULL,
  127456. 0
  127457. };
  127458. static long _vq_quantlist__8c1_s_p3_0[] = {
  127459. 2,
  127460. 1,
  127461. 3,
  127462. 0,
  127463. 4,
  127464. };
  127465. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127466. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0,
  127506. };
  127507. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127508. -1.5, -0.5, 0.5, 1.5,
  127509. };
  127510. static long _vq_quantmap__8c1_s_p3_0[] = {
  127511. 3, 1, 0, 2, 4,
  127512. };
  127513. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127514. _vq_quantthresh__8c1_s_p3_0,
  127515. _vq_quantmap__8c1_s_p3_0,
  127516. 5,
  127517. 5
  127518. };
  127519. static static_codebook _8c1_s_p3_0 = {
  127520. 4, 625,
  127521. _vq_lengthlist__8c1_s_p3_0,
  127522. 1, -533725184, 1611661312, 3, 0,
  127523. _vq_quantlist__8c1_s_p3_0,
  127524. NULL,
  127525. &_vq_auxt__8c1_s_p3_0,
  127526. NULL,
  127527. 0
  127528. };
  127529. static long _vq_quantlist__8c1_s_p4_0[] = {
  127530. 4,
  127531. 3,
  127532. 5,
  127533. 2,
  127534. 6,
  127535. 1,
  127536. 7,
  127537. 0,
  127538. 8,
  127539. };
  127540. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127541. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127542. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127543. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127544. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127545. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127546. 0,
  127547. };
  127548. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127549. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127550. };
  127551. static long _vq_quantmap__8c1_s_p4_0[] = {
  127552. 7, 5, 3, 1, 0, 2, 4, 6,
  127553. 8,
  127554. };
  127555. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127556. _vq_quantthresh__8c1_s_p4_0,
  127557. _vq_quantmap__8c1_s_p4_0,
  127558. 9,
  127559. 9
  127560. };
  127561. static static_codebook _8c1_s_p4_0 = {
  127562. 2, 81,
  127563. _vq_lengthlist__8c1_s_p4_0,
  127564. 1, -531628032, 1611661312, 4, 0,
  127565. _vq_quantlist__8c1_s_p4_0,
  127566. NULL,
  127567. &_vq_auxt__8c1_s_p4_0,
  127568. NULL,
  127569. 0
  127570. };
  127571. static long _vq_quantlist__8c1_s_p5_0[] = {
  127572. 4,
  127573. 3,
  127574. 5,
  127575. 2,
  127576. 6,
  127577. 1,
  127578. 7,
  127579. 0,
  127580. 8,
  127581. };
  127582. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127583. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127584. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127585. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127586. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127587. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127588. 10,
  127589. };
  127590. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127591. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127592. };
  127593. static long _vq_quantmap__8c1_s_p5_0[] = {
  127594. 7, 5, 3, 1, 0, 2, 4, 6,
  127595. 8,
  127596. };
  127597. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127598. _vq_quantthresh__8c1_s_p5_0,
  127599. _vq_quantmap__8c1_s_p5_0,
  127600. 9,
  127601. 9
  127602. };
  127603. static static_codebook _8c1_s_p5_0 = {
  127604. 2, 81,
  127605. _vq_lengthlist__8c1_s_p5_0,
  127606. 1, -531628032, 1611661312, 4, 0,
  127607. _vq_quantlist__8c1_s_p5_0,
  127608. NULL,
  127609. &_vq_auxt__8c1_s_p5_0,
  127610. NULL,
  127611. 0
  127612. };
  127613. static long _vq_quantlist__8c1_s_p6_0[] = {
  127614. 8,
  127615. 7,
  127616. 9,
  127617. 6,
  127618. 10,
  127619. 5,
  127620. 11,
  127621. 4,
  127622. 12,
  127623. 3,
  127624. 13,
  127625. 2,
  127626. 14,
  127627. 1,
  127628. 15,
  127629. 0,
  127630. 16,
  127631. };
  127632. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127633. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127634. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127635. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127636. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127637. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127638. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127639. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127640. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127641. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127642. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127643. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127644. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127645. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127646. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127647. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127648. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127649. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127651. 14,
  127652. };
  127653. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127654. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127655. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127656. };
  127657. static long _vq_quantmap__8c1_s_p6_0[] = {
  127658. 15, 13, 11, 9, 7, 5, 3, 1,
  127659. 0, 2, 4, 6, 8, 10, 12, 14,
  127660. 16,
  127661. };
  127662. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127663. _vq_quantthresh__8c1_s_p6_0,
  127664. _vq_quantmap__8c1_s_p6_0,
  127665. 17,
  127666. 17
  127667. };
  127668. static static_codebook _8c1_s_p6_0 = {
  127669. 2, 289,
  127670. _vq_lengthlist__8c1_s_p6_0,
  127671. 1, -529530880, 1611661312, 5, 0,
  127672. _vq_quantlist__8c1_s_p6_0,
  127673. NULL,
  127674. &_vq_auxt__8c1_s_p6_0,
  127675. NULL,
  127676. 0
  127677. };
  127678. static long _vq_quantlist__8c1_s_p7_0[] = {
  127679. 1,
  127680. 0,
  127681. 2,
  127682. };
  127683. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127684. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127685. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127686. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127687. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127688. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127689. 9,
  127690. };
  127691. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127692. -5.5, 5.5,
  127693. };
  127694. static long _vq_quantmap__8c1_s_p7_0[] = {
  127695. 1, 0, 2,
  127696. };
  127697. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127698. _vq_quantthresh__8c1_s_p7_0,
  127699. _vq_quantmap__8c1_s_p7_0,
  127700. 3,
  127701. 3
  127702. };
  127703. static static_codebook _8c1_s_p7_0 = {
  127704. 4, 81,
  127705. _vq_lengthlist__8c1_s_p7_0,
  127706. 1, -529137664, 1618345984, 2, 0,
  127707. _vq_quantlist__8c1_s_p7_0,
  127708. NULL,
  127709. &_vq_auxt__8c1_s_p7_0,
  127710. NULL,
  127711. 0
  127712. };
  127713. static long _vq_quantlist__8c1_s_p7_1[] = {
  127714. 5,
  127715. 4,
  127716. 6,
  127717. 3,
  127718. 7,
  127719. 2,
  127720. 8,
  127721. 1,
  127722. 9,
  127723. 0,
  127724. 10,
  127725. };
  127726. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127727. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127728. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127729. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127730. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127731. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127732. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127733. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127734. 10,10,10, 8, 8, 8, 8, 8, 8,
  127735. };
  127736. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127737. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127738. 3.5, 4.5,
  127739. };
  127740. static long _vq_quantmap__8c1_s_p7_1[] = {
  127741. 9, 7, 5, 3, 1, 0, 2, 4,
  127742. 6, 8, 10,
  127743. };
  127744. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127745. _vq_quantthresh__8c1_s_p7_1,
  127746. _vq_quantmap__8c1_s_p7_1,
  127747. 11,
  127748. 11
  127749. };
  127750. static static_codebook _8c1_s_p7_1 = {
  127751. 2, 121,
  127752. _vq_lengthlist__8c1_s_p7_1,
  127753. 1, -531365888, 1611661312, 4, 0,
  127754. _vq_quantlist__8c1_s_p7_1,
  127755. NULL,
  127756. &_vq_auxt__8c1_s_p7_1,
  127757. NULL,
  127758. 0
  127759. };
  127760. static long _vq_quantlist__8c1_s_p8_0[] = {
  127761. 6,
  127762. 5,
  127763. 7,
  127764. 4,
  127765. 8,
  127766. 3,
  127767. 9,
  127768. 2,
  127769. 10,
  127770. 1,
  127771. 11,
  127772. 0,
  127773. 12,
  127774. };
  127775. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127776. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127777. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127778. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127779. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127780. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127781. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127782. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127783. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127784. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127785. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127786. 0,12,12,11,10,12,11,13,12,
  127787. };
  127788. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127789. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127790. 12.5, 17.5, 22.5, 27.5,
  127791. };
  127792. static long _vq_quantmap__8c1_s_p8_0[] = {
  127793. 11, 9, 7, 5, 3, 1, 0, 2,
  127794. 4, 6, 8, 10, 12,
  127795. };
  127796. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127797. _vq_quantthresh__8c1_s_p8_0,
  127798. _vq_quantmap__8c1_s_p8_0,
  127799. 13,
  127800. 13
  127801. };
  127802. static static_codebook _8c1_s_p8_0 = {
  127803. 2, 169,
  127804. _vq_lengthlist__8c1_s_p8_0,
  127805. 1, -526516224, 1616117760, 4, 0,
  127806. _vq_quantlist__8c1_s_p8_0,
  127807. NULL,
  127808. &_vq_auxt__8c1_s_p8_0,
  127809. NULL,
  127810. 0
  127811. };
  127812. static long _vq_quantlist__8c1_s_p8_1[] = {
  127813. 2,
  127814. 1,
  127815. 3,
  127816. 0,
  127817. 4,
  127818. };
  127819. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127820. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127821. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127822. };
  127823. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127824. -1.5, -0.5, 0.5, 1.5,
  127825. };
  127826. static long _vq_quantmap__8c1_s_p8_1[] = {
  127827. 3, 1, 0, 2, 4,
  127828. };
  127829. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127830. _vq_quantthresh__8c1_s_p8_1,
  127831. _vq_quantmap__8c1_s_p8_1,
  127832. 5,
  127833. 5
  127834. };
  127835. static static_codebook _8c1_s_p8_1 = {
  127836. 2, 25,
  127837. _vq_lengthlist__8c1_s_p8_1,
  127838. 1, -533725184, 1611661312, 3, 0,
  127839. _vq_quantlist__8c1_s_p8_1,
  127840. NULL,
  127841. &_vq_auxt__8c1_s_p8_1,
  127842. NULL,
  127843. 0
  127844. };
  127845. static long _vq_quantlist__8c1_s_p9_0[] = {
  127846. 6,
  127847. 5,
  127848. 7,
  127849. 4,
  127850. 8,
  127851. 3,
  127852. 9,
  127853. 2,
  127854. 10,
  127855. 1,
  127856. 11,
  127857. 0,
  127858. 12,
  127859. };
  127860. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127861. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127862. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127863. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127864. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127865. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127866. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127867. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127868. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127869. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127871. 10,10,10,10,10, 9, 9, 9, 9,
  127872. };
  127873. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127874. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127875. 787.5, 1102.5, 1417.5, 1732.5,
  127876. };
  127877. static long _vq_quantmap__8c1_s_p9_0[] = {
  127878. 11, 9, 7, 5, 3, 1, 0, 2,
  127879. 4, 6, 8, 10, 12,
  127880. };
  127881. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127882. _vq_quantthresh__8c1_s_p9_0,
  127883. _vq_quantmap__8c1_s_p9_0,
  127884. 13,
  127885. 13
  127886. };
  127887. static static_codebook _8c1_s_p9_0 = {
  127888. 2, 169,
  127889. _vq_lengthlist__8c1_s_p9_0,
  127890. 1, -513964032, 1628680192, 4, 0,
  127891. _vq_quantlist__8c1_s_p9_0,
  127892. NULL,
  127893. &_vq_auxt__8c1_s_p9_0,
  127894. NULL,
  127895. 0
  127896. };
  127897. static long _vq_quantlist__8c1_s_p9_1[] = {
  127898. 7,
  127899. 6,
  127900. 8,
  127901. 5,
  127902. 9,
  127903. 4,
  127904. 10,
  127905. 3,
  127906. 11,
  127907. 2,
  127908. 12,
  127909. 1,
  127910. 13,
  127911. 0,
  127912. 14,
  127913. };
  127914. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127915. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127916. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127917. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127918. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127919. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127920. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127921. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127922. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127923. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127924. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127925. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127926. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127927. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127928. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127929. 15,
  127930. };
  127931. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127932. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127933. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127934. };
  127935. static long _vq_quantmap__8c1_s_p9_1[] = {
  127936. 13, 11, 9, 7, 5, 3, 1, 0,
  127937. 2, 4, 6, 8, 10, 12, 14,
  127938. };
  127939. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127940. _vq_quantthresh__8c1_s_p9_1,
  127941. _vq_quantmap__8c1_s_p9_1,
  127942. 15,
  127943. 15
  127944. };
  127945. static static_codebook _8c1_s_p9_1 = {
  127946. 2, 225,
  127947. _vq_lengthlist__8c1_s_p9_1,
  127948. 1, -520986624, 1620377600, 4, 0,
  127949. _vq_quantlist__8c1_s_p9_1,
  127950. NULL,
  127951. &_vq_auxt__8c1_s_p9_1,
  127952. NULL,
  127953. 0
  127954. };
  127955. static long _vq_quantlist__8c1_s_p9_2[] = {
  127956. 10,
  127957. 9,
  127958. 11,
  127959. 8,
  127960. 12,
  127961. 7,
  127962. 13,
  127963. 6,
  127964. 14,
  127965. 5,
  127966. 15,
  127967. 4,
  127968. 16,
  127969. 3,
  127970. 17,
  127971. 2,
  127972. 18,
  127973. 1,
  127974. 19,
  127975. 0,
  127976. 20,
  127977. };
  127978. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127979. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127980. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127981. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127982. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127983. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127984. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127985. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127986. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127987. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127988. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127989. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127990. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127991. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127992. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127993. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127994. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127995. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127996. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127997. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127998. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127999. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128000. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  128001. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  128002. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128003. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  128004. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  128005. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  128006. 10,10,10,10,10,10,10,10,10,
  128007. };
  128008. static float _vq_quantthresh__8c1_s_p9_2[] = {
  128009. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128010. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128011. 6.5, 7.5, 8.5, 9.5,
  128012. };
  128013. static long _vq_quantmap__8c1_s_p9_2[] = {
  128014. 19, 17, 15, 13, 11, 9, 7, 5,
  128015. 3, 1, 0, 2, 4, 6, 8, 10,
  128016. 12, 14, 16, 18, 20,
  128017. };
  128018. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  128019. _vq_quantthresh__8c1_s_p9_2,
  128020. _vq_quantmap__8c1_s_p9_2,
  128021. 21,
  128022. 21
  128023. };
  128024. static static_codebook _8c1_s_p9_2 = {
  128025. 2, 441,
  128026. _vq_lengthlist__8c1_s_p9_2,
  128027. 1, -529268736, 1611661312, 5, 0,
  128028. _vq_quantlist__8c1_s_p9_2,
  128029. NULL,
  128030. &_vq_auxt__8c1_s_p9_2,
  128031. NULL,
  128032. 0
  128033. };
  128034. static long _huff_lengthlist__8c1_s_single[] = {
  128035. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  128036. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  128037. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  128038. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  128039. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  128040. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  128041. 9, 7, 7, 8,
  128042. };
  128043. static static_codebook _huff_book__8c1_s_single = {
  128044. 2, 100,
  128045. _huff_lengthlist__8c1_s_single,
  128046. 0, 0, 0, 0, 0,
  128047. NULL,
  128048. NULL,
  128049. NULL,
  128050. NULL,
  128051. 0
  128052. };
  128053. static long _huff_lengthlist__44c2_s_long[] = {
  128054. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  128055. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  128056. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  128057. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  128058. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  128059. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  128060. 10, 8, 8, 9,
  128061. };
  128062. static static_codebook _huff_book__44c2_s_long = {
  128063. 2, 100,
  128064. _huff_lengthlist__44c2_s_long,
  128065. 0, 0, 0, 0, 0,
  128066. NULL,
  128067. NULL,
  128068. NULL,
  128069. NULL,
  128070. 0
  128071. };
  128072. static long _vq_quantlist__44c2_s_p1_0[] = {
  128073. 1,
  128074. 0,
  128075. 2,
  128076. };
  128077. static long _vq_lengthlist__44c2_s_p1_0[] = {
  128078. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128079. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128084. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128089. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  128124. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128129. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128134. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128170. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128175. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128180. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0,
  128489. };
  128490. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128491. -0.5, 0.5,
  128492. };
  128493. static long _vq_quantmap__44c2_s_p1_0[] = {
  128494. 1, 0, 2,
  128495. };
  128496. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128497. _vq_quantthresh__44c2_s_p1_0,
  128498. _vq_quantmap__44c2_s_p1_0,
  128499. 3,
  128500. 3
  128501. };
  128502. static static_codebook _44c2_s_p1_0 = {
  128503. 8, 6561,
  128504. _vq_lengthlist__44c2_s_p1_0,
  128505. 1, -535822336, 1611661312, 2, 0,
  128506. _vq_quantlist__44c2_s_p1_0,
  128507. NULL,
  128508. &_vq_auxt__44c2_s_p1_0,
  128509. NULL,
  128510. 0
  128511. };
  128512. static long _vq_quantlist__44c2_s_p2_0[] = {
  128513. 2,
  128514. 1,
  128515. 3,
  128516. 0,
  128517. 4,
  128518. };
  128519. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128520. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128521. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128522. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128523. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128524. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128529. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128530. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128531. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128532. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128537. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128538. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128539. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128545. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128546. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128547. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0,
  128560. };
  128561. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128562. -1.5, -0.5, 0.5, 1.5,
  128563. };
  128564. static long _vq_quantmap__44c2_s_p2_0[] = {
  128565. 3, 1, 0, 2, 4,
  128566. };
  128567. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128568. _vq_quantthresh__44c2_s_p2_0,
  128569. _vq_quantmap__44c2_s_p2_0,
  128570. 5,
  128571. 5
  128572. };
  128573. static static_codebook _44c2_s_p2_0 = {
  128574. 4, 625,
  128575. _vq_lengthlist__44c2_s_p2_0,
  128576. 1, -533725184, 1611661312, 3, 0,
  128577. _vq_quantlist__44c2_s_p2_0,
  128578. NULL,
  128579. &_vq_auxt__44c2_s_p2_0,
  128580. NULL,
  128581. 0
  128582. };
  128583. static long _vq_quantlist__44c2_s_p3_0[] = {
  128584. 2,
  128585. 1,
  128586. 3,
  128587. 0,
  128588. 4,
  128589. };
  128590. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128591. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128594. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128597. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0,
  128631. };
  128632. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128633. -1.5, -0.5, 0.5, 1.5,
  128634. };
  128635. static long _vq_quantmap__44c2_s_p3_0[] = {
  128636. 3, 1, 0, 2, 4,
  128637. };
  128638. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128639. _vq_quantthresh__44c2_s_p3_0,
  128640. _vq_quantmap__44c2_s_p3_0,
  128641. 5,
  128642. 5
  128643. };
  128644. static static_codebook _44c2_s_p3_0 = {
  128645. 4, 625,
  128646. _vq_lengthlist__44c2_s_p3_0,
  128647. 1, -533725184, 1611661312, 3, 0,
  128648. _vq_quantlist__44c2_s_p3_0,
  128649. NULL,
  128650. &_vq_auxt__44c2_s_p3_0,
  128651. NULL,
  128652. 0
  128653. };
  128654. static long _vq_quantlist__44c2_s_p4_0[] = {
  128655. 4,
  128656. 3,
  128657. 5,
  128658. 2,
  128659. 6,
  128660. 1,
  128661. 7,
  128662. 0,
  128663. 8,
  128664. };
  128665. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128666. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128667. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128668. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128669. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128670. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0,
  128672. };
  128673. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128674. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128675. };
  128676. static long _vq_quantmap__44c2_s_p4_0[] = {
  128677. 7, 5, 3, 1, 0, 2, 4, 6,
  128678. 8,
  128679. };
  128680. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128681. _vq_quantthresh__44c2_s_p4_0,
  128682. _vq_quantmap__44c2_s_p4_0,
  128683. 9,
  128684. 9
  128685. };
  128686. static static_codebook _44c2_s_p4_0 = {
  128687. 2, 81,
  128688. _vq_lengthlist__44c2_s_p4_0,
  128689. 1, -531628032, 1611661312, 4, 0,
  128690. _vq_quantlist__44c2_s_p4_0,
  128691. NULL,
  128692. &_vq_auxt__44c2_s_p4_0,
  128693. NULL,
  128694. 0
  128695. };
  128696. static long _vq_quantlist__44c2_s_p5_0[] = {
  128697. 4,
  128698. 3,
  128699. 5,
  128700. 2,
  128701. 6,
  128702. 1,
  128703. 7,
  128704. 0,
  128705. 8,
  128706. };
  128707. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128708. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128709. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128710. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128711. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128712. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128713. 11,
  128714. };
  128715. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128716. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128717. };
  128718. static long _vq_quantmap__44c2_s_p5_0[] = {
  128719. 7, 5, 3, 1, 0, 2, 4, 6,
  128720. 8,
  128721. };
  128722. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128723. _vq_quantthresh__44c2_s_p5_0,
  128724. _vq_quantmap__44c2_s_p5_0,
  128725. 9,
  128726. 9
  128727. };
  128728. static static_codebook _44c2_s_p5_0 = {
  128729. 2, 81,
  128730. _vq_lengthlist__44c2_s_p5_0,
  128731. 1, -531628032, 1611661312, 4, 0,
  128732. _vq_quantlist__44c2_s_p5_0,
  128733. NULL,
  128734. &_vq_auxt__44c2_s_p5_0,
  128735. NULL,
  128736. 0
  128737. };
  128738. static long _vq_quantlist__44c2_s_p6_0[] = {
  128739. 8,
  128740. 7,
  128741. 9,
  128742. 6,
  128743. 10,
  128744. 5,
  128745. 11,
  128746. 4,
  128747. 12,
  128748. 3,
  128749. 13,
  128750. 2,
  128751. 14,
  128752. 1,
  128753. 15,
  128754. 0,
  128755. 16,
  128756. };
  128757. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128758. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128759. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128760. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128761. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128762. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128763. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128764. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128765. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128766. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128767. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128768. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128769. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128770. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128771. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128772. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128773. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128774. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128776. 14,
  128777. };
  128778. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128779. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128780. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128781. };
  128782. static long _vq_quantmap__44c2_s_p6_0[] = {
  128783. 15, 13, 11, 9, 7, 5, 3, 1,
  128784. 0, 2, 4, 6, 8, 10, 12, 14,
  128785. 16,
  128786. };
  128787. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128788. _vq_quantthresh__44c2_s_p6_0,
  128789. _vq_quantmap__44c2_s_p6_0,
  128790. 17,
  128791. 17
  128792. };
  128793. static static_codebook _44c2_s_p6_0 = {
  128794. 2, 289,
  128795. _vq_lengthlist__44c2_s_p6_0,
  128796. 1, -529530880, 1611661312, 5, 0,
  128797. _vq_quantlist__44c2_s_p6_0,
  128798. NULL,
  128799. &_vq_auxt__44c2_s_p6_0,
  128800. NULL,
  128801. 0
  128802. };
  128803. static long _vq_quantlist__44c2_s_p7_0[] = {
  128804. 1,
  128805. 0,
  128806. 2,
  128807. };
  128808. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128809. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128810. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128811. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128812. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128813. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128814. 11,
  128815. };
  128816. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128817. -5.5, 5.5,
  128818. };
  128819. static long _vq_quantmap__44c2_s_p7_0[] = {
  128820. 1, 0, 2,
  128821. };
  128822. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128823. _vq_quantthresh__44c2_s_p7_0,
  128824. _vq_quantmap__44c2_s_p7_0,
  128825. 3,
  128826. 3
  128827. };
  128828. static static_codebook _44c2_s_p7_0 = {
  128829. 4, 81,
  128830. _vq_lengthlist__44c2_s_p7_0,
  128831. 1, -529137664, 1618345984, 2, 0,
  128832. _vq_quantlist__44c2_s_p7_0,
  128833. NULL,
  128834. &_vq_auxt__44c2_s_p7_0,
  128835. NULL,
  128836. 0
  128837. };
  128838. static long _vq_quantlist__44c2_s_p7_1[] = {
  128839. 5,
  128840. 4,
  128841. 6,
  128842. 3,
  128843. 7,
  128844. 2,
  128845. 8,
  128846. 1,
  128847. 9,
  128848. 0,
  128849. 10,
  128850. };
  128851. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128852. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128853. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128854. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128855. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128856. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128857. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128858. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128859. 10,10,10, 8, 8, 8, 8, 8, 8,
  128860. };
  128861. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128862. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128863. 3.5, 4.5,
  128864. };
  128865. static long _vq_quantmap__44c2_s_p7_1[] = {
  128866. 9, 7, 5, 3, 1, 0, 2, 4,
  128867. 6, 8, 10,
  128868. };
  128869. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128870. _vq_quantthresh__44c2_s_p7_1,
  128871. _vq_quantmap__44c2_s_p7_1,
  128872. 11,
  128873. 11
  128874. };
  128875. static static_codebook _44c2_s_p7_1 = {
  128876. 2, 121,
  128877. _vq_lengthlist__44c2_s_p7_1,
  128878. 1, -531365888, 1611661312, 4, 0,
  128879. _vq_quantlist__44c2_s_p7_1,
  128880. NULL,
  128881. &_vq_auxt__44c2_s_p7_1,
  128882. NULL,
  128883. 0
  128884. };
  128885. static long _vq_quantlist__44c2_s_p8_0[] = {
  128886. 6,
  128887. 5,
  128888. 7,
  128889. 4,
  128890. 8,
  128891. 3,
  128892. 9,
  128893. 2,
  128894. 10,
  128895. 1,
  128896. 11,
  128897. 0,
  128898. 12,
  128899. };
  128900. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128901. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128902. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128903. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128904. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128905. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128906. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128907. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128908. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128909. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128910. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128911. 0,12,12,12,12,13,12,14,14,
  128912. };
  128913. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128914. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128915. 12.5, 17.5, 22.5, 27.5,
  128916. };
  128917. static long _vq_quantmap__44c2_s_p8_0[] = {
  128918. 11, 9, 7, 5, 3, 1, 0, 2,
  128919. 4, 6, 8, 10, 12,
  128920. };
  128921. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128922. _vq_quantthresh__44c2_s_p8_0,
  128923. _vq_quantmap__44c2_s_p8_0,
  128924. 13,
  128925. 13
  128926. };
  128927. static static_codebook _44c2_s_p8_0 = {
  128928. 2, 169,
  128929. _vq_lengthlist__44c2_s_p8_0,
  128930. 1, -526516224, 1616117760, 4, 0,
  128931. _vq_quantlist__44c2_s_p8_0,
  128932. NULL,
  128933. &_vq_auxt__44c2_s_p8_0,
  128934. NULL,
  128935. 0
  128936. };
  128937. static long _vq_quantlist__44c2_s_p8_1[] = {
  128938. 2,
  128939. 1,
  128940. 3,
  128941. 0,
  128942. 4,
  128943. };
  128944. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128945. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128946. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128947. };
  128948. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128949. -1.5, -0.5, 0.5, 1.5,
  128950. };
  128951. static long _vq_quantmap__44c2_s_p8_1[] = {
  128952. 3, 1, 0, 2, 4,
  128953. };
  128954. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128955. _vq_quantthresh__44c2_s_p8_1,
  128956. _vq_quantmap__44c2_s_p8_1,
  128957. 5,
  128958. 5
  128959. };
  128960. static static_codebook _44c2_s_p8_1 = {
  128961. 2, 25,
  128962. _vq_lengthlist__44c2_s_p8_1,
  128963. 1, -533725184, 1611661312, 3, 0,
  128964. _vq_quantlist__44c2_s_p8_1,
  128965. NULL,
  128966. &_vq_auxt__44c2_s_p8_1,
  128967. NULL,
  128968. 0
  128969. };
  128970. static long _vq_quantlist__44c2_s_p9_0[] = {
  128971. 6,
  128972. 5,
  128973. 7,
  128974. 4,
  128975. 8,
  128976. 3,
  128977. 9,
  128978. 2,
  128979. 10,
  128980. 1,
  128981. 11,
  128982. 0,
  128983. 12,
  128984. };
  128985. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128986. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128987. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128988. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128989. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128990. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128991. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128992. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128993. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128994. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128995. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128996. 11,11,11,11,11,11,11,11,11,
  128997. };
  128998. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128999. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  129000. 552.5, 773.5, 994.5, 1215.5,
  129001. };
  129002. static long _vq_quantmap__44c2_s_p9_0[] = {
  129003. 11, 9, 7, 5, 3, 1, 0, 2,
  129004. 4, 6, 8, 10, 12,
  129005. };
  129006. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  129007. _vq_quantthresh__44c2_s_p9_0,
  129008. _vq_quantmap__44c2_s_p9_0,
  129009. 13,
  129010. 13
  129011. };
  129012. static static_codebook _44c2_s_p9_0 = {
  129013. 2, 169,
  129014. _vq_lengthlist__44c2_s_p9_0,
  129015. 1, -514541568, 1627103232, 4, 0,
  129016. _vq_quantlist__44c2_s_p9_0,
  129017. NULL,
  129018. &_vq_auxt__44c2_s_p9_0,
  129019. NULL,
  129020. 0
  129021. };
  129022. static long _vq_quantlist__44c2_s_p9_1[] = {
  129023. 6,
  129024. 5,
  129025. 7,
  129026. 4,
  129027. 8,
  129028. 3,
  129029. 9,
  129030. 2,
  129031. 10,
  129032. 1,
  129033. 11,
  129034. 0,
  129035. 12,
  129036. };
  129037. static long _vq_lengthlist__44c2_s_p9_1[] = {
  129038. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  129039. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  129040. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  129041. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  129042. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  129043. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  129044. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  129045. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  129046. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  129047. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  129048. 17,13,12,12,10,13,11,14,14,
  129049. };
  129050. static float _vq_quantthresh__44c2_s_p9_1[] = {
  129051. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  129052. 42.5, 59.5, 76.5, 93.5,
  129053. };
  129054. static long _vq_quantmap__44c2_s_p9_1[] = {
  129055. 11, 9, 7, 5, 3, 1, 0, 2,
  129056. 4, 6, 8, 10, 12,
  129057. };
  129058. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  129059. _vq_quantthresh__44c2_s_p9_1,
  129060. _vq_quantmap__44c2_s_p9_1,
  129061. 13,
  129062. 13
  129063. };
  129064. static static_codebook _44c2_s_p9_1 = {
  129065. 2, 169,
  129066. _vq_lengthlist__44c2_s_p9_1,
  129067. 1, -522616832, 1620115456, 4, 0,
  129068. _vq_quantlist__44c2_s_p9_1,
  129069. NULL,
  129070. &_vq_auxt__44c2_s_p9_1,
  129071. NULL,
  129072. 0
  129073. };
  129074. static long _vq_quantlist__44c2_s_p9_2[] = {
  129075. 8,
  129076. 7,
  129077. 9,
  129078. 6,
  129079. 10,
  129080. 5,
  129081. 11,
  129082. 4,
  129083. 12,
  129084. 3,
  129085. 13,
  129086. 2,
  129087. 14,
  129088. 1,
  129089. 15,
  129090. 0,
  129091. 16,
  129092. };
  129093. static long _vq_lengthlist__44c2_s_p9_2[] = {
  129094. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129095. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129096. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  129097. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  129098. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  129099. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129100. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  129101. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  129102. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  129103. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  129104. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  129105. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129106. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129107. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129108. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129109. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129110. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129111. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129112. 10,
  129113. };
  129114. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129115. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129116. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129117. };
  129118. static long _vq_quantmap__44c2_s_p9_2[] = {
  129119. 15, 13, 11, 9, 7, 5, 3, 1,
  129120. 0, 2, 4, 6, 8, 10, 12, 14,
  129121. 16,
  129122. };
  129123. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129124. _vq_quantthresh__44c2_s_p9_2,
  129125. _vq_quantmap__44c2_s_p9_2,
  129126. 17,
  129127. 17
  129128. };
  129129. static static_codebook _44c2_s_p9_2 = {
  129130. 2, 289,
  129131. _vq_lengthlist__44c2_s_p9_2,
  129132. 1, -529530880, 1611661312, 5, 0,
  129133. _vq_quantlist__44c2_s_p9_2,
  129134. NULL,
  129135. &_vq_auxt__44c2_s_p9_2,
  129136. NULL,
  129137. 0
  129138. };
  129139. static long _huff_lengthlist__44c2_s_short[] = {
  129140. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129141. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129142. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129143. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129144. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129145. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129146. 6, 8, 9,12,
  129147. };
  129148. static static_codebook _huff_book__44c2_s_short = {
  129149. 2, 100,
  129150. _huff_lengthlist__44c2_s_short,
  129151. 0, 0, 0, 0, 0,
  129152. NULL,
  129153. NULL,
  129154. NULL,
  129155. NULL,
  129156. 0
  129157. };
  129158. static long _huff_lengthlist__44c3_s_long[] = {
  129159. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129160. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129161. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129162. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129163. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129164. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129165. 9, 8, 8, 8,
  129166. };
  129167. static static_codebook _huff_book__44c3_s_long = {
  129168. 2, 100,
  129169. _huff_lengthlist__44c3_s_long,
  129170. 0, 0, 0, 0, 0,
  129171. NULL,
  129172. NULL,
  129173. NULL,
  129174. NULL,
  129175. 0
  129176. };
  129177. static long _vq_quantlist__44c3_s_p1_0[] = {
  129178. 1,
  129179. 0,
  129180. 2,
  129181. };
  129182. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129183. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129184. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129189. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129194. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  129229. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129234. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  129239. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129275. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129280. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129285. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0,
  129594. };
  129595. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129596. -0.5, 0.5,
  129597. };
  129598. static long _vq_quantmap__44c3_s_p1_0[] = {
  129599. 1, 0, 2,
  129600. };
  129601. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129602. _vq_quantthresh__44c3_s_p1_0,
  129603. _vq_quantmap__44c3_s_p1_0,
  129604. 3,
  129605. 3
  129606. };
  129607. static static_codebook _44c3_s_p1_0 = {
  129608. 8, 6561,
  129609. _vq_lengthlist__44c3_s_p1_0,
  129610. 1, -535822336, 1611661312, 2, 0,
  129611. _vq_quantlist__44c3_s_p1_0,
  129612. NULL,
  129613. &_vq_auxt__44c3_s_p1_0,
  129614. NULL,
  129615. 0
  129616. };
  129617. static long _vq_quantlist__44c3_s_p2_0[] = {
  129618. 2,
  129619. 1,
  129620. 3,
  129621. 0,
  129622. 4,
  129623. };
  129624. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129625. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129626. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129627. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129628. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129629. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129634. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129635. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129636. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129637. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129642. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129643. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129644. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129651. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129652. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0,
  129665. };
  129666. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129667. -1.5, -0.5, 0.5, 1.5,
  129668. };
  129669. static long _vq_quantmap__44c3_s_p2_0[] = {
  129670. 3, 1, 0, 2, 4,
  129671. };
  129672. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129673. _vq_quantthresh__44c3_s_p2_0,
  129674. _vq_quantmap__44c3_s_p2_0,
  129675. 5,
  129676. 5
  129677. };
  129678. static static_codebook _44c3_s_p2_0 = {
  129679. 4, 625,
  129680. _vq_lengthlist__44c3_s_p2_0,
  129681. 1, -533725184, 1611661312, 3, 0,
  129682. _vq_quantlist__44c3_s_p2_0,
  129683. NULL,
  129684. &_vq_auxt__44c3_s_p2_0,
  129685. NULL,
  129686. 0
  129687. };
  129688. static long _vq_quantlist__44c3_s_p3_0[] = {
  129689. 2,
  129690. 1,
  129691. 3,
  129692. 0,
  129693. 4,
  129694. };
  129695. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129696. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129699. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129702. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0,
  129736. };
  129737. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129738. -1.5, -0.5, 0.5, 1.5,
  129739. };
  129740. static long _vq_quantmap__44c3_s_p3_0[] = {
  129741. 3, 1, 0, 2, 4,
  129742. };
  129743. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129744. _vq_quantthresh__44c3_s_p3_0,
  129745. _vq_quantmap__44c3_s_p3_0,
  129746. 5,
  129747. 5
  129748. };
  129749. static static_codebook _44c3_s_p3_0 = {
  129750. 4, 625,
  129751. _vq_lengthlist__44c3_s_p3_0,
  129752. 1, -533725184, 1611661312, 3, 0,
  129753. _vq_quantlist__44c3_s_p3_0,
  129754. NULL,
  129755. &_vq_auxt__44c3_s_p3_0,
  129756. NULL,
  129757. 0
  129758. };
  129759. static long _vq_quantlist__44c3_s_p4_0[] = {
  129760. 4,
  129761. 3,
  129762. 5,
  129763. 2,
  129764. 6,
  129765. 1,
  129766. 7,
  129767. 0,
  129768. 8,
  129769. };
  129770. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129771. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129772. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129773. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129774. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129775. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129776. 0,
  129777. };
  129778. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129779. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129780. };
  129781. static long _vq_quantmap__44c3_s_p4_0[] = {
  129782. 7, 5, 3, 1, 0, 2, 4, 6,
  129783. 8,
  129784. };
  129785. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129786. _vq_quantthresh__44c3_s_p4_0,
  129787. _vq_quantmap__44c3_s_p4_0,
  129788. 9,
  129789. 9
  129790. };
  129791. static static_codebook _44c3_s_p4_0 = {
  129792. 2, 81,
  129793. _vq_lengthlist__44c3_s_p4_0,
  129794. 1, -531628032, 1611661312, 4, 0,
  129795. _vq_quantlist__44c3_s_p4_0,
  129796. NULL,
  129797. &_vq_auxt__44c3_s_p4_0,
  129798. NULL,
  129799. 0
  129800. };
  129801. static long _vq_quantlist__44c3_s_p5_0[] = {
  129802. 4,
  129803. 3,
  129804. 5,
  129805. 2,
  129806. 6,
  129807. 1,
  129808. 7,
  129809. 0,
  129810. 8,
  129811. };
  129812. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129813. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129814. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129815. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129816. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129817. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129818. 11,
  129819. };
  129820. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129821. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129822. };
  129823. static long _vq_quantmap__44c3_s_p5_0[] = {
  129824. 7, 5, 3, 1, 0, 2, 4, 6,
  129825. 8,
  129826. };
  129827. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129828. _vq_quantthresh__44c3_s_p5_0,
  129829. _vq_quantmap__44c3_s_p5_0,
  129830. 9,
  129831. 9
  129832. };
  129833. static static_codebook _44c3_s_p5_0 = {
  129834. 2, 81,
  129835. _vq_lengthlist__44c3_s_p5_0,
  129836. 1, -531628032, 1611661312, 4, 0,
  129837. _vq_quantlist__44c3_s_p5_0,
  129838. NULL,
  129839. &_vq_auxt__44c3_s_p5_0,
  129840. NULL,
  129841. 0
  129842. };
  129843. static long _vq_quantlist__44c3_s_p6_0[] = {
  129844. 8,
  129845. 7,
  129846. 9,
  129847. 6,
  129848. 10,
  129849. 5,
  129850. 11,
  129851. 4,
  129852. 12,
  129853. 3,
  129854. 13,
  129855. 2,
  129856. 14,
  129857. 1,
  129858. 15,
  129859. 0,
  129860. 16,
  129861. };
  129862. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129863. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129864. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129865. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129866. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129867. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129868. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129869. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129870. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129871. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129872. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129873. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129874. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129875. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129876. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129877. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129878. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129879. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129881. 13,
  129882. };
  129883. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129884. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129885. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129886. };
  129887. static long _vq_quantmap__44c3_s_p6_0[] = {
  129888. 15, 13, 11, 9, 7, 5, 3, 1,
  129889. 0, 2, 4, 6, 8, 10, 12, 14,
  129890. 16,
  129891. };
  129892. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129893. _vq_quantthresh__44c3_s_p6_0,
  129894. _vq_quantmap__44c3_s_p6_0,
  129895. 17,
  129896. 17
  129897. };
  129898. static static_codebook _44c3_s_p6_0 = {
  129899. 2, 289,
  129900. _vq_lengthlist__44c3_s_p6_0,
  129901. 1, -529530880, 1611661312, 5, 0,
  129902. _vq_quantlist__44c3_s_p6_0,
  129903. NULL,
  129904. &_vq_auxt__44c3_s_p6_0,
  129905. NULL,
  129906. 0
  129907. };
  129908. static long _vq_quantlist__44c3_s_p7_0[] = {
  129909. 1,
  129910. 0,
  129911. 2,
  129912. };
  129913. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129914. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129915. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129916. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129917. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129918. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129919. 10,
  129920. };
  129921. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129922. -5.5, 5.5,
  129923. };
  129924. static long _vq_quantmap__44c3_s_p7_0[] = {
  129925. 1, 0, 2,
  129926. };
  129927. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129928. _vq_quantthresh__44c3_s_p7_0,
  129929. _vq_quantmap__44c3_s_p7_0,
  129930. 3,
  129931. 3
  129932. };
  129933. static static_codebook _44c3_s_p7_0 = {
  129934. 4, 81,
  129935. _vq_lengthlist__44c3_s_p7_0,
  129936. 1, -529137664, 1618345984, 2, 0,
  129937. _vq_quantlist__44c3_s_p7_0,
  129938. NULL,
  129939. &_vq_auxt__44c3_s_p7_0,
  129940. NULL,
  129941. 0
  129942. };
  129943. static long _vq_quantlist__44c3_s_p7_1[] = {
  129944. 5,
  129945. 4,
  129946. 6,
  129947. 3,
  129948. 7,
  129949. 2,
  129950. 8,
  129951. 1,
  129952. 9,
  129953. 0,
  129954. 10,
  129955. };
  129956. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129957. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129958. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129959. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129960. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129961. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129962. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129963. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129964. 10,10,10, 8, 8, 8, 8, 8, 8,
  129965. };
  129966. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129967. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129968. 3.5, 4.5,
  129969. };
  129970. static long _vq_quantmap__44c3_s_p7_1[] = {
  129971. 9, 7, 5, 3, 1, 0, 2, 4,
  129972. 6, 8, 10,
  129973. };
  129974. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129975. _vq_quantthresh__44c3_s_p7_1,
  129976. _vq_quantmap__44c3_s_p7_1,
  129977. 11,
  129978. 11
  129979. };
  129980. static static_codebook _44c3_s_p7_1 = {
  129981. 2, 121,
  129982. _vq_lengthlist__44c3_s_p7_1,
  129983. 1, -531365888, 1611661312, 4, 0,
  129984. _vq_quantlist__44c3_s_p7_1,
  129985. NULL,
  129986. &_vq_auxt__44c3_s_p7_1,
  129987. NULL,
  129988. 0
  129989. };
  129990. static long _vq_quantlist__44c3_s_p8_0[] = {
  129991. 6,
  129992. 5,
  129993. 7,
  129994. 4,
  129995. 8,
  129996. 3,
  129997. 9,
  129998. 2,
  129999. 10,
  130000. 1,
  130001. 11,
  130002. 0,
  130003. 12,
  130004. };
  130005. static long _vq_lengthlist__44c3_s_p8_0[] = {
  130006. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130007. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  130008. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130009. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130010. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  130011. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  130012. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  130013. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130014. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  130015. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  130016. 0,13,13,12,12,13,12,14,13,
  130017. };
  130018. static float _vq_quantthresh__44c3_s_p8_0[] = {
  130019. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130020. 12.5, 17.5, 22.5, 27.5,
  130021. };
  130022. static long _vq_quantmap__44c3_s_p8_0[] = {
  130023. 11, 9, 7, 5, 3, 1, 0, 2,
  130024. 4, 6, 8, 10, 12,
  130025. };
  130026. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  130027. _vq_quantthresh__44c3_s_p8_0,
  130028. _vq_quantmap__44c3_s_p8_0,
  130029. 13,
  130030. 13
  130031. };
  130032. static static_codebook _44c3_s_p8_0 = {
  130033. 2, 169,
  130034. _vq_lengthlist__44c3_s_p8_0,
  130035. 1, -526516224, 1616117760, 4, 0,
  130036. _vq_quantlist__44c3_s_p8_0,
  130037. NULL,
  130038. &_vq_auxt__44c3_s_p8_0,
  130039. NULL,
  130040. 0
  130041. };
  130042. static long _vq_quantlist__44c3_s_p8_1[] = {
  130043. 2,
  130044. 1,
  130045. 3,
  130046. 0,
  130047. 4,
  130048. };
  130049. static long _vq_lengthlist__44c3_s_p8_1[] = {
  130050. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130051. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130052. };
  130053. static float _vq_quantthresh__44c3_s_p8_1[] = {
  130054. -1.5, -0.5, 0.5, 1.5,
  130055. };
  130056. static long _vq_quantmap__44c3_s_p8_1[] = {
  130057. 3, 1, 0, 2, 4,
  130058. };
  130059. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  130060. _vq_quantthresh__44c3_s_p8_1,
  130061. _vq_quantmap__44c3_s_p8_1,
  130062. 5,
  130063. 5
  130064. };
  130065. static static_codebook _44c3_s_p8_1 = {
  130066. 2, 25,
  130067. _vq_lengthlist__44c3_s_p8_1,
  130068. 1, -533725184, 1611661312, 3, 0,
  130069. _vq_quantlist__44c3_s_p8_1,
  130070. NULL,
  130071. &_vq_auxt__44c3_s_p8_1,
  130072. NULL,
  130073. 0
  130074. };
  130075. static long _vq_quantlist__44c3_s_p9_0[] = {
  130076. 6,
  130077. 5,
  130078. 7,
  130079. 4,
  130080. 8,
  130081. 3,
  130082. 9,
  130083. 2,
  130084. 10,
  130085. 1,
  130086. 11,
  130087. 0,
  130088. 12,
  130089. };
  130090. static long _vq_lengthlist__44c3_s_p9_0[] = {
  130091. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  130092. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  130093. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130094. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  130095. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130096. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130097. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130098. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130099. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130100. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130101. 11,11,11,11,11,11,11,11,11,
  130102. };
  130103. static float _vq_quantthresh__44c3_s_p9_0[] = {
  130104. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  130105. 637.5, 892.5, 1147.5, 1402.5,
  130106. };
  130107. static long _vq_quantmap__44c3_s_p9_0[] = {
  130108. 11, 9, 7, 5, 3, 1, 0, 2,
  130109. 4, 6, 8, 10, 12,
  130110. };
  130111. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130112. _vq_quantthresh__44c3_s_p9_0,
  130113. _vq_quantmap__44c3_s_p9_0,
  130114. 13,
  130115. 13
  130116. };
  130117. static static_codebook _44c3_s_p9_0 = {
  130118. 2, 169,
  130119. _vq_lengthlist__44c3_s_p9_0,
  130120. 1, -514332672, 1627381760, 4, 0,
  130121. _vq_quantlist__44c3_s_p9_0,
  130122. NULL,
  130123. &_vq_auxt__44c3_s_p9_0,
  130124. NULL,
  130125. 0
  130126. };
  130127. static long _vq_quantlist__44c3_s_p9_1[] = {
  130128. 7,
  130129. 6,
  130130. 8,
  130131. 5,
  130132. 9,
  130133. 4,
  130134. 10,
  130135. 3,
  130136. 11,
  130137. 2,
  130138. 12,
  130139. 1,
  130140. 13,
  130141. 0,
  130142. 14,
  130143. };
  130144. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130145. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130146. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130147. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130148. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130149. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130150. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130151. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130152. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130153. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130154. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130155. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130156. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130157. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130158. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130159. 15,
  130160. };
  130161. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130162. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130163. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130164. };
  130165. static long _vq_quantmap__44c3_s_p9_1[] = {
  130166. 13, 11, 9, 7, 5, 3, 1, 0,
  130167. 2, 4, 6, 8, 10, 12, 14,
  130168. };
  130169. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130170. _vq_quantthresh__44c3_s_p9_1,
  130171. _vq_quantmap__44c3_s_p9_1,
  130172. 15,
  130173. 15
  130174. };
  130175. static static_codebook _44c3_s_p9_1 = {
  130176. 2, 225,
  130177. _vq_lengthlist__44c3_s_p9_1,
  130178. 1, -522338304, 1620115456, 4, 0,
  130179. _vq_quantlist__44c3_s_p9_1,
  130180. NULL,
  130181. &_vq_auxt__44c3_s_p9_1,
  130182. NULL,
  130183. 0
  130184. };
  130185. static long _vq_quantlist__44c3_s_p9_2[] = {
  130186. 8,
  130187. 7,
  130188. 9,
  130189. 6,
  130190. 10,
  130191. 5,
  130192. 11,
  130193. 4,
  130194. 12,
  130195. 3,
  130196. 13,
  130197. 2,
  130198. 14,
  130199. 1,
  130200. 15,
  130201. 0,
  130202. 16,
  130203. };
  130204. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130205. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130206. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130207. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130208. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130209. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130210. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130211. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130212. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130213. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130214. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130215. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130216. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130217. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130218. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130219. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130220. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130221. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130222. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130223. 10,
  130224. };
  130225. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130226. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130227. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130228. };
  130229. static long _vq_quantmap__44c3_s_p9_2[] = {
  130230. 15, 13, 11, 9, 7, 5, 3, 1,
  130231. 0, 2, 4, 6, 8, 10, 12, 14,
  130232. 16,
  130233. };
  130234. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130235. _vq_quantthresh__44c3_s_p9_2,
  130236. _vq_quantmap__44c3_s_p9_2,
  130237. 17,
  130238. 17
  130239. };
  130240. static static_codebook _44c3_s_p9_2 = {
  130241. 2, 289,
  130242. _vq_lengthlist__44c3_s_p9_2,
  130243. 1, -529530880, 1611661312, 5, 0,
  130244. _vq_quantlist__44c3_s_p9_2,
  130245. NULL,
  130246. &_vq_auxt__44c3_s_p9_2,
  130247. NULL,
  130248. 0
  130249. };
  130250. static long _huff_lengthlist__44c3_s_short[] = {
  130251. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130252. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130253. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130254. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130255. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130256. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130257. 6, 8, 9,11,
  130258. };
  130259. static static_codebook _huff_book__44c3_s_short = {
  130260. 2, 100,
  130261. _huff_lengthlist__44c3_s_short,
  130262. 0, 0, 0, 0, 0,
  130263. NULL,
  130264. NULL,
  130265. NULL,
  130266. NULL,
  130267. 0
  130268. };
  130269. static long _huff_lengthlist__44c4_s_long[] = {
  130270. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130271. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130272. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130273. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130274. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130275. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130276. 9, 8, 7, 7,
  130277. };
  130278. static static_codebook _huff_book__44c4_s_long = {
  130279. 2, 100,
  130280. _huff_lengthlist__44c4_s_long,
  130281. 0, 0, 0, 0, 0,
  130282. NULL,
  130283. NULL,
  130284. NULL,
  130285. NULL,
  130286. 0
  130287. };
  130288. static long _vq_quantlist__44c4_s_p1_0[] = {
  130289. 1,
  130290. 0,
  130291. 2,
  130292. };
  130293. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130294. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130295. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130300. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130305. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  130340. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  130345. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  130350. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130386. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130391. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130396. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0,
  130705. };
  130706. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130707. -0.5, 0.5,
  130708. };
  130709. static long _vq_quantmap__44c4_s_p1_0[] = {
  130710. 1, 0, 2,
  130711. };
  130712. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130713. _vq_quantthresh__44c4_s_p1_0,
  130714. _vq_quantmap__44c4_s_p1_0,
  130715. 3,
  130716. 3
  130717. };
  130718. static static_codebook _44c4_s_p1_0 = {
  130719. 8, 6561,
  130720. _vq_lengthlist__44c4_s_p1_0,
  130721. 1, -535822336, 1611661312, 2, 0,
  130722. _vq_quantlist__44c4_s_p1_0,
  130723. NULL,
  130724. &_vq_auxt__44c4_s_p1_0,
  130725. NULL,
  130726. 0
  130727. };
  130728. static long _vq_quantlist__44c4_s_p2_0[] = {
  130729. 2,
  130730. 1,
  130731. 3,
  130732. 0,
  130733. 4,
  130734. };
  130735. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130736. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130737. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130738. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130739. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130740. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130745. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130746. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130747. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130748. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130753. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130754. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130755. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130761. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130762. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130763. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0,
  130776. };
  130777. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130778. -1.5, -0.5, 0.5, 1.5,
  130779. };
  130780. static long _vq_quantmap__44c4_s_p2_0[] = {
  130781. 3, 1, 0, 2, 4,
  130782. };
  130783. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130784. _vq_quantthresh__44c4_s_p2_0,
  130785. _vq_quantmap__44c4_s_p2_0,
  130786. 5,
  130787. 5
  130788. };
  130789. static static_codebook _44c4_s_p2_0 = {
  130790. 4, 625,
  130791. _vq_lengthlist__44c4_s_p2_0,
  130792. 1, -533725184, 1611661312, 3, 0,
  130793. _vq_quantlist__44c4_s_p2_0,
  130794. NULL,
  130795. &_vq_auxt__44c4_s_p2_0,
  130796. NULL,
  130797. 0
  130798. };
  130799. static long _vq_quantlist__44c4_s_p3_0[] = {
  130800. 2,
  130801. 1,
  130802. 3,
  130803. 0,
  130804. 4,
  130805. };
  130806. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130807. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130810. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0,
  130847. };
  130848. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130849. -1.5, -0.5, 0.5, 1.5,
  130850. };
  130851. static long _vq_quantmap__44c4_s_p3_0[] = {
  130852. 3, 1, 0, 2, 4,
  130853. };
  130854. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130855. _vq_quantthresh__44c4_s_p3_0,
  130856. _vq_quantmap__44c4_s_p3_0,
  130857. 5,
  130858. 5
  130859. };
  130860. static static_codebook _44c4_s_p3_0 = {
  130861. 4, 625,
  130862. _vq_lengthlist__44c4_s_p3_0,
  130863. 1, -533725184, 1611661312, 3, 0,
  130864. _vq_quantlist__44c4_s_p3_0,
  130865. NULL,
  130866. &_vq_auxt__44c4_s_p3_0,
  130867. NULL,
  130868. 0
  130869. };
  130870. static long _vq_quantlist__44c4_s_p4_0[] = {
  130871. 4,
  130872. 3,
  130873. 5,
  130874. 2,
  130875. 6,
  130876. 1,
  130877. 7,
  130878. 0,
  130879. 8,
  130880. };
  130881. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130882. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130883. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130884. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130885. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130886. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0,
  130888. };
  130889. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130890. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130891. };
  130892. static long _vq_quantmap__44c4_s_p4_0[] = {
  130893. 7, 5, 3, 1, 0, 2, 4, 6,
  130894. 8,
  130895. };
  130896. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130897. _vq_quantthresh__44c4_s_p4_0,
  130898. _vq_quantmap__44c4_s_p4_0,
  130899. 9,
  130900. 9
  130901. };
  130902. static static_codebook _44c4_s_p4_0 = {
  130903. 2, 81,
  130904. _vq_lengthlist__44c4_s_p4_0,
  130905. 1, -531628032, 1611661312, 4, 0,
  130906. _vq_quantlist__44c4_s_p4_0,
  130907. NULL,
  130908. &_vq_auxt__44c4_s_p4_0,
  130909. NULL,
  130910. 0
  130911. };
  130912. static long _vq_quantlist__44c4_s_p5_0[] = {
  130913. 4,
  130914. 3,
  130915. 5,
  130916. 2,
  130917. 6,
  130918. 1,
  130919. 7,
  130920. 0,
  130921. 8,
  130922. };
  130923. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130924. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130925. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130926. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130927. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130928. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130929. 10,
  130930. };
  130931. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130932. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130933. };
  130934. static long _vq_quantmap__44c4_s_p5_0[] = {
  130935. 7, 5, 3, 1, 0, 2, 4, 6,
  130936. 8,
  130937. };
  130938. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130939. _vq_quantthresh__44c4_s_p5_0,
  130940. _vq_quantmap__44c4_s_p5_0,
  130941. 9,
  130942. 9
  130943. };
  130944. static static_codebook _44c4_s_p5_0 = {
  130945. 2, 81,
  130946. _vq_lengthlist__44c4_s_p5_0,
  130947. 1, -531628032, 1611661312, 4, 0,
  130948. _vq_quantlist__44c4_s_p5_0,
  130949. NULL,
  130950. &_vq_auxt__44c4_s_p5_0,
  130951. NULL,
  130952. 0
  130953. };
  130954. static long _vq_quantlist__44c4_s_p6_0[] = {
  130955. 8,
  130956. 7,
  130957. 9,
  130958. 6,
  130959. 10,
  130960. 5,
  130961. 11,
  130962. 4,
  130963. 12,
  130964. 3,
  130965. 13,
  130966. 2,
  130967. 14,
  130968. 1,
  130969. 15,
  130970. 0,
  130971. 16,
  130972. };
  130973. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130974. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130975. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130976. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130977. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130978. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130979. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130980. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130981. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130982. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130983. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130984. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130985. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130986. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130987. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130988. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130989. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130990. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130992. 13,
  130993. };
  130994. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130995. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130996. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130997. };
  130998. static long _vq_quantmap__44c4_s_p6_0[] = {
  130999. 15, 13, 11, 9, 7, 5, 3, 1,
  131000. 0, 2, 4, 6, 8, 10, 12, 14,
  131001. 16,
  131002. };
  131003. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  131004. _vq_quantthresh__44c4_s_p6_0,
  131005. _vq_quantmap__44c4_s_p6_0,
  131006. 17,
  131007. 17
  131008. };
  131009. static static_codebook _44c4_s_p6_0 = {
  131010. 2, 289,
  131011. _vq_lengthlist__44c4_s_p6_0,
  131012. 1, -529530880, 1611661312, 5, 0,
  131013. _vq_quantlist__44c4_s_p6_0,
  131014. NULL,
  131015. &_vq_auxt__44c4_s_p6_0,
  131016. NULL,
  131017. 0
  131018. };
  131019. static long _vq_quantlist__44c4_s_p7_0[] = {
  131020. 1,
  131021. 0,
  131022. 2,
  131023. };
  131024. static long _vq_lengthlist__44c4_s_p7_0[] = {
  131025. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131026. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131027. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131028. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131029. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131030. 10,
  131031. };
  131032. static float _vq_quantthresh__44c4_s_p7_0[] = {
  131033. -5.5, 5.5,
  131034. };
  131035. static long _vq_quantmap__44c4_s_p7_0[] = {
  131036. 1, 0, 2,
  131037. };
  131038. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  131039. _vq_quantthresh__44c4_s_p7_0,
  131040. _vq_quantmap__44c4_s_p7_0,
  131041. 3,
  131042. 3
  131043. };
  131044. static static_codebook _44c4_s_p7_0 = {
  131045. 4, 81,
  131046. _vq_lengthlist__44c4_s_p7_0,
  131047. 1, -529137664, 1618345984, 2, 0,
  131048. _vq_quantlist__44c4_s_p7_0,
  131049. NULL,
  131050. &_vq_auxt__44c4_s_p7_0,
  131051. NULL,
  131052. 0
  131053. };
  131054. static long _vq_quantlist__44c4_s_p7_1[] = {
  131055. 5,
  131056. 4,
  131057. 6,
  131058. 3,
  131059. 7,
  131060. 2,
  131061. 8,
  131062. 1,
  131063. 9,
  131064. 0,
  131065. 10,
  131066. };
  131067. static long _vq_lengthlist__44c4_s_p7_1[] = {
  131068. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  131069. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131070. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131071. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131072. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131073. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131074. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  131075. 10,10,10, 8, 8, 8, 8, 9, 9,
  131076. };
  131077. static float _vq_quantthresh__44c4_s_p7_1[] = {
  131078. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131079. 3.5, 4.5,
  131080. };
  131081. static long _vq_quantmap__44c4_s_p7_1[] = {
  131082. 9, 7, 5, 3, 1, 0, 2, 4,
  131083. 6, 8, 10,
  131084. };
  131085. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  131086. _vq_quantthresh__44c4_s_p7_1,
  131087. _vq_quantmap__44c4_s_p7_1,
  131088. 11,
  131089. 11
  131090. };
  131091. static static_codebook _44c4_s_p7_1 = {
  131092. 2, 121,
  131093. _vq_lengthlist__44c4_s_p7_1,
  131094. 1, -531365888, 1611661312, 4, 0,
  131095. _vq_quantlist__44c4_s_p7_1,
  131096. NULL,
  131097. &_vq_auxt__44c4_s_p7_1,
  131098. NULL,
  131099. 0
  131100. };
  131101. static long _vq_quantlist__44c4_s_p8_0[] = {
  131102. 6,
  131103. 5,
  131104. 7,
  131105. 4,
  131106. 8,
  131107. 3,
  131108. 9,
  131109. 2,
  131110. 10,
  131111. 1,
  131112. 11,
  131113. 0,
  131114. 12,
  131115. };
  131116. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131117. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131118. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131119. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131120. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131121. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131122. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131123. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131124. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131125. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131126. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131127. 0,13,12,12,12,12,12,13,13,
  131128. };
  131129. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131130. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131131. 12.5, 17.5, 22.5, 27.5,
  131132. };
  131133. static long _vq_quantmap__44c4_s_p8_0[] = {
  131134. 11, 9, 7, 5, 3, 1, 0, 2,
  131135. 4, 6, 8, 10, 12,
  131136. };
  131137. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131138. _vq_quantthresh__44c4_s_p8_0,
  131139. _vq_quantmap__44c4_s_p8_0,
  131140. 13,
  131141. 13
  131142. };
  131143. static static_codebook _44c4_s_p8_0 = {
  131144. 2, 169,
  131145. _vq_lengthlist__44c4_s_p8_0,
  131146. 1, -526516224, 1616117760, 4, 0,
  131147. _vq_quantlist__44c4_s_p8_0,
  131148. NULL,
  131149. &_vq_auxt__44c4_s_p8_0,
  131150. NULL,
  131151. 0
  131152. };
  131153. static long _vq_quantlist__44c4_s_p8_1[] = {
  131154. 2,
  131155. 1,
  131156. 3,
  131157. 0,
  131158. 4,
  131159. };
  131160. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131161. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131162. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131163. };
  131164. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131165. -1.5, -0.5, 0.5, 1.5,
  131166. };
  131167. static long _vq_quantmap__44c4_s_p8_1[] = {
  131168. 3, 1, 0, 2, 4,
  131169. };
  131170. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131171. _vq_quantthresh__44c4_s_p8_1,
  131172. _vq_quantmap__44c4_s_p8_1,
  131173. 5,
  131174. 5
  131175. };
  131176. static static_codebook _44c4_s_p8_1 = {
  131177. 2, 25,
  131178. _vq_lengthlist__44c4_s_p8_1,
  131179. 1, -533725184, 1611661312, 3, 0,
  131180. _vq_quantlist__44c4_s_p8_1,
  131181. NULL,
  131182. &_vq_auxt__44c4_s_p8_1,
  131183. NULL,
  131184. 0
  131185. };
  131186. static long _vq_quantlist__44c4_s_p9_0[] = {
  131187. 6,
  131188. 5,
  131189. 7,
  131190. 4,
  131191. 8,
  131192. 3,
  131193. 9,
  131194. 2,
  131195. 10,
  131196. 1,
  131197. 11,
  131198. 0,
  131199. 12,
  131200. };
  131201. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131202. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131203. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131204. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131205. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131206. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131207. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131208. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131209. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131210. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131211. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131212. 12,12,12,12,12,12,12,12,12,
  131213. };
  131214. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131215. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131216. 787.5, 1102.5, 1417.5, 1732.5,
  131217. };
  131218. static long _vq_quantmap__44c4_s_p9_0[] = {
  131219. 11, 9, 7, 5, 3, 1, 0, 2,
  131220. 4, 6, 8, 10, 12,
  131221. };
  131222. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131223. _vq_quantthresh__44c4_s_p9_0,
  131224. _vq_quantmap__44c4_s_p9_0,
  131225. 13,
  131226. 13
  131227. };
  131228. static static_codebook _44c4_s_p9_0 = {
  131229. 2, 169,
  131230. _vq_lengthlist__44c4_s_p9_0,
  131231. 1, -513964032, 1628680192, 4, 0,
  131232. _vq_quantlist__44c4_s_p9_0,
  131233. NULL,
  131234. &_vq_auxt__44c4_s_p9_0,
  131235. NULL,
  131236. 0
  131237. };
  131238. static long _vq_quantlist__44c4_s_p9_1[] = {
  131239. 7,
  131240. 6,
  131241. 8,
  131242. 5,
  131243. 9,
  131244. 4,
  131245. 10,
  131246. 3,
  131247. 11,
  131248. 2,
  131249. 12,
  131250. 1,
  131251. 13,
  131252. 0,
  131253. 14,
  131254. };
  131255. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131256. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131257. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131258. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131259. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131260. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131261. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131262. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131263. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131264. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131265. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131266. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131267. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131268. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131269. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131270. 15,
  131271. };
  131272. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131273. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131274. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131275. };
  131276. static long _vq_quantmap__44c4_s_p9_1[] = {
  131277. 13, 11, 9, 7, 5, 3, 1, 0,
  131278. 2, 4, 6, 8, 10, 12, 14,
  131279. };
  131280. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131281. _vq_quantthresh__44c4_s_p9_1,
  131282. _vq_quantmap__44c4_s_p9_1,
  131283. 15,
  131284. 15
  131285. };
  131286. static static_codebook _44c4_s_p9_1 = {
  131287. 2, 225,
  131288. _vq_lengthlist__44c4_s_p9_1,
  131289. 1, -520986624, 1620377600, 4, 0,
  131290. _vq_quantlist__44c4_s_p9_1,
  131291. NULL,
  131292. &_vq_auxt__44c4_s_p9_1,
  131293. NULL,
  131294. 0
  131295. };
  131296. static long _vq_quantlist__44c4_s_p9_2[] = {
  131297. 10,
  131298. 9,
  131299. 11,
  131300. 8,
  131301. 12,
  131302. 7,
  131303. 13,
  131304. 6,
  131305. 14,
  131306. 5,
  131307. 15,
  131308. 4,
  131309. 16,
  131310. 3,
  131311. 17,
  131312. 2,
  131313. 18,
  131314. 1,
  131315. 19,
  131316. 0,
  131317. 20,
  131318. };
  131319. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131320. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131321. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131322. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131323. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131324. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131325. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131326. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131327. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131328. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131329. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131330. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131331. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131332. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131333. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131334. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131335. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131336. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131337. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131338. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131339. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131340. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131341. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131342. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131343. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131344. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131345. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131346. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131347. 10,10,10,10,10,10,10,10,10,
  131348. };
  131349. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131350. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131351. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131352. 6.5, 7.5, 8.5, 9.5,
  131353. };
  131354. static long _vq_quantmap__44c4_s_p9_2[] = {
  131355. 19, 17, 15, 13, 11, 9, 7, 5,
  131356. 3, 1, 0, 2, 4, 6, 8, 10,
  131357. 12, 14, 16, 18, 20,
  131358. };
  131359. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131360. _vq_quantthresh__44c4_s_p9_2,
  131361. _vq_quantmap__44c4_s_p9_2,
  131362. 21,
  131363. 21
  131364. };
  131365. static static_codebook _44c4_s_p9_2 = {
  131366. 2, 441,
  131367. _vq_lengthlist__44c4_s_p9_2,
  131368. 1, -529268736, 1611661312, 5, 0,
  131369. _vq_quantlist__44c4_s_p9_2,
  131370. NULL,
  131371. &_vq_auxt__44c4_s_p9_2,
  131372. NULL,
  131373. 0
  131374. };
  131375. static long _huff_lengthlist__44c4_s_short[] = {
  131376. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131377. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131378. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131379. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131380. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131381. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131382. 7, 9,12,17,
  131383. };
  131384. static static_codebook _huff_book__44c4_s_short = {
  131385. 2, 100,
  131386. _huff_lengthlist__44c4_s_short,
  131387. 0, 0, 0, 0, 0,
  131388. NULL,
  131389. NULL,
  131390. NULL,
  131391. NULL,
  131392. 0
  131393. };
  131394. static long _huff_lengthlist__44c5_s_long[] = {
  131395. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131396. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131397. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131398. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131399. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131400. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131401. 9, 8, 7, 7,
  131402. };
  131403. static static_codebook _huff_book__44c5_s_long = {
  131404. 2, 100,
  131405. _huff_lengthlist__44c5_s_long,
  131406. 0, 0, 0, 0, 0,
  131407. NULL,
  131408. NULL,
  131409. NULL,
  131410. NULL,
  131411. 0
  131412. };
  131413. static long _vq_quantlist__44c5_s_p1_0[] = {
  131414. 1,
  131415. 0,
  131416. 2,
  131417. };
  131418. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131419. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131420. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131425. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131430. 0, 0, 0, 0, 7, 9, 9, 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, 4, 7, 7, 0, 0, 0, 0,
  131465. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131470. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131475. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131511. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131516. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131521. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131829. 0,
  131830. };
  131831. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131832. -0.5, 0.5,
  131833. };
  131834. static long _vq_quantmap__44c5_s_p1_0[] = {
  131835. 1, 0, 2,
  131836. };
  131837. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131838. _vq_quantthresh__44c5_s_p1_0,
  131839. _vq_quantmap__44c5_s_p1_0,
  131840. 3,
  131841. 3
  131842. };
  131843. static static_codebook _44c5_s_p1_0 = {
  131844. 8, 6561,
  131845. _vq_lengthlist__44c5_s_p1_0,
  131846. 1, -535822336, 1611661312, 2, 0,
  131847. _vq_quantlist__44c5_s_p1_0,
  131848. NULL,
  131849. &_vq_auxt__44c5_s_p1_0,
  131850. NULL,
  131851. 0
  131852. };
  131853. static long _vq_quantlist__44c5_s_p2_0[] = {
  131854. 2,
  131855. 1,
  131856. 3,
  131857. 0,
  131858. 4,
  131859. };
  131860. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131861. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131862. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131863. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131864. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131865. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131870. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131871. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131872. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131873. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131878. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131879. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131880. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131886. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131887. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131888. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131900. 0,
  131901. };
  131902. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131903. -1.5, -0.5, 0.5, 1.5,
  131904. };
  131905. static long _vq_quantmap__44c5_s_p2_0[] = {
  131906. 3, 1, 0, 2, 4,
  131907. };
  131908. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131909. _vq_quantthresh__44c5_s_p2_0,
  131910. _vq_quantmap__44c5_s_p2_0,
  131911. 5,
  131912. 5
  131913. };
  131914. static static_codebook _44c5_s_p2_0 = {
  131915. 4, 625,
  131916. _vq_lengthlist__44c5_s_p2_0,
  131917. 1, -533725184, 1611661312, 3, 0,
  131918. _vq_quantlist__44c5_s_p2_0,
  131919. NULL,
  131920. &_vq_auxt__44c5_s_p2_0,
  131921. NULL,
  131922. 0
  131923. };
  131924. static long _vq_quantlist__44c5_s_p3_0[] = {
  131925. 2,
  131926. 1,
  131927. 3,
  131928. 0,
  131929. 4,
  131930. };
  131931. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131932. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131935. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131938. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0,
  131972. };
  131973. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131974. -1.5, -0.5, 0.5, 1.5,
  131975. };
  131976. static long _vq_quantmap__44c5_s_p3_0[] = {
  131977. 3, 1, 0, 2, 4,
  131978. };
  131979. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131980. _vq_quantthresh__44c5_s_p3_0,
  131981. _vq_quantmap__44c5_s_p3_0,
  131982. 5,
  131983. 5
  131984. };
  131985. static static_codebook _44c5_s_p3_0 = {
  131986. 4, 625,
  131987. _vq_lengthlist__44c5_s_p3_0,
  131988. 1, -533725184, 1611661312, 3, 0,
  131989. _vq_quantlist__44c5_s_p3_0,
  131990. NULL,
  131991. &_vq_auxt__44c5_s_p3_0,
  131992. NULL,
  131993. 0
  131994. };
  131995. static long _vq_quantlist__44c5_s_p4_0[] = {
  131996. 4,
  131997. 3,
  131998. 5,
  131999. 2,
  132000. 6,
  132001. 1,
  132002. 7,
  132003. 0,
  132004. 8,
  132005. };
  132006. static long _vq_lengthlist__44c5_s_p4_0[] = {
  132007. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  132008. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  132009. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  132010. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  132011. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132012. 0,
  132013. };
  132014. static float _vq_quantthresh__44c5_s_p4_0[] = {
  132015. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132016. };
  132017. static long _vq_quantmap__44c5_s_p4_0[] = {
  132018. 7, 5, 3, 1, 0, 2, 4, 6,
  132019. 8,
  132020. };
  132021. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  132022. _vq_quantthresh__44c5_s_p4_0,
  132023. _vq_quantmap__44c5_s_p4_0,
  132024. 9,
  132025. 9
  132026. };
  132027. static static_codebook _44c5_s_p4_0 = {
  132028. 2, 81,
  132029. _vq_lengthlist__44c5_s_p4_0,
  132030. 1, -531628032, 1611661312, 4, 0,
  132031. _vq_quantlist__44c5_s_p4_0,
  132032. NULL,
  132033. &_vq_auxt__44c5_s_p4_0,
  132034. NULL,
  132035. 0
  132036. };
  132037. static long _vq_quantlist__44c5_s_p5_0[] = {
  132038. 4,
  132039. 3,
  132040. 5,
  132041. 2,
  132042. 6,
  132043. 1,
  132044. 7,
  132045. 0,
  132046. 8,
  132047. };
  132048. static long _vq_lengthlist__44c5_s_p5_0[] = {
  132049. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132050. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  132051. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  132052. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132053. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132054. 10,
  132055. };
  132056. static float _vq_quantthresh__44c5_s_p5_0[] = {
  132057. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132058. };
  132059. static long _vq_quantmap__44c5_s_p5_0[] = {
  132060. 7, 5, 3, 1, 0, 2, 4, 6,
  132061. 8,
  132062. };
  132063. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  132064. _vq_quantthresh__44c5_s_p5_0,
  132065. _vq_quantmap__44c5_s_p5_0,
  132066. 9,
  132067. 9
  132068. };
  132069. static static_codebook _44c5_s_p5_0 = {
  132070. 2, 81,
  132071. _vq_lengthlist__44c5_s_p5_0,
  132072. 1, -531628032, 1611661312, 4, 0,
  132073. _vq_quantlist__44c5_s_p5_0,
  132074. NULL,
  132075. &_vq_auxt__44c5_s_p5_0,
  132076. NULL,
  132077. 0
  132078. };
  132079. static long _vq_quantlist__44c5_s_p6_0[] = {
  132080. 8,
  132081. 7,
  132082. 9,
  132083. 6,
  132084. 10,
  132085. 5,
  132086. 11,
  132087. 4,
  132088. 12,
  132089. 3,
  132090. 13,
  132091. 2,
  132092. 14,
  132093. 1,
  132094. 15,
  132095. 0,
  132096. 16,
  132097. };
  132098. static long _vq_lengthlist__44c5_s_p6_0[] = {
  132099. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  132100. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  132101. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  132102. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132103. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132104. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132105. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132106. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132107. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132108. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132109. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132110. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132111. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132112. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132113. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132114. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132115. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132116. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132117. 13,
  132118. };
  132119. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132120. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132121. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132122. };
  132123. static long _vq_quantmap__44c5_s_p6_0[] = {
  132124. 15, 13, 11, 9, 7, 5, 3, 1,
  132125. 0, 2, 4, 6, 8, 10, 12, 14,
  132126. 16,
  132127. };
  132128. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132129. _vq_quantthresh__44c5_s_p6_0,
  132130. _vq_quantmap__44c5_s_p6_0,
  132131. 17,
  132132. 17
  132133. };
  132134. static static_codebook _44c5_s_p6_0 = {
  132135. 2, 289,
  132136. _vq_lengthlist__44c5_s_p6_0,
  132137. 1, -529530880, 1611661312, 5, 0,
  132138. _vq_quantlist__44c5_s_p6_0,
  132139. NULL,
  132140. &_vq_auxt__44c5_s_p6_0,
  132141. NULL,
  132142. 0
  132143. };
  132144. static long _vq_quantlist__44c5_s_p7_0[] = {
  132145. 1,
  132146. 0,
  132147. 2,
  132148. };
  132149. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132150. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132151. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132152. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132153. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132154. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132155. 10,
  132156. };
  132157. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132158. -5.5, 5.5,
  132159. };
  132160. static long _vq_quantmap__44c5_s_p7_0[] = {
  132161. 1, 0, 2,
  132162. };
  132163. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132164. _vq_quantthresh__44c5_s_p7_0,
  132165. _vq_quantmap__44c5_s_p7_0,
  132166. 3,
  132167. 3
  132168. };
  132169. static static_codebook _44c5_s_p7_0 = {
  132170. 4, 81,
  132171. _vq_lengthlist__44c5_s_p7_0,
  132172. 1, -529137664, 1618345984, 2, 0,
  132173. _vq_quantlist__44c5_s_p7_0,
  132174. NULL,
  132175. &_vq_auxt__44c5_s_p7_0,
  132176. NULL,
  132177. 0
  132178. };
  132179. static long _vq_quantlist__44c5_s_p7_1[] = {
  132180. 5,
  132181. 4,
  132182. 6,
  132183. 3,
  132184. 7,
  132185. 2,
  132186. 8,
  132187. 1,
  132188. 9,
  132189. 0,
  132190. 10,
  132191. };
  132192. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132193. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132194. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132195. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132196. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132197. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132198. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132199. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132200. 10,10,10, 8, 8, 8, 8, 8, 8,
  132201. };
  132202. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132203. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132204. 3.5, 4.5,
  132205. };
  132206. static long _vq_quantmap__44c5_s_p7_1[] = {
  132207. 9, 7, 5, 3, 1, 0, 2, 4,
  132208. 6, 8, 10,
  132209. };
  132210. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132211. _vq_quantthresh__44c5_s_p7_1,
  132212. _vq_quantmap__44c5_s_p7_1,
  132213. 11,
  132214. 11
  132215. };
  132216. static static_codebook _44c5_s_p7_1 = {
  132217. 2, 121,
  132218. _vq_lengthlist__44c5_s_p7_1,
  132219. 1, -531365888, 1611661312, 4, 0,
  132220. _vq_quantlist__44c5_s_p7_1,
  132221. NULL,
  132222. &_vq_auxt__44c5_s_p7_1,
  132223. NULL,
  132224. 0
  132225. };
  132226. static long _vq_quantlist__44c5_s_p8_0[] = {
  132227. 6,
  132228. 5,
  132229. 7,
  132230. 4,
  132231. 8,
  132232. 3,
  132233. 9,
  132234. 2,
  132235. 10,
  132236. 1,
  132237. 11,
  132238. 0,
  132239. 12,
  132240. };
  132241. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132242. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132243. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132244. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132245. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132246. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132247. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132248. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132249. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132250. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132251. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132252. 0,12,12,12,12,12,12,13,13,
  132253. };
  132254. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132255. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132256. 12.5, 17.5, 22.5, 27.5,
  132257. };
  132258. static long _vq_quantmap__44c5_s_p8_0[] = {
  132259. 11, 9, 7, 5, 3, 1, 0, 2,
  132260. 4, 6, 8, 10, 12,
  132261. };
  132262. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132263. _vq_quantthresh__44c5_s_p8_0,
  132264. _vq_quantmap__44c5_s_p8_0,
  132265. 13,
  132266. 13
  132267. };
  132268. static static_codebook _44c5_s_p8_0 = {
  132269. 2, 169,
  132270. _vq_lengthlist__44c5_s_p8_0,
  132271. 1, -526516224, 1616117760, 4, 0,
  132272. _vq_quantlist__44c5_s_p8_0,
  132273. NULL,
  132274. &_vq_auxt__44c5_s_p8_0,
  132275. NULL,
  132276. 0
  132277. };
  132278. static long _vq_quantlist__44c5_s_p8_1[] = {
  132279. 2,
  132280. 1,
  132281. 3,
  132282. 0,
  132283. 4,
  132284. };
  132285. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132286. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132287. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132288. };
  132289. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132290. -1.5, -0.5, 0.5, 1.5,
  132291. };
  132292. static long _vq_quantmap__44c5_s_p8_1[] = {
  132293. 3, 1, 0, 2, 4,
  132294. };
  132295. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132296. _vq_quantthresh__44c5_s_p8_1,
  132297. _vq_quantmap__44c5_s_p8_1,
  132298. 5,
  132299. 5
  132300. };
  132301. static static_codebook _44c5_s_p8_1 = {
  132302. 2, 25,
  132303. _vq_lengthlist__44c5_s_p8_1,
  132304. 1, -533725184, 1611661312, 3, 0,
  132305. _vq_quantlist__44c5_s_p8_1,
  132306. NULL,
  132307. &_vq_auxt__44c5_s_p8_1,
  132308. NULL,
  132309. 0
  132310. };
  132311. static long _vq_quantlist__44c5_s_p9_0[] = {
  132312. 7,
  132313. 6,
  132314. 8,
  132315. 5,
  132316. 9,
  132317. 4,
  132318. 10,
  132319. 3,
  132320. 11,
  132321. 2,
  132322. 12,
  132323. 1,
  132324. 13,
  132325. 0,
  132326. 14,
  132327. };
  132328. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132329. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132330. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132331. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132332. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132333. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132334. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132335. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132336. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132337. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132338. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132339. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132340. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132341. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132342. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132343. 12,
  132344. };
  132345. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132346. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132347. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132348. };
  132349. static long _vq_quantmap__44c5_s_p9_0[] = {
  132350. 13, 11, 9, 7, 5, 3, 1, 0,
  132351. 2, 4, 6, 8, 10, 12, 14,
  132352. };
  132353. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132354. _vq_quantthresh__44c5_s_p9_0,
  132355. _vq_quantmap__44c5_s_p9_0,
  132356. 15,
  132357. 15
  132358. };
  132359. static static_codebook _44c5_s_p9_0 = {
  132360. 2, 225,
  132361. _vq_lengthlist__44c5_s_p9_0,
  132362. 1, -512522752, 1628852224, 4, 0,
  132363. _vq_quantlist__44c5_s_p9_0,
  132364. NULL,
  132365. &_vq_auxt__44c5_s_p9_0,
  132366. NULL,
  132367. 0
  132368. };
  132369. static long _vq_quantlist__44c5_s_p9_1[] = {
  132370. 8,
  132371. 7,
  132372. 9,
  132373. 6,
  132374. 10,
  132375. 5,
  132376. 11,
  132377. 4,
  132378. 12,
  132379. 3,
  132380. 13,
  132381. 2,
  132382. 14,
  132383. 1,
  132384. 15,
  132385. 0,
  132386. 16,
  132387. };
  132388. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132389. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132390. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132391. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132392. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132393. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132394. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132395. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132396. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132397. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132398. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132399. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132400. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132401. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132402. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132403. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132404. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132405. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132406. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132407. 15,
  132408. };
  132409. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132410. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132411. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132412. };
  132413. static long _vq_quantmap__44c5_s_p9_1[] = {
  132414. 15, 13, 11, 9, 7, 5, 3, 1,
  132415. 0, 2, 4, 6, 8, 10, 12, 14,
  132416. 16,
  132417. };
  132418. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132419. _vq_quantthresh__44c5_s_p9_1,
  132420. _vq_quantmap__44c5_s_p9_1,
  132421. 17,
  132422. 17
  132423. };
  132424. static static_codebook _44c5_s_p9_1 = {
  132425. 2, 289,
  132426. _vq_lengthlist__44c5_s_p9_1,
  132427. 1, -520814592, 1620377600, 5, 0,
  132428. _vq_quantlist__44c5_s_p9_1,
  132429. NULL,
  132430. &_vq_auxt__44c5_s_p9_1,
  132431. NULL,
  132432. 0
  132433. };
  132434. static long _vq_quantlist__44c5_s_p9_2[] = {
  132435. 10,
  132436. 9,
  132437. 11,
  132438. 8,
  132439. 12,
  132440. 7,
  132441. 13,
  132442. 6,
  132443. 14,
  132444. 5,
  132445. 15,
  132446. 4,
  132447. 16,
  132448. 3,
  132449. 17,
  132450. 2,
  132451. 18,
  132452. 1,
  132453. 19,
  132454. 0,
  132455. 20,
  132456. };
  132457. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132458. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132459. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132460. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132461. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132462. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132463. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132464. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132465. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132466. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132467. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132468. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132469. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132470. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132471. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132472. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132473. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132474. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132475. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132476. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132477. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132478. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132479. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132480. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132481. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132482. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132483. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132484. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132485. 10,10,10,10,10,10,10,10,10,
  132486. };
  132487. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132488. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132489. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132490. 6.5, 7.5, 8.5, 9.5,
  132491. };
  132492. static long _vq_quantmap__44c5_s_p9_2[] = {
  132493. 19, 17, 15, 13, 11, 9, 7, 5,
  132494. 3, 1, 0, 2, 4, 6, 8, 10,
  132495. 12, 14, 16, 18, 20,
  132496. };
  132497. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132498. _vq_quantthresh__44c5_s_p9_2,
  132499. _vq_quantmap__44c5_s_p9_2,
  132500. 21,
  132501. 21
  132502. };
  132503. static static_codebook _44c5_s_p9_2 = {
  132504. 2, 441,
  132505. _vq_lengthlist__44c5_s_p9_2,
  132506. 1, -529268736, 1611661312, 5, 0,
  132507. _vq_quantlist__44c5_s_p9_2,
  132508. NULL,
  132509. &_vq_auxt__44c5_s_p9_2,
  132510. NULL,
  132511. 0
  132512. };
  132513. static long _huff_lengthlist__44c5_s_short[] = {
  132514. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132515. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132516. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132517. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132518. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132519. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132520. 6, 8,11,16,
  132521. };
  132522. static static_codebook _huff_book__44c5_s_short = {
  132523. 2, 100,
  132524. _huff_lengthlist__44c5_s_short,
  132525. 0, 0, 0, 0, 0,
  132526. NULL,
  132527. NULL,
  132528. NULL,
  132529. NULL,
  132530. 0
  132531. };
  132532. static long _huff_lengthlist__44c6_s_long[] = {
  132533. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132534. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132535. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132536. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132537. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132538. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132539. 11,10,10,12,
  132540. };
  132541. static static_codebook _huff_book__44c6_s_long = {
  132542. 2, 100,
  132543. _huff_lengthlist__44c6_s_long,
  132544. 0, 0, 0, 0, 0,
  132545. NULL,
  132546. NULL,
  132547. NULL,
  132548. NULL,
  132549. 0
  132550. };
  132551. static long _vq_quantlist__44c6_s_p1_0[] = {
  132552. 1,
  132553. 0,
  132554. 2,
  132555. };
  132556. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132557. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132558. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132559. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132560. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132561. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132562. 8,
  132563. };
  132564. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132565. -0.5, 0.5,
  132566. };
  132567. static long _vq_quantmap__44c6_s_p1_0[] = {
  132568. 1, 0, 2,
  132569. };
  132570. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132571. _vq_quantthresh__44c6_s_p1_0,
  132572. _vq_quantmap__44c6_s_p1_0,
  132573. 3,
  132574. 3
  132575. };
  132576. static static_codebook _44c6_s_p1_0 = {
  132577. 4, 81,
  132578. _vq_lengthlist__44c6_s_p1_0,
  132579. 1, -535822336, 1611661312, 2, 0,
  132580. _vq_quantlist__44c6_s_p1_0,
  132581. NULL,
  132582. &_vq_auxt__44c6_s_p1_0,
  132583. NULL,
  132584. 0
  132585. };
  132586. static long _vq_quantlist__44c6_s_p2_0[] = {
  132587. 2,
  132588. 1,
  132589. 3,
  132590. 0,
  132591. 4,
  132592. };
  132593. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132594. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132595. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132596. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132597. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132598. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132599. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132600. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132601. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132603. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132604. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132605. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132606. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132607. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132608. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132609. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132611. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132612. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132613. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132614. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132615. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132616. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132617. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132619. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132620. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132621. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132622. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132623. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132624. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132625. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132630. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132631. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132632. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132633. 13,
  132634. };
  132635. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132636. -1.5, -0.5, 0.5, 1.5,
  132637. };
  132638. static long _vq_quantmap__44c6_s_p2_0[] = {
  132639. 3, 1, 0, 2, 4,
  132640. };
  132641. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132642. _vq_quantthresh__44c6_s_p2_0,
  132643. _vq_quantmap__44c6_s_p2_0,
  132644. 5,
  132645. 5
  132646. };
  132647. static static_codebook _44c6_s_p2_0 = {
  132648. 4, 625,
  132649. _vq_lengthlist__44c6_s_p2_0,
  132650. 1, -533725184, 1611661312, 3, 0,
  132651. _vq_quantlist__44c6_s_p2_0,
  132652. NULL,
  132653. &_vq_auxt__44c6_s_p2_0,
  132654. NULL,
  132655. 0
  132656. };
  132657. static long _vq_quantlist__44c6_s_p3_0[] = {
  132658. 4,
  132659. 3,
  132660. 5,
  132661. 2,
  132662. 6,
  132663. 1,
  132664. 7,
  132665. 0,
  132666. 8,
  132667. };
  132668. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132669. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132670. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132671. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132672. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132674. 0,
  132675. };
  132676. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132677. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132678. };
  132679. static long _vq_quantmap__44c6_s_p3_0[] = {
  132680. 7, 5, 3, 1, 0, 2, 4, 6,
  132681. 8,
  132682. };
  132683. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132684. _vq_quantthresh__44c6_s_p3_0,
  132685. _vq_quantmap__44c6_s_p3_0,
  132686. 9,
  132687. 9
  132688. };
  132689. static static_codebook _44c6_s_p3_0 = {
  132690. 2, 81,
  132691. _vq_lengthlist__44c6_s_p3_0,
  132692. 1, -531628032, 1611661312, 4, 0,
  132693. _vq_quantlist__44c6_s_p3_0,
  132694. NULL,
  132695. &_vq_auxt__44c6_s_p3_0,
  132696. NULL,
  132697. 0
  132698. };
  132699. static long _vq_quantlist__44c6_s_p4_0[] = {
  132700. 8,
  132701. 7,
  132702. 9,
  132703. 6,
  132704. 10,
  132705. 5,
  132706. 11,
  132707. 4,
  132708. 12,
  132709. 3,
  132710. 13,
  132711. 2,
  132712. 14,
  132713. 1,
  132714. 15,
  132715. 0,
  132716. 16,
  132717. };
  132718. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132719. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132720. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132721. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132722. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132723. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132724. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132725. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132726. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132727. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132728. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132737. 0,
  132738. };
  132739. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132740. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132741. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132742. };
  132743. static long _vq_quantmap__44c6_s_p4_0[] = {
  132744. 15, 13, 11, 9, 7, 5, 3, 1,
  132745. 0, 2, 4, 6, 8, 10, 12, 14,
  132746. 16,
  132747. };
  132748. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132749. _vq_quantthresh__44c6_s_p4_0,
  132750. _vq_quantmap__44c6_s_p4_0,
  132751. 17,
  132752. 17
  132753. };
  132754. static static_codebook _44c6_s_p4_0 = {
  132755. 2, 289,
  132756. _vq_lengthlist__44c6_s_p4_0,
  132757. 1, -529530880, 1611661312, 5, 0,
  132758. _vq_quantlist__44c6_s_p4_0,
  132759. NULL,
  132760. &_vq_auxt__44c6_s_p4_0,
  132761. NULL,
  132762. 0
  132763. };
  132764. static long _vq_quantlist__44c6_s_p5_0[] = {
  132765. 1,
  132766. 0,
  132767. 2,
  132768. };
  132769. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132770. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132771. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132772. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132773. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132774. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132775. 12,
  132776. };
  132777. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132778. -5.5, 5.5,
  132779. };
  132780. static long _vq_quantmap__44c6_s_p5_0[] = {
  132781. 1, 0, 2,
  132782. };
  132783. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132784. _vq_quantthresh__44c6_s_p5_0,
  132785. _vq_quantmap__44c6_s_p5_0,
  132786. 3,
  132787. 3
  132788. };
  132789. static static_codebook _44c6_s_p5_0 = {
  132790. 4, 81,
  132791. _vq_lengthlist__44c6_s_p5_0,
  132792. 1, -529137664, 1618345984, 2, 0,
  132793. _vq_quantlist__44c6_s_p5_0,
  132794. NULL,
  132795. &_vq_auxt__44c6_s_p5_0,
  132796. NULL,
  132797. 0
  132798. };
  132799. static long _vq_quantlist__44c6_s_p5_1[] = {
  132800. 5,
  132801. 4,
  132802. 6,
  132803. 3,
  132804. 7,
  132805. 2,
  132806. 8,
  132807. 1,
  132808. 9,
  132809. 0,
  132810. 10,
  132811. };
  132812. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132813. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132814. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132815. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132816. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132817. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132818. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132819. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132820. 11,10,10, 7, 7, 8, 8, 8, 8,
  132821. };
  132822. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132823. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132824. 3.5, 4.5,
  132825. };
  132826. static long _vq_quantmap__44c6_s_p5_1[] = {
  132827. 9, 7, 5, 3, 1, 0, 2, 4,
  132828. 6, 8, 10,
  132829. };
  132830. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132831. _vq_quantthresh__44c6_s_p5_1,
  132832. _vq_quantmap__44c6_s_p5_1,
  132833. 11,
  132834. 11
  132835. };
  132836. static static_codebook _44c6_s_p5_1 = {
  132837. 2, 121,
  132838. _vq_lengthlist__44c6_s_p5_1,
  132839. 1, -531365888, 1611661312, 4, 0,
  132840. _vq_quantlist__44c6_s_p5_1,
  132841. NULL,
  132842. &_vq_auxt__44c6_s_p5_1,
  132843. NULL,
  132844. 0
  132845. };
  132846. static long _vq_quantlist__44c6_s_p6_0[] = {
  132847. 6,
  132848. 5,
  132849. 7,
  132850. 4,
  132851. 8,
  132852. 3,
  132853. 9,
  132854. 2,
  132855. 10,
  132856. 1,
  132857. 11,
  132858. 0,
  132859. 12,
  132860. };
  132861. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132862. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132863. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132864. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132865. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132866. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132867. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132872. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132873. };
  132874. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132875. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132876. 12.5, 17.5, 22.5, 27.5,
  132877. };
  132878. static long _vq_quantmap__44c6_s_p6_0[] = {
  132879. 11, 9, 7, 5, 3, 1, 0, 2,
  132880. 4, 6, 8, 10, 12,
  132881. };
  132882. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132883. _vq_quantthresh__44c6_s_p6_0,
  132884. _vq_quantmap__44c6_s_p6_0,
  132885. 13,
  132886. 13
  132887. };
  132888. static static_codebook _44c6_s_p6_0 = {
  132889. 2, 169,
  132890. _vq_lengthlist__44c6_s_p6_0,
  132891. 1, -526516224, 1616117760, 4, 0,
  132892. _vq_quantlist__44c6_s_p6_0,
  132893. NULL,
  132894. &_vq_auxt__44c6_s_p6_0,
  132895. NULL,
  132896. 0
  132897. };
  132898. static long _vq_quantlist__44c6_s_p6_1[] = {
  132899. 2,
  132900. 1,
  132901. 3,
  132902. 0,
  132903. 4,
  132904. };
  132905. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132906. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132907. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132908. };
  132909. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132910. -1.5, -0.5, 0.5, 1.5,
  132911. };
  132912. static long _vq_quantmap__44c6_s_p6_1[] = {
  132913. 3, 1, 0, 2, 4,
  132914. };
  132915. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132916. _vq_quantthresh__44c6_s_p6_1,
  132917. _vq_quantmap__44c6_s_p6_1,
  132918. 5,
  132919. 5
  132920. };
  132921. static static_codebook _44c6_s_p6_1 = {
  132922. 2, 25,
  132923. _vq_lengthlist__44c6_s_p6_1,
  132924. 1, -533725184, 1611661312, 3, 0,
  132925. _vq_quantlist__44c6_s_p6_1,
  132926. NULL,
  132927. &_vq_auxt__44c6_s_p6_1,
  132928. NULL,
  132929. 0
  132930. };
  132931. static long _vq_quantlist__44c6_s_p7_0[] = {
  132932. 6,
  132933. 5,
  132934. 7,
  132935. 4,
  132936. 8,
  132937. 3,
  132938. 9,
  132939. 2,
  132940. 10,
  132941. 1,
  132942. 11,
  132943. 0,
  132944. 12,
  132945. };
  132946. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132947. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132948. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132949. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132950. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132951. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132952. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132953. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132954. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132955. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132956. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132957. 20,13,13,13,13,13,13,14,14,
  132958. };
  132959. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132960. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132961. 27.5, 38.5, 49.5, 60.5,
  132962. };
  132963. static long _vq_quantmap__44c6_s_p7_0[] = {
  132964. 11, 9, 7, 5, 3, 1, 0, 2,
  132965. 4, 6, 8, 10, 12,
  132966. };
  132967. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132968. _vq_quantthresh__44c6_s_p7_0,
  132969. _vq_quantmap__44c6_s_p7_0,
  132970. 13,
  132971. 13
  132972. };
  132973. static static_codebook _44c6_s_p7_0 = {
  132974. 2, 169,
  132975. _vq_lengthlist__44c6_s_p7_0,
  132976. 1, -523206656, 1618345984, 4, 0,
  132977. _vq_quantlist__44c6_s_p7_0,
  132978. NULL,
  132979. &_vq_auxt__44c6_s_p7_0,
  132980. NULL,
  132981. 0
  132982. };
  132983. static long _vq_quantlist__44c6_s_p7_1[] = {
  132984. 5,
  132985. 4,
  132986. 6,
  132987. 3,
  132988. 7,
  132989. 2,
  132990. 8,
  132991. 1,
  132992. 9,
  132993. 0,
  132994. 10,
  132995. };
  132996. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132997. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132998. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132999. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  133000. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  133001. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  133002. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  133003. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  133004. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  133005. };
  133006. static float _vq_quantthresh__44c6_s_p7_1[] = {
  133007. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133008. 3.5, 4.5,
  133009. };
  133010. static long _vq_quantmap__44c6_s_p7_1[] = {
  133011. 9, 7, 5, 3, 1, 0, 2, 4,
  133012. 6, 8, 10,
  133013. };
  133014. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  133015. _vq_quantthresh__44c6_s_p7_1,
  133016. _vq_quantmap__44c6_s_p7_1,
  133017. 11,
  133018. 11
  133019. };
  133020. static static_codebook _44c6_s_p7_1 = {
  133021. 2, 121,
  133022. _vq_lengthlist__44c6_s_p7_1,
  133023. 1, -531365888, 1611661312, 4, 0,
  133024. _vq_quantlist__44c6_s_p7_1,
  133025. NULL,
  133026. &_vq_auxt__44c6_s_p7_1,
  133027. NULL,
  133028. 0
  133029. };
  133030. static long _vq_quantlist__44c6_s_p8_0[] = {
  133031. 7,
  133032. 6,
  133033. 8,
  133034. 5,
  133035. 9,
  133036. 4,
  133037. 10,
  133038. 3,
  133039. 11,
  133040. 2,
  133041. 12,
  133042. 1,
  133043. 13,
  133044. 0,
  133045. 14,
  133046. };
  133047. static long _vq_lengthlist__44c6_s_p8_0[] = {
  133048. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  133049. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  133050. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  133051. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  133052. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  133053. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  133054. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  133055. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  133056. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  133057. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  133058. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  133059. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  133060. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  133061. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  133062. 14,
  133063. };
  133064. static float _vq_quantthresh__44c6_s_p8_0[] = {
  133065. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133066. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133067. };
  133068. static long _vq_quantmap__44c6_s_p8_0[] = {
  133069. 13, 11, 9, 7, 5, 3, 1, 0,
  133070. 2, 4, 6, 8, 10, 12, 14,
  133071. };
  133072. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  133073. _vq_quantthresh__44c6_s_p8_0,
  133074. _vq_quantmap__44c6_s_p8_0,
  133075. 15,
  133076. 15
  133077. };
  133078. static static_codebook _44c6_s_p8_0 = {
  133079. 2, 225,
  133080. _vq_lengthlist__44c6_s_p8_0,
  133081. 1, -520986624, 1620377600, 4, 0,
  133082. _vq_quantlist__44c6_s_p8_0,
  133083. NULL,
  133084. &_vq_auxt__44c6_s_p8_0,
  133085. NULL,
  133086. 0
  133087. };
  133088. static long _vq_quantlist__44c6_s_p8_1[] = {
  133089. 10,
  133090. 9,
  133091. 11,
  133092. 8,
  133093. 12,
  133094. 7,
  133095. 13,
  133096. 6,
  133097. 14,
  133098. 5,
  133099. 15,
  133100. 4,
  133101. 16,
  133102. 3,
  133103. 17,
  133104. 2,
  133105. 18,
  133106. 1,
  133107. 19,
  133108. 0,
  133109. 20,
  133110. };
  133111. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133112. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133113. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133114. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133115. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133116. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133117. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133118. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133119. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133120. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133121. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133122. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133123. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133124. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133125. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133126. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133127. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133128. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133129. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133130. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133131. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133132. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133133. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133134. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133135. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133136. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133137. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133138. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133139. 10,10,10,10,10,10,10,10,10,
  133140. };
  133141. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133142. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133143. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133144. 6.5, 7.5, 8.5, 9.5,
  133145. };
  133146. static long _vq_quantmap__44c6_s_p8_1[] = {
  133147. 19, 17, 15, 13, 11, 9, 7, 5,
  133148. 3, 1, 0, 2, 4, 6, 8, 10,
  133149. 12, 14, 16, 18, 20,
  133150. };
  133151. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133152. _vq_quantthresh__44c6_s_p8_1,
  133153. _vq_quantmap__44c6_s_p8_1,
  133154. 21,
  133155. 21
  133156. };
  133157. static static_codebook _44c6_s_p8_1 = {
  133158. 2, 441,
  133159. _vq_lengthlist__44c6_s_p8_1,
  133160. 1, -529268736, 1611661312, 5, 0,
  133161. _vq_quantlist__44c6_s_p8_1,
  133162. NULL,
  133163. &_vq_auxt__44c6_s_p8_1,
  133164. NULL,
  133165. 0
  133166. };
  133167. static long _vq_quantlist__44c6_s_p9_0[] = {
  133168. 6,
  133169. 5,
  133170. 7,
  133171. 4,
  133172. 8,
  133173. 3,
  133174. 9,
  133175. 2,
  133176. 10,
  133177. 1,
  133178. 11,
  133179. 0,
  133180. 12,
  133181. };
  133182. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133183. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133184. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133185. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133186. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133187. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133188. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133189. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133190. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133191. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133192. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133193. 10,10,10,10,10,10,10,10,10,
  133194. };
  133195. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133196. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133197. 1592.5, 2229.5, 2866.5, 3503.5,
  133198. };
  133199. static long _vq_quantmap__44c6_s_p9_0[] = {
  133200. 11, 9, 7, 5, 3, 1, 0, 2,
  133201. 4, 6, 8, 10, 12,
  133202. };
  133203. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133204. _vq_quantthresh__44c6_s_p9_0,
  133205. _vq_quantmap__44c6_s_p9_0,
  133206. 13,
  133207. 13
  133208. };
  133209. static static_codebook _44c6_s_p9_0 = {
  133210. 2, 169,
  133211. _vq_lengthlist__44c6_s_p9_0,
  133212. 1, -511845376, 1630791680, 4, 0,
  133213. _vq_quantlist__44c6_s_p9_0,
  133214. NULL,
  133215. &_vq_auxt__44c6_s_p9_0,
  133216. NULL,
  133217. 0
  133218. };
  133219. static long _vq_quantlist__44c6_s_p9_1[] = {
  133220. 6,
  133221. 5,
  133222. 7,
  133223. 4,
  133224. 8,
  133225. 3,
  133226. 9,
  133227. 2,
  133228. 10,
  133229. 1,
  133230. 11,
  133231. 0,
  133232. 12,
  133233. };
  133234. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133235. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133236. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133237. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133238. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133239. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133240. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133241. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133242. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133243. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133244. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133245. 15,12,10,11,11,13,11,12,13,
  133246. };
  133247. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133248. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133249. 122.5, 171.5, 220.5, 269.5,
  133250. };
  133251. static long _vq_quantmap__44c6_s_p9_1[] = {
  133252. 11, 9, 7, 5, 3, 1, 0, 2,
  133253. 4, 6, 8, 10, 12,
  133254. };
  133255. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133256. _vq_quantthresh__44c6_s_p9_1,
  133257. _vq_quantmap__44c6_s_p9_1,
  133258. 13,
  133259. 13
  133260. };
  133261. static static_codebook _44c6_s_p9_1 = {
  133262. 2, 169,
  133263. _vq_lengthlist__44c6_s_p9_1,
  133264. 1, -518889472, 1622704128, 4, 0,
  133265. _vq_quantlist__44c6_s_p9_1,
  133266. NULL,
  133267. &_vq_auxt__44c6_s_p9_1,
  133268. NULL,
  133269. 0
  133270. };
  133271. static long _vq_quantlist__44c6_s_p9_2[] = {
  133272. 24,
  133273. 23,
  133274. 25,
  133275. 22,
  133276. 26,
  133277. 21,
  133278. 27,
  133279. 20,
  133280. 28,
  133281. 19,
  133282. 29,
  133283. 18,
  133284. 30,
  133285. 17,
  133286. 31,
  133287. 16,
  133288. 32,
  133289. 15,
  133290. 33,
  133291. 14,
  133292. 34,
  133293. 13,
  133294. 35,
  133295. 12,
  133296. 36,
  133297. 11,
  133298. 37,
  133299. 10,
  133300. 38,
  133301. 9,
  133302. 39,
  133303. 8,
  133304. 40,
  133305. 7,
  133306. 41,
  133307. 6,
  133308. 42,
  133309. 5,
  133310. 43,
  133311. 4,
  133312. 44,
  133313. 3,
  133314. 45,
  133315. 2,
  133316. 46,
  133317. 1,
  133318. 47,
  133319. 0,
  133320. 48,
  133321. };
  133322. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133323. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133324. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133325. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133326. 7,
  133327. };
  133328. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133329. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133330. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133331. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133332. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133333. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133334. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133335. };
  133336. static long _vq_quantmap__44c6_s_p9_2[] = {
  133337. 47, 45, 43, 41, 39, 37, 35, 33,
  133338. 31, 29, 27, 25, 23, 21, 19, 17,
  133339. 15, 13, 11, 9, 7, 5, 3, 1,
  133340. 0, 2, 4, 6, 8, 10, 12, 14,
  133341. 16, 18, 20, 22, 24, 26, 28, 30,
  133342. 32, 34, 36, 38, 40, 42, 44, 46,
  133343. 48,
  133344. };
  133345. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133346. _vq_quantthresh__44c6_s_p9_2,
  133347. _vq_quantmap__44c6_s_p9_2,
  133348. 49,
  133349. 49
  133350. };
  133351. static static_codebook _44c6_s_p9_2 = {
  133352. 1, 49,
  133353. _vq_lengthlist__44c6_s_p9_2,
  133354. 1, -526909440, 1611661312, 6, 0,
  133355. _vq_quantlist__44c6_s_p9_2,
  133356. NULL,
  133357. &_vq_auxt__44c6_s_p9_2,
  133358. NULL,
  133359. 0
  133360. };
  133361. static long _huff_lengthlist__44c6_s_short[] = {
  133362. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133363. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133364. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133365. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133366. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133367. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133368. 9,10,17,18,
  133369. };
  133370. static static_codebook _huff_book__44c6_s_short = {
  133371. 2, 100,
  133372. _huff_lengthlist__44c6_s_short,
  133373. 0, 0, 0, 0, 0,
  133374. NULL,
  133375. NULL,
  133376. NULL,
  133377. NULL,
  133378. 0
  133379. };
  133380. static long _huff_lengthlist__44c7_s_long[] = {
  133381. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133382. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133383. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133384. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133385. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133386. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133387. 11,10,10,12,
  133388. };
  133389. static static_codebook _huff_book__44c7_s_long = {
  133390. 2, 100,
  133391. _huff_lengthlist__44c7_s_long,
  133392. 0, 0, 0, 0, 0,
  133393. NULL,
  133394. NULL,
  133395. NULL,
  133396. NULL,
  133397. 0
  133398. };
  133399. static long _vq_quantlist__44c7_s_p1_0[] = {
  133400. 1,
  133401. 0,
  133402. 2,
  133403. };
  133404. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133405. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133406. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133407. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133408. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133409. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133410. 8,
  133411. };
  133412. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133413. -0.5, 0.5,
  133414. };
  133415. static long _vq_quantmap__44c7_s_p1_0[] = {
  133416. 1, 0, 2,
  133417. };
  133418. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133419. _vq_quantthresh__44c7_s_p1_0,
  133420. _vq_quantmap__44c7_s_p1_0,
  133421. 3,
  133422. 3
  133423. };
  133424. static static_codebook _44c7_s_p1_0 = {
  133425. 4, 81,
  133426. _vq_lengthlist__44c7_s_p1_0,
  133427. 1, -535822336, 1611661312, 2, 0,
  133428. _vq_quantlist__44c7_s_p1_0,
  133429. NULL,
  133430. &_vq_auxt__44c7_s_p1_0,
  133431. NULL,
  133432. 0
  133433. };
  133434. static long _vq_quantlist__44c7_s_p2_0[] = {
  133435. 2,
  133436. 1,
  133437. 3,
  133438. 0,
  133439. 4,
  133440. };
  133441. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133442. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133443. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133444. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133445. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133446. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133447. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133448. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133449. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133451. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133452. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133453. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133454. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133455. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133456. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133457. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133459. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133460. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133461. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133462. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133463. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133464. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133465. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133467. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133468. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133469. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133470. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133471. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133472. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133473. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133478. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133479. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133480. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133481. 13,
  133482. };
  133483. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133484. -1.5, -0.5, 0.5, 1.5,
  133485. };
  133486. static long _vq_quantmap__44c7_s_p2_0[] = {
  133487. 3, 1, 0, 2, 4,
  133488. };
  133489. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133490. _vq_quantthresh__44c7_s_p2_0,
  133491. _vq_quantmap__44c7_s_p2_0,
  133492. 5,
  133493. 5
  133494. };
  133495. static static_codebook _44c7_s_p2_0 = {
  133496. 4, 625,
  133497. _vq_lengthlist__44c7_s_p2_0,
  133498. 1, -533725184, 1611661312, 3, 0,
  133499. _vq_quantlist__44c7_s_p2_0,
  133500. NULL,
  133501. &_vq_auxt__44c7_s_p2_0,
  133502. NULL,
  133503. 0
  133504. };
  133505. static long _vq_quantlist__44c7_s_p3_0[] = {
  133506. 4,
  133507. 3,
  133508. 5,
  133509. 2,
  133510. 6,
  133511. 1,
  133512. 7,
  133513. 0,
  133514. 8,
  133515. };
  133516. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133517. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133518. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133519. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133520. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133522. 0,
  133523. };
  133524. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133525. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133526. };
  133527. static long _vq_quantmap__44c7_s_p3_0[] = {
  133528. 7, 5, 3, 1, 0, 2, 4, 6,
  133529. 8,
  133530. };
  133531. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133532. _vq_quantthresh__44c7_s_p3_0,
  133533. _vq_quantmap__44c7_s_p3_0,
  133534. 9,
  133535. 9
  133536. };
  133537. static static_codebook _44c7_s_p3_0 = {
  133538. 2, 81,
  133539. _vq_lengthlist__44c7_s_p3_0,
  133540. 1, -531628032, 1611661312, 4, 0,
  133541. _vq_quantlist__44c7_s_p3_0,
  133542. NULL,
  133543. &_vq_auxt__44c7_s_p3_0,
  133544. NULL,
  133545. 0
  133546. };
  133547. static long _vq_quantlist__44c7_s_p4_0[] = {
  133548. 8,
  133549. 7,
  133550. 9,
  133551. 6,
  133552. 10,
  133553. 5,
  133554. 11,
  133555. 4,
  133556. 12,
  133557. 3,
  133558. 13,
  133559. 2,
  133560. 14,
  133561. 1,
  133562. 15,
  133563. 0,
  133564. 16,
  133565. };
  133566. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133567. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133568. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133569. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133570. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133571. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133572. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133573. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133574. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133575. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133576. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133585. 0,
  133586. };
  133587. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133588. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133589. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133590. };
  133591. static long _vq_quantmap__44c7_s_p4_0[] = {
  133592. 15, 13, 11, 9, 7, 5, 3, 1,
  133593. 0, 2, 4, 6, 8, 10, 12, 14,
  133594. 16,
  133595. };
  133596. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133597. _vq_quantthresh__44c7_s_p4_0,
  133598. _vq_quantmap__44c7_s_p4_0,
  133599. 17,
  133600. 17
  133601. };
  133602. static static_codebook _44c7_s_p4_0 = {
  133603. 2, 289,
  133604. _vq_lengthlist__44c7_s_p4_0,
  133605. 1, -529530880, 1611661312, 5, 0,
  133606. _vq_quantlist__44c7_s_p4_0,
  133607. NULL,
  133608. &_vq_auxt__44c7_s_p4_0,
  133609. NULL,
  133610. 0
  133611. };
  133612. static long _vq_quantlist__44c7_s_p5_0[] = {
  133613. 1,
  133614. 0,
  133615. 2,
  133616. };
  133617. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133618. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133619. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133620. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133621. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133622. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133623. 12,
  133624. };
  133625. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133626. -5.5, 5.5,
  133627. };
  133628. static long _vq_quantmap__44c7_s_p5_0[] = {
  133629. 1, 0, 2,
  133630. };
  133631. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133632. _vq_quantthresh__44c7_s_p5_0,
  133633. _vq_quantmap__44c7_s_p5_0,
  133634. 3,
  133635. 3
  133636. };
  133637. static static_codebook _44c7_s_p5_0 = {
  133638. 4, 81,
  133639. _vq_lengthlist__44c7_s_p5_0,
  133640. 1, -529137664, 1618345984, 2, 0,
  133641. _vq_quantlist__44c7_s_p5_0,
  133642. NULL,
  133643. &_vq_auxt__44c7_s_p5_0,
  133644. NULL,
  133645. 0
  133646. };
  133647. static long _vq_quantlist__44c7_s_p5_1[] = {
  133648. 5,
  133649. 4,
  133650. 6,
  133651. 3,
  133652. 7,
  133653. 2,
  133654. 8,
  133655. 1,
  133656. 9,
  133657. 0,
  133658. 10,
  133659. };
  133660. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133661. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133662. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133663. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133664. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133665. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133666. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133667. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133668. 11,11,11, 7, 7, 8, 8, 8, 8,
  133669. };
  133670. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133671. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133672. 3.5, 4.5,
  133673. };
  133674. static long _vq_quantmap__44c7_s_p5_1[] = {
  133675. 9, 7, 5, 3, 1, 0, 2, 4,
  133676. 6, 8, 10,
  133677. };
  133678. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133679. _vq_quantthresh__44c7_s_p5_1,
  133680. _vq_quantmap__44c7_s_p5_1,
  133681. 11,
  133682. 11
  133683. };
  133684. static static_codebook _44c7_s_p5_1 = {
  133685. 2, 121,
  133686. _vq_lengthlist__44c7_s_p5_1,
  133687. 1, -531365888, 1611661312, 4, 0,
  133688. _vq_quantlist__44c7_s_p5_1,
  133689. NULL,
  133690. &_vq_auxt__44c7_s_p5_1,
  133691. NULL,
  133692. 0
  133693. };
  133694. static long _vq_quantlist__44c7_s_p6_0[] = {
  133695. 6,
  133696. 5,
  133697. 7,
  133698. 4,
  133699. 8,
  133700. 3,
  133701. 9,
  133702. 2,
  133703. 10,
  133704. 1,
  133705. 11,
  133706. 0,
  133707. 12,
  133708. };
  133709. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133710. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133711. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133712. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133713. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133714. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133715. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133720. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133721. };
  133722. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133723. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133724. 12.5, 17.5, 22.5, 27.5,
  133725. };
  133726. static long _vq_quantmap__44c7_s_p6_0[] = {
  133727. 11, 9, 7, 5, 3, 1, 0, 2,
  133728. 4, 6, 8, 10, 12,
  133729. };
  133730. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133731. _vq_quantthresh__44c7_s_p6_0,
  133732. _vq_quantmap__44c7_s_p6_0,
  133733. 13,
  133734. 13
  133735. };
  133736. static static_codebook _44c7_s_p6_0 = {
  133737. 2, 169,
  133738. _vq_lengthlist__44c7_s_p6_0,
  133739. 1, -526516224, 1616117760, 4, 0,
  133740. _vq_quantlist__44c7_s_p6_0,
  133741. NULL,
  133742. &_vq_auxt__44c7_s_p6_0,
  133743. NULL,
  133744. 0
  133745. };
  133746. static long _vq_quantlist__44c7_s_p6_1[] = {
  133747. 2,
  133748. 1,
  133749. 3,
  133750. 0,
  133751. 4,
  133752. };
  133753. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133754. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133755. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133756. };
  133757. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133758. -1.5, -0.5, 0.5, 1.5,
  133759. };
  133760. static long _vq_quantmap__44c7_s_p6_1[] = {
  133761. 3, 1, 0, 2, 4,
  133762. };
  133763. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133764. _vq_quantthresh__44c7_s_p6_1,
  133765. _vq_quantmap__44c7_s_p6_1,
  133766. 5,
  133767. 5
  133768. };
  133769. static static_codebook _44c7_s_p6_1 = {
  133770. 2, 25,
  133771. _vq_lengthlist__44c7_s_p6_1,
  133772. 1, -533725184, 1611661312, 3, 0,
  133773. _vq_quantlist__44c7_s_p6_1,
  133774. NULL,
  133775. &_vq_auxt__44c7_s_p6_1,
  133776. NULL,
  133777. 0
  133778. };
  133779. static long _vq_quantlist__44c7_s_p7_0[] = {
  133780. 6,
  133781. 5,
  133782. 7,
  133783. 4,
  133784. 8,
  133785. 3,
  133786. 9,
  133787. 2,
  133788. 10,
  133789. 1,
  133790. 11,
  133791. 0,
  133792. 12,
  133793. };
  133794. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133795. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133796. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133797. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133798. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133799. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133800. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133801. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133802. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133803. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133804. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133805. 19,13,13,13,13,14,14,15,15,
  133806. };
  133807. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133808. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133809. 27.5, 38.5, 49.5, 60.5,
  133810. };
  133811. static long _vq_quantmap__44c7_s_p7_0[] = {
  133812. 11, 9, 7, 5, 3, 1, 0, 2,
  133813. 4, 6, 8, 10, 12,
  133814. };
  133815. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133816. _vq_quantthresh__44c7_s_p7_0,
  133817. _vq_quantmap__44c7_s_p7_0,
  133818. 13,
  133819. 13
  133820. };
  133821. static static_codebook _44c7_s_p7_0 = {
  133822. 2, 169,
  133823. _vq_lengthlist__44c7_s_p7_0,
  133824. 1, -523206656, 1618345984, 4, 0,
  133825. _vq_quantlist__44c7_s_p7_0,
  133826. NULL,
  133827. &_vq_auxt__44c7_s_p7_0,
  133828. NULL,
  133829. 0
  133830. };
  133831. static long _vq_quantlist__44c7_s_p7_1[] = {
  133832. 5,
  133833. 4,
  133834. 6,
  133835. 3,
  133836. 7,
  133837. 2,
  133838. 8,
  133839. 1,
  133840. 9,
  133841. 0,
  133842. 10,
  133843. };
  133844. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133845. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133846. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133847. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133848. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133849. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133850. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133851. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133852. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133853. };
  133854. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133855. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133856. 3.5, 4.5,
  133857. };
  133858. static long _vq_quantmap__44c7_s_p7_1[] = {
  133859. 9, 7, 5, 3, 1, 0, 2, 4,
  133860. 6, 8, 10,
  133861. };
  133862. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133863. _vq_quantthresh__44c7_s_p7_1,
  133864. _vq_quantmap__44c7_s_p7_1,
  133865. 11,
  133866. 11
  133867. };
  133868. static static_codebook _44c7_s_p7_1 = {
  133869. 2, 121,
  133870. _vq_lengthlist__44c7_s_p7_1,
  133871. 1, -531365888, 1611661312, 4, 0,
  133872. _vq_quantlist__44c7_s_p7_1,
  133873. NULL,
  133874. &_vq_auxt__44c7_s_p7_1,
  133875. NULL,
  133876. 0
  133877. };
  133878. static long _vq_quantlist__44c7_s_p8_0[] = {
  133879. 7,
  133880. 6,
  133881. 8,
  133882. 5,
  133883. 9,
  133884. 4,
  133885. 10,
  133886. 3,
  133887. 11,
  133888. 2,
  133889. 12,
  133890. 1,
  133891. 13,
  133892. 0,
  133893. 14,
  133894. };
  133895. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133896. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133897. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133898. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133899. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133900. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133901. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133902. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133903. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133904. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133905. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133906. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133907. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133908. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133909. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133910. 14,
  133911. };
  133912. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133913. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133914. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133915. };
  133916. static long _vq_quantmap__44c7_s_p8_0[] = {
  133917. 13, 11, 9, 7, 5, 3, 1, 0,
  133918. 2, 4, 6, 8, 10, 12, 14,
  133919. };
  133920. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133921. _vq_quantthresh__44c7_s_p8_0,
  133922. _vq_quantmap__44c7_s_p8_0,
  133923. 15,
  133924. 15
  133925. };
  133926. static static_codebook _44c7_s_p8_0 = {
  133927. 2, 225,
  133928. _vq_lengthlist__44c7_s_p8_0,
  133929. 1, -520986624, 1620377600, 4, 0,
  133930. _vq_quantlist__44c7_s_p8_0,
  133931. NULL,
  133932. &_vq_auxt__44c7_s_p8_0,
  133933. NULL,
  133934. 0
  133935. };
  133936. static long _vq_quantlist__44c7_s_p8_1[] = {
  133937. 10,
  133938. 9,
  133939. 11,
  133940. 8,
  133941. 12,
  133942. 7,
  133943. 13,
  133944. 6,
  133945. 14,
  133946. 5,
  133947. 15,
  133948. 4,
  133949. 16,
  133950. 3,
  133951. 17,
  133952. 2,
  133953. 18,
  133954. 1,
  133955. 19,
  133956. 0,
  133957. 20,
  133958. };
  133959. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133960. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133961. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133962. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133963. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133964. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133965. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133966. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133967. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133968. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133969. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133970. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133971. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133972. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133973. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133974. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133975. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133976. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133977. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133978. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133979. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133980. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133981. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133982. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133983. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133984. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133985. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133986. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133987. 10,10,10,10,10,10,10,10,10,
  133988. };
  133989. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133990. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133991. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133992. 6.5, 7.5, 8.5, 9.5,
  133993. };
  133994. static long _vq_quantmap__44c7_s_p8_1[] = {
  133995. 19, 17, 15, 13, 11, 9, 7, 5,
  133996. 3, 1, 0, 2, 4, 6, 8, 10,
  133997. 12, 14, 16, 18, 20,
  133998. };
  133999. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  134000. _vq_quantthresh__44c7_s_p8_1,
  134001. _vq_quantmap__44c7_s_p8_1,
  134002. 21,
  134003. 21
  134004. };
  134005. static static_codebook _44c7_s_p8_1 = {
  134006. 2, 441,
  134007. _vq_lengthlist__44c7_s_p8_1,
  134008. 1, -529268736, 1611661312, 5, 0,
  134009. _vq_quantlist__44c7_s_p8_1,
  134010. NULL,
  134011. &_vq_auxt__44c7_s_p8_1,
  134012. NULL,
  134013. 0
  134014. };
  134015. static long _vq_quantlist__44c7_s_p9_0[] = {
  134016. 6,
  134017. 5,
  134018. 7,
  134019. 4,
  134020. 8,
  134021. 3,
  134022. 9,
  134023. 2,
  134024. 10,
  134025. 1,
  134026. 11,
  134027. 0,
  134028. 12,
  134029. };
  134030. static long _vq_lengthlist__44c7_s_p9_0[] = {
  134031. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  134032. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  134033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134035. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134037. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134038. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134041. 11,11,11,11,11,11,11,11,11,
  134042. };
  134043. static float _vq_quantthresh__44c7_s_p9_0[] = {
  134044. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  134045. 1592.5, 2229.5, 2866.5, 3503.5,
  134046. };
  134047. static long _vq_quantmap__44c7_s_p9_0[] = {
  134048. 11, 9, 7, 5, 3, 1, 0, 2,
  134049. 4, 6, 8, 10, 12,
  134050. };
  134051. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  134052. _vq_quantthresh__44c7_s_p9_0,
  134053. _vq_quantmap__44c7_s_p9_0,
  134054. 13,
  134055. 13
  134056. };
  134057. static static_codebook _44c7_s_p9_0 = {
  134058. 2, 169,
  134059. _vq_lengthlist__44c7_s_p9_0,
  134060. 1, -511845376, 1630791680, 4, 0,
  134061. _vq_quantlist__44c7_s_p9_0,
  134062. NULL,
  134063. &_vq_auxt__44c7_s_p9_0,
  134064. NULL,
  134065. 0
  134066. };
  134067. static long _vq_quantlist__44c7_s_p9_1[] = {
  134068. 6,
  134069. 5,
  134070. 7,
  134071. 4,
  134072. 8,
  134073. 3,
  134074. 9,
  134075. 2,
  134076. 10,
  134077. 1,
  134078. 11,
  134079. 0,
  134080. 12,
  134081. };
  134082. static long _vq_lengthlist__44c7_s_p9_1[] = {
  134083. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  134084. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  134085. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  134086. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  134087. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  134088. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  134089. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  134090. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  134091. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  134092. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  134093. 15,11,11,10,10,12,12,12,12,
  134094. };
  134095. static float _vq_quantthresh__44c7_s_p9_1[] = {
  134096. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  134097. 122.5, 171.5, 220.5, 269.5,
  134098. };
  134099. static long _vq_quantmap__44c7_s_p9_1[] = {
  134100. 11, 9, 7, 5, 3, 1, 0, 2,
  134101. 4, 6, 8, 10, 12,
  134102. };
  134103. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  134104. _vq_quantthresh__44c7_s_p9_1,
  134105. _vq_quantmap__44c7_s_p9_1,
  134106. 13,
  134107. 13
  134108. };
  134109. static static_codebook _44c7_s_p9_1 = {
  134110. 2, 169,
  134111. _vq_lengthlist__44c7_s_p9_1,
  134112. 1, -518889472, 1622704128, 4, 0,
  134113. _vq_quantlist__44c7_s_p9_1,
  134114. NULL,
  134115. &_vq_auxt__44c7_s_p9_1,
  134116. NULL,
  134117. 0
  134118. };
  134119. static long _vq_quantlist__44c7_s_p9_2[] = {
  134120. 24,
  134121. 23,
  134122. 25,
  134123. 22,
  134124. 26,
  134125. 21,
  134126. 27,
  134127. 20,
  134128. 28,
  134129. 19,
  134130. 29,
  134131. 18,
  134132. 30,
  134133. 17,
  134134. 31,
  134135. 16,
  134136. 32,
  134137. 15,
  134138. 33,
  134139. 14,
  134140. 34,
  134141. 13,
  134142. 35,
  134143. 12,
  134144. 36,
  134145. 11,
  134146. 37,
  134147. 10,
  134148. 38,
  134149. 9,
  134150. 39,
  134151. 8,
  134152. 40,
  134153. 7,
  134154. 41,
  134155. 6,
  134156. 42,
  134157. 5,
  134158. 43,
  134159. 4,
  134160. 44,
  134161. 3,
  134162. 45,
  134163. 2,
  134164. 46,
  134165. 1,
  134166. 47,
  134167. 0,
  134168. 48,
  134169. };
  134170. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134171. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134172. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134173. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134174. 7,
  134175. };
  134176. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134177. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134178. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134179. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134180. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134181. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134182. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134183. };
  134184. static long _vq_quantmap__44c7_s_p9_2[] = {
  134185. 47, 45, 43, 41, 39, 37, 35, 33,
  134186. 31, 29, 27, 25, 23, 21, 19, 17,
  134187. 15, 13, 11, 9, 7, 5, 3, 1,
  134188. 0, 2, 4, 6, 8, 10, 12, 14,
  134189. 16, 18, 20, 22, 24, 26, 28, 30,
  134190. 32, 34, 36, 38, 40, 42, 44, 46,
  134191. 48,
  134192. };
  134193. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134194. _vq_quantthresh__44c7_s_p9_2,
  134195. _vq_quantmap__44c7_s_p9_2,
  134196. 49,
  134197. 49
  134198. };
  134199. static static_codebook _44c7_s_p9_2 = {
  134200. 1, 49,
  134201. _vq_lengthlist__44c7_s_p9_2,
  134202. 1, -526909440, 1611661312, 6, 0,
  134203. _vq_quantlist__44c7_s_p9_2,
  134204. NULL,
  134205. &_vq_auxt__44c7_s_p9_2,
  134206. NULL,
  134207. 0
  134208. };
  134209. static long _huff_lengthlist__44c7_s_short[] = {
  134210. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134211. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134212. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134213. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134214. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134215. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134216. 10, 9,11,14,
  134217. };
  134218. static static_codebook _huff_book__44c7_s_short = {
  134219. 2, 100,
  134220. _huff_lengthlist__44c7_s_short,
  134221. 0, 0, 0, 0, 0,
  134222. NULL,
  134223. NULL,
  134224. NULL,
  134225. NULL,
  134226. 0
  134227. };
  134228. static long _huff_lengthlist__44c8_s_long[] = {
  134229. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134230. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134231. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134232. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134233. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134234. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134235. 11, 9, 9,10,
  134236. };
  134237. static static_codebook _huff_book__44c8_s_long = {
  134238. 2, 100,
  134239. _huff_lengthlist__44c8_s_long,
  134240. 0, 0, 0, 0, 0,
  134241. NULL,
  134242. NULL,
  134243. NULL,
  134244. NULL,
  134245. 0
  134246. };
  134247. static long _vq_quantlist__44c8_s_p1_0[] = {
  134248. 1,
  134249. 0,
  134250. 2,
  134251. };
  134252. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134253. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134254. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134255. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134256. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134257. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134258. 8,
  134259. };
  134260. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134261. -0.5, 0.5,
  134262. };
  134263. static long _vq_quantmap__44c8_s_p1_0[] = {
  134264. 1, 0, 2,
  134265. };
  134266. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134267. _vq_quantthresh__44c8_s_p1_0,
  134268. _vq_quantmap__44c8_s_p1_0,
  134269. 3,
  134270. 3
  134271. };
  134272. static static_codebook _44c8_s_p1_0 = {
  134273. 4, 81,
  134274. _vq_lengthlist__44c8_s_p1_0,
  134275. 1, -535822336, 1611661312, 2, 0,
  134276. _vq_quantlist__44c8_s_p1_0,
  134277. NULL,
  134278. &_vq_auxt__44c8_s_p1_0,
  134279. NULL,
  134280. 0
  134281. };
  134282. static long _vq_quantlist__44c8_s_p2_0[] = {
  134283. 2,
  134284. 1,
  134285. 3,
  134286. 0,
  134287. 4,
  134288. };
  134289. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134290. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134291. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134292. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134293. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134294. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134295. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134296. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134297. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134299. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134300. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134301. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134302. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134303. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134304. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134305. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134307. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134308. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134309. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134310. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134311. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134312. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134313. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134315. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134316. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134317. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134318. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134319. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134320. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134321. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134326. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134327. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134328. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134329. 13,
  134330. };
  134331. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134332. -1.5, -0.5, 0.5, 1.5,
  134333. };
  134334. static long _vq_quantmap__44c8_s_p2_0[] = {
  134335. 3, 1, 0, 2, 4,
  134336. };
  134337. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134338. _vq_quantthresh__44c8_s_p2_0,
  134339. _vq_quantmap__44c8_s_p2_0,
  134340. 5,
  134341. 5
  134342. };
  134343. static static_codebook _44c8_s_p2_0 = {
  134344. 4, 625,
  134345. _vq_lengthlist__44c8_s_p2_0,
  134346. 1, -533725184, 1611661312, 3, 0,
  134347. _vq_quantlist__44c8_s_p2_0,
  134348. NULL,
  134349. &_vq_auxt__44c8_s_p2_0,
  134350. NULL,
  134351. 0
  134352. };
  134353. static long _vq_quantlist__44c8_s_p3_0[] = {
  134354. 4,
  134355. 3,
  134356. 5,
  134357. 2,
  134358. 6,
  134359. 1,
  134360. 7,
  134361. 0,
  134362. 8,
  134363. };
  134364. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134365. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134366. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134367. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134368. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134370. 0,
  134371. };
  134372. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134373. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134374. };
  134375. static long _vq_quantmap__44c8_s_p3_0[] = {
  134376. 7, 5, 3, 1, 0, 2, 4, 6,
  134377. 8,
  134378. };
  134379. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134380. _vq_quantthresh__44c8_s_p3_0,
  134381. _vq_quantmap__44c8_s_p3_0,
  134382. 9,
  134383. 9
  134384. };
  134385. static static_codebook _44c8_s_p3_0 = {
  134386. 2, 81,
  134387. _vq_lengthlist__44c8_s_p3_0,
  134388. 1, -531628032, 1611661312, 4, 0,
  134389. _vq_quantlist__44c8_s_p3_0,
  134390. NULL,
  134391. &_vq_auxt__44c8_s_p3_0,
  134392. NULL,
  134393. 0
  134394. };
  134395. static long _vq_quantlist__44c8_s_p4_0[] = {
  134396. 8,
  134397. 7,
  134398. 9,
  134399. 6,
  134400. 10,
  134401. 5,
  134402. 11,
  134403. 4,
  134404. 12,
  134405. 3,
  134406. 13,
  134407. 2,
  134408. 14,
  134409. 1,
  134410. 15,
  134411. 0,
  134412. 16,
  134413. };
  134414. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134415. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134416. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134417. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134418. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134419. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134420. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134421. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134422. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134423. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134424. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134433. 0,
  134434. };
  134435. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134436. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134437. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134438. };
  134439. static long _vq_quantmap__44c8_s_p4_0[] = {
  134440. 15, 13, 11, 9, 7, 5, 3, 1,
  134441. 0, 2, 4, 6, 8, 10, 12, 14,
  134442. 16,
  134443. };
  134444. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134445. _vq_quantthresh__44c8_s_p4_0,
  134446. _vq_quantmap__44c8_s_p4_0,
  134447. 17,
  134448. 17
  134449. };
  134450. static static_codebook _44c8_s_p4_0 = {
  134451. 2, 289,
  134452. _vq_lengthlist__44c8_s_p4_0,
  134453. 1, -529530880, 1611661312, 5, 0,
  134454. _vq_quantlist__44c8_s_p4_0,
  134455. NULL,
  134456. &_vq_auxt__44c8_s_p4_0,
  134457. NULL,
  134458. 0
  134459. };
  134460. static long _vq_quantlist__44c8_s_p5_0[] = {
  134461. 1,
  134462. 0,
  134463. 2,
  134464. };
  134465. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134466. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134467. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134468. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134469. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134470. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134471. 12,
  134472. };
  134473. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134474. -5.5, 5.5,
  134475. };
  134476. static long _vq_quantmap__44c8_s_p5_0[] = {
  134477. 1, 0, 2,
  134478. };
  134479. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134480. _vq_quantthresh__44c8_s_p5_0,
  134481. _vq_quantmap__44c8_s_p5_0,
  134482. 3,
  134483. 3
  134484. };
  134485. static static_codebook _44c8_s_p5_0 = {
  134486. 4, 81,
  134487. _vq_lengthlist__44c8_s_p5_0,
  134488. 1, -529137664, 1618345984, 2, 0,
  134489. _vq_quantlist__44c8_s_p5_0,
  134490. NULL,
  134491. &_vq_auxt__44c8_s_p5_0,
  134492. NULL,
  134493. 0
  134494. };
  134495. static long _vq_quantlist__44c8_s_p5_1[] = {
  134496. 5,
  134497. 4,
  134498. 6,
  134499. 3,
  134500. 7,
  134501. 2,
  134502. 8,
  134503. 1,
  134504. 9,
  134505. 0,
  134506. 10,
  134507. };
  134508. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134509. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134510. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134511. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134512. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134513. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134514. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134515. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134516. 11,11,11, 7, 7, 7, 7, 8, 8,
  134517. };
  134518. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134519. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134520. 3.5, 4.5,
  134521. };
  134522. static long _vq_quantmap__44c8_s_p5_1[] = {
  134523. 9, 7, 5, 3, 1, 0, 2, 4,
  134524. 6, 8, 10,
  134525. };
  134526. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134527. _vq_quantthresh__44c8_s_p5_1,
  134528. _vq_quantmap__44c8_s_p5_1,
  134529. 11,
  134530. 11
  134531. };
  134532. static static_codebook _44c8_s_p5_1 = {
  134533. 2, 121,
  134534. _vq_lengthlist__44c8_s_p5_1,
  134535. 1, -531365888, 1611661312, 4, 0,
  134536. _vq_quantlist__44c8_s_p5_1,
  134537. NULL,
  134538. &_vq_auxt__44c8_s_p5_1,
  134539. NULL,
  134540. 0
  134541. };
  134542. static long _vq_quantlist__44c8_s_p6_0[] = {
  134543. 6,
  134544. 5,
  134545. 7,
  134546. 4,
  134547. 8,
  134548. 3,
  134549. 9,
  134550. 2,
  134551. 10,
  134552. 1,
  134553. 11,
  134554. 0,
  134555. 12,
  134556. };
  134557. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134558. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134559. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134560. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134561. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134562. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134563. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134568. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134569. };
  134570. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134571. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134572. 12.5, 17.5, 22.5, 27.5,
  134573. };
  134574. static long _vq_quantmap__44c8_s_p6_0[] = {
  134575. 11, 9, 7, 5, 3, 1, 0, 2,
  134576. 4, 6, 8, 10, 12,
  134577. };
  134578. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134579. _vq_quantthresh__44c8_s_p6_0,
  134580. _vq_quantmap__44c8_s_p6_0,
  134581. 13,
  134582. 13
  134583. };
  134584. static static_codebook _44c8_s_p6_0 = {
  134585. 2, 169,
  134586. _vq_lengthlist__44c8_s_p6_0,
  134587. 1, -526516224, 1616117760, 4, 0,
  134588. _vq_quantlist__44c8_s_p6_0,
  134589. NULL,
  134590. &_vq_auxt__44c8_s_p6_0,
  134591. NULL,
  134592. 0
  134593. };
  134594. static long _vq_quantlist__44c8_s_p6_1[] = {
  134595. 2,
  134596. 1,
  134597. 3,
  134598. 0,
  134599. 4,
  134600. };
  134601. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134602. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134603. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134604. };
  134605. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134606. -1.5, -0.5, 0.5, 1.5,
  134607. };
  134608. static long _vq_quantmap__44c8_s_p6_1[] = {
  134609. 3, 1, 0, 2, 4,
  134610. };
  134611. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134612. _vq_quantthresh__44c8_s_p6_1,
  134613. _vq_quantmap__44c8_s_p6_1,
  134614. 5,
  134615. 5
  134616. };
  134617. static static_codebook _44c8_s_p6_1 = {
  134618. 2, 25,
  134619. _vq_lengthlist__44c8_s_p6_1,
  134620. 1, -533725184, 1611661312, 3, 0,
  134621. _vq_quantlist__44c8_s_p6_1,
  134622. NULL,
  134623. &_vq_auxt__44c8_s_p6_1,
  134624. NULL,
  134625. 0
  134626. };
  134627. static long _vq_quantlist__44c8_s_p7_0[] = {
  134628. 6,
  134629. 5,
  134630. 7,
  134631. 4,
  134632. 8,
  134633. 3,
  134634. 9,
  134635. 2,
  134636. 10,
  134637. 1,
  134638. 11,
  134639. 0,
  134640. 12,
  134641. };
  134642. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134643. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134644. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134645. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134646. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134647. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134648. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134649. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134650. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134651. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134652. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134653. 20,13,13,13,13,14,13,15,15,
  134654. };
  134655. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134656. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134657. 27.5, 38.5, 49.5, 60.5,
  134658. };
  134659. static long _vq_quantmap__44c8_s_p7_0[] = {
  134660. 11, 9, 7, 5, 3, 1, 0, 2,
  134661. 4, 6, 8, 10, 12,
  134662. };
  134663. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134664. _vq_quantthresh__44c8_s_p7_0,
  134665. _vq_quantmap__44c8_s_p7_0,
  134666. 13,
  134667. 13
  134668. };
  134669. static static_codebook _44c8_s_p7_0 = {
  134670. 2, 169,
  134671. _vq_lengthlist__44c8_s_p7_0,
  134672. 1, -523206656, 1618345984, 4, 0,
  134673. _vq_quantlist__44c8_s_p7_0,
  134674. NULL,
  134675. &_vq_auxt__44c8_s_p7_0,
  134676. NULL,
  134677. 0
  134678. };
  134679. static long _vq_quantlist__44c8_s_p7_1[] = {
  134680. 5,
  134681. 4,
  134682. 6,
  134683. 3,
  134684. 7,
  134685. 2,
  134686. 8,
  134687. 1,
  134688. 9,
  134689. 0,
  134690. 10,
  134691. };
  134692. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134693. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134694. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134695. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134696. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134697. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134698. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134699. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134700. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134701. };
  134702. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134703. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134704. 3.5, 4.5,
  134705. };
  134706. static long _vq_quantmap__44c8_s_p7_1[] = {
  134707. 9, 7, 5, 3, 1, 0, 2, 4,
  134708. 6, 8, 10,
  134709. };
  134710. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134711. _vq_quantthresh__44c8_s_p7_1,
  134712. _vq_quantmap__44c8_s_p7_1,
  134713. 11,
  134714. 11
  134715. };
  134716. static static_codebook _44c8_s_p7_1 = {
  134717. 2, 121,
  134718. _vq_lengthlist__44c8_s_p7_1,
  134719. 1, -531365888, 1611661312, 4, 0,
  134720. _vq_quantlist__44c8_s_p7_1,
  134721. NULL,
  134722. &_vq_auxt__44c8_s_p7_1,
  134723. NULL,
  134724. 0
  134725. };
  134726. static long _vq_quantlist__44c8_s_p8_0[] = {
  134727. 7,
  134728. 6,
  134729. 8,
  134730. 5,
  134731. 9,
  134732. 4,
  134733. 10,
  134734. 3,
  134735. 11,
  134736. 2,
  134737. 12,
  134738. 1,
  134739. 13,
  134740. 0,
  134741. 14,
  134742. };
  134743. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134744. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134745. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134746. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134747. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134748. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134749. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134750. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134751. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134752. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134753. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134754. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134755. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134756. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134757. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134758. 15,
  134759. };
  134760. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134761. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134762. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134763. };
  134764. static long _vq_quantmap__44c8_s_p8_0[] = {
  134765. 13, 11, 9, 7, 5, 3, 1, 0,
  134766. 2, 4, 6, 8, 10, 12, 14,
  134767. };
  134768. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134769. _vq_quantthresh__44c8_s_p8_0,
  134770. _vq_quantmap__44c8_s_p8_0,
  134771. 15,
  134772. 15
  134773. };
  134774. static static_codebook _44c8_s_p8_0 = {
  134775. 2, 225,
  134776. _vq_lengthlist__44c8_s_p8_0,
  134777. 1, -520986624, 1620377600, 4, 0,
  134778. _vq_quantlist__44c8_s_p8_0,
  134779. NULL,
  134780. &_vq_auxt__44c8_s_p8_0,
  134781. NULL,
  134782. 0
  134783. };
  134784. static long _vq_quantlist__44c8_s_p8_1[] = {
  134785. 10,
  134786. 9,
  134787. 11,
  134788. 8,
  134789. 12,
  134790. 7,
  134791. 13,
  134792. 6,
  134793. 14,
  134794. 5,
  134795. 15,
  134796. 4,
  134797. 16,
  134798. 3,
  134799. 17,
  134800. 2,
  134801. 18,
  134802. 1,
  134803. 19,
  134804. 0,
  134805. 20,
  134806. };
  134807. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134808. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134809. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134810. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134811. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134812. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134813. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134814. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134815. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134816. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134817. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134818. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134819. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134820. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134821. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134822. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134823. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134824. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134825. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134826. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134827. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134828. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134829. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134830. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134831. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134832. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134833. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134834. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134835. 10, 9, 9,10,10, 9,10, 9, 9,
  134836. };
  134837. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134838. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134839. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134840. 6.5, 7.5, 8.5, 9.5,
  134841. };
  134842. static long _vq_quantmap__44c8_s_p8_1[] = {
  134843. 19, 17, 15, 13, 11, 9, 7, 5,
  134844. 3, 1, 0, 2, 4, 6, 8, 10,
  134845. 12, 14, 16, 18, 20,
  134846. };
  134847. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134848. _vq_quantthresh__44c8_s_p8_1,
  134849. _vq_quantmap__44c8_s_p8_1,
  134850. 21,
  134851. 21
  134852. };
  134853. static static_codebook _44c8_s_p8_1 = {
  134854. 2, 441,
  134855. _vq_lengthlist__44c8_s_p8_1,
  134856. 1, -529268736, 1611661312, 5, 0,
  134857. _vq_quantlist__44c8_s_p8_1,
  134858. NULL,
  134859. &_vq_auxt__44c8_s_p8_1,
  134860. NULL,
  134861. 0
  134862. };
  134863. static long _vq_quantlist__44c8_s_p9_0[] = {
  134864. 8,
  134865. 7,
  134866. 9,
  134867. 6,
  134868. 10,
  134869. 5,
  134870. 11,
  134871. 4,
  134872. 12,
  134873. 3,
  134874. 13,
  134875. 2,
  134876. 14,
  134877. 1,
  134878. 15,
  134879. 0,
  134880. 16,
  134881. };
  134882. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134883. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134884. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134885. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134890. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134892. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134893. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134896. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134897. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134898. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134899. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134900. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134901. 10,
  134902. };
  134903. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134904. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134905. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134906. };
  134907. static long _vq_quantmap__44c8_s_p9_0[] = {
  134908. 15, 13, 11, 9, 7, 5, 3, 1,
  134909. 0, 2, 4, 6, 8, 10, 12, 14,
  134910. 16,
  134911. };
  134912. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134913. _vq_quantthresh__44c8_s_p9_0,
  134914. _vq_quantmap__44c8_s_p9_0,
  134915. 17,
  134916. 17
  134917. };
  134918. static static_codebook _44c8_s_p9_0 = {
  134919. 2, 289,
  134920. _vq_lengthlist__44c8_s_p9_0,
  134921. 1, -509798400, 1631393792, 5, 0,
  134922. _vq_quantlist__44c8_s_p9_0,
  134923. NULL,
  134924. &_vq_auxt__44c8_s_p9_0,
  134925. NULL,
  134926. 0
  134927. };
  134928. static long _vq_quantlist__44c8_s_p9_1[] = {
  134929. 9,
  134930. 8,
  134931. 10,
  134932. 7,
  134933. 11,
  134934. 6,
  134935. 12,
  134936. 5,
  134937. 13,
  134938. 4,
  134939. 14,
  134940. 3,
  134941. 15,
  134942. 2,
  134943. 16,
  134944. 1,
  134945. 17,
  134946. 0,
  134947. 18,
  134948. };
  134949. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134950. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134951. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134952. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134953. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134954. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134955. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134956. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134957. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134958. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134959. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134960. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134961. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134962. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134963. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134964. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134965. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134966. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134967. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134968. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134969. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134970. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134971. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134972. 14,13,13,14,14,15,14,15,14,
  134973. };
  134974. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134975. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134976. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134977. 367.5, 416.5,
  134978. };
  134979. static long _vq_quantmap__44c8_s_p9_1[] = {
  134980. 17, 15, 13, 11, 9, 7, 5, 3,
  134981. 1, 0, 2, 4, 6, 8, 10, 12,
  134982. 14, 16, 18,
  134983. };
  134984. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134985. _vq_quantthresh__44c8_s_p9_1,
  134986. _vq_quantmap__44c8_s_p9_1,
  134987. 19,
  134988. 19
  134989. };
  134990. static static_codebook _44c8_s_p9_1 = {
  134991. 2, 361,
  134992. _vq_lengthlist__44c8_s_p9_1,
  134993. 1, -518287360, 1622704128, 5, 0,
  134994. _vq_quantlist__44c8_s_p9_1,
  134995. NULL,
  134996. &_vq_auxt__44c8_s_p9_1,
  134997. NULL,
  134998. 0
  134999. };
  135000. static long _vq_quantlist__44c8_s_p9_2[] = {
  135001. 24,
  135002. 23,
  135003. 25,
  135004. 22,
  135005. 26,
  135006. 21,
  135007. 27,
  135008. 20,
  135009. 28,
  135010. 19,
  135011. 29,
  135012. 18,
  135013. 30,
  135014. 17,
  135015. 31,
  135016. 16,
  135017. 32,
  135018. 15,
  135019. 33,
  135020. 14,
  135021. 34,
  135022. 13,
  135023. 35,
  135024. 12,
  135025. 36,
  135026. 11,
  135027. 37,
  135028. 10,
  135029. 38,
  135030. 9,
  135031. 39,
  135032. 8,
  135033. 40,
  135034. 7,
  135035. 41,
  135036. 6,
  135037. 42,
  135038. 5,
  135039. 43,
  135040. 4,
  135041. 44,
  135042. 3,
  135043. 45,
  135044. 2,
  135045. 46,
  135046. 1,
  135047. 47,
  135048. 0,
  135049. 48,
  135050. };
  135051. static long _vq_lengthlist__44c8_s_p9_2[] = {
  135052. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135053. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135054. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135055. 7,
  135056. };
  135057. static float _vq_quantthresh__44c8_s_p9_2[] = {
  135058. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135059. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135060. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135061. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135062. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135063. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135064. };
  135065. static long _vq_quantmap__44c8_s_p9_2[] = {
  135066. 47, 45, 43, 41, 39, 37, 35, 33,
  135067. 31, 29, 27, 25, 23, 21, 19, 17,
  135068. 15, 13, 11, 9, 7, 5, 3, 1,
  135069. 0, 2, 4, 6, 8, 10, 12, 14,
  135070. 16, 18, 20, 22, 24, 26, 28, 30,
  135071. 32, 34, 36, 38, 40, 42, 44, 46,
  135072. 48,
  135073. };
  135074. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  135075. _vq_quantthresh__44c8_s_p9_2,
  135076. _vq_quantmap__44c8_s_p9_2,
  135077. 49,
  135078. 49
  135079. };
  135080. static static_codebook _44c8_s_p9_2 = {
  135081. 1, 49,
  135082. _vq_lengthlist__44c8_s_p9_2,
  135083. 1, -526909440, 1611661312, 6, 0,
  135084. _vq_quantlist__44c8_s_p9_2,
  135085. NULL,
  135086. &_vq_auxt__44c8_s_p9_2,
  135087. NULL,
  135088. 0
  135089. };
  135090. static long _huff_lengthlist__44c8_s_short[] = {
  135091. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  135092. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  135093. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  135094. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  135095. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  135096. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  135097. 10, 9,11,14,
  135098. };
  135099. static static_codebook _huff_book__44c8_s_short = {
  135100. 2, 100,
  135101. _huff_lengthlist__44c8_s_short,
  135102. 0, 0, 0, 0, 0,
  135103. NULL,
  135104. NULL,
  135105. NULL,
  135106. NULL,
  135107. 0
  135108. };
  135109. static long _huff_lengthlist__44c9_s_long[] = {
  135110. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135111. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135112. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135113. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135114. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135115. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135116. 10, 9, 8, 9,
  135117. };
  135118. static static_codebook _huff_book__44c9_s_long = {
  135119. 2, 100,
  135120. _huff_lengthlist__44c9_s_long,
  135121. 0, 0, 0, 0, 0,
  135122. NULL,
  135123. NULL,
  135124. NULL,
  135125. NULL,
  135126. 0
  135127. };
  135128. static long _vq_quantlist__44c9_s_p1_0[] = {
  135129. 1,
  135130. 0,
  135131. 2,
  135132. };
  135133. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135134. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135135. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135136. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135137. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135138. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135139. 7,
  135140. };
  135141. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135142. -0.5, 0.5,
  135143. };
  135144. static long _vq_quantmap__44c9_s_p1_0[] = {
  135145. 1, 0, 2,
  135146. };
  135147. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135148. _vq_quantthresh__44c9_s_p1_0,
  135149. _vq_quantmap__44c9_s_p1_0,
  135150. 3,
  135151. 3
  135152. };
  135153. static static_codebook _44c9_s_p1_0 = {
  135154. 4, 81,
  135155. _vq_lengthlist__44c9_s_p1_0,
  135156. 1, -535822336, 1611661312, 2, 0,
  135157. _vq_quantlist__44c9_s_p1_0,
  135158. NULL,
  135159. &_vq_auxt__44c9_s_p1_0,
  135160. NULL,
  135161. 0
  135162. };
  135163. static long _vq_quantlist__44c9_s_p2_0[] = {
  135164. 2,
  135165. 1,
  135166. 3,
  135167. 0,
  135168. 4,
  135169. };
  135170. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135171. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135172. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135173. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135174. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135175. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135176. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135177. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135178. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  135179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135180. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135181. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135182. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135183. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135184. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135185. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135186. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135188. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135189. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135190. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135191. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135192. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135193. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135194. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135196. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135197. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135198. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135199. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135200. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135201. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135202. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135207. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135208. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135209. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135210. 12,
  135211. };
  135212. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135213. -1.5, -0.5, 0.5, 1.5,
  135214. };
  135215. static long _vq_quantmap__44c9_s_p2_0[] = {
  135216. 3, 1, 0, 2, 4,
  135217. };
  135218. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135219. _vq_quantthresh__44c9_s_p2_0,
  135220. _vq_quantmap__44c9_s_p2_0,
  135221. 5,
  135222. 5
  135223. };
  135224. static static_codebook _44c9_s_p2_0 = {
  135225. 4, 625,
  135226. _vq_lengthlist__44c9_s_p2_0,
  135227. 1, -533725184, 1611661312, 3, 0,
  135228. _vq_quantlist__44c9_s_p2_0,
  135229. NULL,
  135230. &_vq_auxt__44c9_s_p2_0,
  135231. NULL,
  135232. 0
  135233. };
  135234. static long _vq_quantlist__44c9_s_p3_0[] = {
  135235. 4,
  135236. 3,
  135237. 5,
  135238. 2,
  135239. 6,
  135240. 1,
  135241. 7,
  135242. 0,
  135243. 8,
  135244. };
  135245. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135246. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135247. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135248. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135249. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135251. 0,
  135252. };
  135253. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135254. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135255. };
  135256. static long _vq_quantmap__44c9_s_p3_0[] = {
  135257. 7, 5, 3, 1, 0, 2, 4, 6,
  135258. 8,
  135259. };
  135260. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135261. _vq_quantthresh__44c9_s_p3_0,
  135262. _vq_quantmap__44c9_s_p3_0,
  135263. 9,
  135264. 9
  135265. };
  135266. static static_codebook _44c9_s_p3_0 = {
  135267. 2, 81,
  135268. _vq_lengthlist__44c9_s_p3_0,
  135269. 1, -531628032, 1611661312, 4, 0,
  135270. _vq_quantlist__44c9_s_p3_0,
  135271. NULL,
  135272. &_vq_auxt__44c9_s_p3_0,
  135273. NULL,
  135274. 0
  135275. };
  135276. static long _vq_quantlist__44c9_s_p4_0[] = {
  135277. 8,
  135278. 7,
  135279. 9,
  135280. 6,
  135281. 10,
  135282. 5,
  135283. 11,
  135284. 4,
  135285. 12,
  135286. 3,
  135287. 13,
  135288. 2,
  135289. 14,
  135290. 1,
  135291. 15,
  135292. 0,
  135293. 16,
  135294. };
  135295. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135296. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135297. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135298. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135299. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135300. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135301. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135302. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135303. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135304. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135305. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0,
  135315. };
  135316. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135317. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135318. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135319. };
  135320. static long _vq_quantmap__44c9_s_p4_0[] = {
  135321. 15, 13, 11, 9, 7, 5, 3, 1,
  135322. 0, 2, 4, 6, 8, 10, 12, 14,
  135323. 16,
  135324. };
  135325. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135326. _vq_quantthresh__44c9_s_p4_0,
  135327. _vq_quantmap__44c9_s_p4_0,
  135328. 17,
  135329. 17
  135330. };
  135331. static static_codebook _44c9_s_p4_0 = {
  135332. 2, 289,
  135333. _vq_lengthlist__44c9_s_p4_0,
  135334. 1, -529530880, 1611661312, 5, 0,
  135335. _vq_quantlist__44c9_s_p4_0,
  135336. NULL,
  135337. &_vq_auxt__44c9_s_p4_0,
  135338. NULL,
  135339. 0
  135340. };
  135341. static long _vq_quantlist__44c9_s_p5_0[] = {
  135342. 1,
  135343. 0,
  135344. 2,
  135345. };
  135346. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135347. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135348. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135349. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135350. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135351. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135352. 12,
  135353. };
  135354. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135355. -5.5, 5.5,
  135356. };
  135357. static long _vq_quantmap__44c9_s_p5_0[] = {
  135358. 1, 0, 2,
  135359. };
  135360. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135361. _vq_quantthresh__44c9_s_p5_0,
  135362. _vq_quantmap__44c9_s_p5_0,
  135363. 3,
  135364. 3
  135365. };
  135366. static static_codebook _44c9_s_p5_0 = {
  135367. 4, 81,
  135368. _vq_lengthlist__44c9_s_p5_0,
  135369. 1, -529137664, 1618345984, 2, 0,
  135370. _vq_quantlist__44c9_s_p5_0,
  135371. NULL,
  135372. &_vq_auxt__44c9_s_p5_0,
  135373. NULL,
  135374. 0
  135375. };
  135376. static long _vq_quantlist__44c9_s_p5_1[] = {
  135377. 5,
  135378. 4,
  135379. 6,
  135380. 3,
  135381. 7,
  135382. 2,
  135383. 8,
  135384. 1,
  135385. 9,
  135386. 0,
  135387. 10,
  135388. };
  135389. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135390. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135391. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135392. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135393. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135394. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135395. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135396. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135397. 11,11,11, 7, 7, 7, 7, 7, 7,
  135398. };
  135399. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135400. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135401. 3.5, 4.5,
  135402. };
  135403. static long _vq_quantmap__44c9_s_p5_1[] = {
  135404. 9, 7, 5, 3, 1, 0, 2, 4,
  135405. 6, 8, 10,
  135406. };
  135407. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135408. _vq_quantthresh__44c9_s_p5_1,
  135409. _vq_quantmap__44c9_s_p5_1,
  135410. 11,
  135411. 11
  135412. };
  135413. static static_codebook _44c9_s_p5_1 = {
  135414. 2, 121,
  135415. _vq_lengthlist__44c9_s_p5_1,
  135416. 1, -531365888, 1611661312, 4, 0,
  135417. _vq_quantlist__44c9_s_p5_1,
  135418. NULL,
  135419. &_vq_auxt__44c9_s_p5_1,
  135420. NULL,
  135421. 0
  135422. };
  135423. static long _vq_quantlist__44c9_s_p6_0[] = {
  135424. 6,
  135425. 5,
  135426. 7,
  135427. 4,
  135428. 8,
  135429. 3,
  135430. 9,
  135431. 2,
  135432. 10,
  135433. 1,
  135434. 11,
  135435. 0,
  135436. 12,
  135437. };
  135438. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135439. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135440. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135441. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135442. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135443. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135444. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135449. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135450. };
  135451. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135452. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135453. 12.5, 17.5, 22.5, 27.5,
  135454. };
  135455. static long _vq_quantmap__44c9_s_p6_0[] = {
  135456. 11, 9, 7, 5, 3, 1, 0, 2,
  135457. 4, 6, 8, 10, 12,
  135458. };
  135459. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135460. _vq_quantthresh__44c9_s_p6_0,
  135461. _vq_quantmap__44c9_s_p6_0,
  135462. 13,
  135463. 13
  135464. };
  135465. static static_codebook _44c9_s_p6_0 = {
  135466. 2, 169,
  135467. _vq_lengthlist__44c9_s_p6_0,
  135468. 1, -526516224, 1616117760, 4, 0,
  135469. _vq_quantlist__44c9_s_p6_0,
  135470. NULL,
  135471. &_vq_auxt__44c9_s_p6_0,
  135472. NULL,
  135473. 0
  135474. };
  135475. static long _vq_quantlist__44c9_s_p6_1[] = {
  135476. 2,
  135477. 1,
  135478. 3,
  135479. 0,
  135480. 4,
  135481. };
  135482. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135483. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135484. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135485. };
  135486. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135487. -1.5, -0.5, 0.5, 1.5,
  135488. };
  135489. static long _vq_quantmap__44c9_s_p6_1[] = {
  135490. 3, 1, 0, 2, 4,
  135491. };
  135492. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135493. _vq_quantthresh__44c9_s_p6_1,
  135494. _vq_quantmap__44c9_s_p6_1,
  135495. 5,
  135496. 5
  135497. };
  135498. static static_codebook _44c9_s_p6_1 = {
  135499. 2, 25,
  135500. _vq_lengthlist__44c9_s_p6_1,
  135501. 1, -533725184, 1611661312, 3, 0,
  135502. _vq_quantlist__44c9_s_p6_1,
  135503. NULL,
  135504. &_vq_auxt__44c9_s_p6_1,
  135505. NULL,
  135506. 0
  135507. };
  135508. static long _vq_quantlist__44c9_s_p7_0[] = {
  135509. 6,
  135510. 5,
  135511. 7,
  135512. 4,
  135513. 8,
  135514. 3,
  135515. 9,
  135516. 2,
  135517. 10,
  135518. 1,
  135519. 11,
  135520. 0,
  135521. 12,
  135522. };
  135523. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135524. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135525. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135526. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135527. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135528. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135529. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135530. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135531. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135532. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135533. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135534. 19,12,12,12,12,13,13,14,14,
  135535. };
  135536. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135537. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135538. 27.5, 38.5, 49.5, 60.5,
  135539. };
  135540. static long _vq_quantmap__44c9_s_p7_0[] = {
  135541. 11, 9, 7, 5, 3, 1, 0, 2,
  135542. 4, 6, 8, 10, 12,
  135543. };
  135544. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135545. _vq_quantthresh__44c9_s_p7_0,
  135546. _vq_quantmap__44c9_s_p7_0,
  135547. 13,
  135548. 13
  135549. };
  135550. static static_codebook _44c9_s_p7_0 = {
  135551. 2, 169,
  135552. _vq_lengthlist__44c9_s_p7_0,
  135553. 1, -523206656, 1618345984, 4, 0,
  135554. _vq_quantlist__44c9_s_p7_0,
  135555. NULL,
  135556. &_vq_auxt__44c9_s_p7_0,
  135557. NULL,
  135558. 0
  135559. };
  135560. static long _vq_quantlist__44c9_s_p7_1[] = {
  135561. 5,
  135562. 4,
  135563. 6,
  135564. 3,
  135565. 7,
  135566. 2,
  135567. 8,
  135568. 1,
  135569. 9,
  135570. 0,
  135571. 10,
  135572. };
  135573. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135574. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135575. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135576. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135577. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135578. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135579. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135580. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135581. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135582. };
  135583. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135584. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135585. 3.5, 4.5,
  135586. };
  135587. static long _vq_quantmap__44c9_s_p7_1[] = {
  135588. 9, 7, 5, 3, 1, 0, 2, 4,
  135589. 6, 8, 10,
  135590. };
  135591. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135592. _vq_quantthresh__44c9_s_p7_1,
  135593. _vq_quantmap__44c9_s_p7_1,
  135594. 11,
  135595. 11
  135596. };
  135597. static static_codebook _44c9_s_p7_1 = {
  135598. 2, 121,
  135599. _vq_lengthlist__44c9_s_p7_1,
  135600. 1, -531365888, 1611661312, 4, 0,
  135601. _vq_quantlist__44c9_s_p7_1,
  135602. NULL,
  135603. &_vq_auxt__44c9_s_p7_1,
  135604. NULL,
  135605. 0
  135606. };
  135607. static long _vq_quantlist__44c9_s_p8_0[] = {
  135608. 7,
  135609. 6,
  135610. 8,
  135611. 5,
  135612. 9,
  135613. 4,
  135614. 10,
  135615. 3,
  135616. 11,
  135617. 2,
  135618. 12,
  135619. 1,
  135620. 13,
  135621. 0,
  135622. 14,
  135623. };
  135624. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135625. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135626. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135627. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135628. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135629. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135630. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135631. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135632. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135633. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135634. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135635. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135636. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135637. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135638. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135639. 14,
  135640. };
  135641. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135642. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135643. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135644. };
  135645. static long _vq_quantmap__44c9_s_p8_0[] = {
  135646. 13, 11, 9, 7, 5, 3, 1, 0,
  135647. 2, 4, 6, 8, 10, 12, 14,
  135648. };
  135649. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135650. _vq_quantthresh__44c9_s_p8_0,
  135651. _vq_quantmap__44c9_s_p8_0,
  135652. 15,
  135653. 15
  135654. };
  135655. static static_codebook _44c9_s_p8_0 = {
  135656. 2, 225,
  135657. _vq_lengthlist__44c9_s_p8_0,
  135658. 1, -520986624, 1620377600, 4, 0,
  135659. _vq_quantlist__44c9_s_p8_0,
  135660. NULL,
  135661. &_vq_auxt__44c9_s_p8_0,
  135662. NULL,
  135663. 0
  135664. };
  135665. static long _vq_quantlist__44c9_s_p8_1[] = {
  135666. 10,
  135667. 9,
  135668. 11,
  135669. 8,
  135670. 12,
  135671. 7,
  135672. 13,
  135673. 6,
  135674. 14,
  135675. 5,
  135676. 15,
  135677. 4,
  135678. 16,
  135679. 3,
  135680. 17,
  135681. 2,
  135682. 18,
  135683. 1,
  135684. 19,
  135685. 0,
  135686. 20,
  135687. };
  135688. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135689. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135690. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135691. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135692. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135693. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135694. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135695. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135696. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135697. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135698. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135699. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135700. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135701. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135702. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135703. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135704. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135705. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135706. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135707. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135708. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135709. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135710. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135711. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135712. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135713. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135714. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135715. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135716. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135717. };
  135718. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135719. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135720. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135721. 6.5, 7.5, 8.5, 9.5,
  135722. };
  135723. static long _vq_quantmap__44c9_s_p8_1[] = {
  135724. 19, 17, 15, 13, 11, 9, 7, 5,
  135725. 3, 1, 0, 2, 4, 6, 8, 10,
  135726. 12, 14, 16, 18, 20,
  135727. };
  135728. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135729. _vq_quantthresh__44c9_s_p8_1,
  135730. _vq_quantmap__44c9_s_p8_1,
  135731. 21,
  135732. 21
  135733. };
  135734. static static_codebook _44c9_s_p8_1 = {
  135735. 2, 441,
  135736. _vq_lengthlist__44c9_s_p8_1,
  135737. 1, -529268736, 1611661312, 5, 0,
  135738. _vq_quantlist__44c9_s_p8_1,
  135739. NULL,
  135740. &_vq_auxt__44c9_s_p8_1,
  135741. NULL,
  135742. 0
  135743. };
  135744. static long _vq_quantlist__44c9_s_p9_0[] = {
  135745. 9,
  135746. 8,
  135747. 10,
  135748. 7,
  135749. 11,
  135750. 6,
  135751. 12,
  135752. 5,
  135753. 13,
  135754. 4,
  135755. 14,
  135756. 3,
  135757. 15,
  135758. 2,
  135759. 16,
  135760. 1,
  135761. 17,
  135762. 0,
  135763. 18,
  135764. };
  135765. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135766. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135767. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135768. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135769. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135770. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135771. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135772. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135773. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135774. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135775. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135776. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135777. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135778. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135779. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135780. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135781. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135782. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135787. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135788. 11,11,11,11,11,11,11,11,11,
  135789. };
  135790. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135791. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135792. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135793. 6982.5, 7913.5,
  135794. };
  135795. static long _vq_quantmap__44c9_s_p9_0[] = {
  135796. 17, 15, 13, 11, 9, 7, 5, 3,
  135797. 1, 0, 2, 4, 6, 8, 10, 12,
  135798. 14, 16, 18,
  135799. };
  135800. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135801. _vq_quantthresh__44c9_s_p9_0,
  135802. _vq_quantmap__44c9_s_p9_0,
  135803. 19,
  135804. 19
  135805. };
  135806. static static_codebook _44c9_s_p9_0 = {
  135807. 2, 361,
  135808. _vq_lengthlist__44c9_s_p9_0,
  135809. 1, -508535424, 1631393792, 5, 0,
  135810. _vq_quantlist__44c9_s_p9_0,
  135811. NULL,
  135812. &_vq_auxt__44c9_s_p9_0,
  135813. NULL,
  135814. 0
  135815. };
  135816. static long _vq_quantlist__44c9_s_p9_1[] = {
  135817. 9,
  135818. 8,
  135819. 10,
  135820. 7,
  135821. 11,
  135822. 6,
  135823. 12,
  135824. 5,
  135825. 13,
  135826. 4,
  135827. 14,
  135828. 3,
  135829. 15,
  135830. 2,
  135831. 16,
  135832. 1,
  135833. 17,
  135834. 0,
  135835. 18,
  135836. };
  135837. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135838. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135839. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135840. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135841. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135842. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135843. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135844. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135845. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135846. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135847. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135848. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135849. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135850. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135851. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135852. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135853. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135854. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135855. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135856. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135857. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135858. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135859. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135860. 13,13,13,14,13,14,15,15,15,
  135861. };
  135862. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135863. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135864. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135865. 367.5, 416.5,
  135866. };
  135867. static long _vq_quantmap__44c9_s_p9_1[] = {
  135868. 17, 15, 13, 11, 9, 7, 5, 3,
  135869. 1, 0, 2, 4, 6, 8, 10, 12,
  135870. 14, 16, 18,
  135871. };
  135872. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135873. _vq_quantthresh__44c9_s_p9_1,
  135874. _vq_quantmap__44c9_s_p9_1,
  135875. 19,
  135876. 19
  135877. };
  135878. static static_codebook _44c9_s_p9_1 = {
  135879. 2, 361,
  135880. _vq_lengthlist__44c9_s_p9_1,
  135881. 1, -518287360, 1622704128, 5, 0,
  135882. _vq_quantlist__44c9_s_p9_1,
  135883. NULL,
  135884. &_vq_auxt__44c9_s_p9_1,
  135885. NULL,
  135886. 0
  135887. };
  135888. static long _vq_quantlist__44c9_s_p9_2[] = {
  135889. 24,
  135890. 23,
  135891. 25,
  135892. 22,
  135893. 26,
  135894. 21,
  135895. 27,
  135896. 20,
  135897. 28,
  135898. 19,
  135899. 29,
  135900. 18,
  135901. 30,
  135902. 17,
  135903. 31,
  135904. 16,
  135905. 32,
  135906. 15,
  135907. 33,
  135908. 14,
  135909. 34,
  135910. 13,
  135911. 35,
  135912. 12,
  135913. 36,
  135914. 11,
  135915. 37,
  135916. 10,
  135917. 38,
  135918. 9,
  135919. 39,
  135920. 8,
  135921. 40,
  135922. 7,
  135923. 41,
  135924. 6,
  135925. 42,
  135926. 5,
  135927. 43,
  135928. 4,
  135929. 44,
  135930. 3,
  135931. 45,
  135932. 2,
  135933. 46,
  135934. 1,
  135935. 47,
  135936. 0,
  135937. 48,
  135938. };
  135939. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135940. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135941. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135942. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135943. 7,
  135944. };
  135945. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135946. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135947. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135948. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135949. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135950. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135951. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135952. };
  135953. static long _vq_quantmap__44c9_s_p9_2[] = {
  135954. 47, 45, 43, 41, 39, 37, 35, 33,
  135955. 31, 29, 27, 25, 23, 21, 19, 17,
  135956. 15, 13, 11, 9, 7, 5, 3, 1,
  135957. 0, 2, 4, 6, 8, 10, 12, 14,
  135958. 16, 18, 20, 22, 24, 26, 28, 30,
  135959. 32, 34, 36, 38, 40, 42, 44, 46,
  135960. 48,
  135961. };
  135962. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135963. _vq_quantthresh__44c9_s_p9_2,
  135964. _vq_quantmap__44c9_s_p9_2,
  135965. 49,
  135966. 49
  135967. };
  135968. static static_codebook _44c9_s_p9_2 = {
  135969. 1, 49,
  135970. _vq_lengthlist__44c9_s_p9_2,
  135971. 1, -526909440, 1611661312, 6, 0,
  135972. _vq_quantlist__44c9_s_p9_2,
  135973. NULL,
  135974. &_vq_auxt__44c9_s_p9_2,
  135975. NULL,
  135976. 0
  135977. };
  135978. static long _huff_lengthlist__44c9_s_short[] = {
  135979. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135980. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135981. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135982. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135983. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135984. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135985. 9, 8,10,13,
  135986. };
  135987. static static_codebook _huff_book__44c9_s_short = {
  135988. 2, 100,
  135989. _huff_lengthlist__44c9_s_short,
  135990. 0, 0, 0, 0, 0,
  135991. NULL,
  135992. NULL,
  135993. NULL,
  135994. NULL,
  135995. 0
  135996. };
  135997. static long _huff_lengthlist__44c0_s_long[] = {
  135998. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135999. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  136000. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  136001. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  136002. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  136003. 12,
  136004. };
  136005. static static_codebook _huff_book__44c0_s_long = {
  136006. 2, 81,
  136007. _huff_lengthlist__44c0_s_long,
  136008. 0, 0, 0, 0, 0,
  136009. NULL,
  136010. NULL,
  136011. NULL,
  136012. NULL,
  136013. 0
  136014. };
  136015. static long _vq_quantlist__44c0_s_p1_0[] = {
  136016. 1,
  136017. 0,
  136018. 2,
  136019. };
  136020. static long _vq_lengthlist__44c0_s_p1_0[] = {
  136021. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136022. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136027. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136032. 0, 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0,
  136067. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136072. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  136077. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136113. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136118. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136123. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0,
  136432. };
  136433. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136434. -0.5, 0.5,
  136435. };
  136436. static long _vq_quantmap__44c0_s_p1_0[] = {
  136437. 1, 0, 2,
  136438. };
  136439. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136440. _vq_quantthresh__44c0_s_p1_0,
  136441. _vq_quantmap__44c0_s_p1_0,
  136442. 3,
  136443. 3
  136444. };
  136445. static static_codebook _44c0_s_p1_0 = {
  136446. 8, 6561,
  136447. _vq_lengthlist__44c0_s_p1_0,
  136448. 1, -535822336, 1611661312, 2, 0,
  136449. _vq_quantlist__44c0_s_p1_0,
  136450. NULL,
  136451. &_vq_auxt__44c0_s_p1_0,
  136452. NULL,
  136453. 0
  136454. };
  136455. static long _vq_quantlist__44c0_s_p2_0[] = {
  136456. 2,
  136457. 1,
  136458. 3,
  136459. 0,
  136460. 4,
  136461. };
  136462. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136463. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0,
  136503. };
  136504. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136505. -1.5, -0.5, 0.5, 1.5,
  136506. };
  136507. static long _vq_quantmap__44c0_s_p2_0[] = {
  136508. 3, 1, 0, 2, 4,
  136509. };
  136510. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136511. _vq_quantthresh__44c0_s_p2_0,
  136512. _vq_quantmap__44c0_s_p2_0,
  136513. 5,
  136514. 5
  136515. };
  136516. static static_codebook _44c0_s_p2_0 = {
  136517. 4, 625,
  136518. _vq_lengthlist__44c0_s_p2_0,
  136519. 1, -533725184, 1611661312, 3, 0,
  136520. _vq_quantlist__44c0_s_p2_0,
  136521. NULL,
  136522. &_vq_auxt__44c0_s_p2_0,
  136523. NULL,
  136524. 0
  136525. };
  136526. static long _vq_quantlist__44c0_s_p3_0[] = {
  136527. 4,
  136528. 3,
  136529. 5,
  136530. 2,
  136531. 6,
  136532. 1,
  136533. 7,
  136534. 0,
  136535. 8,
  136536. };
  136537. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136538. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136539. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136540. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136541. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136542. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136543. 0,
  136544. };
  136545. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136546. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136547. };
  136548. static long _vq_quantmap__44c0_s_p3_0[] = {
  136549. 7, 5, 3, 1, 0, 2, 4, 6,
  136550. 8,
  136551. };
  136552. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136553. _vq_quantthresh__44c0_s_p3_0,
  136554. _vq_quantmap__44c0_s_p3_0,
  136555. 9,
  136556. 9
  136557. };
  136558. static static_codebook _44c0_s_p3_0 = {
  136559. 2, 81,
  136560. _vq_lengthlist__44c0_s_p3_0,
  136561. 1, -531628032, 1611661312, 4, 0,
  136562. _vq_quantlist__44c0_s_p3_0,
  136563. NULL,
  136564. &_vq_auxt__44c0_s_p3_0,
  136565. NULL,
  136566. 0
  136567. };
  136568. static long _vq_quantlist__44c0_s_p4_0[] = {
  136569. 4,
  136570. 3,
  136571. 5,
  136572. 2,
  136573. 6,
  136574. 1,
  136575. 7,
  136576. 0,
  136577. 8,
  136578. };
  136579. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136580. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136581. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136582. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136583. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136584. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136585. 10,
  136586. };
  136587. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136588. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136589. };
  136590. static long _vq_quantmap__44c0_s_p4_0[] = {
  136591. 7, 5, 3, 1, 0, 2, 4, 6,
  136592. 8,
  136593. };
  136594. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136595. _vq_quantthresh__44c0_s_p4_0,
  136596. _vq_quantmap__44c0_s_p4_0,
  136597. 9,
  136598. 9
  136599. };
  136600. static static_codebook _44c0_s_p4_0 = {
  136601. 2, 81,
  136602. _vq_lengthlist__44c0_s_p4_0,
  136603. 1, -531628032, 1611661312, 4, 0,
  136604. _vq_quantlist__44c0_s_p4_0,
  136605. NULL,
  136606. &_vq_auxt__44c0_s_p4_0,
  136607. NULL,
  136608. 0
  136609. };
  136610. static long _vq_quantlist__44c0_s_p5_0[] = {
  136611. 8,
  136612. 7,
  136613. 9,
  136614. 6,
  136615. 10,
  136616. 5,
  136617. 11,
  136618. 4,
  136619. 12,
  136620. 3,
  136621. 13,
  136622. 2,
  136623. 14,
  136624. 1,
  136625. 15,
  136626. 0,
  136627. 16,
  136628. };
  136629. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136630. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136631. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136632. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136633. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136634. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136635. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136636. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136637. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136638. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136639. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136640. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136641. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136642. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136643. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136644. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136645. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136646. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136648. 14,
  136649. };
  136650. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136651. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136652. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136653. };
  136654. static long _vq_quantmap__44c0_s_p5_0[] = {
  136655. 15, 13, 11, 9, 7, 5, 3, 1,
  136656. 0, 2, 4, 6, 8, 10, 12, 14,
  136657. 16,
  136658. };
  136659. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136660. _vq_quantthresh__44c0_s_p5_0,
  136661. _vq_quantmap__44c0_s_p5_0,
  136662. 17,
  136663. 17
  136664. };
  136665. static static_codebook _44c0_s_p5_0 = {
  136666. 2, 289,
  136667. _vq_lengthlist__44c0_s_p5_0,
  136668. 1, -529530880, 1611661312, 5, 0,
  136669. _vq_quantlist__44c0_s_p5_0,
  136670. NULL,
  136671. &_vq_auxt__44c0_s_p5_0,
  136672. NULL,
  136673. 0
  136674. };
  136675. static long _vq_quantlist__44c0_s_p6_0[] = {
  136676. 1,
  136677. 0,
  136678. 2,
  136679. };
  136680. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136681. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136682. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136683. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136684. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136685. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136686. 10,
  136687. };
  136688. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136689. -5.5, 5.5,
  136690. };
  136691. static long _vq_quantmap__44c0_s_p6_0[] = {
  136692. 1, 0, 2,
  136693. };
  136694. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136695. _vq_quantthresh__44c0_s_p6_0,
  136696. _vq_quantmap__44c0_s_p6_0,
  136697. 3,
  136698. 3
  136699. };
  136700. static static_codebook _44c0_s_p6_0 = {
  136701. 4, 81,
  136702. _vq_lengthlist__44c0_s_p6_0,
  136703. 1, -529137664, 1618345984, 2, 0,
  136704. _vq_quantlist__44c0_s_p6_0,
  136705. NULL,
  136706. &_vq_auxt__44c0_s_p6_0,
  136707. NULL,
  136708. 0
  136709. };
  136710. static long _vq_quantlist__44c0_s_p6_1[] = {
  136711. 5,
  136712. 4,
  136713. 6,
  136714. 3,
  136715. 7,
  136716. 2,
  136717. 8,
  136718. 1,
  136719. 9,
  136720. 0,
  136721. 10,
  136722. };
  136723. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136724. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136725. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136726. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136727. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136728. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136729. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136730. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136731. 10,10,10, 8, 8, 8, 8, 8, 8,
  136732. };
  136733. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136734. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136735. 3.5, 4.5,
  136736. };
  136737. static long _vq_quantmap__44c0_s_p6_1[] = {
  136738. 9, 7, 5, 3, 1, 0, 2, 4,
  136739. 6, 8, 10,
  136740. };
  136741. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136742. _vq_quantthresh__44c0_s_p6_1,
  136743. _vq_quantmap__44c0_s_p6_1,
  136744. 11,
  136745. 11
  136746. };
  136747. static static_codebook _44c0_s_p6_1 = {
  136748. 2, 121,
  136749. _vq_lengthlist__44c0_s_p6_1,
  136750. 1, -531365888, 1611661312, 4, 0,
  136751. _vq_quantlist__44c0_s_p6_1,
  136752. NULL,
  136753. &_vq_auxt__44c0_s_p6_1,
  136754. NULL,
  136755. 0
  136756. };
  136757. static long _vq_quantlist__44c0_s_p7_0[] = {
  136758. 6,
  136759. 5,
  136760. 7,
  136761. 4,
  136762. 8,
  136763. 3,
  136764. 9,
  136765. 2,
  136766. 10,
  136767. 1,
  136768. 11,
  136769. 0,
  136770. 12,
  136771. };
  136772. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136773. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136774. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136775. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136776. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136777. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136778. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136779. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136780. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136781. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136782. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136783. 0,12,12,11,11,12,12,13,13,
  136784. };
  136785. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136786. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136787. 12.5, 17.5, 22.5, 27.5,
  136788. };
  136789. static long _vq_quantmap__44c0_s_p7_0[] = {
  136790. 11, 9, 7, 5, 3, 1, 0, 2,
  136791. 4, 6, 8, 10, 12,
  136792. };
  136793. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136794. _vq_quantthresh__44c0_s_p7_0,
  136795. _vq_quantmap__44c0_s_p7_0,
  136796. 13,
  136797. 13
  136798. };
  136799. static static_codebook _44c0_s_p7_0 = {
  136800. 2, 169,
  136801. _vq_lengthlist__44c0_s_p7_0,
  136802. 1, -526516224, 1616117760, 4, 0,
  136803. _vq_quantlist__44c0_s_p7_0,
  136804. NULL,
  136805. &_vq_auxt__44c0_s_p7_0,
  136806. NULL,
  136807. 0
  136808. };
  136809. static long _vq_quantlist__44c0_s_p7_1[] = {
  136810. 2,
  136811. 1,
  136812. 3,
  136813. 0,
  136814. 4,
  136815. };
  136816. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136817. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136818. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136819. };
  136820. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136821. -1.5, -0.5, 0.5, 1.5,
  136822. };
  136823. static long _vq_quantmap__44c0_s_p7_1[] = {
  136824. 3, 1, 0, 2, 4,
  136825. };
  136826. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136827. _vq_quantthresh__44c0_s_p7_1,
  136828. _vq_quantmap__44c0_s_p7_1,
  136829. 5,
  136830. 5
  136831. };
  136832. static static_codebook _44c0_s_p7_1 = {
  136833. 2, 25,
  136834. _vq_lengthlist__44c0_s_p7_1,
  136835. 1, -533725184, 1611661312, 3, 0,
  136836. _vq_quantlist__44c0_s_p7_1,
  136837. NULL,
  136838. &_vq_auxt__44c0_s_p7_1,
  136839. NULL,
  136840. 0
  136841. };
  136842. static long _vq_quantlist__44c0_s_p8_0[] = {
  136843. 2,
  136844. 1,
  136845. 3,
  136846. 0,
  136847. 4,
  136848. };
  136849. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136850. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136851. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136853. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136854. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136857. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136858. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136860. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136861. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136862. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136865. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136875. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136876. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136877. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136878. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136881. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136882. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136883. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136884. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136885. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136889. 11,
  136890. };
  136891. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136892. -331.5, -110.5, 110.5, 331.5,
  136893. };
  136894. static long _vq_quantmap__44c0_s_p8_0[] = {
  136895. 3, 1, 0, 2, 4,
  136896. };
  136897. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136898. _vq_quantthresh__44c0_s_p8_0,
  136899. _vq_quantmap__44c0_s_p8_0,
  136900. 5,
  136901. 5
  136902. };
  136903. static static_codebook _44c0_s_p8_0 = {
  136904. 4, 625,
  136905. _vq_lengthlist__44c0_s_p8_0,
  136906. 1, -518283264, 1627103232, 3, 0,
  136907. _vq_quantlist__44c0_s_p8_0,
  136908. NULL,
  136909. &_vq_auxt__44c0_s_p8_0,
  136910. NULL,
  136911. 0
  136912. };
  136913. static long _vq_quantlist__44c0_s_p8_1[] = {
  136914. 6,
  136915. 5,
  136916. 7,
  136917. 4,
  136918. 8,
  136919. 3,
  136920. 9,
  136921. 2,
  136922. 10,
  136923. 1,
  136924. 11,
  136925. 0,
  136926. 12,
  136927. };
  136928. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136929. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136930. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136931. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136932. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136933. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136934. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136935. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136936. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136937. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136938. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136939. 16,13,13,12,12,14,14,15,13,
  136940. };
  136941. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136942. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136943. 42.5, 59.5, 76.5, 93.5,
  136944. };
  136945. static long _vq_quantmap__44c0_s_p8_1[] = {
  136946. 11, 9, 7, 5, 3, 1, 0, 2,
  136947. 4, 6, 8, 10, 12,
  136948. };
  136949. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136950. _vq_quantthresh__44c0_s_p8_1,
  136951. _vq_quantmap__44c0_s_p8_1,
  136952. 13,
  136953. 13
  136954. };
  136955. static static_codebook _44c0_s_p8_1 = {
  136956. 2, 169,
  136957. _vq_lengthlist__44c0_s_p8_1,
  136958. 1, -522616832, 1620115456, 4, 0,
  136959. _vq_quantlist__44c0_s_p8_1,
  136960. NULL,
  136961. &_vq_auxt__44c0_s_p8_1,
  136962. NULL,
  136963. 0
  136964. };
  136965. static long _vq_quantlist__44c0_s_p8_2[] = {
  136966. 8,
  136967. 7,
  136968. 9,
  136969. 6,
  136970. 10,
  136971. 5,
  136972. 11,
  136973. 4,
  136974. 12,
  136975. 3,
  136976. 13,
  136977. 2,
  136978. 14,
  136979. 1,
  136980. 15,
  136981. 0,
  136982. 16,
  136983. };
  136984. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136985. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136986. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136987. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136988. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136989. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136990. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136991. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136992. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136993. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136994. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136995. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136996. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136997. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136998. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136999. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  137000. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  137001. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  137002. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  137003. 10,
  137004. };
  137005. static float _vq_quantthresh__44c0_s_p8_2[] = {
  137006. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137007. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137008. };
  137009. static long _vq_quantmap__44c0_s_p8_2[] = {
  137010. 15, 13, 11, 9, 7, 5, 3, 1,
  137011. 0, 2, 4, 6, 8, 10, 12, 14,
  137012. 16,
  137013. };
  137014. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  137015. _vq_quantthresh__44c0_s_p8_2,
  137016. _vq_quantmap__44c0_s_p8_2,
  137017. 17,
  137018. 17
  137019. };
  137020. static static_codebook _44c0_s_p8_2 = {
  137021. 2, 289,
  137022. _vq_lengthlist__44c0_s_p8_2,
  137023. 1, -529530880, 1611661312, 5, 0,
  137024. _vq_quantlist__44c0_s_p8_2,
  137025. NULL,
  137026. &_vq_auxt__44c0_s_p8_2,
  137027. NULL,
  137028. 0
  137029. };
  137030. static long _huff_lengthlist__44c0_s_short[] = {
  137031. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  137032. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  137033. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  137034. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  137035. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  137036. 12,
  137037. };
  137038. static static_codebook _huff_book__44c0_s_short = {
  137039. 2, 81,
  137040. _huff_lengthlist__44c0_s_short,
  137041. 0, 0, 0, 0, 0,
  137042. NULL,
  137043. NULL,
  137044. NULL,
  137045. NULL,
  137046. 0
  137047. };
  137048. static long _huff_lengthlist__44c0_sm_long[] = {
  137049. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  137050. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  137051. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  137052. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  137053. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  137054. 13,
  137055. };
  137056. static static_codebook _huff_book__44c0_sm_long = {
  137057. 2, 81,
  137058. _huff_lengthlist__44c0_sm_long,
  137059. 0, 0, 0, 0, 0,
  137060. NULL,
  137061. NULL,
  137062. NULL,
  137063. NULL,
  137064. 0
  137065. };
  137066. static long _vq_quantlist__44c0_sm_p1_0[] = {
  137067. 1,
  137068. 0,
  137069. 2,
  137070. };
  137071. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  137072. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137073. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137078. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137083. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  137118. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  137123. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  137128. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137164. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137169. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137174. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0,
  137483. };
  137484. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137485. -0.5, 0.5,
  137486. };
  137487. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137488. 1, 0, 2,
  137489. };
  137490. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137491. _vq_quantthresh__44c0_sm_p1_0,
  137492. _vq_quantmap__44c0_sm_p1_0,
  137493. 3,
  137494. 3
  137495. };
  137496. static static_codebook _44c0_sm_p1_0 = {
  137497. 8, 6561,
  137498. _vq_lengthlist__44c0_sm_p1_0,
  137499. 1, -535822336, 1611661312, 2, 0,
  137500. _vq_quantlist__44c0_sm_p1_0,
  137501. NULL,
  137502. &_vq_auxt__44c0_sm_p1_0,
  137503. NULL,
  137504. 0
  137505. };
  137506. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137507. 2,
  137508. 1,
  137509. 3,
  137510. 0,
  137511. 4,
  137512. };
  137513. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137514. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137517. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0,
  137554. };
  137555. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137556. -1.5, -0.5, 0.5, 1.5,
  137557. };
  137558. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137559. 3, 1, 0, 2, 4,
  137560. };
  137561. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137562. _vq_quantthresh__44c0_sm_p2_0,
  137563. _vq_quantmap__44c0_sm_p2_0,
  137564. 5,
  137565. 5
  137566. };
  137567. static static_codebook _44c0_sm_p2_0 = {
  137568. 4, 625,
  137569. _vq_lengthlist__44c0_sm_p2_0,
  137570. 1, -533725184, 1611661312, 3, 0,
  137571. _vq_quantlist__44c0_sm_p2_0,
  137572. NULL,
  137573. &_vq_auxt__44c0_sm_p2_0,
  137574. NULL,
  137575. 0
  137576. };
  137577. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137578. 4,
  137579. 3,
  137580. 5,
  137581. 2,
  137582. 6,
  137583. 1,
  137584. 7,
  137585. 0,
  137586. 8,
  137587. };
  137588. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137589. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137590. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137591. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137592. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137593. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0,
  137595. };
  137596. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137597. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137598. };
  137599. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137600. 7, 5, 3, 1, 0, 2, 4, 6,
  137601. 8,
  137602. };
  137603. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137604. _vq_quantthresh__44c0_sm_p3_0,
  137605. _vq_quantmap__44c0_sm_p3_0,
  137606. 9,
  137607. 9
  137608. };
  137609. static static_codebook _44c0_sm_p3_0 = {
  137610. 2, 81,
  137611. _vq_lengthlist__44c0_sm_p3_0,
  137612. 1, -531628032, 1611661312, 4, 0,
  137613. _vq_quantlist__44c0_sm_p3_0,
  137614. NULL,
  137615. &_vq_auxt__44c0_sm_p3_0,
  137616. NULL,
  137617. 0
  137618. };
  137619. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137620. 4,
  137621. 3,
  137622. 5,
  137623. 2,
  137624. 6,
  137625. 1,
  137626. 7,
  137627. 0,
  137628. 8,
  137629. };
  137630. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137631. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137632. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137633. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137634. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137635. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137636. 11,
  137637. };
  137638. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137639. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137640. };
  137641. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137642. 7, 5, 3, 1, 0, 2, 4, 6,
  137643. 8,
  137644. };
  137645. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137646. _vq_quantthresh__44c0_sm_p4_0,
  137647. _vq_quantmap__44c0_sm_p4_0,
  137648. 9,
  137649. 9
  137650. };
  137651. static static_codebook _44c0_sm_p4_0 = {
  137652. 2, 81,
  137653. _vq_lengthlist__44c0_sm_p4_0,
  137654. 1, -531628032, 1611661312, 4, 0,
  137655. _vq_quantlist__44c0_sm_p4_0,
  137656. NULL,
  137657. &_vq_auxt__44c0_sm_p4_0,
  137658. NULL,
  137659. 0
  137660. };
  137661. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137662. 8,
  137663. 7,
  137664. 9,
  137665. 6,
  137666. 10,
  137667. 5,
  137668. 11,
  137669. 4,
  137670. 12,
  137671. 3,
  137672. 13,
  137673. 2,
  137674. 14,
  137675. 1,
  137676. 15,
  137677. 0,
  137678. 16,
  137679. };
  137680. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137681. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137682. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137683. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137684. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137685. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137686. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137687. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137688. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137689. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137690. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137691. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137692. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137693. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137694. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137695. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137696. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137697. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137699. 14,
  137700. };
  137701. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137702. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137703. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137704. };
  137705. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137706. 15, 13, 11, 9, 7, 5, 3, 1,
  137707. 0, 2, 4, 6, 8, 10, 12, 14,
  137708. 16,
  137709. };
  137710. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137711. _vq_quantthresh__44c0_sm_p5_0,
  137712. _vq_quantmap__44c0_sm_p5_0,
  137713. 17,
  137714. 17
  137715. };
  137716. static static_codebook _44c0_sm_p5_0 = {
  137717. 2, 289,
  137718. _vq_lengthlist__44c0_sm_p5_0,
  137719. 1, -529530880, 1611661312, 5, 0,
  137720. _vq_quantlist__44c0_sm_p5_0,
  137721. NULL,
  137722. &_vq_auxt__44c0_sm_p5_0,
  137723. NULL,
  137724. 0
  137725. };
  137726. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137727. 1,
  137728. 0,
  137729. 2,
  137730. };
  137731. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137732. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137733. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137734. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137735. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137736. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137737. 11,
  137738. };
  137739. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137740. -5.5, 5.5,
  137741. };
  137742. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137743. 1, 0, 2,
  137744. };
  137745. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137746. _vq_quantthresh__44c0_sm_p6_0,
  137747. _vq_quantmap__44c0_sm_p6_0,
  137748. 3,
  137749. 3
  137750. };
  137751. static static_codebook _44c0_sm_p6_0 = {
  137752. 4, 81,
  137753. _vq_lengthlist__44c0_sm_p6_0,
  137754. 1, -529137664, 1618345984, 2, 0,
  137755. _vq_quantlist__44c0_sm_p6_0,
  137756. NULL,
  137757. &_vq_auxt__44c0_sm_p6_0,
  137758. NULL,
  137759. 0
  137760. };
  137761. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137762. 5,
  137763. 4,
  137764. 6,
  137765. 3,
  137766. 7,
  137767. 2,
  137768. 8,
  137769. 1,
  137770. 9,
  137771. 0,
  137772. 10,
  137773. };
  137774. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137775. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137776. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137777. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137778. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137779. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137780. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137781. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137782. 10,10,10, 8, 8, 8, 8, 8, 8,
  137783. };
  137784. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137785. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137786. 3.5, 4.5,
  137787. };
  137788. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137789. 9, 7, 5, 3, 1, 0, 2, 4,
  137790. 6, 8, 10,
  137791. };
  137792. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137793. _vq_quantthresh__44c0_sm_p6_1,
  137794. _vq_quantmap__44c0_sm_p6_1,
  137795. 11,
  137796. 11
  137797. };
  137798. static static_codebook _44c0_sm_p6_1 = {
  137799. 2, 121,
  137800. _vq_lengthlist__44c0_sm_p6_1,
  137801. 1, -531365888, 1611661312, 4, 0,
  137802. _vq_quantlist__44c0_sm_p6_1,
  137803. NULL,
  137804. &_vq_auxt__44c0_sm_p6_1,
  137805. NULL,
  137806. 0
  137807. };
  137808. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137809. 6,
  137810. 5,
  137811. 7,
  137812. 4,
  137813. 8,
  137814. 3,
  137815. 9,
  137816. 2,
  137817. 10,
  137818. 1,
  137819. 11,
  137820. 0,
  137821. 12,
  137822. };
  137823. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137824. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137825. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137826. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137827. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137828. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137829. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137830. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137831. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137832. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137833. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137834. 0,12,12,11,11,13,12,14,14,
  137835. };
  137836. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137837. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137838. 12.5, 17.5, 22.5, 27.5,
  137839. };
  137840. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137841. 11, 9, 7, 5, 3, 1, 0, 2,
  137842. 4, 6, 8, 10, 12,
  137843. };
  137844. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137845. _vq_quantthresh__44c0_sm_p7_0,
  137846. _vq_quantmap__44c0_sm_p7_0,
  137847. 13,
  137848. 13
  137849. };
  137850. static static_codebook _44c0_sm_p7_0 = {
  137851. 2, 169,
  137852. _vq_lengthlist__44c0_sm_p7_0,
  137853. 1, -526516224, 1616117760, 4, 0,
  137854. _vq_quantlist__44c0_sm_p7_0,
  137855. NULL,
  137856. &_vq_auxt__44c0_sm_p7_0,
  137857. NULL,
  137858. 0
  137859. };
  137860. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137861. 2,
  137862. 1,
  137863. 3,
  137864. 0,
  137865. 4,
  137866. };
  137867. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137868. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137869. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137870. };
  137871. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137872. -1.5, -0.5, 0.5, 1.5,
  137873. };
  137874. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137875. 3, 1, 0, 2, 4,
  137876. };
  137877. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137878. _vq_quantthresh__44c0_sm_p7_1,
  137879. _vq_quantmap__44c0_sm_p7_1,
  137880. 5,
  137881. 5
  137882. };
  137883. static static_codebook _44c0_sm_p7_1 = {
  137884. 2, 25,
  137885. _vq_lengthlist__44c0_sm_p7_1,
  137886. 1, -533725184, 1611661312, 3, 0,
  137887. _vq_quantlist__44c0_sm_p7_1,
  137888. NULL,
  137889. &_vq_auxt__44c0_sm_p7_1,
  137890. NULL,
  137891. 0
  137892. };
  137893. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137894. 4,
  137895. 3,
  137896. 5,
  137897. 2,
  137898. 6,
  137899. 1,
  137900. 7,
  137901. 0,
  137902. 8,
  137903. };
  137904. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137905. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137906. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137908. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137909. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137910. 12,
  137911. };
  137912. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137913. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137914. };
  137915. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137916. 7, 5, 3, 1, 0, 2, 4, 6,
  137917. 8,
  137918. };
  137919. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137920. _vq_quantthresh__44c0_sm_p8_0,
  137921. _vq_quantmap__44c0_sm_p8_0,
  137922. 9,
  137923. 9
  137924. };
  137925. static static_codebook _44c0_sm_p8_0 = {
  137926. 2, 81,
  137927. _vq_lengthlist__44c0_sm_p8_0,
  137928. 1, -516186112, 1627103232, 4, 0,
  137929. _vq_quantlist__44c0_sm_p8_0,
  137930. NULL,
  137931. &_vq_auxt__44c0_sm_p8_0,
  137932. NULL,
  137933. 0
  137934. };
  137935. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137936. 6,
  137937. 5,
  137938. 7,
  137939. 4,
  137940. 8,
  137941. 3,
  137942. 9,
  137943. 2,
  137944. 10,
  137945. 1,
  137946. 11,
  137947. 0,
  137948. 12,
  137949. };
  137950. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137951. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137952. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137953. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137954. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137955. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137956. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137957. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137958. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137959. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137960. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137961. 20,13,13,12,12,16,13,15,13,
  137962. };
  137963. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137964. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137965. 42.5, 59.5, 76.5, 93.5,
  137966. };
  137967. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137968. 11, 9, 7, 5, 3, 1, 0, 2,
  137969. 4, 6, 8, 10, 12,
  137970. };
  137971. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137972. _vq_quantthresh__44c0_sm_p8_1,
  137973. _vq_quantmap__44c0_sm_p8_1,
  137974. 13,
  137975. 13
  137976. };
  137977. static static_codebook _44c0_sm_p8_1 = {
  137978. 2, 169,
  137979. _vq_lengthlist__44c0_sm_p8_1,
  137980. 1, -522616832, 1620115456, 4, 0,
  137981. _vq_quantlist__44c0_sm_p8_1,
  137982. NULL,
  137983. &_vq_auxt__44c0_sm_p8_1,
  137984. NULL,
  137985. 0
  137986. };
  137987. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137988. 8,
  137989. 7,
  137990. 9,
  137991. 6,
  137992. 10,
  137993. 5,
  137994. 11,
  137995. 4,
  137996. 12,
  137997. 3,
  137998. 13,
  137999. 2,
  138000. 14,
  138001. 1,
  138002. 15,
  138003. 0,
  138004. 16,
  138005. };
  138006. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  138007. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138008. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138009. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138010. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138011. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138012. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138013. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138014. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138015. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  138016. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  138017. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  138018. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  138019. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  138020. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  138021. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138022. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138023. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138024. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138025. 9,
  138026. };
  138027. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  138028. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138029. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138030. };
  138031. static long _vq_quantmap__44c0_sm_p8_2[] = {
  138032. 15, 13, 11, 9, 7, 5, 3, 1,
  138033. 0, 2, 4, 6, 8, 10, 12, 14,
  138034. 16,
  138035. };
  138036. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  138037. _vq_quantthresh__44c0_sm_p8_2,
  138038. _vq_quantmap__44c0_sm_p8_2,
  138039. 17,
  138040. 17
  138041. };
  138042. static static_codebook _44c0_sm_p8_2 = {
  138043. 2, 289,
  138044. _vq_lengthlist__44c0_sm_p8_2,
  138045. 1, -529530880, 1611661312, 5, 0,
  138046. _vq_quantlist__44c0_sm_p8_2,
  138047. NULL,
  138048. &_vq_auxt__44c0_sm_p8_2,
  138049. NULL,
  138050. 0
  138051. };
  138052. static long _huff_lengthlist__44c0_sm_short[] = {
  138053. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  138054. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  138055. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  138056. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  138057. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  138058. 12,
  138059. };
  138060. static static_codebook _huff_book__44c0_sm_short = {
  138061. 2, 81,
  138062. _huff_lengthlist__44c0_sm_short,
  138063. 0, 0, 0, 0, 0,
  138064. NULL,
  138065. NULL,
  138066. NULL,
  138067. NULL,
  138068. 0
  138069. };
  138070. static long _huff_lengthlist__44c1_s_long[] = {
  138071. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  138072. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  138073. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  138074. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  138075. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  138076. 11,
  138077. };
  138078. static static_codebook _huff_book__44c1_s_long = {
  138079. 2, 81,
  138080. _huff_lengthlist__44c1_s_long,
  138081. 0, 0, 0, 0, 0,
  138082. NULL,
  138083. NULL,
  138084. NULL,
  138085. NULL,
  138086. 0
  138087. };
  138088. static long _vq_quantlist__44c1_s_p1_0[] = {
  138089. 1,
  138090. 0,
  138091. 2,
  138092. };
  138093. static long _vq_lengthlist__44c1_s_p1_0[] = {
  138094. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  138095. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138100. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138105. 0, 0, 0, 0, 7, 8, 8, 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, 4, 7, 7, 0, 0, 0, 0,
  138140. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  138145. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  138150. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138186. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138191. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138196. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0,
  138505. };
  138506. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138507. -0.5, 0.5,
  138508. };
  138509. static long _vq_quantmap__44c1_s_p1_0[] = {
  138510. 1, 0, 2,
  138511. };
  138512. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138513. _vq_quantthresh__44c1_s_p1_0,
  138514. _vq_quantmap__44c1_s_p1_0,
  138515. 3,
  138516. 3
  138517. };
  138518. static static_codebook _44c1_s_p1_0 = {
  138519. 8, 6561,
  138520. _vq_lengthlist__44c1_s_p1_0,
  138521. 1, -535822336, 1611661312, 2, 0,
  138522. _vq_quantlist__44c1_s_p1_0,
  138523. NULL,
  138524. &_vq_auxt__44c1_s_p1_0,
  138525. NULL,
  138526. 0
  138527. };
  138528. static long _vq_quantlist__44c1_s_p2_0[] = {
  138529. 2,
  138530. 1,
  138531. 3,
  138532. 0,
  138533. 4,
  138534. };
  138535. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138536. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138539. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138542. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0,
  138576. };
  138577. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138578. -1.5, -0.5, 0.5, 1.5,
  138579. };
  138580. static long _vq_quantmap__44c1_s_p2_0[] = {
  138581. 3, 1, 0, 2, 4,
  138582. };
  138583. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138584. _vq_quantthresh__44c1_s_p2_0,
  138585. _vq_quantmap__44c1_s_p2_0,
  138586. 5,
  138587. 5
  138588. };
  138589. static static_codebook _44c1_s_p2_0 = {
  138590. 4, 625,
  138591. _vq_lengthlist__44c1_s_p2_0,
  138592. 1, -533725184, 1611661312, 3, 0,
  138593. _vq_quantlist__44c1_s_p2_0,
  138594. NULL,
  138595. &_vq_auxt__44c1_s_p2_0,
  138596. NULL,
  138597. 0
  138598. };
  138599. static long _vq_quantlist__44c1_s_p3_0[] = {
  138600. 4,
  138601. 3,
  138602. 5,
  138603. 2,
  138604. 6,
  138605. 1,
  138606. 7,
  138607. 0,
  138608. 8,
  138609. };
  138610. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138611. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138612. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138613. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138614. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138615. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0,
  138617. };
  138618. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138619. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138620. };
  138621. static long _vq_quantmap__44c1_s_p3_0[] = {
  138622. 7, 5, 3, 1, 0, 2, 4, 6,
  138623. 8,
  138624. };
  138625. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138626. _vq_quantthresh__44c1_s_p3_0,
  138627. _vq_quantmap__44c1_s_p3_0,
  138628. 9,
  138629. 9
  138630. };
  138631. static static_codebook _44c1_s_p3_0 = {
  138632. 2, 81,
  138633. _vq_lengthlist__44c1_s_p3_0,
  138634. 1, -531628032, 1611661312, 4, 0,
  138635. _vq_quantlist__44c1_s_p3_0,
  138636. NULL,
  138637. &_vq_auxt__44c1_s_p3_0,
  138638. NULL,
  138639. 0
  138640. };
  138641. static long _vq_quantlist__44c1_s_p4_0[] = {
  138642. 4,
  138643. 3,
  138644. 5,
  138645. 2,
  138646. 6,
  138647. 1,
  138648. 7,
  138649. 0,
  138650. 8,
  138651. };
  138652. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138653. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138654. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138655. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138656. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138657. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138658. 11,
  138659. };
  138660. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138661. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138662. };
  138663. static long _vq_quantmap__44c1_s_p4_0[] = {
  138664. 7, 5, 3, 1, 0, 2, 4, 6,
  138665. 8,
  138666. };
  138667. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138668. _vq_quantthresh__44c1_s_p4_0,
  138669. _vq_quantmap__44c1_s_p4_0,
  138670. 9,
  138671. 9
  138672. };
  138673. static static_codebook _44c1_s_p4_0 = {
  138674. 2, 81,
  138675. _vq_lengthlist__44c1_s_p4_0,
  138676. 1, -531628032, 1611661312, 4, 0,
  138677. _vq_quantlist__44c1_s_p4_0,
  138678. NULL,
  138679. &_vq_auxt__44c1_s_p4_0,
  138680. NULL,
  138681. 0
  138682. };
  138683. static long _vq_quantlist__44c1_s_p5_0[] = {
  138684. 8,
  138685. 7,
  138686. 9,
  138687. 6,
  138688. 10,
  138689. 5,
  138690. 11,
  138691. 4,
  138692. 12,
  138693. 3,
  138694. 13,
  138695. 2,
  138696. 14,
  138697. 1,
  138698. 15,
  138699. 0,
  138700. 16,
  138701. };
  138702. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138703. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138704. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138705. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138706. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138707. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138708. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138709. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138710. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138711. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138712. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138713. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138714. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138715. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138716. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138717. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138718. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138719. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138720. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138721. 14,
  138722. };
  138723. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138724. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138725. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138726. };
  138727. static long _vq_quantmap__44c1_s_p5_0[] = {
  138728. 15, 13, 11, 9, 7, 5, 3, 1,
  138729. 0, 2, 4, 6, 8, 10, 12, 14,
  138730. 16,
  138731. };
  138732. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138733. _vq_quantthresh__44c1_s_p5_0,
  138734. _vq_quantmap__44c1_s_p5_0,
  138735. 17,
  138736. 17
  138737. };
  138738. static static_codebook _44c1_s_p5_0 = {
  138739. 2, 289,
  138740. _vq_lengthlist__44c1_s_p5_0,
  138741. 1, -529530880, 1611661312, 5, 0,
  138742. _vq_quantlist__44c1_s_p5_0,
  138743. NULL,
  138744. &_vq_auxt__44c1_s_p5_0,
  138745. NULL,
  138746. 0
  138747. };
  138748. static long _vq_quantlist__44c1_s_p6_0[] = {
  138749. 1,
  138750. 0,
  138751. 2,
  138752. };
  138753. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138754. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138755. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138756. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138757. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138758. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138759. 11,
  138760. };
  138761. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138762. -5.5, 5.5,
  138763. };
  138764. static long _vq_quantmap__44c1_s_p6_0[] = {
  138765. 1, 0, 2,
  138766. };
  138767. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138768. _vq_quantthresh__44c1_s_p6_0,
  138769. _vq_quantmap__44c1_s_p6_0,
  138770. 3,
  138771. 3
  138772. };
  138773. static static_codebook _44c1_s_p6_0 = {
  138774. 4, 81,
  138775. _vq_lengthlist__44c1_s_p6_0,
  138776. 1, -529137664, 1618345984, 2, 0,
  138777. _vq_quantlist__44c1_s_p6_0,
  138778. NULL,
  138779. &_vq_auxt__44c1_s_p6_0,
  138780. NULL,
  138781. 0
  138782. };
  138783. static long _vq_quantlist__44c1_s_p6_1[] = {
  138784. 5,
  138785. 4,
  138786. 6,
  138787. 3,
  138788. 7,
  138789. 2,
  138790. 8,
  138791. 1,
  138792. 9,
  138793. 0,
  138794. 10,
  138795. };
  138796. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138797. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138798. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138799. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138800. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138801. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138802. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138803. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138804. 10,10,10, 8, 8, 8, 8, 8, 8,
  138805. };
  138806. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138807. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138808. 3.5, 4.5,
  138809. };
  138810. static long _vq_quantmap__44c1_s_p6_1[] = {
  138811. 9, 7, 5, 3, 1, 0, 2, 4,
  138812. 6, 8, 10,
  138813. };
  138814. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138815. _vq_quantthresh__44c1_s_p6_1,
  138816. _vq_quantmap__44c1_s_p6_1,
  138817. 11,
  138818. 11
  138819. };
  138820. static static_codebook _44c1_s_p6_1 = {
  138821. 2, 121,
  138822. _vq_lengthlist__44c1_s_p6_1,
  138823. 1, -531365888, 1611661312, 4, 0,
  138824. _vq_quantlist__44c1_s_p6_1,
  138825. NULL,
  138826. &_vq_auxt__44c1_s_p6_1,
  138827. NULL,
  138828. 0
  138829. };
  138830. static long _vq_quantlist__44c1_s_p7_0[] = {
  138831. 6,
  138832. 5,
  138833. 7,
  138834. 4,
  138835. 8,
  138836. 3,
  138837. 9,
  138838. 2,
  138839. 10,
  138840. 1,
  138841. 11,
  138842. 0,
  138843. 12,
  138844. };
  138845. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138846. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138847. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138848. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138849. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138850. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138851. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138852. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138853. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138854. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138855. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138856. 0,12,11,11,11,13,10,14,13,
  138857. };
  138858. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138859. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138860. 12.5, 17.5, 22.5, 27.5,
  138861. };
  138862. static long _vq_quantmap__44c1_s_p7_0[] = {
  138863. 11, 9, 7, 5, 3, 1, 0, 2,
  138864. 4, 6, 8, 10, 12,
  138865. };
  138866. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138867. _vq_quantthresh__44c1_s_p7_0,
  138868. _vq_quantmap__44c1_s_p7_0,
  138869. 13,
  138870. 13
  138871. };
  138872. static static_codebook _44c1_s_p7_0 = {
  138873. 2, 169,
  138874. _vq_lengthlist__44c1_s_p7_0,
  138875. 1, -526516224, 1616117760, 4, 0,
  138876. _vq_quantlist__44c1_s_p7_0,
  138877. NULL,
  138878. &_vq_auxt__44c1_s_p7_0,
  138879. NULL,
  138880. 0
  138881. };
  138882. static long _vq_quantlist__44c1_s_p7_1[] = {
  138883. 2,
  138884. 1,
  138885. 3,
  138886. 0,
  138887. 4,
  138888. };
  138889. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138890. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138891. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138892. };
  138893. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138894. -1.5, -0.5, 0.5, 1.5,
  138895. };
  138896. static long _vq_quantmap__44c1_s_p7_1[] = {
  138897. 3, 1, 0, 2, 4,
  138898. };
  138899. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138900. _vq_quantthresh__44c1_s_p7_1,
  138901. _vq_quantmap__44c1_s_p7_1,
  138902. 5,
  138903. 5
  138904. };
  138905. static static_codebook _44c1_s_p7_1 = {
  138906. 2, 25,
  138907. _vq_lengthlist__44c1_s_p7_1,
  138908. 1, -533725184, 1611661312, 3, 0,
  138909. _vq_quantlist__44c1_s_p7_1,
  138910. NULL,
  138911. &_vq_auxt__44c1_s_p7_1,
  138912. NULL,
  138913. 0
  138914. };
  138915. static long _vq_quantlist__44c1_s_p8_0[] = {
  138916. 6,
  138917. 5,
  138918. 7,
  138919. 4,
  138920. 8,
  138921. 3,
  138922. 9,
  138923. 2,
  138924. 10,
  138925. 1,
  138926. 11,
  138927. 0,
  138928. 12,
  138929. };
  138930. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138931. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138932. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138933. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138934. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138935. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138936. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138937. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138938. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138940. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138941. 10,10,10,10,10,10,10,10,10,
  138942. };
  138943. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138944. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138945. 552.5, 773.5, 994.5, 1215.5,
  138946. };
  138947. static long _vq_quantmap__44c1_s_p8_0[] = {
  138948. 11, 9, 7, 5, 3, 1, 0, 2,
  138949. 4, 6, 8, 10, 12,
  138950. };
  138951. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138952. _vq_quantthresh__44c1_s_p8_0,
  138953. _vq_quantmap__44c1_s_p8_0,
  138954. 13,
  138955. 13
  138956. };
  138957. static static_codebook _44c1_s_p8_0 = {
  138958. 2, 169,
  138959. _vq_lengthlist__44c1_s_p8_0,
  138960. 1, -514541568, 1627103232, 4, 0,
  138961. _vq_quantlist__44c1_s_p8_0,
  138962. NULL,
  138963. &_vq_auxt__44c1_s_p8_0,
  138964. NULL,
  138965. 0
  138966. };
  138967. static long _vq_quantlist__44c1_s_p8_1[] = {
  138968. 6,
  138969. 5,
  138970. 7,
  138971. 4,
  138972. 8,
  138973. 3,
  138974. 9,
  138975. 2,
  138976. 10,
  138977. 1,
  138978. 11,
  138979. 0,
  138980. 12,
  138981. };
  138982. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138983. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138984. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138985. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138986. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138987. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138988. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138989. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138990. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138991. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138992. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138993. 16,13,12,12,11,14,12,15,13,
  138994. };
  138995. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138996. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138997. 42.5, 59.5, 76.5, 93.5,
  138998. };
  138999. static long _vq_quantmap__44c1_s_p8_1[] = {
  139000. 11, 9, 7, 5, 3, 1, 0, 2,
  139001. 4, 6, 8, 10, 12,
  139002. };
  139003. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  139004. _vq_quantthresh__44c1_s_p8_1,
  139005. _vq_quantmap__44c1_s_p8_1,
  139006. 13,
  139007. 13
  139008. };
  139009. static static_codebook _44c1_s_p8_1 = {
  139010. 2, 169,
  139011. _vq_lengthlist__44c1_s_p8_1,
  139012. 1, -522616832, 1620115456, 4, 0,
  139013. _vq_quantlist__44c1_s_p8_1,
  139014. NULL,
  139015. &_vq_auxt__44c1_s_p8_1,
  139016. NULL,
  139017. 0
  139018. };
  139019. static long _vq_quantlist__44c1_s_p8_2[] = {
  139020. 8,
  139021. 7,
  139022. 9,
  139023. 6,
  139024. 10,
  139025. 5,
  139026. 11,
  139027. 4,
  139028. 12,
  139029. 3,
  139030. 13,
  139031. 2,
  139032. 14,
  139033. 1,
  139034. 15,
  139035. 0,
  139036. 16,
  139037. };
  139038. static long _vq_lengthlist__44c1_s_p8_2[] = {
  139039. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139040. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139041. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  139042. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139043. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  139044. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139045. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139046. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  139047. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  139048. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139049. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  139050. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139051. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  139052. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  139053. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139054. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  139055. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139056. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  139057. 9,
  139058. };
  139059. static float _vq_quantthresh__44c1_s_p8_2[] = {
  139060. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139061. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139062. };
  139063. static long _vq_quantmap__44c1_s_p8_2[] = {
  139064. 15, 13, 11, 9, 7, 5, 3, 1,
  139065. 0, 2, 4, 6, 8, 10, 12, 14,
  139066. 16,
  139067. };
  139068. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  139069. _vq_quantthresh__44c1_s_p8_2,
  139070. _vq_quantmap__44c1_s_p8_2,
  139071. 17,
  139072. 17
  139073. };
  139074. static static_codebook _44c1_s_p8_2 = {
  139075. 2, 289,
  139076. _vq_lengthlist__44c1_s_p8_2,
  139077. 1, -529530880, 1611661312, 5, 0,
  139078. _vq_quantlist__44c1_s_p8_2,
  139079. NULL,
  139080. &_vq_auxt__44c1_s_p8_2,
  139081. NULL,
  139082. 0
  139083. };
  139084. static long _huff_lengthlist__44c1_s_short[] = {
  139085. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  139086. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  139087. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  139088. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  139089. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  139090. 11,
  139091. };
  139092. static static_codebook _huff_book__44c1_s_short = {
  139093. 2, 81,
  139094. _huff_lengthlist__44c1_s_short,
  139095. 0, 0, 0, 0, 0,
  139096. NULL,
  139097. NULL,
  139098. NULL,
  139099. NULL,
  139100. 0
  139101. };
  139102. static long _huff_lengthlist__44c1_sm_long[] = {
  139103. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  139104. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  139105. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139106. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139107. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139108. 11,
  139109. };
  139110. static static_codebook _huff_book__44c1_sm_long = {
  139111. 2, 81,
  139112. _huff_lengthlist__44c1_sm_long,
  139113. 0, 0, 0, 0, 0,
  139114. NULL,
  139115. NULL,
  139116. NULL,
  139117. NULL,
  139118. 0
  139119. };
  139120. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139121. 1,
  139122. 0,
  139123. 2,
  139124. };
  139125. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139126. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139127. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139132. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139137. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  139172. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  139177. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  139182. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139218. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139223. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139228. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0,
  139537. };
  139538. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139539. -0.5, 0.5,
  139540. };
  139541. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139542. 1, 0, 2,
  139543. };
  139544. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139545. _vq_quantthresh__44c1_sm_p1_0,
  139546. _vq_quantmap__44c1_sm_p1_0,
  139547. 3,
  139548. 3
  139549. };
  139550. static static_codebook _44c1_sm_p1_0 = {
  139551. 8, 6561,
  139552. _vq_lengthlist__44c1_sm_p1_0,
  139553. 1, -535822336, 1611661312, 2, 0,
  139554. _vq_quantlist__44c1_sm_p1_0,
  139555. NULL,
  139556. &_vq_auxt__44c1_sm_p1_0,
  139557. NULL,
  139558. 0
  139559. };
  139560. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139561. 2,
  139562. 1,
  139563. 3,
  139564. 0,
  139565. 4,
  139566. };
  139567. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139568. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139571. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139574. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0,
  139608. };
  139609. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139610. -1.5, -0.5, 0.5, 1.5,
  139611. };
  139612. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139613. 3, 1, 0, 2, 4,
  139614. };
  139615. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139616. _vq_quantthresh__44c1_sm_p2_0,
  139617. _vq_quantmap__44c1_sm_p2_0,
  139618. 5,
  139619. 5
  139620. };
  139621. static static_codebook _44c1_sm_p2_0 = {
  139622. 4, 625,
  139623. _vq_lengthlist__44c1_sm_p2_0,
  139624. 1, -533725184, 1611661312, 3, 0,
  139625. _vq_quantlist__44c1_sm_p2_0,
  139626. NULL,
  139627. &_vq_auxt__44c1_sm_p2_0,
  139628. NULL,
  139629. 0
  139630. };
  139631. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139632. 4,
  139633. 3,
  139634. 5,
  139635. 2,
  139636. 6,
  139637. 1,
  139638. 7,
  139639. 0,
  139640. 8,
  139641. };
  139642. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139643. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139644. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139645. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139646. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139647. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0,
  139649. };
  139650. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139651. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139652. };
  139653. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139654. 7, 5, 3, 1, 0, 2, 4, 6,
  139655. 8,
  139656. };
  139657. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139658. _vq_quantthresh__44c1_sm_p3_0,
  139659. _vq_quantmap__44c1_sm_p3_0,
  139660. 9,
  139661. 9
  139662. };
  139663. static static_codebook _44c1_sm_p3_0 = {
  139664. 2, 81,
  139665. _vq_lengthlist__44c1_sm_p3_0,
  139666. 1, -531628032, 1611661312, 4, 0,
  139667. _vq_quantlist__44c1_sm_p3_0,
  139668. NULL,
  139669. &_vq_auxt__44c1_sm_p3_0,
  139670. NULL,
  139671. 0
  139672. };
  139673. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139674. 4,
  139675. 3,
  139676. 5,
  139677. 2,
  139678. 6,
  139679. 1,
  139680. 7,
  139681. 0,
  139682. 8,
  139683. };
  139684. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139685. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139686. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139687. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139688. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139689. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139690. 11,
  139691. };
  139692. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139693. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139694. };
  139695. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139696. 7, 5, 3, 1, 0, 2, 4, 6,
  139697. 8,
  139698. };
  139699. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139700. _vq_quantthresh__44c1_sm_p4_0,
  139701. _vq_quantmap__44c1_sm_p4_0,
  139702. 9,
  139703. 9
  139704. };
  139705. static static_codebook _44c1_sm_p4_0 = {
  139706. 2, 81,
  139707. _vq_lengthlist__44c1_sm_p4_0,
  139708. 1, -531628032, 1611661312, 4, 0,
  139709. _vq_quantlist__44c1_sm_p4_0,
  139710. NULL,
  139711. &_vq_auxt__44c1_sm_p4_0,
  139712. NULL,
  139713. 0
  139714. };
  139715. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139716. 8,
  139717. 7,
  139718. 9,
  139719. 6,
  139720. 10,
  139721. 5,
  139722. 11,
  139723. 4,
  139724. 12,
  139725. 3,
  139726. 13,
  139727. 2,
  139728. 14,
  139729. 1,
  139730. 15,
  139731. 0,
  139732. 16,
  139733. };
  139734. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139735. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139736. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139737. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139738. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139739. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139740. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139741. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139742. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139743. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139744. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139745. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139746. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139747. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139748. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139749. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139750. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139751. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139752. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139753. 14,
  139754. };
  139755. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139756. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139757. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139758. };
  139759. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139760. 15, 13, 11, 9, 7, 5, 3, 1,
  139761. 0, 2, 4, 6, 8, 10, 12, 14,
  139762. 16,
  139763. };
  139764. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139765. _vq_quantthresh__44c1_sm_p5_0,
  139766. _vq_quantmap__44c1_sm_p5_0,
  139767. 17,
  139768. 17
  139769. };
  139770. static static_codebook _44c1_sm_p5_0 = {
  139771. 2, 289,
  139772. _vq_lengthlist__44c1_sm_p5_0,
  139773. 1, -529530880, 1611661312, 5, 0,
  139774. _vq_quantlist__44c1_sm_p5_0,
  139775. NULL,
  139776. &_vq_auxt__44c1_sm_p5_0,
  139777. NULL,
  139778. 0
  139779. };
  139780. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139781. 1,
  139782. 0,
  139783. 2,
  139784. };
  139785. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139786. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139787. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139788. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139789. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139790. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139791. 11,
  139792. };
  139793. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139794. -5.5, 5.5,
  139795. };
  139796. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139797. 1, 0, 2,
  139798. };
  139799. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139800. _vq_quantthresh__44c1_sm_p6_0,
  139801. _vq_quantmap__44c1_sm_p6_0,
  139802. 3,
  139803. 3
  139804. };
  139805. static static_codebook _44c1_sm_p6_0 = {
  139806. 4, 81,
  139807. _vq_lengthlist__44c1_sm_p6_0,
  139808. 1, -529137664, 1618345984, 2, 0,
  139809. _vq_quantlist__44c1_sm_p6_0,
  139810. NULL,
  139811. &_vq_auxt__44c1_sm_p6_0,
  139812. NULL,
  139813. 0
  139814. };
  139815. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139816. 5,
  139817. 4,
  139818. 6,
  139819. 3,
  139820. 7,
  139821. 2,
  139822. 8,
  139823. 1,
  139824. 9,
  139825. 0,
  139826. 10,
  139827. };
  139828. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139829. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139830. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139831. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139832. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139833. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139834. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139835. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139836. 10,10,10, 8, 8, 8, 8, 8, 8,
  139837. };
  139838. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139839. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139840. 3.5, 4.5,
  139841. };
  139842. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139843. 9, 7, 5, 3, 1, 0, 2, 4,
  139844. 6, 8, 10,
  139845. };
  139846. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139847. _vq_quantthresh__44c1_sm_p6_1,
  139848. _vq_quantmap__44c1_sm_p6_1,
  139849. 11,
  139850. 11
  139851. };
  139852. static static_codebook _44c1_sm_p6_1 = {
  139853. 2, 121,
  139854. _vq_lengthlist__44c1_sm_p6_1,
  139855. 1, -531365888, 1611661312, 4, 0,
  139856. _vq_quantlist__44c1_sm_p6_1,
  139857. NULL,
  139858. &_vq_auxt__44c1_sm_p6_1,
  139859. NULL,
  139860. 0
  139861. };
  139862. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139863. 6,
  139864. 5,
  139865. 7,
  139866. 4,
  139867. 8,
  139868. 3,
  139869. 9,
  139870. 2,
  139871. 10,
  139872. 1,
  139873. 11,
  139874. 0,
  139875. 12,
  139876. };
  139877. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139878. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139879. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139880. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139881. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139882. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139883. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139884. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139885. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139886. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139887. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139888. 0,12,12,11,11,13,12,14,13,
  139889. };
  139890. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139891. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139892. 12.5, 17.5, 22.5, 27.5,
  139893. };
  139894. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139895. 11, 9, 7, 5, 3, 1, 0, 2,
  139896. 4, 6, 8, 10, 12,
  139897. };
  139898. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139899. _vq_quantthresh__44c1_sm_p7_0,
  139900. _vq_quantmap__44c1_sm_p7_0,
  139901. 13,
  139902. 13
  139903. };
  139904. static static_codebook _44c1_sm_p7_0 = {
  139905. 2, 169,
  139906. _vq_lengthlist__44c1_sm_p7_0,
  139907. 1, -526516224, 1616117760, 4, 0,
  139908. _vq_quantlist__44c1_sm_p7_0,
  139909. NULL,
  139910. &_vq_auxt__44c1_sm_p7_0,
  139911. NULL,
  139912. 0
  139913. };
  139914. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139915. 2,
  139916. 1,
  139917. 3,
  139918. 0,
  139919. 4,
  139920. };
  139921. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139922. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139923. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139924. };
  139925. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139926. -1.5, -0.5, 0.5, 1.5,
  139927. };
  139928. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139929. 3, 1, 0, 2, 4,
  139930. };
  139931. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139932. _vq_quantthresh__44c1_sm_p7_1,
  139933. _vq_quantmap__44c1_sm_p7_1,
  139934. 5,
  139935. 5
  139936. };
  139937. static static_codebook _44c1_sm_p7_1 = {
  139938. 2, 25,
  139939. _vq_lengthlist__44c1_sm_p7_1,
  139940. 1, -533725184, 1611661312, 3, 0,
  139941. _vq_quantlist__44c1_sm_p7_1,
  139942. NULL,
  139943. &_vq_auxt__44c1_sm_p7_1,
  139944. NULL,
  139945. 0
  139946. };
  139947. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139948. 6,
  139949. 5,
  139950. 7,
  139951. 4,
  139952. 8,
  139953. 3,
  139954. 9,
  139955. 2,
  139956. 10,
  139957. 1,
  139958. 11,
  139959. 0,
  139960. 12,
  139961. };
  139962. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139963. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139964. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139965. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139966. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139967. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139968. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139969. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139970. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139971. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139972. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139973. 13,13,13,13,13,13,13,13,13,
  139974. };
  139975. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139976. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139977. 552.5, 773.5, 994.5, 1215.5,
  139978. };
  139979. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139980. 11, 9, 7, 5, 3, 1, 0, 2,
  139981. 4, 6, 8, 10, 12,
  139982. };
  139983. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139984. _vq_quantthresh__44c1_sm_p8_0,
  139985. _vq_quantmap__44c1_sm_p8_0,
  139986. 13,
  139987. 13
  139988. };
  139989. static static_codebook _44c1_sm_p8_0 = {
  139990. 2, 169,
  139991. _vq_lengthlist__44c1_sm_p8_0,
  139992. 1, -514541568, 1627103232, 4, 0,
  139993. _vq_quantlist__44c1_sm_p8_0,
  139994. NULL,
  139995. &_vq_auxt__44c1_sm_p8_0,
  139996. NULL,
  139997. 0
  139998. };
  139999. static long _vq_quantlist__44c1_sm_p8_1[] = {
  140000. 6,
  140001. 5,
  140002. 7,
  140003. 4,
  140004. 8,
  140005. 3,
  140006. 9,
  140007. 2,
  140008. 10,
  140009. 1,
  140010. 11,
  140011. 0,
  140012. 12,
  140013. };
  140014. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  140015. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  140016. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  140017. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  140018. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  140019. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  140020. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  140021. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  140022. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  140023. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  140024. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  140025. 20,13,12,12,12,14,12,14,13,
  140026. };
  140027. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  140028. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140029. 42.5, 59.5, 76.5, 93.5,
  140030. };
  140031. static long _vq_quantmap__44c1_sm_p8_1[] = {
  140032. 11, 9, 7, 5, 3, 1, 0, 2,
  140033. 4, 6, 8, 10, 12,
  140034. };
  140035. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  140036. _vq_quantthresh__44c1_sm_p8_1,
  140037. _vq_quantmap__44c1_sm_p8_1,
  140038. 13,
  140039. 13
  140040. };
  140041. static static_codebook _44c1_sm_p8_1 = {
  140042. 2, 169,
  140043. _vq_lengthlist__44c1_sm_p8_1,
  140044. 1, -522616832, 1620115456, 4, 0,
  140045. _vq_quantlist__44c1_sm_p8_1,
  140046. NULL,
  140047. &_vq_auxt__44c1_sm_p8_1,
  140048. NULL,
  140049. 0
  140050. };
  140051. static long _vq_quantlist__44c1_sm_p8_2[] = {
  140052. 8,
  140053. 7,
  140054. 9,
  140055. 6,
  140056. 10,
  140057. 5,
  140058. 11,
  140059. 4,
  140060. 12,
  140061. 3,
  140062. 13,
  140063. 2,
  140064. 14,
  140065. 1,
  140066. 15,
  140067. 0,
  140068. 16,
  140069. };
  140070. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  140071. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  140072. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140073. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140074. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140075. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140076. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  140077. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  140078. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  140079. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  140080. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  140081. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  140082. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  140083. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  140084. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  140085. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  140086. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  140087. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  140088. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  140089. 9,
  140090. };
  140091. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  140092. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140093. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140094. };
  140095. static long _vq_quantmap__44c1_sm_p8_2[] = {
  140096. 15, 13, 11, 9, 7, 5, 3, 1,
  140097. 0, 2, 4, 6, 8, 10, 12, 14,
  140098. 16,
  140099. };
  140100. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  140101. _vq_quantthresh__44c1_sm_p8_2,
  140102. _vq_quantmap__44c1_sm_p8_2,
  140103. 17,
  140104. 17
  140105. };
  140106. static static_codebook _44c1_sm_p8_2 = {
  140107. 2, 289,
  140108. _vq_lengthlist__44c1_sm_p8_2,
  140109. 1, -529530880, 1611661312, 5, 0,
  140110. _vq_quantlist__44c1_sm_p8_2,
  140111. NULL,
  140112. &_vq_auxt__44c1_sm_p8_2,
  140113. NULL,
  140114. 0
  140115. };
  140116. static long _huff_lengthlist__44c1_sm_short[] = {
  140117. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140118. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140119. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140120. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140121. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140122. 11,
  140123. };
  140124. static static_codebook _huff_book__44c1_sm_short = {
  140125. 2, 81,
  140126. _huff_lengthlist__44c1_sm_short,
  140127. 0, 0, 0, 0, 0,
  140128. NULL,
  140129. NULL,
  140130. NULL,
  140131. NULL,
  140132. 0
  140133. };
  140134. static long _huff_lengthlist__44cn1_s_long[] = {
  140135. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140136. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140137. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140138. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140139. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140140. 20,
  140141. };
  140142. static static_codebook _huff_book__44cn1_s_long = {
  140143. 2, 81,
  140144. _huff_lengthlist__44cn1_s_long,
  140145. 0, 0, 0, 0, 0,
  140146. NULL,
  140147. NULL,
  140148. NULL,
  140149. NULL,
  140150. 0
  140151. };
  140152. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140153. 1,
  140154. 0,
  140155. 2,
  140156. };
  140157. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140158. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140159. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140164. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140169. 0, 0, 0, 0, 8,10, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  140204. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  140209. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  140214. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140250. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140255. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140260. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0,
  140569. };
  140570. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140571. -0.5, 0.5,
  140572. };
  140573. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140574. 1, 0, 2,
  140575. };
  140576. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140577. _vq_quantthresh__44cn1_s_p1_0,
  140578. _vq_quantmap__44cn1_s_p1_0,
  140579. 3,
  140580. 3
  140581. };
  140582. static static_codebook _44cn1_s_p1_0 = {
  140583. 8, 6561,
  140584. _vq_lengthlist__44cn1_s_p1_0,
  140585. 1, -535822336, 1611661312, 2, 0,
  140586. _vq_quantlist__44cn1_s_p1_0,
  140587. NULL,
  140588. &_vq_auxt__44cn1_s_p1_0,
  140589. NULL,
  140590. 0
  140591. };
  140592. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140593. 2,
  140594. 1,
  140595. 3,
  140596. 0,
  140597. 4,
  140598. };
  140599. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140600. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140603. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0,
  140640. };
  140641. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140642. -1.5, -0.5, 0.5, 1.5,
  140643. };
  140644. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140645. 3, 1, 0, 2, 4,
  140646. };
  140647. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140648. _vq_quantthresh__44cn1_s_p2_0,
  140649. _vq_quantmap__44cn1_s_p2_0,
  140650. 5,
  140651. 5
  140652. };
  140653. static static_codebook _44cn1_s_p2_0 = {
  140654. 4, 625,
  140655. _vq_lengthlist__44cn1_s_p2_0,
  140656. 1, -533725184, 1611661312, 3, 0,
  140657. _vq_quantlist__44cn1_s_p2_0,
  140658. NULL,
  140659. &_vq_auxt__44cn1_s_p2_0,
  140660. NULL,
  140661. 0
  140662. };
  140663. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140664. 4,
  140665. 3,
  140666. 5,
  140667. 2,
  140668. 6,
  140669. 1,
  140670. 7,
  140671. 0,
  140672. 8,
  140673. };
  140674. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140675. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140676. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140677. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140678. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140679. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140680. 0,
  140681. };
  140682. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140683. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140684. };
  140685. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140686. 7, 5, 3, 1, 0, 2, 4, 6,
  140687. 8,
  140688. };
  140689. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140690. _vq_quantthresh__44cn1_s_p3_0,
  140691. _vq_quantmap__44cn1_s_p3_0,
  140692. 9,
  140693. 9
  140694. };
  140695. static static_codebook _44cn1_s_p3_0 = {
  140696. 2, 81,
  140697. _vq_lengthlist__44cn1_s_p3_0,
  140698. 1, -531628032, 1611661312, 4, 0,
  140699. _vq_quantlist__44cn1_s_p3_0,
  140700. NULL,
  140701. &_vq_auxt__44cn1_s_p3_0,
  140702. NULL,
  140703. 0
  140704. };
  140705. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140706. 4,
  140707. 3,
  140708. 5,
  140709. 2,
  140710. 6,
  140711. 1,
  140712. 7,
  140713. 0,
  140714. 8,
  140715. };
  140716. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140717. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140718. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140719. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140720. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140721. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140722. 11,
  140723. };
  140724. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140725. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140726. };
  140727. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140728. 7, 5, 3, 1, 0, 2, 4, 6,
  140729. 8,
  140730. };
  140731. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140732. _vq_quantthresh__44cn1_s_p4_0,
  140733. _vq_quantmap__44cn1_s_p4_0,
  140734. 9,
  140735. 9
  140736. };
  140737. static static_codebook _44cn1_s_p4_0 = {
  140738. 2, 81,
  140739. _vq_lengthlist__44cn1_s_p4_0,
  140740. 1, -531628032, 1611661312, 4, 0,
  140741. _vq_quantlist__44cn1_s_p4_0,
  140742. NULL,
  140743. &_vq_auxt__44cn1_s_p4_0,
  140744. NULL,
  140745. 0
  140746. };
  140747. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140748. 8,
  140749. 7,
  140750. 9,
  140751. 6,
  140752. 10,
  140753. 5,
  140754. 11,
  140755. 4,
  140756. 12,
  140757. 3,
  140758. 13,
  140759. 2,
  140760. 14,
  140761. 1,
  140762. 15,
  140763. 0,
  140764. 16,
  140765. };
  140766. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140767. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140768. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140769. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140770. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140771. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140772. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140773. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140774. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140775. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140776. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140777. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140778. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140779. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140780. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140781. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140782. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140783. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140784. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140785. 14,
  140786. };
  140787. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140788. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140789. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140790. };
  140791. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140792. 15, 13, 11, 9, 7, 5, 3, 1,
  140793. 0, 2, 4, 6, 8, 10, 12, 14,
  140794. 16,
  140795. };
  140796. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140797. _vq_quantthresh__44cn1_s_p5_0,
  140798. _vq_quantmap__44cn1_s_p5_0,
  140799. 17,
  140800. 17
  140801. };
  140802. static static_codebook _44cn1_s_p5_0 = {
  140803. 2, 289,
  140804. _vq_lengthlist__44cn1_s_p5_0,
  140805. 1, -529530880, 1611661312, 5, 0,
  140806. _vq_quantlist__44cn1_s_p5_0,
  140807. NULL,
  140808. &_vq_auxt__44cn1_s_p5_0,
  140809. NULL,
  140810. 0
  140811. };
  140812. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140813. 1,
  140814. 0,
  140815. 2,
  140816. };
  140817. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140818. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140819. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140820. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140821. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140822. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140823. 10,
  140824. };
  140825. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140826. -5.5, 5.5,
  140827. };
  140828. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140829. 1, 0, 2,
  140830. };
  140831. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140832. _vq_quantthresh__44cn1_s_p6_0,
  140833. _vq_quantmap__44cn1_s_p6_0,
  140834. 3,
  140835. 3
  140836. };
  140837. static static_codebook _44cn1_s_p6_0 = {
  140838. 4, 81,
  140839. _vq_lengthlist__44cn1_s_p6_0,
  140840. 1, -529137664, 1618345984, 2, 0,
  140841. _vq_quantlist__44cn1_s_p6_0,
  140842. NULL,
  140843. &_vq_auxt__44cn1_s_p6_0,
  140844. NULL,
  140845. 0
  140846. };
  140847. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140848. 5,
  140849. 4,
  140850. 6,
  140851. 3,
  140852. 7,
  140853. 2,
  140854. 8,
  140855. 1,
  140856. 9,
  140857. 0,
  140858. 10,
  140859. };
  140860. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140861. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140862. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140863. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140864. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140865. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140866. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140867. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140868. 10,10,10, 9, 9, 9, 9, 9, 9,
  140869. };
  140870. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140871. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140872. 3.5, 4.5,
  140873. };
  140874. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140875. 9, 7, 5, 3, 1, 0, 2, 4,
  140876. 6, 8, 10,
  140877. };
  140878. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140879. _vq_quantthresh__44cn1_s_p6_1,
  140880. _vq_quantmap__44cn1_s_p6_1,
  140881. 11,
  140882. 11
  140883. };
  140884. static static_codebook _44cn1_s_p6_1 = {
  140885. 2, 121,
  140886. _vq_lengthlist__44cn1_s_p6_1,
  140887. 1, -531365888, 1611661312, 4, 0,
  140888. _vq_quantlist__44cn1_s_p6_1,
  140889. NULL,
  140890. &_vq_auxt__44cn1_s_p6_1,
  140891. NULL,
  140892. 0
  140893. };
  140894. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140895. 6,
  140896. 5,
  140897. 7,
  140898. 4,
  140899. 8,
  140900. 3,
  140901. 9,
  140902. 2,
  140903. 10,
  140904. 1,
  140905. 11,
  140906. 0,
  140907. 12,
  140908. };
  140909. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140910. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140911. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140912. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140913. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140914. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140915. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140916. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140917. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140918. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140919. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140920. 0,13,13,12,12,13,13,13,14,
  140921. };
  140922. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140923. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140924. 12.5, 17.5, 22.5, 27.5,
  140925. };
  140926. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140927. 11, 9, 7, 5, 3, 1, 0, 2,
  140928. 4, 6, 8, 10, 12,
  140929. };
  140930. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140931. _vq_quantthresh__44cn1_s_p7_0,
  140932. _vq_quantmap__44cn1_s_p7_0,
  140933. 13,
  140934. 13
  140935. };
  140936. static static_codebook _44cn1_s_p7_0 = {
  140937. 2, 169,
  140938. _vq_lengthlist__44cn1_s_p7_0,
  140939. 1, -526516224, 1616117760, 4, 0,
  140940. _vq_quantlist__44cn1_s_p7_0,
  140941. NULL,
  140942. &_vq_auxt__44cn1_s_p7_0,
  140943. NULL,
  140944. 0
  140945. };
  140946. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140947. 2,
  140948. 1,
  140949. 3,
  140950. 0,
  140951. 4,
  140952. };
  140953. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140954. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140955. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140956. };
  140957. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140958. -1.5, -0.5, 0.5, 1.5,
  140959. };
  140960. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140961. 3, 1, 0, 2, 4,
  140962. };
  140963. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140964. _vq_quantthresh__44cn1_s_p7_1,
  140965. _vq_quantmap__44cn1_s_p7_1,
  140966. 5,
  140967. 5
  140968. };
  140969. static static_codebook _44cn1_s_p7_1 = {
  140970. 2, 25,
  140971. _vq_lengthlist__44cn1_s_p7_1,
  140972. 1, -533725184, 1611661312, 3, 0,
  140973. _vq_quantlist__44cn1_s_p7_1,
  140974. NULL,
  140975. &_vq_auxt__44cn1_s_p7_1,
  140976. NULL,
  140977. 0
  140978. };
  140979. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140980. 2,
  140981. 1,
  140982. 3,
  140983. 0,
  140984. 4,
  140985. };
  140986. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140987. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140988. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140989. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140990. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140991. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140992. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140993. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140994. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140995. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140996. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141000. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141002. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  141003. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141020. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  141021. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141022. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141023. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141024. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141025. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141026. 12,
  141027. };
  141028. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  141029. -331.5, -110.5, 110.5, 331.5,
  141030. };
  141031. static long _vq_quantmap__44cn1_s_p8_0[] = {
  141032. 3, 1, 0, 2, 4,
  141033. };
  141034. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  141035. _vq_quantthresh__44cn1_s_p8_0,
  141036. _vq_quantmap__44cn1_s_p8_0,
  141037. 5,
  141038. 5
  141039. };
  141040. static static_codebook _44cn1_s_p8_0 = {
  141041. 4, 625,
  141042. _vq_lengthlist__44cn1_s_p8_0,
  141043. 1, -518283264, 1627103232, 3, 0,
  141044. _vq_quantlist__44cn1_s_p8_0,
  141045. NULL,
  141046. &_vq_auxt__44cn1_s_p8_0,
  141047. NULL,
  141048. 0
  141049. };
  141050. static long _vq_quantlist__44cn1_s_p8_1[] = {
  141051. 6,
  141052. 5,
  141053. 7,
  141054. 4,
  141055. 8,
  141056. 3,
  141057. 9,
  141058. 2,
  141059. 10,
  141060. 1,
  141061. 11,
  141062. 0,
  141063. 12,
  141064. };
  141065. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  141066. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  141067. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  141068. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  141069. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  141070. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  141071. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  141072. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  141073. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  141074. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  141075. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  141076. 15,12,12,11,11,14,12,13,14,
  141077. };
  141078. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  141079. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141080. 42.5, 59.5, 76.5, 93.5,
  141081. };
  141082. static long _vq_quantmap__44cn1_s_p8_1[] = {
  141083. 11, 9, 7, 5, 3, 1, 0, 2,
  141084. 4, 6, 8, 10, 12,
  141085. };
  141086. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  141087. _vq_quantthresh__44cn1_s_p8_1,
  141088. _vq_quantmap__44cn1_s_p8_1,
  141089. 13,
  141090. 13
  141091. };
  141092. static static_codebook _44cn1_s_p8_1 = {
  141093. 2, 169,
  141094. _vq_lengthlist__44cn1_s_p8_1,
  141095. 1, -522616832, 1620115456, 4, 0,
  141096. _vq_quantlist__44cn1_s_p8_1,
  141097. NULL,
  141098. &_vq_auxt__44cn1_s_p8_1,
  141099. NULL,
  141100. 0
  141101. };
  141102. static long _vq_quantlist__44cn1_s_p8_2[] = {
  141103. 8,
  141104. 7,
  141105. 9,
  141106. 6,
  141107. 10,
  141108. 5,
  141109. 11,
  141110. 4,
  141111. 12,
  141112. 3,
  141113. 13,
  141114. 2,
  141115. 14,
  141116. 1,
  141117. 15,
  141118. 0,
  141119. 16,
  141120. };
  141121. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141122. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141123. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141124. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141125. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141126. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141127. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141128. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141129. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141130. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141131. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141132. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141133. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141134. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141135. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141136. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141137. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141138. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141139. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141140. 9,
  141141. };
  141142. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141143. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141144. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141145. };
  141146. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141147. 15, 13, 11, 9, 7, 5, 3, 1,
  141148. 0, 2, 4, 6, 8, 10, 12, 14,
  141149. 16,
  141150. };
  141151. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141152. _vq_quantthresh__44cn1_s_p8_2,
  141153. _vq_quantmap__44cn1_s_p8_2,
  141154. 17,
  141155. 17
  141156. };
  141157. static static_codebook _44cn1_s_p8_2 = {
  141158. 2, 289,
  141159. _vq_lengthlist__44cn1_s_p8_2,
  141160. 1, -529530880, 1611661312, 5, 0,
  141161. _vq_quantlist__44cn1_s_p8_2,
  141162. NULL,
  141163. &_vq_auxt__44cn1_s_p8_2,
  141164. NULL,
  141165. 0
  141166. };
  141167. static long _huff_lengthlist__44cn1_s_short[] = {
  141168. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141169. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141170. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141171. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141172. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141173. 10,
  141174. };
  141175. static static_codebook _huff_book__44cn1_s_short = {
  141176. 2, 81,
  141177. _huff_lengthlist__44cn1_s_short,
  141178. 0, 0, 0, 0, 0,
  141179. NULL,
  141180. NULL,
  141181. NULL,
  141182. NULL,
  141183. 0
  141184. };
  141185. static long _huff_lengthlist__44cn1_sm_long[] = {
  141186. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141187. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141188. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141189. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141190. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141191. 17,
  141192. };
  141193. static static_codebook _huff_book__44cn1_sm_long = {
  141194. 2, 81,
  141195. _huff_lengthlist__44cn1_sm_long,
  141196. 0, 0, 0, 0, 0,
  141197. NULL,
  141198. NULL,
  141199. NULL,
  141200. NULL,
  141201. 0
  141202. };
  141203. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141204. 1,
  141205. 0,
  141206. 2,
  141207. };
  141208. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141209. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141210. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141215. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141220. 0, 0, 0, 0, 8, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  141255. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  141260. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  141265. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141301. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141306. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141311. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141619. 0,
  141620. };
  141621. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141622. -0.5, 0.5,
  141623. };
  141624. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141625. 1, 0, 2,
  141626. };
  141627. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141628. _vq_quantthresh__44cn1_sm_p1_0,
  141629. _vq_quantmap__44cn1_sm_p1_0,
  141630. 3,
  141631. 3
  141632. };
  141633. static static_codebook _44cn1_sm_p1_0 = {
  141634. 8, 6561,
  141635. _vq_lengthlist__44cn1_sm_p1_0,
  141636. 1, -535822336, 1611661312, 2, 0,
  141637. _vq_quantlist__44cn1_sm_p1_0,
  141638. NULL,
  141639. &_vq_auxt__44cn1_sm_p1_0,
  141640. NULL,
  141641. 0
  141642. };
  141643. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141644. 2,
  141645. 1,
  141646. 3,
  141647. 0,
  141648. 4,
  141649. };
  141650. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141651. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141654. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141657. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141690. 0,
  141691. };
  141692. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141693. -1.5, -0.5, 0.5, 1.5,
  141694. };
  141695. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141696. 3, 1, 0, 2, 4,
  141697. };
  141698. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141699. _vq_quantthresh__44cn1_sm_p2_0,
  141700. _vq_quantmap__44cn1_sm_p2_0,
  141701. 5,
  141702. 5
  141703. };
  141704. static static_codebook _44cn1_sm_p2_0 = {
  141705. 4, 625,
  141706. _vq_lengthlist__44cn1_sm_p2_0,
  141707. 1, -533725184, 1611661312, 3, 0,
  141708. _vq_quantlist__44cn1_sm_p2_0,
  141709. NULL,
  141710. &_vq_auxt__44cn1_sm_p2_0,
  141711. NULL,
  141712. 0
  141713. };
  141714. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141715. 4,
  141716. 3,
  141717. 5,
  141718. 2,
  141719. 6,
  141720. 1,
  141721. 7,
  141722. 0,
  141723. 8,
  141724. };
  141725. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141726. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141727. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141728. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141729. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141730. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141731. 0,
  141732. };
  141733. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141734. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141735. };
  141736. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141737. 7, 5, 3, 1, 0, 2, 4, 6,
  141738. 8,
  141739. };
  141740. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141741. _vq_quantthresh__44cn1_sm_p3_0,
  141742. _vq_quantmap__44cn1_sm_p3_0,
  141743. 9,
  141744. 9
  141745. };
  141746. static static_codebook _44cn1_sm_p3_0 = {
  141747. 2, 81,
  141748. _vq_lengthlist__44cn1_sm_p3_0,
  141749. 1, -531628032, 1611661312, 4, 0,
  141750. _vq_quantlist__44cn1_sm_p3_0,
  141751. NULL,
  141752. &_vq_auxt__44cn1_sm_p3_0,
  141753. NULL,
  141754. 0
  141755. };
  141756. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141757. 4,
  141758. 3,
  141759. 5,
  141760. 2,
  141761. 6,
  141762. 1,
  141763. 7,
  141764. 0,
  141765. 8,
  141766. };
  141767. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141768. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141769. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141770. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141771. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141772. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141773. 11,
  141774. };
  141775. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141776. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141777. };
  141778. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141779. 7, 5, 3, 1, 0, 2, 4, 6,
  141780. 8,
  141781. };
  141782. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141783. _vq_quantthresh__44cn1_sm_p4_0,
  141784. _vq_quantmap__44cn1_sm_p4_0,
  141785. 9,
  141786. 9
  141787. };
  141788. static static_codebook _44cn1_sm_p4_0 = {
  141789. 2, 81,
  141790. _vq_lengthlist__44cn1_sm_p4_0,
  141791. 1, -531628032, 1611661312, 4, 0,
  141792. _vq_quantlist__44cn1_sm_p4_0,
  141793. NULL,
  141794. &_vq_auxt__44cn1_sm_p4_0,
  141795. NULL,
  141796. 0
  141797. };
  141798. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141799. 8,
  141800. 7,
  141801. 9,
  141802. 6,
  141803. 10,
  141804. 5,
  141805. 11,
  141806. 4,
  141807. 12,
  141808. 3,
  141809. 13,
  141810. 2,
  141811. 14,
  141812. 1,
  141813. 15,
  141814. 0,
  141815. 16,
  141816. };
  141817. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141818. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141819. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141820. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141821. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141822. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141823. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141824. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141825. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141826. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141827. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141828. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141829. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141830. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141831. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141832. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141833. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141834. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141835. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141836. 14,
  141837. };
  141838. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141839. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141840. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141841. };
  141842. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141843. 15, 13, 11, 9, 7, 5, 3, 1,
  141844. 0, 2, 4, 6, 8, 10, 12, 14,
  141845. 16,
  141846. };
  141847. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141848. _vq_quantthresh__44cn1_sm_p5_0,
  141849. _vq_quantmap__44cn1_sm_p5_0,
  141850. 17,
  141851. 17
  141852. };
  141853. static static_codebook _44cn1_sm_p5_0 = {
  141854. 2, 289,
  141855. _vq_lengthlist__44cn1_sm_p5_0,
  141856. 1, -529530880, 1611661312, 5, 0,
  141857. _vq_quantlist__44cn1_sm_p5_0,
  141858. NULL,
  141859. &_vq_auxt__44cn1_sm_p5_0,
  141860. NULL,
  141861. 0
  141862. };
  141863. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141864. 1,
  141865. 0,
  141866. 2,
  141867. };
  141868. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141869. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141870. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141871. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141872. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141873. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141874. 10,
  141875. };
  141876. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141877. -5.5, 5.5,
  141878. };
  141879. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141880. 1, 0, 2,
  141881. };
  141882. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141883. _vq_quantthresh__44cn1_sm_p6_0,
  141884. _vq_quantmap__44cn1_sm_p6_0,
  141885. 3,
  141886. 3
  141887. };
  141888. static static_codebook _44cn1_sm_p6_0 = {
  141889. 4, 81,
  141890. _vq_lengthlist__44cn1_sm_p6_0,
  141891. 1, -529137664, 1618345984, 2, 0,
  141892. _vq_quantlist__44cn1_sm_p6_0,
  141893. NULL,
  141894. &_vq_auxt__44cn1_sm_p6_0,
  141895. NULL,
  141896. 0
  141897. };
  141898. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141899. 5,
  141900. 4,
  141901. 6,
  141902. 3,
  141903. 7,
  141904. 2,
  141905. 8,
  141906. 1,
  141907. 9,
  141908. 0,
  141909. 10,
  141910. };
  141911. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141912. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141913. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141914. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141915. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141916. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141917. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141918. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141919. 10,10,10, 8, 9, 8, 8, 9, 8,
  141920. };
  141921. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141922. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141923. 3.5, 4.5,
  141924. };
  141925. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141926. 9, 7, 5, 3, 1, 0, 2, 4,
  141927. 6, 8, 10,
  141928. };
  141929. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141930. _vq_quantthresh__44cn1_sm_p6_1,
  141931. _vq_quantmap__44cn1_sm_p6_1,
  141932. 11,
  141933. 11
  141934. };
  141935. static static_codebook _44cn1_sm_p6_1 = {
  141936. 2, 121,
  141937. _vq_lengthlist__44cn1_sm_p6_1,
  141938. 1, -531365888, 1611661312, 4, 0,
  141939. _vq_quantlist__44cn1_sm_p6_1,
  141940. NULL,
  141941. &_vq_auxt__44cn1_sm_p6_1,
  141942. NULL,
  141943. 0
  141944. };
  141945. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141946. 6,
  141947. 5,
  141948. 7,
  141949. 4,
  141950. 8,
  141951. 3,
  141952. 9,
  141953. 2,
  141954. 10,
  141955. 1,
  141956. 11,
  141957. 0,
  141958. 12,
  141959. };
  141960. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141961. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141962. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141963. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141964. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141965. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141966. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141967. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141968. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141969. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141970. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141971. 0,13,12,12,12,13,13,13,14,
  141972. };
  141973. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141974. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141975. 12.5, 17.5, 22.5, 27.5,
  141976. };
  141977. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141978. 11, 9, 7, 5, 3, 1, 0, 2,
  141979. 4, 6, 8, 10, 12,
  141980. };
  141981. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141982. _vq_quantthresh__44cn1_sm_p7_0,
  141983. _vq_quantmap__44cn1_sm_p7_0,
  141984. 13,
  141985. 13
  141986. };
  141987. static static_codebook _44cn1_sm_p7_0 = {
  141988. 2, 169,
  141989. _vq_lengthlist__44cn1_sm_p7_0,
  141990. 1, -526516224, 1616117760, 4, 0,
  141991. _vq_quantlist__44cn1_sm_p7_0,
  141992. NULL,
  141993. &_vq_auxt__44cn1_sm_p7_0,
  141994. NULL,
  141995. 0
  141996. };
  141997. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141998. 2,
  141999. 1,
  142000. 3,
  142001. 0,
  142002. 4,
  142003. };
  142004. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  142005. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  142006. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  142007. };
  142008. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  142009. -1.5, -0.5, 0.5, 1.5,
  142010. };
  142011. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  142012. 3, 1, 0, 2, 4,
  142013. };
  142014. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  142015. _vq_quantthresh__44cn1_sm_p7_1,
  142016. _vq_quantmap__44cn1_sm_p7_1,
  142017. 5,
  142018. 5
  142019. };
  142020. static static_codebook _44cn1_sm_p7_1 = {
  142021. 2, 25,
  142022. _vq_lengthlist__44cn1_sm_p7_1,
  142023. 1, -533725184, 1611661312, 3, 0,
  142024. _vq_quantlist__44cn1_sm_p7_1,
  142025. NULL,
  142026. &_vq_auxt__44cn1_sm_p7_1,
  142027. NULL,
  142028. 0
  142029. };
  142030. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  142031. 4,
  142032. 3,
  142033. 5,
  142034. 2,
  142035. 6,
  142036. 1,
  142037. 7,
  142038. 0,
  142039. 8,
  142040. };
  142041. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  142042. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  142043. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  142044. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  142045. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  142046. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  142047. 14,
  142048. };
  142049. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  142050. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  142051. };
  142052. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  142053. 7, 5, 3, 1, 0, 2, 4, 6,
  142054. 8,
  142055. };
  142056. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  142057. _vq_quantthresh__44cn1_sm_p8_0,
  142058. _vq_quantmap__44cn1_sm_p8_0,
  142059. 9,
  142060. 9
  142061. };
  142062. static static_codebook _44cn1_sm_p8_0 = {
  142063. 2, 81,
  142064. _vq_lengthlist__44cn1_sm_p8_0,
  142065. 1, -516186112, 1627103232, 4, 0,
  142066. _vq_quantlist__44cn1_sm_p8_0,
  142067. NULL,
  142068. &_vq_auxt__44cn1_sm_p8_0,
  142069. NULL,
  142070. 0
  142071. };
  142072. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  142073. 6,
  142074. 5,
  142075. 7,
  142076. 4,
  142077. 8,
  142078. 3,
  142079. 9,
  142080. 2,
  142081. 10,
  142082. 1,
  142083. 11,
  142084. 0,
  142085. 12,
  142086. };
  142087. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  142088. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  142089. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  142090. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  142091. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  142092. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  142093. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  142094. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  142095. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  142096. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  142097. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  142098. 17,12,12,11,10,13,11,13,13,
  142099. };
  142100. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  142101. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  142102. 42.5, 59.5, 76.5, 93.5,
  142103. };
  142104. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  142105. 11, 9, 7, 5, 3, 1, 0, 2,
  142106. 4, 6, 8, 10, 12,
  142107. };
  142108. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142109. _vq_quantthresh__44cn1_sm_p8_1,
  142110. _vq_quantmap__44cn1_sm_p8_1,
  142111. 13,
  142112. 13
  142113. };
  142114. static static_codebook _44cn1_sm_p8_1 = {
  142115. 2, 169,
  142116. _vq_lengthlist__44cn1_sm_p8_1,
  142117. 1, -522616832, 1620115456, 4, 0,
  142118. _vq_quantlist__44cn1_sm_p8_1,
  142119. NULL,
  142120. &_vq_auxt__44cn1_sm_p8_1,
  142121. NULL,
  142122. 0
  142123. };
  142124. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142125. 8,
  142126. 7,
  142127. 9,
  142128. 6,
  142129. 10,
  142130. 5,
  142131. 11,
  142132. 4,
  142133. 12,
  142134. 3,
  142135. 13,
  142136. 2,
  142137. 14,
  142138. 1,
  142139. 15,
  142140. 0,
  142141. 16,
  142142. };
  142143. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142144. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142145. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142146. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142147. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142148. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142149. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142150. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142151. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142152. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142153. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142154. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142155. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142156. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142157. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142158. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142159. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142160. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142161. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142162. 9,
  142163. };
  142164. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142165. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142166. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142167. };
  142168. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142169. 15, 13, 11, 9, 7, 5, 3, 1,
  142170. 0, 2, 4, 6, 8, 10, 12, 14,
  142171. 16,
  142172. };
  142173. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142174. _vq_quantthresh__44cn1_sm_p8_2,
  142175. _vq_quantmap__44cn1_sm_p8_2,
  142176. 17,
  142177. 17
  142178. };
  142179. static static_codebook _44cn1_sm_p8_2 = {
  142180. 2, 289,
  142181. _vq_lengthlist__44cn1_sm_p8_2,
  142182. 1, -529530880, 1611661312, 5, 0,
  142183. _vq_quantlist__44cn1_sm_p8_2,
  142184. NULL,
  142185. &_vq_auxt__44cn1_sm_p8_2,
  142186. NULL,
  142187. 0
  142188. };
  142189. static long _huff_lengthlist__44cn1_sm_short[] = {
  142190. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142191. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142192. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142193. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142194. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142195. 9,
  142196. };
  142197. static static_codebook _huff_book__44cn1_sm_short = {
  142198. 2, 81,
  142199. _huff_lengthlist__44cn1_sm_short,
  142200. 0, 0, 0, 0, 0,
  142201. NULL,
  142202. NULL,
  142203. NULL,
  142204. NULL,
  142205. 0
  142206. };
  142207. /*** End of inlined file: res_books_stereo.h ***/
  142208. /***** residue backends *********************************************/
  142209. static vorbis_info_residue0 _residue_44_low={
  142210. 0,-1, -1, 9,-1,
  142211. /* 0 1 2 3 4 5 6 7 */
  142212. {0},
  142213. {-1},
  142214. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142215. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142216. };
  142217. static vorbis_info_residue0 _residue_44_mid={
  142218. 0,-1, -1, 10,-1,
  142219. /* 0 1 2 3 4 5 6 7 8 */
  142220. {0},
  142221. {-1},
  142222. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142223. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142224. };
  142225. static vorbis_info_residue0 _residue_44_high={
  142226. 0,-1, -1, 10,-1,
  142227. /* 0 1 2 3 4 5 6 7 8 */
  142228. {0},
  142229. {-1},
  142230. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142231. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142232. };
  142233. static static_bookblock _resbook_44s_n1={
  142234. {
  142235. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142236. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142237. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142238. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142239. }
  142240. };
  142241. static static_bookblock _resbook_44sm_n1={
  142242. {
  142243. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142244. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142245. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142246. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142247. }
  142248. };
  142249. static static_bookblock _resbook_44s_0={
  142250. {
  142251. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142252. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142253. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142254. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142255. }
  142256. };
  142257. static static_bookblock _resbook_44sm_0={
  142258. {
  142259. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142260. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142261. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142262. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142263. }
  142264. };
  142265. static static_bookblock _resbook_44s_1={
  142266. {
  142267. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142268. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142269. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142270. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142271. }
  142272. };
  142273. static static_bookblock _resbook_44sm_1={
  142274. {
  142275. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142276. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142277. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142278. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142279. }
  142280. };
  142281. static static_bookblock _resbook_44s_2={
  142282. {
  142283. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142284. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142285. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142286. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142287. }
  142288. };
  142289. static static_bookblock _resbook_44s_3={
  142290. {
  142291. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142292. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142293. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142294. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142295. }
  142296. };
  142297. static static_bookblock _resbook_44s_4={
  142298. {
  142299. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142300. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142301. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142302. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142303. }
  142304. };
  142305. static static_bookblock _resbook_44s_5={
  142306. {
  142307. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142308. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142309. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142310. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142311. }
  142312. };
  142313. static static_bookblock _resbook_44s_6={
  142314. {
  142315. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142316. {0,0,&_44c6_s_p4_0},
  142317. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142318. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142319. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142320. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142321. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142322. }
  142323. };
  142324. static static_bookblock _resbook_44s_7={
  142325. {
  142326. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142327. {0,0,&_44c7_s_p4_0},
  142328. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142329. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142330. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142331. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142332. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142333. }
  142334. };
  142335. static static_bookblock _resbook_44s_8={
  142336. {
  142337. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142338. {0,0,&_44c8_s_p4_0},
  142339. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142340. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142341. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142342. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142343. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142344. }
  142345. };
  142346. static static_bookblock _resbook_44s_9={
  142347. {
  142348. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142349. {0,0,&_44c9_s_p4_0},
  142350. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142351. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142352. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142353. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142354. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142355. }
  142356. };
  142357. static vorbis_residue_template _res_44s_n1[]={
  142358. {2,0, &_residue_44_low,
  142359. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142360. &_resbook_44s_n1,&_resbook_44sm_n1},
  142361. {2,0, &_residue_44_low,
  142362. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142363. &_resbook_44s_n1,&_resbook_44sm_n1}
  142364. };
  142365. static vorbis_residue_template _res_44s_0[]={
  142366. {2,0, &_residue_44_low,
  142367. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142368. &_resbook_44s_0,&_resbook_44sm_0},
  142369. {2,0, &_residue_44_low,
  142370. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142371. &_resbook_44s_0,&_resbook_44sm_0}
  142372. };
  142373. static vorbis_residue_template _res_44s_1[]={
  142374. {2,0, &_residue_44_low,
  142375. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142376. &_resbook_44s_1,&_resbook_44sm_1},
  142377. {2,0, &_residue_44_low,
  142378. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142379. &_resbook_44s_1,&_resbook_44sm_1}
  142380. };
  142381. static vorbis_residue_template _res_44s_2[]={
  142382. {2,0, &_residue_44_mid,
  142383. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142384. &_resbook_44s_2,&_resbook_44s_2},
  142385. {2,0, &_residue_44_mid,
  142386. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142387. &_resbook_44s_2,&_resbook_44s_2}
  142388. };
  142389. static vorbis_residue_template _res_44s_3[]={
  142390. {2,0, &_residue_44_mid,
  142391. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142392. &_resbook_44s_3,&_resbook_44s_3},
  142393. {2,0, &_residue_44_mid,
  142394. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142395. &_resbook_44s_3,&_resbook_44s_3}
  142396. };
  142397. static vorbis_residue_template _res_44s_4[]={
  142398. {2,0, &_residue_44_mid,
  142399. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142400. &_resbook_44s_4,&_resbook_44s_4},
  142401. {2,0, &_residue_44_mid,
  142402. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142403. &_resbook_44s_4,&_resbook_44s_4}
  142404. };
  142405. static vorbis_residue_template _res_44s_5[]={
  142406. {2,0, &_residue_44_mid,
  142407. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142408. &_resbook_44s_5,&_resbook_44s_5},
  142409. {2,0, &_residue_44_mid,
  142410. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142411. &_resbook_44s_5,&_resbook_44s_5}
  142412. };
  142413. static vorbis_residue_template _res_44s_6[]={
  142414. {2,0, &_residue_44_high,
  142415. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142416. &_resbook_44s_6,&_resbook_44s_6},
  142417. {2,0, &_residue_44_high,
  142418. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142419. &_resbook_44s_6,&_resbook_44s_6}
  142420. };
  142421. static vorbis_residue_template _res_44s_7[]={
  142422. {2,0, &_residue_44_high,
  142423. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142424. &_resbook_44s_7,&_resbook_44s_7},
  142425. {2,0, &_residue_44_high,
  142426. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142427. &_resbook_44s_7,&_resbook_44s_7}
  142428. };
  142429. static vorbis_residue_template _res_44s_8[]={
  142430. {2,0, &_residue_44_high,
  142431. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142432. &_resbook_44s_8,&_resbook_44s_8},
  142433. {2,0, &_residue_44_high,
  142434. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142435. &_resbook_44s_8,&_resbook_44s_8}
  142436. };
  142437. static vorbis_residue_template _res_44s_9[]={
  142438. {2,0, &_residue_44_high,
  142439. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142440. &_resbook_44s_9,&_resbook_44s_9},
  142441. {2,0, &_residue_44_high,
  142442. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142443. &_resbook_44s_9,&_resbook_44s_9}
  142444. };
  142445. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142446. { _map_nominal, _res_44s_n1 }, /* -1 */
  142447. { _map_nominal, _res_44s_0 }, /* 0 */
  142448. { _map_nominal, _res_44s_1 }, /* 1 */
  142449. { _map_nominal, _res_44s_2 }, /* 2 */
  142450. { _map_nominal, _res_44s_3 }, /* 3 */
  142451. { _map_nominal, _res_44s_4 }, /* 4 */
  142452. { _map_nominal, _res_44s_5 }, /* 5 */
  142453. { _map_nominal, _res_44s_6 }, /* 6 */
  142454. { _map_nominal, _res_44s_7 }, /* 7 */
  142455. { _map_nominal, _res_44s_8 }, /* 8 */
  142456. { _map_nominal, _res_44s_9 }, /* 9 */
  142457. };
  142458. /*** End of inlined file: residue_44.h ***/
  142459. /*** Start of inlined file: psych_44.h ***/
  142460. /* preecho trigger settings *****************************************/
  142461. static vorbis_info_psy_global _psy_global_44[5]={
  142462. {8, /* lines per eighth octave */
  142463. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142464. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142465. -6.f,
  142466. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142467. },
  142468. {8, /* lines per eighth octave */
  142469. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142470. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142471. -6.f,
  142472. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142473. },
  142474. {8, /* lines per eighth octave */
  142475. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142476. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142477. -6.f,
  142478. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142479. },
  142480. {8, /* lines per eighth octave */
  142481. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142482. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142483. -6.f,
  142484. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142485. },
  142486. {8, /* lines per eighth octave */
  142487. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142488. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142489. -6.f,
  142490. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142491. },
  142492. };
  142493. /* noise compander lookups * low, mid, high quality ****************/
  142494. static compandblock _psy_compand_44[6]={
  142495. /* sub-mode Z short */
  142496. {{
  142497. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142498. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142499. 16,17,18,19,20,21,22, 23, /* 23dB */
  142500. 24,25,26,27,28,29,30, 31, /* 31dB */
  142501. 32,33,34,35,36,37,38, 39, /* 39dB */
  142502. }},
  142503. /* mode_Z nominal short */
  142504. {{
  142505. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142506. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142507. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142508. 15,16,17,17,17,18,18, 19, /* 31dB */
  142509. 19,19,20,21,22,23,24, 25, /* 39dB */
  142510. }},
  142511. /* mode A short */
  142512. {{
  142513. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142514. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142515. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142516. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142517. 11,12,13,14,15,16,17, 18, /* 39dB */
  142518. }},
  142519. /* sub-mode Z long */
  142520. {{
  142521. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142522. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142523. 16,17,18,19,20,21,22, 23, /* 23dB */
  142524. 24,25,26,27,28,29,30, 31, /* 31dB */
  142525. 32,33,34,35,36,37,38, 39, /* 39dB */
  142526. }},
  142527. /* mode_Z nominal long */
  142528. {{
  142529. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142530. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142531. 13,14,14,14,15,15,15, 15, /* 23dB */
  142532. 16,16,17,17,17,18,18, 19, /* 31dB */
  142533. 19,19,20,21,22,23,24, 25, /* 39dB */
  142534. }},
  142535. /* mode A long */
  142536. {{
  142537. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142538. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142539. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142540. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142541. 11,12,13,14,15,16,17, 18, /* 39dB */
  142542. }}
  142543. };
  142544. /* tonal masking curve level adjustments *************************/
  142545. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142546. /* 63 125 250 500 1 2 4 8 16 */
  142547. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142548. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142549. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142550. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142551. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142552. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142553. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142554. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142555. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142556. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142557. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142558. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142559. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142560. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142561. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142562. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142563. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142564. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142565. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142566. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142567. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142568. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142569. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142570. };
  142571. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142572. /* 63 125 250 500 1 2 4 8 16 */
  142573. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142574. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142575. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142576. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142577. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142578. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142579. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142580. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142581. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142582. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142583. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142584. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142585. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142586. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142587. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142588. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142589. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142590. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142591. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142592. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142593. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142594. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142595. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142596. };
  142597. /* noise bias (transition block) */
  142598. static noise3 _psy_noisebias_trans[12]={
  142599. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142600. /* -1 */
  142601. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142602. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142603. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142604. /* 0
  142605. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142606. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142607. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142608. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142609. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142610. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142611. /* 1
  142612. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142613. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142614. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142615. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142616. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142617. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142618. /* 2
  142619. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142620. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142621. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142622. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142623. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142624. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142625. /* 3
  142626. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142627. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142628. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142629. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142630. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142631. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142632. /* 4
  142633. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142634. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142635. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142636. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142637. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142638. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142639. /* 5
  142640. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142641. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142642. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142643. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142644. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142645. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142646. /* 6
  142647. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142648. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142649. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142650. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142651. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142652. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142653. /* 7
  142654. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142655. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142656. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142657. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142658. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142659. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142660. /* 8
  142661. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142662. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142663. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142664. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142665. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142666. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142667. /* 9
  142668. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142669. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142670. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142671. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142672. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142673. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142674. /* 10 */
  142675. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142676. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142677. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142678. };
  142679. /* noise bias (long block) */
  142680. static noise3 _psy_noisebias_long[12]={
  142681. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142682. /* -1 */
  142683. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142684. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142685. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142686. /* 0 */
  142687. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142688. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142689. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142690. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142691. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142692. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142693. /* 1 */
  142694. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142695. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142696. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142697. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142698. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142699. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142700. /* 2 */
  142701. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142702. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142703. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142704. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142705. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142706. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142707. /* 3 */
  142708. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142709. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142710. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142711. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142712. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142713. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142714. /* 4 */
  142715. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142716. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142717. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142718. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142719. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142720. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142721. /* 5 */
  142722. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142723. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142724. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142725. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142726. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142727. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142728. /* 6 */
  142729. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142730. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142731. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142732. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142733. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142734. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142735. /* 7 */
  142736. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142737. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142738. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142739. /* 8 */
  142740. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142741. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142742. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142743. /* 9 */
  142744. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142745. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142746. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142747. /* 10 */
  142748. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142749. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142750. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142751. };
  142752. /* noise bias (impulse block) */
  142753. static noise3 _psy_noisebias_impulse[12]={
  142754. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142755. /* -1 */
  142756. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142757. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142758. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142759. /* 0 */
  142760. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142761. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142762. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142763. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142764. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142765. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142766. /* 1 */
  142767. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142768. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142769. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142770. /* 2 */
  142771. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142772. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142773. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142774. /* 3 */
  142775. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142776. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142777. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142778. /* 4 */
  142779. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142780. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142781. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142782. /* 5 */
  142783. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142784. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142785. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142786. /* 6
  142787. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142788. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142789. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142790. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142791. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142792. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142793. /* 7 */
  142794. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142795. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142796. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142797. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142798. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142799. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142800. /* 8 */
  142801. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142802. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142803. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142804. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142805. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142806. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142807. /* 9 */
  142808. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142809. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142810. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142811. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142812. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142813. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142814. /* 10 */
  142815. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142816. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142817. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142818. };
  142819. /* noise bias (padding block) */
  142820. static noise3 _psy_noisebias_padding[12]={
  142821. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142822. /* -1 */
  142823. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142824. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142825. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142826. /* 0 */
  142827. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142828. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142829. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142830. /* 1 */
  142831. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142832. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142833. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142834. /* 2 */
  142835. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142836. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142837. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142838. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142839. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142840. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142841. /* 3 */
  142842. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142843. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142844. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142845. /* 4 */
  142846. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142847. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142848. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142849. /* 5 */
  142850. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142851. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142852. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142853. /* 6 */
  142854. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142855. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142856. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142857. /* 7 */
  142858. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142859. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142860. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142861. /* 8 */
  142862. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142863. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142864. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142865. /* 9 */
  142866. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142867. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142868. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142869. /* 10 */
  142870. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142871. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142872. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142873. };
  142874. static noiseguard _psy_noiseguards_44[4]={
  142875. {3,3,15},
  142876. {3,3,15},
  142877. {10,10,100},
  142878. {10,10,100},
  142879. };
  142880. static int _psy_tone_suppress[12]={
  142881. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142882. };
  142883. static int _psy_tone_0dB[12]={
  142884. 90,90,95,95,95,95,105,105,105,105,105,105,
  142885. };
  142886. static int _psy_noise_suppress[12]={
  142887. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142888. };
  142889. static vorbis_info_psy _psy_info_template={
  142890. /* blockflag */
  142891. -1,
  142892. /* ath_adjatt, ath_maxatt */
  142893. -140.,-140.,
  142894. /* tonemask att boost/decay,suppr,curves */
  142895. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142896. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142897. 1, -0.f, .5f, .5f, 0,0,0,
  142898. /* noiseoffset*3, noisecompand, max_curve_dB */
  142899. {{-1},{-1},{-1}},{-1},105.f,
  142900. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142901. 0,0,-1,-1,0.,
  142902. };
  142903. /* ath ****************/
  142904. static int _psy_ath_floater[12]={
  142905. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142906. };
  142907. static int _psy_ath_abs[12]={
  142908. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142909. };
  142910. /* stereo setup. These don't map directly to quality level, there's
  142911. an additional indirection as several of the below may be used in a
  142912. single bitmanaged stream
  142913. ****************/
  142914. /* various stereo possibilities */
  142915. /* stereo mode by base quality level */
  142916. static adj_stereo _psy_stereo_modes_44[12]={
  142917. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142918. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142919. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142920. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142921. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142922. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142923. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142924. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142925. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142926. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142927. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142928. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142929. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142930. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142931. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142932. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142933. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142934. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142935. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142936. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142937. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142938. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142939. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142940. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142941. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142942. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142943. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142944. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142945. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142946. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142947. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142948. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142949. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142950. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142951. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142952. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142953. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142954. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142955. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142956. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142957. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142958. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142959. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142960. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142961. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142962. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142963. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142964. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142965. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142966. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142967. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142968. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142969. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142970. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142971. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142972. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142973. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142974. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142975. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142976. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142977. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142978. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142979. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142980. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142981. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142982. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142983. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142984. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142985. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142986. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142987. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142988. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142989. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142990. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142991. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142992. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142993. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142994. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142995. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142996. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142997. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142998. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142999. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143000. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143001. };
  143002. /* tone master attenuation by base quality mode and bitrate tweak */
  143003. static att3 _psy_tone_masteratt_44[12]={
  143004. {{ 35, 21, 9}, 0, 0}, /* -1 */
  143005. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  143006. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  143007. {{ 25, 12, 2}, 0, 0}, /* 1 */
  143008. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  143009. {{ 20, 9, -3}, 0, 0}, /* 2 */
  143010. {{ 20, 9, -4}, 0, 0}, /* 3 */
  143011. {{ 20, 9, -4}, 0, 0}, /* 4 */
  143012. {{ 20, 6, -6}, 0, 0}, /* 5 */
  143013. {{ 20, 3, -10}, 0, 0}, /* 6 */
  143014. {{ 18, 1, -14}, 0, 0}, /* 7 */
  143015. {{ 18, 0, -16}, 0, 0}, /* 8 */
  143016. {{ 18, -2, -16}, 0, 0}, /* 9 */
  143017. {{ 12, -2, -20}, 0, 0}, /* 10 */
  143018. };
  143019. /* lowpass by mode **************/
  143020. static double _psy_lowpass_44[12]={
  143021. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  143022. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  143023. };
  143024. /* noise normalization **********/
  143025. static int _noise_start_short_44[11]={
  143026. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  143027. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  143028. };
  143029. static int _noise_start_long_44[11]={
  143030. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  143031. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  143032. };
  143033. static int _noise_part_short_44[11]={
  143034. 8,8,8,8,8,8,8,8,8,8,8
  143035. };
  143036. static int _noise_part_long_44[11]={
  143037. 32,32,32,32,32,32,32,32,32,32,32
  143038. };
  143039. static double _noise_thresh_44[11]={
  143040. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  143041. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  143042. };
  143043. static double _noise_thresh_5only[2]={
  143044. .5,.5,
  143045. };
  143046. /*** End of inlined file: psych_44.h ***/
  143047. static double rate_mapping_44_stereo[12]={
  143048. 22500.,32000.,40000.,48000.,56000.,64000.,
  143049. 80000.,96000.,112000.,128000.,160000.,250001.
  143050. };
  143051. static double quality_mapping_44[12]={
  143052. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  143053. };
  143054. static int blocksize_short_44[11]={
  143055. 512,256,256,256,256,256,256,256,256,256,256
  143056. };
  143057. static int blocksize_long_44[11]={
  143058. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  143059. };
  143060. static double _psy_compand_short_mapping[12]={
  143061. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  143062. };
  143063. static double _psy_compand_long_mapping[12]={
  143064. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  143065. };
  143066. static double _global_mapping_44[12]={
  143067. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  143068. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  143069. };
  143070. static int _floor_short_mapping_44[11]={
  143071. 1,0,0,2,2,4,5,5,5,5,5
  143072. };
  143073. static int _floor_long_mapping_44[11]={
  143074. 8,7,7,7,7,7,7,7,7,7,7
  143075. };
  143076. ve_setup_data_template ve_setup_44_stereo={
  143077. 11,
  143078. rate_mapping_44_stereo,
  143079. quality_mapping_44,
  143080. 2,
  143081. 40000,
  143082. 50000,
  143083. blocksize_short_44,
  143084. blocksize_long_44,
  143085. _psy_tone_masteratt_44,
  143086. _psy_tone_0dB,
  143087. _psy_tone_suppress,
  143088. _vp_tonemask_adj_otherblock,
  143089. _vp_tonemask_adj_longblock,
  143090. _vp_tonemask_adj_otherblock,
  143091. _psy_noiseguards_44,
  143092. _psy_noisebias_impulse,
  143093. _psy_noisebias_padding,
  143094. _psy_noisebias_trans,
  143095. _psy_noisebias_long,
  143096. _psy_noise_suppress,
  143097. _psy_compand_44,
  143098. _psy_compand_short_mapping,
  143099. _psy_compand_long_mapping,
  143100. {_noise_start_short_44,_noise_start_long_44},
  143101. {_noise_part_short_44,_noise_part_long_44},
  143102. _noise_thresh_44,
  143103. _psy_ath_floater,
  143104. _psy_ath_abs,
  143105. _psy_lowpass_44,
  143106. _psy_global_44,
  143107. _global_mapping_44,
  143108. _psy_stereo_modes_44,
  143109. _floor_books,
  143110. _floor,
  143111. _floor_short_mapping_44,
  143112. _floor_long_mapping_44,
  143113. _mapres_template_44_stereo
  143114. };
  143115. /*** End of inlined file: setup_44.h ***/
  143116. /*** Start of inlined file: setup_44u.h ***/
  143117. /*** Start of inlined file: residue_44u.h ***/
  143118. /*** Start of inlined file: res_books_uncoupled.h ***/
  143119. static long _vq_quantlist__16u0__p1_0[] = {
  143120. 1,
  143121. 0,
  143122. 2,
  143123. };
  143124. static long _vq_lengthlist__16u0__p1_0[] = {
  143125. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143126. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143127. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143128. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143129. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143130. 12,
  143131. };
  143132. static float _vq_quantthresh__16u0__p1_0[] = {
  143133. -0.5, 0.5,
  143134. };
  143135. static long _vq_quantmap__16u0__p1_0[] = {
  143136. 1, 0, 2,
  143137. };
  143138. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143139. _vq_quantthresh__16u0__p1_0,
  143140. _vq_quantmap__16u0__p1_0,
  143141. 3,
  143142. 3
  143143. };
  143144. static static_codebook _16u0__p1_0 = {
  143145. 4, 81,
  143146. _vq_lengthlist__16u0__p1_0,
  143147. 1, -535822336, 1611661312, 2, 0,
  143148. _vq_quantlist__16u0__p1_0,
  143149. NULL,
  143150. &_vq_auxt__16u0__p1_0,
  143151. NULL,
  143152. 0
  143153. };
  143154. static long _vq_quantlist__16u0__p2_0[] = {
  143155. 1,
  143156. 0,
  143157. 2,
  143158. };
  143159. static long _vq_lengthlist__16u0__p2_0[] = {
  143160. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143161. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143162. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143163. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143164. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143165. 8,
  143166. };
  143167. static float _vq_quantthresh__16u0__p2_0[] = {
  143168. -0.5, 0.5,
  143169. };
  143170. static long _vq_quantmap__16u0__p2_0[] = {
  143171. 1, 0, 2,
  143172. };
  143173. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143174. _vq_quantthresh__16u0__p2_0,
  143175. _vq_quantmap__16u0__p2_0,
  143176. 3,
  143177. 3
  143178. };
  143179. static static_codebook _16u0__p2_0 = {
  143180. 4, 81,
  143181. _vq_lengthlist__16u0__p2_0,
  143182. 1, -535822336, 1611661312, 2, 0,
  143183. _vq_quantlist__16u0__p2_0,
  143184. NULL,
  143185. &_vq_auxt__16u0__p2_0,
  143186. NULL,
  143187. 0
  143188. };
  143189. static long _vq_quantlist__16u0__p3_0[] = {
  143190. 2,
  143191. 1,
  143192. 3,
  143193. 0,
  143194. 4,
  143195. };
  143196. static long _vq_lengthlist__16u0__p3_0[] = {
  143197. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143198. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143199. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143200. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143201. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143202. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143203. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143204. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143205. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143206. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143207. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143208. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143209. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143210. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143211. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143212. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143213. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143214. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143215. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143216. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143217. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143218. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143219. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143220. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143221. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143222. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143223. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143224. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143225. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143226. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143227. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143228. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143229. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143230. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143231. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143232. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143233. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143234. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143235. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143236. 18,
  143237. };
  143238. static float _vq_quantthresh__16u0__p3_0[] = {
  143239. -1.5, -0.5, 0.5, 1.5,
  143240. };
  143241. static long _vq_quantmap__16u0__p3_0[] = {
  143242. 3, 1, 0, 2, 4,
  143243. };
  143244. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143245. _vq_quantthresh__16u0__p3_0,
  143246. _vq_quantmap__16u0__p3_0,
  143247. 5,
  143248. 5
  143249. };
  143250. static static_codebook _16u0__p3_0 = {
  143251. 4, 625,
  143252. _vq_lengthlist__16u0__p3_0,
  143253. 1, -533725184, 1611661312, 3, 0,
  143254. _vq_quantlist__16u0__p3_0,
  143255. NULL,
  143256. &_vq_auxt__16u0__p3_0,
  143257. NULL,
  143258. 0
  143259. };
  143260. static long _vq_quantlist__16u0__p4_0[] = {
  143261. 2,
  143262. 1,
  143263. 3,
  143264. 0,
  143265. 4,
  143266. };
  143267. static long _vq_lengthlist__16u0__p4_0[] = {
  143268. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143269. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143270. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143271. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143272. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143273. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143274. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143275. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143276. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143277. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143278. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143279. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143280. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143281. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143282. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143283. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143284. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143285. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143286. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143287. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143288. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143289. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143290. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143291. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143292. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143293. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143294. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143295. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143296. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143297. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143298. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143299. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143300. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143301. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143302. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143303. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143304. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143305. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143306. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143307. 11,
  143308. };
  143309. static float _vq_quantthresh__16u0__p4_0[] = {
  143310. -1.5, -0.5, 0.5, 1.5,
  143311. };
  143312. static long _vq_quantmap__16u0__p4_0[] = {
  143313. 3, 1, 0, 2, 4,
  143314. };
  143315. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143316. _vq_quantthresh__16u0__p4_0,
  143317. _vq_quantmap__16u0__p4_0,
  143318. 5,
  143319. 5
  143320. };
  143321. static static_codebook _16u0__p4_0 = {
  143322. 4, 625,
  143323. _vq_lengthlist__16u0__p4_0,
  143324. 1, -533725184, 1611661312, 3, 0,
  143325. _vq_quantlist__16u0__p4_0,
  143326. NULL,
  143327. &_vq_auxt__16u0__p4_0,
  143328. NULL,
  143329. 0
  143330. };
  143331. static long _vq_quantlist__16u0__p5_0[] = {
  143332. 4,
  143333. 3,
  143334. 5,
  143335. 2,
  143336. 6,
  143337. 1,
  143338. 7,
  143339. 0,
  143340. 8,
  143341. };
  143342. static long _vq_lengthlist__16u0__p5_0[] = {
  143343. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143344. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143345. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143346. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143347. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143348. 12,
  143349. };
  143350. static float _vq_quantthresh__16u0__p5_0[] = {
  143351. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143352. };
  143353. static long _vq_quantmap__16u0__p5_0[] = {
  143354. 7, 5, 3, 1, 0, 2, 4, 6,
  143355. 8,
  143356. };
  143357. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143358. _vq_quantthresh__16u0__p5_0,
  143359. _vq_quantmap__16u0__p5_0,
  143360. 9,
  143361. 9
  143362. };
  143363. static static_codebook _16u0__p5_0 = {
  143364. 2, 81,
  143365. _vq_lengthlist__16u0__p5_0,
  143366. 1, -531628032, 1611661312, 4, 0,
  143367. _vq_quantlist__16u0__p5_0,
  143368. NULL,
  143369. &_vq_auxt__16u0__p5_0,
  143370. NULL,
  143371. 0
  143372. };
  143373. static long _vq_quantlist__16u0__p6_0[] = {
  143374. 6,
  143375. 5,
  143376. 7,
  143377. 4,
  143378. 8,
  143379. 3,
  143380. 9,
  143381. 2,
  143382. 10,
  143383. 1,
  143384. 11,
  143385. 0,
  143386. 12,
  143387. };
  143388. static long _vq_lengthlist__16u0__p6_0[] = {
  143389. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143390. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143391. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143392. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143393. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143394. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143395. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143396. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143397. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143398. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143399. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143400. };
  143401. static float _vq_quantthresh__16u0__p6_0[] = {
  143402. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143403. 12.5, 17.5, 22.5, 27.5,
  143404. };
  143405. static long _vq_quantmap__16u0__p6_0[] = {
  143406. 11, 9, 7, 5, 3, 1, 0, 2,
  143407. 4, 6, 8, 10, 12,
  143408. };
  143409. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143410. _vq_quantthresh__16u0__p6_0,
  143411. _vq_quantmap__16u0__p6_0,
  143412. 13,
  143413. 13
  143414. };
  143415. static static_codebook _16u0__p6_0 = {
  143416. 2, 169,
  143417. _vq_lengthlist__16u0__p6_0,
  143418. 1, -526516224, 1616117760, 4, 0,
  143419. _vq_quantlist__16u0__p6_0,
  143420. NULL,
  143421. &_vq_auxt__16u0__p6_0,
  143422. NULL,
  143423. 0
  143424. };
  143425. static long _vq_quantlist__16u0__p6_1[] = {
  143426. 2,
  143427. 1,
  143428. 3,
  143429. 0,
  143430. 4,
  143431. };
  143432. static long _vq_lengthlist__16u0__p6_1[] = {
  143433. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143434. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143435. };
  143436. static float _vq_quantthresh__16u0__p6_1[] = {
  143437. -1.5, -0.5, 0.5, 1.5,
  143438. };
  143439. static long _vq_quantmap__16u0__p6_1[] = {
  143440. 3, 1, 0, 2, 4,
  143441. };
  143442. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143443. _vq_quantthresh__16u0__p6_1,
  143444. _vq_quantmap__16u0__p6_1,
  143445. 5,
  143446. 5
  143447. };
  143448. static static_codebook _16u0__p6_1 = {
  143449. 2, 25,
  143450. _vq_lengthlist__16u0__p6_1,
  143451. 1, -533725184, 1611661312, 3, 0,
  143452. _vq_quantlist__16u0__p6_1,
  143453. NULL,
  143454. &_vq_auxt__16u0__p6_1,
  143455. NULL,
  143456. 0
  143457. };
  143458. static long _vq_quantlist__16u0__p7_0[] = {
  143459. 1,
  143460. 0,
  143461. 2,
  143462. };
  143463. static long _vq_lengthlist__16u0__p7_0[] = {
  143464. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143465. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143466. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143467. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143468. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143469. 7,
  143470. };
  143471. static float _vq_quantthresh__16u0__p7_0[] = {
  143472. -157.5, 157.5,
  143473. };
  143474. static long _vq_quantmap__16u0__p7_0[] = {
  143475. 1, 0, 2,
  143476. };
  143477. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143478. _vq_quantthresh__16u0__p7_0,
  143479. _vq_quantmap__16u0__p7_0,
  143480. 3,
  143481. 3
  143482. };
  143483. static static_codebook _16u0__p7_0 = {
  143484. 4, 81,
  143485. _vq_lengthlist__16u0__p7_0,
  143486. 1, -518803456, 1628680192, 2, 0,
  143487. _vq_quantlist__16u0__p7_0,
  143488. NULL,
  143489. &_vq_auxt__16u0__p7_0,
  143490. NULL,
  143491. 0
  143492. };
  143493. static long _vq_quantlist__16u0__p7_1[] = {
  143494. 7,
  143495. 6,
  143496. 8,
  143497. 5,
  143498. 9,
  143499. 4,
  143500. 10,
  143501. 3,
  143502. 11,
  143503. 2,
  143504. 12,
  143505. 1,
  143506. 13,
  143507. 0,
  143508. 14,
  143509. };
  143510. static long _vq_lengthlist__16u0__p7_1[] = {
  143511. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143512. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143513. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143514. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143515. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143516. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143517. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143518. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143519. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143520. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143521. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143522. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143523. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143525. 10,
  143526. };
  143527. static float _vq_quantthresh__16u0__p7_1[] = {
  143528. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143529. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143530. };
  143531. static long _vq_quantmap__16u0__p7_1[] = {
  143532. 13, 11, 9, 7, 5, 3, 1, 0,
  143533. 2, 4, 6, 8, 10, 12, 14,
  143534. };
  143535. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143536. _vq_quantthresh__16u0__p7_1,
  143537. _vq_quantmap__16u0__p7_1,
  143538. 15,
  143539. 15
  143540. };
  143541. static static_codebook _16u0__p7_1 = {
  143542. 2, 225,
  143543. _vq_lengthlist__16u0__p7_1,
  143544. 1, -520986624, 1620377600, 4, 0,
  143545. _vq_quantlist__16u0__p7_1,
  143546. NULL,
  143547. &_vq_auxt__16u0__p7_1,
  143548. NULL,
  143549. 0
  143550. };
  143551. static long _vq_quantlist__16u0__p7_2[] = {
  143552. 10,
  143553. 9,
  143554. 11,
  143555. 8,
  143556. 12,
  143557. 7,
  143558. 13,
  143559. 6,
  143560. 14,
  143561. 5,
  143562. 15,
  143563. 4,
  143564. 16,
  143565. 3,
  143566. 17,
  143567. 2,
  143568. 18,
  143569. 1,
  143570. 19,
  143571. 0,
  143572. 20,
  143573. };
  143574. static long _vq_lengthlist__16u0__p7_2[] = {
  143575. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143576. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143577. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143578. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143579. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143580. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143581. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143582. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143583. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143584. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143585. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143586. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143587. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143588. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143589. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143590. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143591. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143592. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143593. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143594. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143595. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143596. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143597. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143598. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143599. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143600. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143601. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143602. 10,10,12,11,10,11,11,11,10,
  143603. };
  143604. static float _vq_quantthresh__16u0__p7_2[] = {
  143605. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143606. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143607. 6.5, 7.5, 8.5, 9.5,
  143608. };
  143609. static long _vq_quantmap__16u0__p7_2[] = {
  143610. 19, 17, 15, 13, 11, 9, 7, 5,
  143611. 3, 1, 0, 2, 4, 6, 8, 10,
  143612. 12, 14, 16, 18, 20,
  143613. };
  143614. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143615. _vq_quantthresh__16u0__p7_2,
  143616. _vq_quantmap__16u0__p7_2,
  143617. 21,
  143618. 21
  143619. };
  143620. static static_codebook _16u0__p7_2 = {
  143621. 2, 441,
  143622. _vq_lengthlist__16u0__p7_2,
  143623. 1, -529268736, 1611661312, 5, 0,
  143624. _vq_quantlist__16u0__p7_2,
  143625. NULL,
  143626. &_vq_auxt__16u0__p7_2,
  143627. NULL,
  143628. 0
  143629. };
  143630. static long _huff_lengthlist__16u0__single[] = {
  143631. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143632. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143633. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143634. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143635. };
  143636. static static_codebook _huff_book__16u0__single = {
  143637. 2, 64,
  143638. _huff_lengthlist__16u0__single,
  143639. 0, 0, 0, 0, 0,
  143640. NULL,
  143641. NULL,
  143642. NULL,
  143643. NULL,
  143644. 0
  143645. };
  143646. static long _huff_lengthlist__16u1__long[] = {
  143647. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143648. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143649. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143650. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143651. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143652. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143653. 16,13,16,18,
  143654. };
  143655. static static_codebook _huff_book__16u1__long = {
  143656. 2, 100,
  143657. _huff_lengthlist__16u1__long,
  143658. 0, 0, 0, 0, 0,
  143659. NULL,
  143660. NULL,
  143661. NULL,
  143662. NULL,
  143663. 0
  143664. };
  143665. static long _vq_quantlist__16u1__p1_0[] = {
  143666. 1,
  143667. 0,
  143668. 2,
  143669. };
  143670. static long _vq_lengthlist__16u1__p1_0[] = {
  143671. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143672. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143673. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143674. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143675. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143676. 11,
  143677. };
  143678. static float _vq_quantthresh__16u1__p1_0[] = {
  143679. -0.5, 0.5,
  143680. };
  143681. static long _vq_quantmap__16u1__p1_0[] = {
  143682. 1, 0, 2,
  143683. };
  143684. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143685. _vq_quantthresh__16u1__p1_0,
  143686. _vq_quantmap__16u1__p1_0,
  143687. 3,
  143688. 3
  143689. };
  143690. static static_codebook _16u1__p1_0 = {
  143691. 4, 81,
  143692. _vq_lengthlist__16u1__p1_0,
  143693. 1, -535822336, 1611661312, 2, 0,
  143694. _vq_quantlist__16u1__p1_0,
  143695. NULL,
  143696. &_vq_auxt__16u1__p1_0,
  143697. NULL,
  143698. 0
  143699. };
  143700. static long _vq_quantlist__16u1__p2_0[] = {
  143701. 1,
  143702. 0,
  143703. 2,
  143704. };
  143705. static long _vq_lengthlist__16u1__p2_0[] = {
  143706. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143707. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143708. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143709. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143710. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143711. 8,
  143712. };
  143713. static float _vq_quantthresh__16u1__p2_0[] = {
  143714. -0.5, 0.5,
  143715. };
  143716. static long _vq_quantmap__16u1__p2_0[] = {
  143717. 1, 0, 2,
  143718. };
  143719. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143720. _vq_quantthresh__16u1__p2_0,
  143721. _vq_quantmap__16u1__p2_0,
  143722. 3,
  143723. 3
  143724. };
  143725. static static_codebook _16u1__p2_0 = {
  143726. 4, 81,
  143727. _vq_lengthlist__16u1__p2_0,
  143728. 1, -535822336, 1611661312, 2, 0,
  143729. _vq_quantlist__16u1__p2_0,
  143730. NULL,
  143731. &_vq_auxt__16u1__p2_0,
  143732. NULL,
  143733. 0
  143734. };
  143735. static long _vq_quantlist__16u1__p3_0[] = {
  143736. 2,
  143737. 1,
  143738. 3,
  143739. 0,
  143740. 4,
  143741. };
  143742. static long _vq_lengthlist__16u1__p3_0[] = {
  143743. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143744. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143745. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143746. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143747. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143748. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143749. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143750. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143751. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143752. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143753. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143754. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143755. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143756. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143757. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143758. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143759. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143760. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143761. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143762. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143763. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143764. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143765. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143766. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143767. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143768. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143769. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143770. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143771. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143772. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143773. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143774. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143775. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143776. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143777. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143778. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143779. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143780. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143781. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143782. 16,
  143783. };
  143784. static float _vq_quantthresh__16u1__p3_0[] = {
  143785. -1.5, -0.5, 0.5, 1.5,
  143786. };
  143787. static long _vq_quantmap__16u1__p3_0[] = {
  143788. 3, 1, 0, 2, 4,
  143789. };
  143790. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143791. _vq_quantthresh__16u1__p3_0,
  143792. _vq_quantmap__16u1__p3_0,
  143793. 5,
  143794. 5
  143795. };
  143796. static static_codebook _16u1__p3_0 = {
  143797. 4, 625,
  143798. _vq_lengthlist__16u1__p3_0,
  143799. 1, -533725184, 1611661312, 3, 0,
  143800. _vq_quantlist__16u1__p3_0,
  143801. NULL,
  143802. &_vq_auxt__16u1__p3_0,
  143803. NULL,
  143804. 0
  143805. };
  143806. static long _vq_quantlist__16u1__p4_0[] = {
  143807. 2,
  143808. 1,
  143809. 3,
  143810. 0,
  143811. 4,
  143812. };
  143813. static long _vq_lengthlist__16u1__p4_0[] = {
  143814. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143815. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143816. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143817. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143818. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143819. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143820. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143821. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143822. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143823. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143824. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143825. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143826. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143827. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143828. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143829. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143830. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143831. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143832. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143833. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143834. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143835. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143836. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143837. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143838. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143839. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143840. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143841. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143842. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143843. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143844. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143845. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143846. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143847. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143848. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143849. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143850. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143851. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143852. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143853. 11,
  143854. };
  143855. static float _vq_quantthresh__16u1__p4_0[] = {
  143856. -1.5, -0.5, 0.5, 1.5,
  143857. };
  143858. static long _vq_quantmap__16u1__p4_0[] = {
  143859. 3, 1, 0, 2, 4,
  143860. };
  143861. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143862. _vq_quantthresh__16u1__p4_0,
  143863. _vq_quantmap__16u1__p4_0,
  143864. 5,
  143865. 5
  143866. };
  143867. static static_codebook _16u1__p4_0 = {
  143868. 4, 625,
  143869. _vq_lengthlist__16u1__p4_0,
  143870. 1, -533725184, 1611661312, 3, 0,
  143871. _vq_quantlist__16u1__p4_0,
  143872. NULL,
  143873. &_vq_auxt__16u1__p4_0,
  143874. NULL,
  143875. 0
  143876. };
  143877. static long _vq_quantlist__16u1__p5_0[] = {
  143878. 4,
  143879. 3,
  143880. 5,
  143881. 2,
  143882. 6,
  143883. 1,
  143884. 7,
  143885. 0,
  143886. 8,
  143887. };
  143888. static long _vq_lengthlist__16u1__p5_0[] = {
  143889. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143890. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143891. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143892. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143893. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143894. 13,
  143895. };
  143896. static float _vq_quantthresh__16u1__p5_0[] = {
  143897. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143898. };
  143899. static long _vq_quantmap__16u1__p5_0[] = {
  143900. 7, 5, 3, 1, 0, 2, 4, 6,
  143901. 8,
  143902. };
  143903. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143904. _vq_quantthresh__16u1__p5_0,
  143905. _vq_quantmap__16u1__p5_0,
  143906. 9,
  143907. 9
  143908. };
  143909. static static_codebook _16u1__p5_0 = {
  143910. 2, 81,
  143911. _vq_lengthlist__16u1__p5_0,
  143912. 1, -531628032, 1611661312, 4, 0,
  143913. _vq_quantlist__16u1__p5_0,
  143914. NULL,
  143915. &_vq_auxt__16u1__p5_0,
  143916. NULL,
  143917. 0
  143918. };
  143919. static long _vq_quantlist__16u1__p6_0[] = {
  143920. 4,
  143921. 3,
  143922. 5,
  143923. 2,
  143924. 6,
  143925. 1,
  143926. 7,
  143927. 0,
  143928. 8,
  143929. };
  143930. static long _vq_lengthlist__16u1__p6_0[] = {
  143931. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143932. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143933. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143934. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143935. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143936. 11,
  143937. };
  143938. static float _vq_quantthresh__16u1__p6_0[] = {
  143939. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143940. };
  143941. static long _vq_quantmap__16u1__p6_0[] = {
  143942. 7, 5, 3, 1, 0, 2, 4, 6,
  143943. 8,
  143944. };
  143945. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143946. _vq_quantthresh__16u1__p6_0,
  143947. _vq_quantmap__16u1__p6_0,
  143948. 9,
  143949. 9
  143950. };
  143951. static static_codebook _16u1__p6_0 = {
  143952. 2, 81,
  143953. _vq_lengthlist__16u1__p6_0,
  143954. 1, -531628032, 1611661312, 4, 0,
  143955. _vq_quantlist__16u1__p6_0,
  143956. NULL,
  143957. &_vq_auxt__16u1__p6_0,
  143958. NULL,
  143959. 0
  143960. };
  143961. static long _vq_quantlist__16u1__p7_0[] = {
  143962. 1,
  143963. 0,
  143964. 2,
  143965. };
  143966. static long _vq_lengthlist__16u1__p7_0[] = {
  143967. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143968. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143969. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143970. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143971. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143972. 13,
  143973. };
  143974. static float _vq_quantthresh__16u1__p7_0[] = {
  143975. -5.5, 5.5,
  143976. };
  143977. static long _vq_quantmap__16u1__p7_0[] = {
  143978. 1, 0, 2,
  143979. };
  143980. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143981. _vq_quantthresh__16u1__p7_0,
  143982. _vq_quantmap__16u1__p7_0,
  143983. 3,
  143984. 3
  143985. };
  143986. static static_codebook _16u1__p7_0 = {
  143987. 4, 81,
  143988. _vq_lengthlist__16u1__p7_0,
  143989. 1, -529137664, 1618345984, 2, 0,
  143990. _vq_quantlist__16u1__p7_0,
  143991. NULL,
  143992. &_vq_auxt__16u1__p7_0,
  143993. NULL,
  143994. 0
  143995. };
  143996. static long _vq_quantlist__16u1__p7_1[] = {
  143997. 5,
  143998. 4,
  143999. 6,
  144000. 3,
  144001. 7,
  144002. 2,
  144003. 8,
  144004. 1,
  144005. 9,
  144006. 0,
  144007. 10,
  144008. };
  144009. static long _vq_lengthlist__16u1__p7_1[] = {
  144010. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  144011. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  144012. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144013. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  144014. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  144015. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  144016. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  144017. 8, 9, 9,10,10,10,10,10,10,
  144018. };
  144019. static float _vq_quantthresh__16u1__p7_1[] = {
  144020. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144021. 3.5, 4.5,
  144022. };
  144023. static long _vq_quantmap__16u1__p7_1[] = {
  144024. 9, 7, 5, 3, 1, 0, 2, 4,
  144025. 6, 8, 10,
  144026. };
  144027. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  144028. _vq_quantthresh__16u1__p7_1,
  144029. _vq_quantmap__16u1__p7_1,
  144030. 11,
  144031. 11
  144032. };
  144033. static static_codebook _16u1__p7_1 = {
  144034. 2, 121,
  144035. _vq_lengthlist__16u1__p7_1,
  144036. 1, -531365888, 1611661312, 4, 0,
  144037. _vq_quantlist__16u1__p7_1,
  144038. NULL,
  144039. &_vq_auxt__16u1__p7_1,
  144040. NULL,
  144041. 0
  144042. };
  144043. static long _vq_quantlist__16u1__p8_0[] = {
  144044. 5,
  144045. 4,
  144046. 6,
  144047. 3,
  144048. 7,
  144049. 2,
  144050. 8,
  144051. 1,
  144052. 9,
  144053. 0,
  144054. 10,
  144055. };
  144056. static long _vq_lengthlist__16u1__p8_0[] = {
  144057. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  144058. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  144059. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  144060. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  144061. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  144062. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  144063. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  144064. 13,14,14,15,15,16,16,15,16,
  144065. };
  144066. static float _vq_quantthresh__16u1__p8_0[] = {
  144067. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144068. 38.5, 49.5,
  144069. };
  144070. static long _vq_quantmap__16u1__p8_0[] = {
  144071. 9, 7, 5, 3, 1, 0, 2, 4,
  144072. 6, 8, 10,
  144073. };
  144074. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  144075. _vq_quantthresh__16u1__p8_0,
  144076. _vq_quantmap__16u1__p8_0,
  144077. 11,
  144078. 11
  144079. };
  144080. static static_codebook _16u1__p8_0 = {
  144081. 2, 121,
  144082. _vq_lengthlist__16u1__p8_0,
  144083. 1, -524582912, 1618345984, 4, 0,
  144084. _vq_quantlist__16u1__p8_0,
  144085. NULL,
  144086. &_vq_auxt__16u1__p8_0,
  144087. NULL,
  144088. 0
  144089. };
  144090. static long _vq_quantlist__16u1__p8_1[] = {
  144091. 5,
  144092. 4,
  144093. 6,
  144094. 3,
  144095. 7,
  144096. 2,
  144097. 8,
  144098. 1,
  144099. 9,
  144100. 0,
  144101. 10,
  144102. };
  144103. static long _vq_lengthlist__16u1__p8_1[] = {
  144104. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  144105. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144106. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144107. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144108. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144109. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144110. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144111. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144112. };
  144113. static float _vq_quantthresh__16u1__p8_1[] = {
  144114. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144115. 3.5, 4.5,
  144116. };
  144117. static long _vq_quantmap__16u1__p8_1[] = {
  144118. 9, 7, 5, 3, 1, 0, 2, 4,
  144119. 6, 8, 10,
  144120. };
  144121. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144122. _vq_quantthresh__16u1__p8_1,
  144123. _vq_quantmap__16u1__p8_1,
  144124. 11,
  144125. 11
  144126. };
  144127. static static_codebook _16u1__p8_1 = {
  144128. 2, 121,
  144129. _vq_lengthlist__16u1__p8_1,
  144130. 1, -531365888, 1611661312, 4, 0,
  144131. _vq_quantlist__16u1__p8_1,
  144132. NULL,
  144133. &_vq_auxt__16u1__p8_1,
  144134. NULL,
  144135. 0
  144136. };
  144137. static long _vq_quantlist__16u1__p9_0[] = {
  144138. 7,
  144139. 6,
  144140. 8,
  144141. 5,
  144142. 9,
  144143. 4,
  144144. 10,
  144145. 3,
  144146. 11,
  144147. 2,
  144148. 12,
  144149. 1,
  144150. 13,
  144151. 0,
  144152. 14,
  144153. };
  144154. static long _vq_lengthlist__16u1__p9_0[] = {
  144155. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144156. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144157. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144158. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144159. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144160. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144161. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144162. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144163. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144164. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144165. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144166. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144167. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144168. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144169. 8,
  144170. };
  144171. static float _vq_quantthresh__16u1__p9_0[] = {
  144172. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144173. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144174. };
  144175. static long _vq_quantmap__16u1__p9_0[] = {
  144176. 13, 11, 9, 7, 5, 3, 1, 0,
  144177. 2, 4, 6, 8, 10, 12, 14,
  144178. };
  144179. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144180. _vq_quantthresh__16u1__p9_0,
  144181. _vq_quantmap__16u1__p9_0,
  144182. 15,
  144183. 15
  144184. };
  144185. static static_codebook _16u1__p9_0 = {
  144186. 2, 225,
  144187. _vq_lengthlist__16u1__p9_0,
  144188. 1, -514071552, 1627381760, 4, 0,
  144189. _vq_quantlist__16u1__p9_0,
  144190. NULL,
  144191. &_vq_auxt__16u1__p9_0,
  144192. NULL,
  144193. 0
  144194. };
  144195. static long _vq_quantlist__16u1__p9_1[] = {
  144196. 7,
  144197. 6,
  144198. 8,
  144199. 5,
  144200. 9,
  144201. 4,
  144202. 10,
  144203. 3,
  144204. 11,
  144205. 2,
  144206. 12,
  144207. 1,
  144208. 13,
  144209. 0,
  144210. 14,
  144211. };
  144212. static long _vq_lengthlist__16u1__p9_1[] = {
  144213. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144214. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144215. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144216. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144217. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144218. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144219. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144220. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144221. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144222. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144223. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144224. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144225. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144226. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144227. 9,
  144228. };
  144229. static float _vq_quantthresh__16u1__p9_1[] = {
  144230. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144231. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144232. };
  144233. static long _vq_quantmap__16u1__p9_1[] = {
  144234. 13, 11, 9, 7, 5, 3, 1, 0,
  144235. 2, 4, 6, 8, 10, 12, 14,
  144236. };
  144237. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144238. _vq_quantthresh__16u1__p9_1,
  144239. _vq_quantmap__16u1__p9_1,
  144240. 15,
  144241. 15
  144242. };
  144243. static static_codebook _16u1__p9_1 = {
  144244. 2, 225,
  144245. _vq_lengthlist__16u1__p9_1,
  144246. 1, -522338304, 1620115456, 4, 0,
  144247. _vq_quantlist__16u1__p9_1,
  144248. NULL,
  144249. &_vq_auxt__16u1__p9_1,
  144250. NULL,
  144251. 0
  144252. };
  144253. static long _vq_quantlist__16u1__p9_2[] = {
  144254. 8,
  144255. 7,
  144256. 9,
  144257. 6,
  144258. 10,
  144259. 5,
  144260. 11,
  144261. 4,
  144262. 12,
  144263. 3,
  144264. 13,
  144265. 2,
  144266. 14,
  144267. 1,
  144268. 15,
  144269. 0,
  144270. 16,
  144271. };
  144272. static long _vq_lengthlist__16u1__p9_2[] = {
  144273. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144274. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144275. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144276. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144277. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144278. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144279. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144280. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144281. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144282. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144283. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144284. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144285. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144286. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144287. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144288. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144289. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144290. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144291. 10,
  144292. };
  144293. static float _vq_quantthresh__16u1__p9_2[] = {
  144294. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144295. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144296. };
  144297. static long _vq_quantmap__16u1__p9_2[] = {
  144298. 15, 13, 11, 9, 7, 5, 3, 1,
  144299. 0, 2, 4, 6, 8, 10, 12, 14,
  144300. 16,
  144301. };
  144302. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144303. _vq_quantthresh__16u1__p9_2,
  144304. _vq_quantmap__16u1__p9_2,
  144305. 17,
  144306. 17
  144307. };
  144308. static static_codebook _16u1__p9_2 = {
  144309. 2, 289,
  144310. _vq_lengthlist__16u1__p9_2,
  144311. 1, -529530880, 1611661312, 5, 0,
  144312. _vq_quantlist__16u1__p9_2,
  144313. NULL,
  144314. &_vq_auxt__16u1__p9_2,
  144315. NULL,
  144316. 0
  144317. };
  144318. static long _huff_lengthlist__16u1__short[] = {
  144319. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144320. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144321. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144322. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144323. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144324. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144325. 16,16,16,16,
  144326. };
  144327. static static_codebook _huff_book__16u1__short = {
  144328. 2, 100,
  144329. _huff_lengthlist__16u1__short,
  144330. 0, 0, 0, 0, 0,
  144331. NULL,
  144332. NULL,
  144333. NULL,
  144334. NULL,
  144335. 0
  144336. };
  144337. static long _huff_lengthlist__16u2__long[] = {
  144338. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144339. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144340. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144341. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144342. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144343. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144344. 13,14,18,18,
  144345. };
  144346. static static_codebook _huff_book__16u2__long = {
  144347. 2, 100,
  144348. _huff_lengthlist__16u2__long,
  144349. 0, 0, 0, 0, 0,
  144350. NULL,
  144351. NULL,
  144352. NULL,
  144353. NULL,
  144354. 0
  144355. };
  144356. static long _huff_lengthlist__16u2__short[] = {
  144357. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144358. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144359. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144360. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144361. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144362. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144363. 16,16,16,16,
  144364. };
  144365. static static_codebook _huff_book__16u2__short = {
  144366. 2, 100,
  144367. _huff_lengthlist__16u2__short,
  144368. 0, 0, 0, 0, 0,
  144369. NULL,
  144370. NULL,
  144371. NULL,
  144372. NULL,
  144373. 0
  144374. };
  144375. static long _vq_quantlist__16u2_p1_0[] = {
  144376. 1,
  144377. 0,
  144378. 2,
  144379. };
  144380. static long _vq_lengthlist__16u2_p1_0[] = {
  144381. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144382. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144383. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144384. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144385. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144386. 10,
  144387. };
  144388. static float _vq_quantthresh__16u2_p1_0[] = {
  144389. -0.5, 0.5,
  144390. };
  144391. static long _vq_quantmap__16u2_p1_0[] = {
  144392. 1, 0, 2,
  144393. };
  144394. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144395. _vq_quantthresh__16u2_p1_0,
  144396. _vq_quantmap__16u2_p1_0,
  144397. 3,
  144398. 3
  144399. };
  144400. static static_codebook _16u2_p1_0 = {
  144401. 4, 81,
  144402. _vq_lengthlist__16u2_p1_0,
  144403. 1, -535822336, 1611661312, 2, 0,
  144404. _vq_quantlist__16u2_p1_0,
  144405. NULL,
  144406. &_vq_auxt__16u2_p1_0,
  144407. NULL,
  144408. 0
  144409. };
  144410. static long _vq_quantlist__16u2_p2_0[] = {
  144411. 2,
  144412. 1,
  144413. 3,
  144414. 0,
  144415. 4,
  144416. };
  144417. static long _vq_lengthlist__16u2_p2_0[] = {
  144418. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144419. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144420. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144421. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144422. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144423. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144424. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144425. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144426. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144427. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144428. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144429. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144430. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144431. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144432. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144433. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144434. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144435. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144436. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144437. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144438. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144439. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144440. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144441. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144442. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144443. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144444. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144445. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144446. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144447. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144448. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144449. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144450. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144451. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144452. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144453. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144454. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144455. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144456. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144457. 13,
  144458. };
  144459. static float _vq_quantthresh__16u2_p2_0[] = {
  144460. -1.5, -0.5, 0.5, 1.5,
  144461. };
  144462. static long _vq_quantmap__16u2_p2_0[] = {
  144463. 3, 1, 0, 2, 4,
  144464. };
  144465. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144466. _vq_quantthresh__16u2_p2_0,
  144467. _vq_quantmap__16u2_p2_0,
  144468. 5,
  144469. 5
  144470. };
  144471. static static_codebook _16u2_p2_0 = {
  144472. 4, 625,
  144473. _vq_lengthlist__16u2_p2_0,
  144474. 1, -533725184, 1611661312, 3, 0,
  144475. _vq_quantlist__16u2_p2_0,
  144476. NULL,
  144477. &_vq_auxt__16u2_p2_0,
  144478. NULL,
  144479. 0
  144480. };
  144481. static long _vq_quantlist__16u2_p3_0[] = {
  144482. 4,
  144483. 3,
  144484. 5,
  144485. 2,
  144486. 6,
  144487. 1,
  144488. 7,
  144489. 0,
  144490. 8,
  144491. };
  144492. static long _vq_lengthlist__16u2_p3_0[] = {
  144493. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144494. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144495. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144496. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144497. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144498. 11,
  144499. };
  144500. static float _vq_quantthresh__16u2_p3_0[] = {
  144501. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144502. };
  144503. static long _vq_quantmap__16u2_p3_0[] = {
  144504. 7, 5, 3, 1, 0, 2, 4, 6,
  144505. 8,
  144506. };
  144507. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144508. _vq_quantthresh__16u2_p3_0,
  144509. _vq_quantmap__16u2_p3_0,
  144510. 9,
  144511. 9
  144512. };
  144513. static static_codebook _16u2_p3_0 = {
  144514. 2, 81,
  144515. _vq_lengthlist__16u2_p3_0,
  144516. 1, -531628032, 1611661312, 4, 0,
  144517. _vq_quantlist__16u2_p3_0,
  144518. NULL,
  144519. &_vq_auxt__16u2_p3_0,
  144520. NULL,
  144521. 0
  144522. };
  144523. static long _vq_quantlist__16u2_p4_0[] = {
  144524. 8,
  144525. 7,
  144526. 9,
  144527. 6,
  144528. 10,
  144529. 5,
  144530. 11,
  144531. 4,
  144532. 12,
  144533. 3,
  144534. 13,
  144535. 2,
  144536. 14,
  144537. 1,
  144538. 15,
  144539. 0,
  144540. 16,
  144541. };
  144542. static long _vq_lengthlist__16u2_p4_0[] = {
  144543. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144544. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144545. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144546. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144547. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144548. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144549. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144550. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144551. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144552. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144553. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144554. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144555. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144556. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144557. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144558. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144559. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144560. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144561. 14,
  144562. };
  144563. static float _vq_quantthresh__16u2_p4_0[] = {
  144564. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144565. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144566. };
  144567. static long _vq_quantmap__16u2_p4_0[] = {
  144568. 15, 13, 11, 9, 7, 5, 3, 1,
  144569. 0, 2, 4, 6, 8, 10, 12, 14,
  144570. 16,
  144571. };
  144572. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144573. _vq_quantthresh__16u2_p4_0,
  144574. _vq_quantmap__16u2_p4_0,
  144575. 17,
  144576. 17
  144577. };
  144578. static static_codebook _16u2_p4_0 = {
  144579. 2, 289,
  144580. _vq_lengthlist__16u2_p4_0,
  144581. 1, -529530880, 1611661312, 5, 0,
  144582. _vq_quantlist__16u2_p4_0,
  144583. NULL,
  144584. &_vq_auxt__16u2_p4_0,
  144585. NULL,
  144586. 0
  144587. };
  144588. static long _vq_quantlist__16u2_p5_0[] = {
  144589. 1,
  144590. 0,
  144591. 2,
  144592. };
  144593. static long _vq_lengthlist__16u2_p5_0[] = {
  144594. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144595. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144596. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144597. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144598. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144599. 10,
  144600. };
  144601. static float _vq_quantthresh__16u2_p5_0[] = {
  144602. -5.5, 5.5,
  144603. };
  144604. static long _vq_quantmap__16u2_p5_0[] = {
  144605. 1, 0, 2,
  144606. };
  144607. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144608. _vq_quantthresh__16u2_p5_0,
  144609. _vq_quantmap__16u2_p5_0,
  144610. 3,
  144611. 3
  144612. };
  144613. static static_codebook _16u2_p5_0 = {
  144614. 4, 81,
  144615. _vq_lengthlist__16u2_p5_0,
  144616. 1, -529137664, 1618345984, 2, 0,
  144617. _vq_quantlist__16u2_p5_0,
  144618. NULL,
  144619. &_vq_auxt__16u2_p5_0,
  144620. NULL,
  144621. 0
  144622. };
  144623. static long _vq_quantlist__16u2_p5_1[] = {
  144624. 5,
  144625. 4,
  144626. 6,
  144627. 3,
  144628. 7,
  144629. 2,
  144630. 8,
  144631. 1,
  144632. 9,
  144633. 0,
  144634. 10,
  144635. };
  144636. static long _vq_lengthlist__16u2_p5_1[] = {
  144637. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144638. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144639. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144640. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144641. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144642. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144643. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144644. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144645. };
  144646. static float _vq_quantthresh__16u2_p5_1[] = {
  144647. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144648. 3.5, 4.5,
  144649. };
  144650. static long _vq_quantmap__16u2_p5_1[] = {
  144651. 9, 7, 5, 3, 1, 0, 2, 4,
  144652. 6, 8, 10,
  144653. };
  144654. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144655. _vq_quantthresh__16u2_p5_1,
  144656. _vq_quantmap__16u2_p5_1,
  144657. 11,
  144658. 11
  144659. };
  144660. static static_codebook _16u2_p5_1 = {
  144661. 2, 121,
  144662. _vq_lengthlist__16u2_p5_1,
  144663. 1, -531365888, 1611661312, 4, 0,
  144664. _vq_quantlist__16u2_p5_1,
  144665. NULL,
  144666. &_vq_auxt__16u2_p5_1,
  144667. NULL,
  144668. 0
  144669. };
  144670. static long _vq_quantlist__16u2_p6_0[] = {
  144671. 6,
  144672. 5,
  144673. 7,
  144674. 4,
  144675. 8,
  144676. 3,
  144677. 9,
  144678. 2,
  144679. 10,
  144680. 1,
  144681. 11,
  144682. 0,
  144683. 12,
  144684. };
  144685. static long _vq_lengthlist__16u2_p6_0[] = {
  144686. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144687. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144688. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144689. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144690. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144691. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144692. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144693. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144694. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144695. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144696. 12,13,13,14,14,14,14,15,15,
  144697. };
  144698. static float _vq_quantthresh__16u2_p6_0[] = {
  144699. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144700. 12.5, 17.5, 22.5, 27.5,
  144701. };
  144702. static long _vq_quantmap__16u2_p6_0[] = {
  144703. 11, 9, 7, 5, 3, 1, 0, 2,
  144704. 4, 6, 8, 10, 12,
  144705. };
  144706. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144707. _vq_quantthresh__16u2_p6_0,
  144708. _vq_quantmap__16u2_p6_0,
  144709. 13,
  144710. 13
  144711. };
  144712. static static_codebook _16u2_p6_0 = {
  144713. 2, 169,
  144714. _vq_lengthlist__16u2_p6_0,
  144715. 1, -526516224, 1616117760, 4, 0,
  144716. _vq_quantlist__16u2_p6_0,
  144717. NULL,
  144718. &_vq_auxt__16u2_p6_0,
  144719. NULL,
  144720. 0
  144721. };
  144722. static long _vq_quantlist__16u2_p6_1[] = {
  144723. 2,
  144724. 1,
  144725. 3,
  144726. 0,
  144727. 4,
  144728. };
  144729. static long _vq_lengthlist__16u2_p6_1[] = {
  144730. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144731. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144732. };
  144733. static float _vq_quantthresh__16u2_p6_1[] = {
  144734. -1.5, -0.5, 0.5, 1.5,
  144735. };
  144736. static long _vq_quantmap__16u2_p6_1[] = {
  144737. 3, 1, 0, 2, 4,
  144738. };
  144739. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144740. _vq_quantthresh__16u2_p6_1,
  144741. _vq_quantmap__16u2_p6_1,
  144742. 5,
  144743. 5
  144744. };
  144745. static static_codebook _16u2_p6_1 = {
  144746. 2, 25,
  144747. _vq_lengthlist__16u2_p6_1,
  144748. 1, -533725184, 1611661312, 3, 0,
  144749. _vq_quantlist__16u2_p6_1,
  144750. NULL,
  144751. &_vq_auxt__16u2_p6_1,
  144752. NULL,
  144753. 0
  144754. };
  144755. static long _vq_quantlist__16u2_p7_0[] = {
  144756. 6,
  144757. 5,
  144758. 7,
  144759. 4,
  144760. 8,
  144761. 3,
  144762. 9,
  144763. 2,
  144764. 10,
  144765. 1,
  144766. 11,
  144767. 0,
  144768. 12,
  144769. };
  144770. static long _vq_lengthlist__16u2_p7_0[] = {
  144771. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144772. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144773. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144774. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144775. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144776. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144777. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144778. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144779. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144780. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144781. 12,13,13,13,14,14,14,15,14,
  144782. };
  144783. static float _vq_quantthresh__16u2_p7_0[] = {
  144784. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144785. 27.5, 38.5, 49.5, 60.5,
  144786. };
  144787. static long _vq_quantmap__16u2_p7_0[] = {
  144788. 11, 9, 7, 5, 3, 1, 0, 2,
  144789. 4, 6, 8, 10, 12,
  144790. };
  144791. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144792. _vq_quantthresh__16u2_p7_0,
  144793. _vq_quantmap__16u2_p7_0,
  144794. 13,
  144795. 13
  144796. };
  144797. static static_codebook _16u2_p7_0 = {
  144798. 2, 169,
  144799. _vq_lengthlist__16u2_p7_0,
  144800. 1, -523206656, 1618345984, 4, 0,
  144801. _vq_quantlist__16u2_p7_0,
  144802. NULL,
  144803. &_vq_auxt__16u2_p7_0,
  144804. NULL,
  144805. 0
  144806. };
  144807. static long _vq_quantlist__16u2_p7_1[] = {
  144808. 5,
  144809. 4,
  144810. 6,
  144811. 3,
  144812. 7,
  144813. 2,
  144814. 8,
  144815. 1,
  144816. 9,
  144817. 0,
  144818. 10,
  144819. };
  144820. static long _vq_lengthlist__16u2_p7_1[] = {
  144821. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144822. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144823. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144824. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144825. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144826. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144827. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144828. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144829. };
  144830. static float _vq_quantthresh__16u2_p7_1[] = {
  144831. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144832. 3.5, 4.5,
  144833. };
  144834. static long _vq_quantmap__16u2_p7_1[] = {
  144835. 9, 7, 5, 3, 1, 0, 2, 4,
  144836. 6, 8, 10,
  144837. };
  144838. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144839. _vq_quantthresh__16u2_p7_1,
  144840. _vq_quantmap__16u2_p7_1,
  144841. 11,
  144842. 11
  144843. };
  144844. static static_codebook _16u2_p7_1 = {
  144845. 2, 121,
  144846. _vq_lengthlist__16u2_p7_1,
  144847. 1, -531365888, 1611661312, 4, 0,
  144848. _vq_quantlist__16u2_p7_1,
  144849. NULL,
  144850. &_vq_auxt__16u2_p7_1,
  144851. NULL,
  144852. 0
  144853. };
  144854. static long _vq_quantlist__16u2_p8_0[] = {
  144855. 7,
  144856. 6,
  144857. 8,
  144858. 5,
  144859. 9,
  144860. 4,
  144861. 10,
  144862. 3,
  144863. 11,
  144864. 2,
  144865. 12,
  144866. 1,
  144867. 13,
  144868. 0,
  144869. 14,
  144870. };
  144871. static long _vq_lengthlist__16u2_p8_0[] = {
  144872. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144873. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144874. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144875. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144876. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144877. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144878. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144879. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144880. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144881. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144882. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144883. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144884. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144885. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144886. 14,
  144887. };
  144888. static float _vq_quantthresh__16u2_p8_0[] = {
  144889. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144890. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144891. };
  144892. static long _vq_quantmap__16u2_p8_0[] = {
  144893. 13, 11, 9, 7, 5, 3, 1, 0,
  144894. 2, 4, 6, 8, 10, 12, 14,
  144895. };
  144896. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144897. _vq_quantthresh__16u2_p8_0,
  144898. _vq_quantmap__16u2_p8_0,
  144899. 15,
  144900. 15
  144901. };
  144902. static static_codebook _16u2_p8_0 = {
  144903. 2, 225,
  144904. _vq_lengthlist__16u2_p8_0,
  144905. 1, -520986624, 1620377600, 4, 0,
  144906. _vq_quantlist__16u2_p8_0,
  144907. NULL,
  144908. &_vq_auxt__16u2_p8_0,
  144909. NULL,
  144910. 0
  144911. };
  144912. static long _vq_quantlist__16u2_p8_1[] = {
  144913. 10,
  144914. 9,
  144915. 11,
  144916. 8,
  144917. 12,
  144918. 7,
  144919. 13,
  144920. 6,
  144921. 14,
  144922. 5,
  144923. 15,
  144924. 4,
  144925. 16,
  144926. 3,
  144927. 17,
  144928. 2,
  144929. 18,
  144930. 1,
  144931. 19,
  144932. 0,
  144933. 20,
  144934. };
  144935. static long _vq_lengthlist__16u2_p8_1[] = {
  144936. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144937. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144938. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144939. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144940. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144941. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144942. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144943. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144944. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144945. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144946. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144947. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144948. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144949. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144950. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144951. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144952. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144953. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144954. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144955. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144956. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144957. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144958. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144959. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144960. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144961. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144962. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144963. 11,11,10,11,11,11,10,11,11,
  144964. };
  144965. static float _vq_quantthresh__16u2_p8_1[] = {
  144966. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144967. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144968. 6.5, 7.5, 8.5, 9.5,
  144969. };
  144970. static long _vq_quantmap__16u2_p8_1[] = {
  144971. 19, 17, 15, 13, 11, 9, 7, 5,
  144972. 3, 1, 0, 2, 4, 6, 8, 10,
  144973. 12, 14, 16, 18, 20,
  144974. };
  144975. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144976. _vq_quantthresh__16u2_p8_1,
  144977. _vq_quantmap__16u2_p8_1,
  144978. 21,
  144979. 21
  144980. };
  144981. static static_codebook _16u2_p8_1 = {
  144982. 2, 441,
  144983. _vq_lengthlist__16u2_p8_1,
  144984. 1, -529268736, 1611661312, 5, 0,
  144985. _vq_quantlist__16u2_p8_1,
  144986. NULL,
  144987. &_vq_auxt__16u2_p8_1,
  144988. NULL,
  144989. 0
  144990. };
  144991. static long _vq_quantlist__16u2_p9_0[] = {
  144992. 5586,
  144993. 4655,
  144994. 6517,
  144995. 3724,
  144996. 7448,
  144997. 2793,
  144998. 8379,
  144999. 1862,
  145000. 9310,
  145001. 931,
  145002. 10241,
  145003. 0,
  145004. 11172,
  145005. 5521,
  145006. 5651,
  145007. };
  145008. static long _vq_lengthlist__16u2_p9_0[] = {
  145009. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  145010. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145011. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145012. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145013. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145014. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145015. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145016. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145017. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145018. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145019. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145020. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145021. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  145022. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  145023. 5,
  145024. };
  145025. static float _vq_quantthresh__16u2_p9_0[] = {
  145026. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  145027. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  145028. };
  145029. static long _vq_quantmap__16u2_p9_0[] = {
  145030. 11, 9, 7, 5, 3, 1, 13, 0,
  145031. 14, 2, 4, 6, 8, 10, 12,
  145032. };
  145033. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  145034. _vq_quantthresh__16u2_p9_0,
  145035. _vq_quantmap__16u2_p9_0,
  145036. 15,
  145037. 15
  145038. };
  145039. static static_codebook _16u2_p9_0 = {
  145040. 2, 225,
  145041. _vq_lengthlist__16u2_p9_0,
  145042. 1, -510275072, 1611661312, 14, 0,
  145043. _vq_quantlist__16u2_p9_0,
  145044. NULL,
  145045. &_vq_auxt__16u2_p9_0,
  145046. NULL,
  145047. 0
  145048. };
  145049. static long _vq_quantlist__16u2_p9_1[] = {
  145050. 392,
  145051. 343,
  145052. 441,
  145053. 294,
  145054. 490,
  145055. 245,
  145056. 539,
  145057. 196,
  145058. 588,
  145059. 147,
  145060. 637,
  145061. 98,
  145062. 686,
  145063. 49,
  145064. 735,
  145065. 0,
  145066. 784,
  145067. 388,
  145068. 396,
  145069. };
  145070. static long _vq_lengthlist__16u2_p9_1[] = {
  145071. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  145072. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  145073. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  145074. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  145075. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  145076. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  145077. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145078. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  145079. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  145080. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145081. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145082. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145083. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145084. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145085. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  145086. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145091. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  145092. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  145093. 11,11,11,11,11,11,11, 5, 4,
  145094. };
  145095. static float _vq_quantthresh__16u2_p9_1[] = {
  145096. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  145097. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  145098. 318.5, 367.5,
  145099. };
  145100. static long _vq_quantmap__16u2_p9_1[] = {
  145101. 15, 13, 11, 9, 7, 5, 3, 1,
  145102. 17, 0, 18, 2, 4, 6, 8, 10,
  145103. 12, 14, 16,
  145104. };
  145105. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145106. _vq_quantthresh__16u2_p9_1,
  145107. _vq_quantmap__16u2_p9_1,
  145108. 19,
  145109. 19
  145110. };
  145111. static static_codebook _16u2_p9_1 = {
  145112. 2, 361,
  145113. _vq_lengthlist__16u2_p9_1,
  145114. 1, -518488064, 1611661312, 10, 0,
  145115. _vq_quantlist__16u2_p9_1,
  145116. NULL,
  145117. &_vq_auxt__16u2_p9_1,
  145118. NULL,
  145119. 0
  145120. };
  145121. static long _vq_quantlist__16u2_p9_2[] = {
  145122. 24,
  145123. 23,
  145124. 25,
  145125. 22,
  145126. 26,
  145127. 21,
  145128. 27,
  145129. 20,
  145130. 28,
  145131. 19,
  145132. 29,
  145133. 18,
  145134. 30,
  145135. 17,
  145136. 31,
  145137. 16,
  145138. 32,
  145139. 15,
  145140. 33,
  145141. 14,
  145142. 34,
  145143. 13,
  145144. 35,
  145145. 12,
  145146. 36,
  145147. 11,
  145148. 37,
  145149. 10,
  145150. 38,
  145151. 9,
  145152. 39,
  145153. 8,
  145154. 40,
  145155. 7,
  145156. 41,
  145157. 6,
  145158. 42,
  145159. 5,
  145160. 43,
  145161. 4,
  145162. 44,
  145163. 3,
  145164. 45,
  145165. 2,
  145166. 46,
  145167. 1,
  145168. 47,
  145169. 0,
  145170. 48,
  145171. };
  145172. static long _vq_lengthlist__16u2_p9_2[] = {
  145173. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145174. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145175. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145176. 11,
  145177. };
  145178. static float _vq_quantthresh__16u2_p9_2[] = {
  145179. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145180. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145181. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145182. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145183. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145184. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145185. };
  145186. static long _vq_quantmap__16u2_p9_2[] = {
  145187. 47, 45, 43, 41, 39, 37, 35, 33,
  145188. 31, 29, 27, 25, 23, 21, 19, 17,
  145189. 15, 13, 11, 9, 7, 5, 3, 1,
  145190. 0, 2, 4, 6, 8, 10, 12, 14,
  145191. 16, 18, 20, 22, 24, 26, 28, 30,
  145192. 32, 34, 36, 38, 40, 42, 44, 46,
  145193. 48,
  145194. };
  145195. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145196. _vq_quantthresh__16u2_p9_2,
  145197. _vq_quantmap__16u2_p9_2,
  145198. 49,
  145199. 49
  145200. };
  145201. static static_codebook _16u2_p9_2 = {
  145202. 1, 49,
  145203. _vq_lengthlist__16u2_p9_2,
  145204. 1, -526909440, 1611661312, 6, 0,
  145205. _vq_quantlist__16u2_p9_2,
  145206. NULL,
  145207. &_vq_auxt__16u2_p9_2,
  145208. NULL,
  145209. 0
  145210. };
  145211. static long _vq_quantlist__8u0__p1_0[] = {
  145212. 1,
  145213. 0,
  145214. 2,
  145215. };
  145216. static long _vq_lengthlist__8u0__p1_0[] = {
  145217. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145218. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145219. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145220. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145221. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145222. 11,
  145223. };
  145224. static float _vq_quantthresh__8u0__p1_0[] = {
  145225. -0.5, 0.5,
  145226. };
  145227. static long _vq_quantmap__8u0__p1_0[] = {
  145228. 1, 0, 2,
  145229. };
  145230. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145231. _vq_quantthresh__8u0__p1_0,
  145232. _vq_quantmap__8u0__p1_0,
  145233. 3,
  145234. 3
  145235. };
  145236. static static_codebook _8u0__p1_0 = {
  145237. 4, 81,
  145238. _vq_lengthlist__8u0__p1_0,
  145239. 1, -535822336, 1611661312, 2, 0,
  145240. _vq_quantlist__8u0__p1_0,
  145241. NULL,
  145242. &_vq_auxt__8u0__p1_0,
  145243. NULL,
  145244. 0
  145245. };
  145246. static long _vq_quantlist__8u0__p2_0[] = {
  145247. 1,
  145248. 0,
  145249. 2,
  145250. };
  145251. static long _vq_lengthlist__8u0__p2_0[] = {
  145252. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145253. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145254. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145255. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145256. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145257. 8,
  145258. };
  145259. static float _vq_quantthresh__8u0__p2_0[] = {
  145260. -0.5, 0.5,
  145261. };
  145262. static long _vq_quantmap__8u0__p2_0[] = {
  145263. 1, 0, 2,
  145264. };
  145265. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145266. _vq_quantthresh__8u0__p2_0,
  145267. _vq_quantmap__8u0__p2_0,
  145268. 3,
  145269. 3
  145270. };
  145271. static static_codebook _8u0__p2_0 = {
  145272. 4, 81,
  145273. _vq_lengthlist__8u0__p2_0,
  145274. 1, -535822336, 1611661312, 2, 0,
  145275. _vq_quantlist__8u0__p2_0,
  145276. NULL,
  145277. &_vq_auxt__8u0__p2_0,
  145278. NULL,
  145279. 0
  145280. };
  145281. static long _vq_quantlist__8u0__p3_0[] = {
  145282. 2,
  145283. 1,
  145284. 3,
  145285. 0,
  145286. 4,
  145287. };
  145288. static long _vq_lengthlist__8u0__p3_0[] = {
  145289. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145290. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145291. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145292. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145293. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145294. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145295. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145296. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145297. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145298. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145299. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145300. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145301. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145302. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145303. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145304. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145305. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145306. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145307. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145308. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145309. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145310. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145311. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145312. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145313. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145314. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145315. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145316. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145317. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145318. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145319. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145320. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145321. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145322. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145323. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145324. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145325. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145326. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145327. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145328. 16,
  145329. };
  145330. static float _vq_quantthresh__8u0__p3_0[] = {
  145331. -1.5, -0.5, 0.5, 1.5,
  145332. };
  145333. static long _vq_quantmap__8u0__p3_0[] = {
  145334. 3, 1, 0, 2, 4,
  145335. };
  145336. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145337. _vq_quantthresh__8u0__p3_0,
  145338. _vq_quantmap__8u0__p3_0,
  145339. 5,
  145340. 5
  145341. };
  145342. static static_codebook _8u0__p3_0 = {
  145343. 4, 625,
  145344. _vq_lengthlist__8u0__p3_0,
  145345. 1, -533725184, 1611661312, 3, 0,
  145346. _vq_quantlist__8u0__p3_0,
  145347. NULL,
  145348. &_vq_auxt__8u0__p3_0,
  145349. NULL,
  145350. 0
  145351. };
  145352. static long _vq_quantlist__8u0__p4_0[] = {
  145353. 2,
  145354. 1,
  145355. 3,
  145356. 0,
  145357. 4,
  145358. };
  145359. static long _vq_lengthlist__8u0__p4_0[] = {
  145360. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145361. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145362. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145363. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145364. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145365. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145366. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145367. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145368. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145369. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145370. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145371. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145372. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145373. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145374. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145375. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145376. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145377. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145378. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145379. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145380. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145381. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145382. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145383. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145384. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145385. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145386. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145387. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145388. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145389. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145390. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145391. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145392. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145393. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145394. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145395. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145396. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145397. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145398. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145399. 12,
  145400. };
  145401. static float _vq_quantthresh__8u0__p4_0[] = {
  145402. -1.5, -0.5, 0.5, 1.5,
  145403. };
  145404. static long _vq_quantmap__8u0__p4_0[] = {
  145405. 3, 1, 0, 2, 4,
  145406. };
  145407. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145408. _vq_quantthresh__8u0__p4_0,
  145409. _vq_quantmap__8u0__p4_0,
  145410. 5,
  145411. 5
  145412. };
  145413. static static_codebook _8u0__p4_0 = {
  145414. 4, 625,
  145415. _vq_lengthlist__8u0__p4_0,
  145416. 1, -533725184, 1611661312, 3, 0,
  145417. _vq_quantlist__8u0__p4_0,
  145418. NULL,
  145419. &_vq_auxt__8u0__p4_0,
  145420. NULL,
  145421. 0
  145422. };
  145423. static long _vq_quantlist__8u0__p5_0[] = {
  145424. 4,
  145425. 3,
  145426. 5,
  145427. 2,
  145428. 6,
  145429. 1,
  145430. 7,
  145431. 0,
  145432. 8,
  145433. };
  145434. static long _vq_lengthlist__8u0__p5_0[] = {
  145435. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145436. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145437. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145438. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145439. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145440. 12,
  145441. };
  145442. static float _vq_quantthresh__8u0__p5_0[] = {
  145443. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145444. };
  145445. static long _vq_quantmap__8u0__p5_0[] = {
  145446. 7, 5, 3, 1, 0, 2, 4, 6,
  145447. 8,
  145448. };
  145449. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145450. _vq_quantthresh__8u0__p5_0,
  145451. _vq_quantmap__8u0__p5_0,
  145452. 9,
  145453. 9
  145454. };
  145455. static static_codebook _8u0__p5_0 = {
  145456. 2, 81,
  145457. _vq_lengthlist__8u0__p5_0,
  145458. 1, -531628032, 1611661312, 4, 0,
  145459. _vq_quantlist__8u0__p5_0,
  145460. NULL,
  145461. &_vq_auxt__8u0__p5_0,
  145462. NULL,
  145463. 0
  145464. };
  145465. static long _vq_quantlist__8u0__p6_0[] = {
  145466. 6,
  145467. 5,
  145468. 7,
  145469. 4,
  145470. 8,
  145471. 3,
  145472. 9,
  145473. 2,
  145474. 10,
  145475. 1,
  145476. 11,
  145477. 0,
  145478. 12,
  145479. };
  145480. static long _vq_lengthlist__8u0__p6_0[] = {
  145481. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145482. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145483. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145484. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145485. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145486. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145487. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145488. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145489. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145490. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145491. 16, 0,15, 0,17, 0, 0, 0, 0,
  145492. };
  145493. static float _vq_quantthresh__8u0__p6_0[] = {
  145494. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145495. 12.5, 17.5, 22.5, 27.5,
  145496. };
  145497. static long _vq_quantmap__8u0__p6_0[] = {
  145498. 11, 9, 7, 5, 3, 1, 0, 2,
  145499. 4, 6, 8, 10, 12,
  145500. };
  145501. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145502. _vq_quantthresh__8u0__p6_0,
  145503. _vq_quantmap__8u0__p6_0,
  145504. 13,
  145505. 13
  145506. };
  145507. static static_codebook _8u0__p6_0 = {
  145508. 2, 169,
  145509. _vq_lengthlist__8u0__p6_0,
  145510. 1, -526516224, 1616117760, 4, 0,
  145511. _vq_quantlist__8u0__p6_0,
  145512. NULL,
  145513. &_vq_auxt__8u0__p6_0,
  145514. NULL,
  145515. 0
  145516. };
  145517. static long _vq_quantlist__8u0__p6_1[] = {
  145518. 2,
  145519. 1,
  145520. 3,
  145521. 0,
  145522. 4,
  145523. };
  145524. static long _vq_lengthlist__8u0__p6_1[] = {
  145525. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145526. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145527. };
  145528. static float _vq_quantthresh__8u0__p6_1[] = {
  145529. -1.5, -0.5, 0.5, 1.5,
  145530. };
  145531. static long _vq_quantmap__8u0__p6_1[] = {
  145532. 3, 1, 0, 2, 4,
  145533. };
  145534. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145535. _vq_quantthresh__8u0__p6_1,
  145536. _vq_quantmap__8u0__p6_1,
  145537. 5,
  145538. 5
  145539. };
  145540. static static_codebook _8u0__p6_1 = {
  145541. 2, 25,
  145542. _vq_lengthlist__8u0__p6_1,
  145543. 1, -533725184, 1611661312, 3, 0,
  145544. _vq_quantlist__8u0__p6_1,
  145545. NULL,
  145546. &_vq_auxt__8u0__p6_1,
  145547. NULL,
  145548. 0
  145549. };
  145550. static long _vq_quantlist__8u0__p7_0[] = {
  145551. 1,
  145552. 0,
  145553. 2,
  145554. };
  145555. static long _vq_lengthlist__8u0__p7_0[] = {
  145556. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145557. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145558. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145559. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145560. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145561. 7,
  145562. };
  145563. static float _vq_quantthresh__8u0__p7_0[] = {
  145564. -157.5, 157.5,
  145565. };
  145566. static long _vq_quantmap__8u0__p7_0[] = {
  145567. 1, 0, 2,
  145568. };
  145569. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145570. _vq_quantthresh__8u0__p7_0,
  145571. _vq_quantmap__8u0__p7_0,
  145572. 3,
  145573. 3
  145574. };
  145575. static static_codebook _8u0__p7_0 = {
  145576. 4, 81,
  145577. _vq_lengthlist__8u0__p7_0,
  145578. 1, -518803456, 1628680192, 2, 0,
  145579. _vq_quantlist__8u0__p7_0,
  145580. NULL,
  145581. &_vq_auxt__8u0__p7_0,
  145582. NULL,
  145583. 0
  145584. };
  145585. static long _vq_quantlist__8u0__p7_1[] = {
  145586. 7,
  145587. 6,
  145588. 8,
  145589. 5,
  145590. 9,
  145591. 4,
  145592. 10,
  145593. 3,
  145594. 11,
  145595. 2,
  145596. 12,
  145597. 1,
  145598. 13,
  145599. 0,
  145600. 14,
  145601. };
  145602. static long _vq_lengthlist__8u0__p7_1[] = {
  145603. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145604. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145605. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145606. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145607. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145608. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145612. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145613. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145614. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145615. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145616. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145617. 10,
  145618. };
  145619. static float _vq_quantthresh__8u0__p7_1[] = {
  145620. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145621. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145622. };
  145623. static long _vq_quantmap__8u0__p7_1[] = {
  145624. 13, 11, 9, 7, 5, 3, 1, 0,
  145625. 2, 4, 6, 8, 10, 12, 14,
  145626. };
  145627. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145628. _vq_quantthresh__8u0__p7_1,
  145629. _vq_quantmap__8u0__p7_1,
  145630. 15,
  145631. 15
  145632. };
  145633. static static_codebook _8u0__p7_1 = {
  145634. 2, 225,
  145635. _vq_lengthlist__8u0__p7_1,
  145636. 1, -520986624, 1620377600, 4, 0,
  145637. _vq_quantlist__8u0__p7_1,
  145638. NULL,
  145639. &_vq_auxt__8u0__p7_1,
  145640. NULL,
  145641. 0
  145642. };
  145643. static long _vq_quantlist__8u0__p7_2[] = {
  145644. 10,
  145645. 9,
  145646. 11,
  145647. 8,
  145648. 12,
  145649. 7,
  145650. 13,
  145651. 6,
  145652. 14,
  145653. 5,
  145654. 15,
  145655. 4,
  145656. 16,
  145657. 3,
  145658. 17,
  145659. 2,
  145660. 18,
  145661. 1,
  145662. 19,
  145663. 0,
  145664. 20,
  145665. };
  145666. static long _vq_lengthlist__8u0__p7_2[] = {
  145667. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145668. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145669. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145670. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145671. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145672. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145673. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145674. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145675. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145676. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145677. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145678. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145679. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145680. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145681. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145682. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145683. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145684. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145685. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145686. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145687. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145688. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145689. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145690. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145691. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145692. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145693. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145694. 11,12,11,11,11,10,10,11,11,
  145695. };
  145696. static float _vq_quantthresh__8u0__p7_2[] = {
  145697. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145698. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145699. 6.5, 7.5, 8.5, 9.5,
  145700. };
  145701. static long _vq_quantmap__8u0__p7_2[] = {
  145702. 19, 17, 15, 13, 11, 9, 7, 5,
  145703. 3, 1, 0, 2, 4, 6, 8, 10,
  145704. 12, 14, 16, 18, 20,
  145705. };
  145706. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145707. _vq_quantthresh__8u0__p7_2,
  145708. _vq_quantmap__8u0__p7_2,
  145709. 21,
  145710. 21
  145711. };
  145712. static static_codebook _8u0__p7_2 = {
  145713. 2, 441,
  145714. _vq_lengthlist__8u0__p7_2,
  145715. 1, -529268736, 1611661312, 5, 0,
  145716. _vq_quantlist__8u0__p7_2,
  145717. NULL,
  145718. &_vq_auxt__8u0__p7_2,
  145719. NULL,
  145720. 0
  145721. };
  145722. static long _huff_lengthlist__8u0__single[] = {
  145723. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145724. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145725. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145726. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145727. };
  145728. static static_codebook _huff_book__8u0__single = {
  145729. 2, 64,
  145730. _huff_lengthlist__8u0__single,
  145731. 0, 0, 0, 0, 0,
  145732. NULL,
  145733. NULL,
  145734. NULL,
  145735. NULL,
  145736. 0
  145737. };
  145738. static long _vq_quantlist__8u1__p1_0[] = {
  145739. 1,
  145740. 0,
  145741. 2,
  145742. };
  145743. static long _vq_lengthlist__8u1__p1_0[] = {
  145744. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145745. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145746. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145747. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145748. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145749. 10,
  145750. };
  145751. static float _vq_quantthresh__8u1__p1_0[] = {
  145752. -0.5, 0.5,
  145753. };
  145754. static long _vq_quantmap__8u1__p1_0[] = {
  145755. 1, 0, 2,
  145756. };
  145757. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145758. _vq_quantthresh__8u1__p1_0,
  145759. _vq_quantmap__8u1__p1_0,
  145760. 3,
  145761. 3
  145762. };
  145763. static static_codebook _8u1__p1_0 = {
  145764. 4, 81,
  145765. _vq_lengthlist__8u1__p1_0,
  145766. 1, -535822336, 1611661312, 2, 0,
  145767. _vq_quantlist__8u1__p1_0,
  145768. NULL,
  145769. &_vq_auxt__8u1__p1_0,
  145770. NULL,
  145771. 0
  145772. };
  145773. static long _vq_quantlist__8u1__p2_0[] = {
  145774. 1,
  145775. 0,
  145776. 2,
  145777. };
  145778. static long _vq_lengthlist__8u1__p2_0[] = {
  145779. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145780. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145781. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145782. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145783. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145784. 7,
  145785. };
  145786. static float _vq_quantthresh__8u1__p2_0[] = {
  145787. -0.5, 0.5,
  145788. };
  145789. static long _vq_quantmap__8u1__p2_0[] = {
  145790. 1, 0, 2,
  145791. };
  145792. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145793. _vq_quantthresh__8u1__p2_0,
  145794. _vq_quantmap__8u1__p2_0,
  145795. 3,
  145796. 3
  145797. };
  145798. static static_codebook _8u1__p2_0 = {
  145799. 4, 81,
  145800. _vq_lengthlist__8u1__p2_0,
  145801. 1, -535822336, 1611661312, 2, 0,
  145802. _vq_quantlist__8u1__p2_0,
  145803. NULL,
  145804. &_vq_auxt__8u1__p2_0,
  145805. NULL,
  145806. 0
  145807. };
  145808. static long _vq_quantlist__8u1__p3_0[] = {
  145809. 2,
  145810. 1,
  145811. 3,
  145812. 0,
  145813. 4,
  145814. };
  145815. static long _vq_lengthlist__8u1__p3_0[] = {
  145816. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145817. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145818. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145819. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145820. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145821. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145822. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145823. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145824. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145825. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145826. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145827. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145828. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145829. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145830. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145831. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145832. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145833. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145834. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145835. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145836. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145837. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145838. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145839. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145840. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145841. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145842. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145843. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145844. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145845. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145846. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145847. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145848. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145849. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145850. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145851. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145852. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145853. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145854. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145855. 16,
  145856. };
  145857. static float _vq_quantthresh__8u1__p3_0[] = {
  145858. -1.5, -0.5, 0.5, 1.5,
  145859. };
  145860. static long _vq_quantmap__8u1__p3_0[] = {
  145861. 3, 1, 0, 2, 4,
  145862. };
  145863. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145864. _vq_quantthresh__8u1__p3_0,
  145865. _vq_quantmap__8u1__p3_0,
  145866. 5,
  145867. 5
  145868. };
  145869. static static_codebook _8u1__p3_0 = {
  145870. 4, 625,
  145871. _vq_lengthlist__8u1__p3_0,
  145872. 1, -533725184, 1611661312, 3, 0,
  145873. _vq_quantlist__8u1__p3_0,
  145874. NULL,
  145875. &_vq_auxt__8u1__p3_0,
  145876. NULL,
  145877. 0
  145878. };
  145879. static long _vq_quantlist__8u1__p4_0[] = {
  145880. 2,
  145881. 1,
  145882. 3,
  145883. 0,
  145884. 4,
  145885. };
  145886. static long _vq_lengthlist__8u1__p4_0[] = {
  145887. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145888. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145889. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145890. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145891. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145892. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145893. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145894. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145895. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145896. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145897. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145898. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145899. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145900. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145901. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145902. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145903. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145904. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145905. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145906. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145907. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145908. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145909. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145910. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145911. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145912. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145913. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145914. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145915. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145916. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145917. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145918. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145919. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145920. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145921. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145922. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145923. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145924. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145925. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145926. 10,
  145927. };
  145928. static float _vq_quantthresh__8u1__p4_0[] = {
  145929. -1.5, -0.5, 0.5, 1.5,
  145930. };
  145931. static long _vq_quantmap__8u1__p4_0[] = {
  145932. 3, 1, 0, 2, 4,
  145933. };
  145934. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145935. _vq_quantthresh__8u1__p4_0,
  145936. _vq_quantmap__8u1__p4_0,
  145937. 5,
  145938. 5
  145939. };
  145940. static static_codebook _8u1__p4_0 = {
  145941. 4, 625,
  145942. _vq_lengthlist__8u1__p4_0,
  145943. 1, -533725184, 1611661312, 3, 0,
  145944. _vq_quantlist__8u1__p4_0,
  145945. NULL,
  145946. &_vq_auxt__8u1__p4_0,
  145947. NULL,
  145948. 0
  145949. };
  145950. static long _vq_quantlist__8u1__p5_0[] = {
  145951. 4,
  145952. 3,
  145953. 5,
  145954. 2,
  145955. 6,
  145956. 1,
  145957. 7,
  145958. 0,
  145959. 8,
  145960. };
  145961. static long _vq_lengthlist__8u1__p5_0[] = {
  145962. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145963. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145964. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145965. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145966. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145967. 13,
  145968. };
  145969. static float _vq_quantthresh__8u1__p5_0[] = {
  145970. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145971. };
  145972. static long _vq_quantmap__8u1__p5_0[] = {
  145973. 7, 5, 3, 1, 0, 2, 4, 6,
  145974. 8,
  145975. };
  145976. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145977. _vq_quantthresh__8u1__p5_0,
  145978. _vq_quantmap__8u1__p5_0,
  145979. 9,
  145980. 9
  145981. };
  145982. static static_codebook _8u1__p5_0 = {
  145983. 2, 81,
  145984. _vq_lengthlist__8u1__p5_0,
  145985. 1, -531628032, 1611661312, 4, 0,
  145986. _vq_quantlist__8u1__p5_0,
  145987. NULL,
  145988. &_vq_auxt__8u1__p5_0,
  145989. NULL,
  145990. 0
  145991. };
  145992. static long _vq_quantlist__8u1__p6_0[] = {
  145993. 4,
  145994. 3,
  145995. 5,
  145996. 2,
  145997. 6,
  145998. 1,
  145999. 7,
  146000. 0,
  146001. 8,
  146002. };
  146003. static long _vq_lengthlist__8u1__p6_0[] = {
  146004. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  146005. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  146006. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146007. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  146008. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146009. 10,
  146010. };
  146011. static float _vq_quantthresh__8u1__p6_0[] = {
  146012. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146013. };
  146014. static long _vq_quantmap__8u1__p6_0[] = {
  146015. 7, 5, 3, 1, 0, 2, 4, 6,
  146016. 8,
  146017. };
  146018. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  146019. _vq_quantthresh__8u1__p6_0,
  146020. _vq_quantmap__8u1__p6_0,
  146021. 9,
  146022. 9
  146023. };
  146024. static static_codebook _8u1__p6_0 = {
  146025. 2, 81,
  146026. _vq_lengthlist__8u1__p6_0,
  146027. 1, -531628032, 1611661312, 4, 0,
  146028. _vq_quantlist__8u1__p6_0,
  146029. NULL,
  146030. &_vq_auxt__8u1__p6_0,
  146031. NULL,
  146032. 0
  146033. };
  146034. static long _vq_quantlist__8u1__p7_0[] = {
  146035. 1,
  146036. 0,
  146037. 2,
  146038. };
  146039. static long _vq_lengthlist__8u1__p7_0[] = {
  146040. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  146041. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  146042. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  146043. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  146044. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  146045. 11,
  146046. };
  146047. static float _vq_quantthresh__8u1__p7_0[] = {
  146048. -5.5, 5.5,
  146049. };
  146050. static long _vq_quantmap__8u1__p7_0[] = {
  146051. 1, 0, 2,
  146052. };
  146053. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  146054. _vq_quantthresh__8u1__p7_0,
  146055. _vq_quantmap__8u1__p7_0,
  146056. 3,
  146057. 3
  146058. };
  146059. static static_codebook _8u1__p7_0 = {
  146060. 4, 81,
  146061. _vq_lengthlist__8u1__p7_0,
  146062. 1, -529137664, 1618345984, 2, 0,
  146063. _vq_quantlist__8u1__p7_0,
  146064. NULL,
  146065. &_vq_auxt__8u1__p7_0,
  146066. NULL,
  146067. 0
  146068. };
  146069. static long _vq_quantlist__8u1__p7_1[] = {
  146070. 5,
  146071. 4,
  146072. 6,
  146073. 3,
  146074. 7,
  146075. 2,
  146076. 8,
  146077. 1,
  146078. 9,
  146079. 0,
  146080. 10,
  146081. };
  146082. static long _vq_lengthlist__8u1__p7_1[] = {
  146083. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146084. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  146085. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146086. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146087. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146088. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146089. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146090. 9, 9, 9, 9, 9,10,10,10,10,
  146091. };
  146092. static float _vq_quantthresh__8u1__p7_1[] = {
  146093. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146094. 3.5, 4.5,
  146095. };
  146096. static long _vq_quantmap__8u1__p7_1[] = {
  146097. 9, 7, 5, 3, 1, 0, 2, 4,
  146098. 6, 8, 10,
  146099. };
  146100. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  146101. _vq_quantthresh__8u1__p7_1,
  146102. _vq_quantmap__8u1__p7_1,
  146103. 11,
  146104. 11
  146105. };
  146106. static static_codebook _8u1__p7_1 = {
  146107. 2, 121,
  146108. _vq_lengthlist__8u1__p7_1,
  146109. 1, -531365888, 1611661312, 4, 0,
  146110. _vq_quantlist__8u1__p7_1,
  146111. NULL,
  146112. &_vq_auxt__8u1__p7_1,
  146113. NULL,
  146114. 0
  146115. };
  146116. static long _vq_quantlist__8u1__p8_0[] = {
  146117. 5,
  146118. 4,
  146119. 6,
  146120. 3,
  146121. 7,
  146122. 2,
  146123. 8,
  146124. 1,
  146125. 9,
  146126. 0,
  146127. 10,
  146128. };
  146129. static long _vq_lengthlist__8u1__p8_0[] = {
  146130. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146131. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146132. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146133. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146134. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146135. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146136. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146137. 12,13,13,14,14,15,15,15,15,
  146138. };
  146139. static float _vq_quantthresh__8u1__p8_0[] = {
  146140. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146141. 38.5, 49.5,
  146142. };
  146143. static long _vq_quantmap__8u1__p8_0[] = {
  146144. 9, 7, 5, 3, 1, 0, 2, 4,
  146145. 6, 8, 10,
  146146. };
  146147. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146148. _vq_quantthresh__8u1__p8_0,
  146149. _vq_quantmap__8u1__p8_0,
  146150. 11,
  146151. 11
  146152. };
  146153. static static_codebook _8u1__p8_0 = {
  146154. 2, 121,
  146155. _vq_lengthlist__8u1__p8_0,
  146156. 1, -524582912, 1618345984, 4, 0,
  146157. _vq_quantlist__8u1__p8_0,
  146158. NULL,
  146159. &_vq_auxt__8u1__p8_0,
  146160. NULL,
  146161. 0
  146162. };
  146163. static long _vq_quantlist__8u1__p8_1[] = {
  146164. 5,
  146165. 4,
  146166. 6,
  146167. 3,
  146168. 7,
  146169. 2,
  146170. 8,
  146171. 1,
  146172. 9,
  146173. 0,
  146174. 10,
  146175. };
  146176. static long _vq_lengthlist__8u1__p8_1[] = {
  146177. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146178. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146179. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146180. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146181. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146182. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146183. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146184. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146185. };
  146186. static float _vq_quantthresh__8u1__p8_1[] = {
  146187. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146188. 3.5, 4.5,
  146189. };
  146190. static long _vq_quantmap__8u1__p8_1[] = {
  146191. 9, 7, 5, 3, 1, 0, 2, 4,
  146192. 6, 8, 10,
  146193. };
  146194. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146195. _vq_quantthresh__8u1__p8_1,
  146196. _vq_quantmap__8u1__p8_1,
  146197. 11,
  146198. 11
  146199. };
  146200. static static_codebook _8u1__p8_1 = {
  146201. 2, 121,
  146202. _vq_lengthlist__8u1__p8_1,
  146203. 1, -531365888, 1611661312, 4, 0,
  146204. _vq_quantlist__8u1__p8_1,
  146205. NULL,
  146206. &_vq_auxt__8u1__p8_1,
  146207. NULL,
  146208. 0
  146209. };
  146210. static long _vq_quantlist__8u1__p9_0[] = {
  146211. 7,
  146212. 6,
  146213. 8,
  146214. 5,
  146215. 9,
  146216. 4,
  146217. 10,
  146218. 3,
  146219. 11,
  146220. 2,
  146221. 12,
  146222. 1,
  146223. 13,
  146224. 0,
  146225. 14,
  146226. };
  146227. static long _vq_lengthlist__8u1__p9_0[] = {
  146228. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146229. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146230. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146231. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146232. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146233. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146234. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146235. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146236. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146237. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146238. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146239. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146240. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146241. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146242. 10,
  146243. };
  146244. static float _vq_quantthresh__8u1__p9_0[] = {
  146245. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146246. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146247. };
  146248. static long _vq_quantmap__8u1__p9_0[] = {
  146249. 13, 11, 9, 7, 5, 3, 1, 0,
  146250. 2, 4, 6, 8, 10, 12, 14,
  146251. };
  146252. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146253. _vq_quantthresh__8u1__p9_0,
  146254. _vq_quantmap__8u1__p9_0,
  146255. 15,
  146256. 15
  146257. };
  146258. static static_codebook _8u1__p9_0 = {
  146259. 2, 225,
  146260. _vq_lengthlist__8u1__p9_0,
  146261. 1, -514071552, 1627381760, 4, 0,
  146262. _vq_quantlist__8u1__p9_0,
  146263. NULL,
  146264. &_vq_auxt__8u1__p9_0,
  146265. NULL,
  146266. 0
  146267. };
  146268. static long _vq_quantlist__8u1__p9_1[] = {
  146269. 7,
  146270. 6,
  146271. 8,
  146272. 5,
  146273. 9,
  146274. 4,
  146275. 10,
  146276. 3,
  146277. 11,
  146278. 2,
  146279. 12,
  146280. 1,
  146281. 13,
  146282. 0,
  146283. 14,
  146284. };
  146285. static long _vq_lengthlist__8u1__p9_1[] = {
  146286. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146287. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146288. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146289. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146290. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146291. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146292. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146293. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146294. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146295. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146296. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146297. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146298. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146299. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146300. 13,
  146301. };
  146302. static float _vq_quantthresh__8u1__p9_1[] = {
  146303. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146304. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146305. };
  146306. static long _vq_quantmap__8u1__p9_1[] = {
  146307. 13, 11, 9, 7, 5, 3, 1, 0,
  146308. 2, 4, 6, 8, 10, 12, 14,
  146309. };
  146310. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146311. _vq_quantthresh__8u1__p9_1,
  146312. _vq_quantmap__8u1__p9_1,
  146313. 15,
  146314. 15
  146315. };
  146316. static static_codebook _8u1__p9_1 = {
  146317. 2, 225,
  146318. _vq_lengthlist__8u1__p9_1,
  146319. 1, -522338304, 1620115456, 4, 0,
  146320. _vq_quantlist__8u1__p9_1,
  146321. NULL,
  146322. &_vq_auxt__8u1__p9_1,
  146323. NULL,
  146324. 0
  146325. };
  146326. static long _vq_quantlist__8u1__p9_2[] = {
  146327. 8,
  146328. 7,
  146329. 9,
  146330. 6,
  146331. 10,
  146332. 5,
  146333. 11,
  146334. 4,
  146335. 12,
  146336. 3,
  146337. 13,
  146338. 2,
  146339. 14,
  146340. 1,
  146341. 15,
  146342. 0,
  146343. 16,
  146344. };
  146345. static long _vq_lengthlist__8u1__p9_2[] = {
  146346. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146347. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146348. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146349. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146350. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146351. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146352. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146353. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146354. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146355. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146356. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146357. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146358. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146359. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146360. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146361. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146362. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146363. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146364. 10,
  146365. };
  146366. static float _vq_quantthresh__8u1__p9_2[] = {
  146367. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146368. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146369. };
  146370. static long _vq_quantmap__8u1__p9_2[] = {
  146371. 15, 13, 11, 9, 7, 5, 3, 1,
  146372. 0, 2, 4, 6, 8, 10, 12, 14,
  146373. 16,
  146374. };
  146375. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146376. _vq_quantthresh__8u1__p9_2,
  146377. _vq_quantmap__8u1__p9_2,
  146378. 17,
  146379. 17
  146380. };
  146381. static static_codebook _8u1__p9_2 = {
  146382. 2, 289,
  146383. _vq_lengthlist__8u1__p9_2,
  146384. 1, -529530880, 1611661312, 5, 0,
  146385. _vq_quantlist__8u1__p9_2,
  146386. NULL,
  146387. &_vq_auxt__8u1__p9_2,
  146388. NULL,
  146389. 0
  146390. };
  146391. static long _huff_lengthlist__8u1__single[] = {
  146392. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146393. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146394. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146395. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146396. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146397. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146398. 13, 8, 8,15,
  146399. };
  146400. static static_codebook _huff_book__8u1__single = {
  146401. 2, 100,
  146402. _huff_lengthlist__8u1__single,
  146403. 0, 0, 0, 0, 0,
  146404. NULL,
  146405. NULL,
  146406. NULL,
  146407. NULL,
  146408. 0
  146409. };
  146410. static long _huff_lengthlist__44u0__long[] = {
  146411. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146412. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146413. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146414. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146415. };
  146416. static static_codebook _huff_book__44u0__long = {
  146417. 2, 64,
  146418. _huff_lengthlist__44u0__long,
  146419. 0, 0, 0, 0, 0,
  146420. NULL,
  146421. NULL,
  146422. NULL,
  146423. NULL,
  146424. 0
  146425. };
  146426. static long _vq_quantlist__44u0__p1_0[] = {
  146427. 1,
  146428. 0,
  146429. 2,
  146430. };
  146431. static long _vq_lengthlist__44u0__p1_0[] = {
  146432. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146433. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146434. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146435. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146436. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146437. 13,
  146438. };
  146439. static float _vq_quantthresh__44u0__p1_0[] = {
  146440. -0.5, 0.5,
  146441. };
  146442. static long _vq_quantmap__44u0__p1_0[] = {
  146443. 1, 0, 2,
  146444. };
  146445. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146446. _vq_quantthresh__44u0__p1_0,
  146447. _vq_quantmap__44u0__p1_0,
  146448. 3,
  146449. 3
  146450. };
  146451. static static_codebook _44u0__p1_0 = {
  146452. 4, 81,
  146453. _vq_lengthlist__44u0__p1_0,
  146454. 1, -535822336, 1611661312, 2, 0,
  146455. _vq_quantlist__44u0__p1_0,
  146456. NULL,
  146457. &_vq_auxt__44u0__p1_0,
  146458. NULL,
  146459. 0
  146460. };
  146461. static long _vq_quantlist__44u0__p2_0[] = {
  146462. 1,
  146463. 0,
  146464. 2,
  146465. };
  146466. static long _vq_lengthlist__44u0__p2_0[] = {
  146467. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146468. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146469. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146470. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146471. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146472. 9,
  146473. };
  146474. static float _vq_quantthresh__44u0__p2_0[] = {
  146475. -0.5, 0.5,
  146476. };
  146477. static long _vq_quantmap__44u0__p2_0[] = {
  146478. 1, 0, 2,
  146479. };
  146480. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146481. _vq_quantthresh__44u0__p2_0,
  146482. _vq_quantmap__44u0__p2_0,
  146483. 3,
  146484. 3
  146485. };
  146486. static static_codebook _44u0__p2_0 = {
  146487. 4, 81,
  146488. _vq_lengthlist__44u0__p2_0,
  146489. 1, -535822336, 1611661312, 2, 0,
  146490. _vq_quantlist__44u0__p2_0,
  146491. NULL,
  146492. &_vq_auxt__44u0__p2_0,
  146493. NULL,
  146494. 0
  146495. };
  146496. static long _vq_quantlist__44u0__p3_0[] = {
  146497. 2,
  146498. 1,
  146499. 3,
  146500. 0,
  146501. 4,
  146502. };
  146503. static long _vq_lengthlist__44u0__p3_0[] = {
  146504. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146505. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146506. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146507. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146508. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146509. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146510. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146511. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146512. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146513. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146514. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146515. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146516. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146517. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146518. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146519. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146520. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146521. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146522. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146523. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146524. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146525. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146526. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146527. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146528. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146529. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146530. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146531. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146532. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146533. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146534. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146535. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146536. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146537. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146538. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146539. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146540. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146541. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146542. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146543. 19,
  146544. };
  146545. static float _vq_quantthresh__44u0__p3_0[] = {
  146546. -1.5, -0.5, 0.5, 1.5,
  146547. };
  146548. static long _vq_quantmap__44u0__p3_0[] = {
  146549. 3, 1, 0, 2, 4,
  146550. };
  146551. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146552. _vq_quantthresh__44u0__p3_0,
  146553. _vq_quantmap__44u0__p3_0,
  146554. 5,
  146555. 5
  146556. };
  146557. static static_codebook _44u0__p3_0 = {
  146558. 4, 625,
  146559. _vq_lengthlist__44u0__p3_0,
  146560. 1, -533725184, 1611661312, 3, 0,
  146561. _vq_quantlist__44u0__p3_0,
  146562. NULL,
  146563. &_vq_auxt__44u0__p3_0,
  146564. NULL,
  146565. 0
  146566. };
  146567. static long _vq_quantlist__44u0__p4_0[] = {
  146568. 2,
  146569. 1,
  146570. 3,
  146571. 0,
  146572. 4,
  146573. };
  146574. static long _vq_lengthlist__44u0__p4_0[] = {
  146575. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146576. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146577. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146578. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146579. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146580. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146581. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146582. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146583. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146584. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146585. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146586. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146587. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146588. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146589. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146590. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146591. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146592. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146593. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146594. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146595. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146596. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146597. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146598. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146599. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146600. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146601. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146602. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146603. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146604. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146605. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146606. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146607. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146608. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146609. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146610. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146611. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146612. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146613. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146614. 12,
  146615. };
  146616. static float _vq_quantthresh__44u0__p4_0[] = {
  146617. -1.5, -0.5, 0.5, 1.5,
  146618. };
  146619. static long _vq_quantmap__44u0__p4_0[] = {
  146620. 3, 1, 0, 2, 4,
  146621. };
  146622. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146623. _vq_quantthresh__44u0__p4_0,
  146624. _vq_quantmap__44u0__p4_0,
  146625. 5,
  146626. 5
  146627. };
  146628. static static_codebook _44u0__p4_0 = {
  146629. 4, 625,
  146630. _vq_lengthlist__44u0__p4_0,
  146631. 1, -533725184, 1611661312, 3, 0,
  146632. _vq_quantlist__44u0__p4_0,
  146633. NULL,
  146634. &_vq_auxt__44u0__p4_0,
  146635. NULL,
  146636. 0
  146637. };
  146638. static long _vq_quantlist__44u0__p5_0[] = {
  146639. 4,
  146640. 3,
  146641. 5,
  146642. 2,
  146643. 6,
  146644. 1,
  146645. 7,
  146646. 0,
  146647. 8,
  146648. };
  146649. static long _vq_lengthlist__44u0__p5_0[] = {
  146650. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146651. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146652. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146653. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146654. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146655. 12,
  146656. };
  146657. static float _vq_quantthresh__44u0__p5_0[] = {
  146658. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146659. };
  146660. static long _vq_quantmap__44u0__p5_0[] = {
  146661. 7, 5, 3, 1, 0, 2, 4, 6,
  146662. 8,
  146663. };
  146664. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146665. _vq_quantthresh__44u0__p5_0,
  146666. _vq_quantmap__44u0__p5_0,
  146667. 9,
  146668. 9
  146669. };
  146670. static static_codebook _44u0__p5_0 = {
  146671. 2, 81,
  146672. _vq_lengthlist__44u0__p5_0,
  146673. 1, -531628032, 1611661312, 4, 0,
  146674. _vq_quantlist__44u0__p5_0,
  146675. NULL,
  146676. &_vq_auxt__44u0__p5_0,
  146677. NULL,
  146678. 0
  146679. };
  146680. static long _vq_quantlist__44u0__p6_0[] = {
  146681. 6,
  146682. 5,
  146683. 7,
  146684. 4,
  146685. 8,
  146686. 3,
  146687. 9,
  146688. 2,
  146689. 10,
  146690. 1,
  146691. 11,
  146692. 0,
  146693. 12,
  146694. };
  146695. static long _vq_lengthlist__44u0__p6_0[] = {
  146696. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146697. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146698. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146699. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146700. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146701. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146702. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146703. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146704. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146705. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146706. 15,17,16,17,18,17,17,18, 0,
  146707. };
  146708. static float _vq_quantthresh__44u0__p6_0[] = {
  146709. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146710. 12.5, 17.5, 22.5, 27.5,
  146711. };
  146712. static long _vq_quantmap__44u0__p6_0[] = {
  146713. 11, 9, 7, 5, 3, 1, 0, 2,
  146714. 4, 6, 8, 10, 12,
  146715. };
  146716. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146717. _vq_quantthresh__44u0__p6_0,
  146718. _vq_quantmap__44u0__p6_0,
  146719. 13,
  146720. 13
  146721. };
  146722. static static_codebook _44u0__p6_0 = {
  146723. 2, 169,
  146724. _vq_lengthlist__44u0__p6_0,
  146725. 1, -526516224, 1616117760, 4, 0,
  146726. _vq_quantlist__44u0__p6_0,
  146727. NULL,
  146728. &_vq_auxt__44u0__p6_0,
  146729. NULL,
  146730. 0
  146731. };
  146732. static long _vq_quantlist__44u0__p6_1[] = {
  146733. 2,
  146734. 1,
  146735. 3,
  146736. 0,
  146737. 4,
  146738. };
  146739. static long _vq_lengthlist__44u0__p6_1[] = {
  146740. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146741. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146742. };
  146743. static float _vq_quantthresh__44u0__p6_1[] = {
  146744. -1.5, -0.5, 0.5, 1.5,
  146745. };
  146746. static long _vq_quantmap__44u0__p6_1[] = {
  146747. 3, 1, 0, 2, 4,
  146748. };
  146749. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146750. _vq_quantthresh__44u0__p6_1,
  146751. _vq_quantmap__44u0__p6_1,
  146752. 5,
  146753. 5
  146754. };
  146755. static static_codebook _44u0__p6_1 = {
  146756. 2, 25,
  146757. _vq_lengthlist__44u0__p6_1,
  146758. 1, -533725184, 1611661312, 3, 0,
  146759. _vq_quantlist__44u0__p6_1,
  146760. NULL,
  146761. &_vq_auxt__44u0__p6_1,
  146762. NULL,
  146763. 0
  146764. };
  146765. static long _vq_quantlist__44u0__p7_0[] = {
  146766. 2,
  146767. 1,
  146768. 3,
  146769. 0,
  146770. 4,
  146771. };
  146772. static long _vq_lengthlist__44u0__p7_0[] = {
  146773. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146775. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146776. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146777. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146778. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146780. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146787. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146803. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146804. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146805. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146806. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146807. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146808. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146809. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146810. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146811. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146812. 10,
  146813. };
  146814. static float _vq_quantthresh__44u0__p7_0[] = {
  146815. -253.5, -84.5, 84.5, 253.5,
  146816. };
  146817. static long _vq_quantmap__44u0__p7_0[] = {
  146818. 3, 1, 0, 2, 4,
  146819. };
  146820. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146821. _vq_quantthresh__44u0__p7_0,
  146822. _vq_quantmap__44u0__p7_0,
  146823. 5,
  146824. 5
  146825. };
  146826. static static_codebook _44u0__p7_0 = {
  146827. 4, 625,
  146828. _vq_lengthlist__44u0__p7_0,
  146829. 1, -518709248, 1626677248, 3, 0,
  146830. _vq_quantlist__44u0__p7_0,
  146831. NULL,
  146832. &_vq_auxt__44u0__p7_0,
  146833. NULL,
  146834. 0
  146835. };
  146836. static long _vq_quantlist__44u0__p7_1[] = {
  146837. 6,
  146838. 5,
  146839. 7,
  146840. 4,
  146841. 8,
  146842. 3,
  146843. 9,
  146844. 2,
  146845. 10,
  146846. 1,
  146847. 11,
  146848. 0,
  146849. 12,
  146850. };
  146851. static long _vq_lengthlist__44u0__p7_1[] = {
  146852. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146853. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146854. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146855. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146856. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146857. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146858. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146859. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146860. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146861. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146862. 15,15,15,15,15,15,15,15,15,
  146863. };
  146864. static float _vq_quantthresh__44u0__p7_1[] = {
  146865. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146866. 32.5, 45.5, 58.5, 71.5,
  146867. };
  146868. static long _vq_quantmap__44u0__p7_1[] = {
  146869. 11, 9, 7, 5, 3, 1, 0, 2,
  146870. 4, 6, 8, 10, 12,
  146871. };
  146872. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146873. _vq_quantthresh__44u0__p7_1,
  146874. _vq_quantmap__44u0__p7_1,
  146875. 13,
  146876. 13
  146877. };
  146878. static static_codebook _44u0__p7_1 = {
  146879. 2, 169,
  146880. _vq_lengthlist__44u0__p7_1,
  146881. 1, -523010048, 1618608128, 4, 0,
  146882. _vq_quantlist__44u0__p7_1,
  146883. NULL,
  146884. &_vq_auxt__44u0__p7_1,
  146885. NULL,
  146886. 0
  146887. };
  146888. static long _vq_quantlist__44u0__p7_2[] = {
  146889. 6,
  146890. 5,
  146891. 7,
  146892. 4,
  146893. 8,
  146894. 3,
  146895. 9,
  146896. 2,
  146897. 10,
  146898. 1,
  146899. 11,
  146900. 0,
  146901. 12,
  146902. };
  146903. static long _vq_lengthlist__44u0__p7_2[] = {
  146904. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146905. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146906. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146907. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146908. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146909. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146910. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146911. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146912. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146913. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146914. 9, 9, 9,10, 9, 9,10,10, 9,
  146915. };
  146916. static float _vq_quantthresh__44u0__p7_2[] = {
  146917. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146918. 2.5, 3.5, 4.5, 5.5,
  146919. };
  146920. static long _vq_quantmap__44u0__p7_2[] = {
  146921. 11, 9, 7, 5, 3, 1, 0, 2,
  146922. 4, 6, 8, 10, 12,
  146923. };
  146924. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146925. _vq_quantthresh__44u0__p7_2,
  146926. _vq_quantmap__44u0__p7_2,
  146927. 13,
  146928. 13
  146929. };
  146930. static static_codebook _44u0__p7_2 = {
  146931. 2, 169,
  146932. _vq_lengthlist__44u0__p7_2,
  146933. 1, -531103744, 1611661312, 4, 0,
  146934. _vq_quantlist__44u0__p7_2,
  146935. NULL,
  146936. &_vq_auxt__44u0__p7_2,
  146937. NULL,
  146938. 0
  146939. };
  146940. static long _huff_lengthlist__44u0__short[] = {
  146941. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146942. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146943. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146944. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146945. };
  146946. static static_codebook _huff_book__44u0__short = {
  146947. 2, 64,
  146948. _huff_lengthlist__44u0__short,
  146949. 0, 0, 0, 0, 0,
  146950. NULL,
  146951. NULL,
  146952. NULL,
  146953. NULL,
  146954. 0
  146955. };
  146956. static long _huff_lengthlist__44u1__long[] = {
  146957. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146958. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146959. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146960. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146961. };
  146962. static static_codebook _huff_book__44u1__long = {
  146963. 2, 64,
  146964. _huff_lengthlist__44u1__long,
  146965. 0, 0, 0, 0, 0,
  146966. NULL,
  146967. NULL,
  146968. NULL,
  146969. NULL,
  146970. 0
  146971. };
  146972. static long _vq_quantlist__44u1__p1_0[] = {
  146973. 1,
  146974. 0,
  146975. 2,
  146976. };
  146977. static long _vq_lengthlist__44u1__p1_0[] = {
  146978. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146979. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146980. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146981. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146982. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146983. 13,
  146984. };
  146985. static float _vq_quantthresh__44u1__p1_0[] = {
  146986. -0.5, 0.5,
  146987. };
  146988. static long _vq_quantmap__44u1__p1_0[] = {
  146989. 1, 0, 2,
  146990. };
  146991. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146992. _vq_quantthresh__44u1__p1_0,
  146993. _vq_quantmap__44u1__p1_0,
  146994. 3,
  146995. 3
  146996. };
  146997. static static_codebook _44u1__p1_0 = {
  146998. 4, 81,
  146999. _vq_lengthlist__44u1__p1_0,
  147000. 1, -535822336, 1611661312, 2, 0,
  147001. _vq_quantlist__44u1__p1_0,
  147002. NULL,
  147003. &_vq_auxt__44u1__p1_0,
  147004. NULL,
  147005. 0
  147006. };
  147007. static long _vq_quantlist__44u1__p2_0[] = {
  147008. 1,
  147009. 0,
  147010. 2,
  147011. };
  147012. static long _vq_lengthlist__44u1__p2_0[] = {
  147013. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147014. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  147015. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147016. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  147017. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147018. 9,
  147019. };
  147020. static float _vq_quantthresh__44u1__p2_0[] = {
  147021. -0.5, 0.5,
  147022. };
  147023. static long _vq_quantmap__44u1__p2_0[] = {
  147024. 1, 0, 2,
  147025. };
  147026. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  147027. _vq_quantthresh__44u1__p2_0,
  147028. _vq_quantmap__44u1__p2_0,
  147029. 3,
  147030. 3
  147031. };
  147032. static static_codebook _44u1__p2_0 = {
  147033. 4, 81,
  147034. _vq_lengthlist__44u1__p2_0,
  147035. 1, -535822336, 1611661312, 2, 0,
  147036. _vq_quantlist__44u1__p2_0,
  147037. NULL,
  147038. &_vq_auxt__44u1__p2_0,
  147039. NULL,
  147040. 0
  147041. };
  147042. static long _vq_quantlist__44u1__p3_0[] = {
  147043. 2,
  147044. 1,
  147045. 3,
  147046. 0,
  147047. 4,
  147048. };
  147049. static long _vq_lengthlist__44u1__p3_0[] = {
  147050. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147051. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  147052. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  147053. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  147054. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  147055. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  147056. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  147057. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  147058. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  147059. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  147060. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  147061. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  147062. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  147063. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  147064. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  147065. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  147066. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  147067. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147068. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147069. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147070. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147071. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147072. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147073. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147074. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147075. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147076. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147077. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147078. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147079. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147080. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147081. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147082. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147083. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147084. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147085. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147086. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147087. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147088. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147089. 19,
  147090. };
  147091. static float _vq_quantthresh__44u1__p3_0[] = {
  147092. -1.5, -0.5, 0.5, 1.5,
  147093. };
  147094. static long _vq_quantmap__44u1__p3_0[] = {
  147095. 3, 1, 0, 2, 4,
  147096. };
  147097. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  147098. _vq_quantthresh__44u1__p3_0,
  147099. _vq_quantmap__44u1__p3_0,
  147100. 5,
  147101. 5
  147102. };
  147103. static static_codebook _44u1__p3_0 = {
  147104. 4, 625,
  147105. _vq_lengthlist__44u1__p3_0,
  147106. 1, -533725184, 1611661312, 3, 0,
  147107. _vq_quantlist__44u1__p3_0,
  147108. NULL,
  147109. &_vq_auxt__44u1__p3_0,
  147110. NULL,
  147111. 0
  147112. };
  147113. static long _vq_quantlist__44u1__p4_0[] = {
  147114. 2,
  147115. 1,
  147116. 3,
  147117. 0,
  147118. 4,
  147119. };
  147120. static long _vq_lengthlist__44u1__p4_0[] = {
  147121. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147122. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147123. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147124. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147125. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147126. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147127. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147128. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147129. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147130. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147131. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147132. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147133. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147134. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147135. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147136. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147137. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147138. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147139. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147140. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147141. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147142. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147143. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147144. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147145. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147146. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147147. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147148. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147149. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147150. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147151. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147152. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147153. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147154. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147155. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147156. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147157. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147158. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147159. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147160. 12,
  147161. };
  147162. static float _vq_quantthresh__44u1__p4_0[] = {
  147163. -1.5, -0.5, 0.5, 1.5,
  147164. };
  147165. static long _vq_quantmap__44u1__p4_0[] = {
  147166. 3, 1, 0, 2, 4,
  147167. };
  147168. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147169. _vq_quantthresh__44u1__p4_0,
  147170. _vq_quantmap__44u1__p4_0,
  147171. 5,
  147172. 5
  147173. };
  147174. static static_codebook _44u1__p4_0 = {
  147175. 4, 625,
  147176. _vq_lengthlist__44u1__p4_0,
  147177. 1, -533725184, 1611661312, 3, 0,
  147178. _vq_quantlist__44u1__p4_0,
  147179. NULL,
  147180. &_vq_auxt__44u1__p4_0,
  147181. NULL,
  147182. 0
  147183. };
  147184. static long _vq_quantlist__44u1__p5_0[] = {
  147185. 4,
  147186. 3,
  147187. 5,
  147188. 2,
  147189. 6,
  147190. 1,
  147191. 7,
  147192. 0,
  147193. 8,
  147194. };
  147195. static long _vq_lengthlist__44u1__p5_0[] = {
  147196. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147197. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147198. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147199. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147200. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147201. 12,
  147202. };
  147203. static float _vq_quantthresh__44u1__p5_0[] = {
  147204. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147205. };
  147206. static long _vq_quantmap__44u1__p5_0[] = {
  147207. 7, 5, 3, 1, 0, 2, 4, 6,
  147208. 8,
  147209. };
  147210. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147211. _vq_quantthresh__44u1__p5_0,
  147212. _vq_quantmap__44u1__p5_0,
  147213. 9,
  147214. 9
  147215. };
  147216. static static_codebook _44u1__p5_0 = {
  147217. 2, 81,
  147218. _vq_lengthlist__44u1__p5_0,
  147219. 1, -531628032, 1611661312, 4, 0,
  147220. _vq_quantlist__44u1__p5_0,
  147221. NULL,
  147222. &_vq_auxt__44u1__p5_0,
  147223. NULL,
  147224. 0
  147225. };
  147226. static long _vq_quantlist__44u1__p6_0[] = {
  147227. 6,
  147228. 5,
  147229. 7,
  147230. 4,
  147231. 8,
  147232. 3,
  147233. 9,
  147234. 2,
  147235. 10,
  147236. 1,
  147237. 11,
  147238. 0,
  147239. 12,
  147240. };
  147241. static long _vq_lengthlist__44u1__p6_0[] = {
  147242. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147243. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147244. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147245. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147246. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147247. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147248. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147249. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147250. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147251. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147252. 15,17,16,17,18,17,17,18, 0,
  147253. };
  147254. static float _vq_quantthresh__44u1__p6_0[] = {
  147255. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147256. 12.5, 17.5, 22.5, 27.5,
  147257. };
  147258. static long _vq_quantmap__44u1__p6_0[] = {
  147259. 11, 9, 7, 5, 3, 1, 0, 2,
  147260. 4, 6, 8, 10, 12,
  147261. };
  147262. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147263. _vq_quantthresh__44u1__p6_0,
  147264. _vq_quantmap__44u1__p6_0,
  147265. 13,
  147266. 13
  147267. };
  147268. static static_codebook _44u1__p6_0 = {
  147269. 2, 169,
  147270. _vq_lengthlist__44u1__p6_0,
  147271. 1, -526516224, 1616117760, 4, 0,
  147272. _vq_quantlist__44u1__p6_0,
  147273. NULL,
  147274. &_vq_auxt__44u1__p6_0,
  147275. NULL,
  147276. 0
  147277. };
  147278. static long _vq_quantlist__44u1__p6_1[] = {
  147279. 2,
  147280. 1,
  147281. 3,
  147282. 0,
  147283. 4,
  147284. };
  147285. static long _vq_lengthlist__44u1__p6_1[] = {
  147286. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147287. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147288. };
  147289. static float _vq_quantthresh__44u1__p6_1[] = {
  147290. -1.5, -0.5, 0.5, 1.5,
  147291. };
  147292. static long _vq_quantmap__44u1__p6_1[] = {
  147293. 3, 1, 0, 2, 4,
  147294. };
  147295. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147296. _vq_quantthresh__44u1__p6_1,
  147297. _vq_quantmap__44u1__p6_1,
  147298. 5,
  147299. 5
  147300. };
  147301. static static_codebook _44u1__p6_1 = {
  147302. 2, 25,
  147303. _vq_lengthlist__44u1__p6_1,
  147304. 1, -533725184, 1611661312, 3, 0,
  147305. _vq_quantlist__44u1__p6_1,
  147306. NULL,
  147307. &_vq_auxt__44u1__p6_1,
  147308. NULL,
  147309. 0
  147310. };
  147311. static long _vq_quantlist__44u1__p7_0[] = {
  147312. 3,
  147313. 2,
  147314. 4,
  147315. 1,
  147316. 5,
  147317. 0,
  147318. 6,
  147319. };
  147320. static long _vq_lengthlist__44u1__p7_0[] = {
  147321. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147322. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147323. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147324. 8,
  147325. };
  147326. static float _vq_quantthresh__44u1__p7_0[] = {
  147327. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147328. };
  147329. static long _vq_quantmap__44u1__p7_0[] = {
  147330. 5, 3, 1, 0, 2, 4, 6,
  147331. };
  147332. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147333. _vq_quantthresh__44u1__p7_0,
  147334. _vq_quantmap__44u1__p7_0,
  147335. 7,
  147336. 7
  147337. };
  147338. static static_codebook _44u1__p7_0 = {
  147339. 2, 49,
  147340. _vq_lengthlist__44u1__p7_0,
  147341. 1, -518017024, 1626677248, 3, 0,
  147342. _vq_quantlist__44u1__p7_0,
  147343. NULL,
  147344. &_vq_auxt__44u1__p7_0,
  147345. NULL,
  147346. 0
  147347. };
  147348. static long _vq_quantlist__44u1__p7_1[] = {
  147349. 6,
  147350. 5,
  147351. 7,
  147352. 4,
  147353. 8,
  147354. 3,
  147355. 9,
  147356. 2,
  147357. 10,
  147358. 1,
  147359. 11,
  147360. 0,
  147361. 12,
  147362. };
  147363. static long _vq_lengthlist__44u1__p7_1[] = {
  147364. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147365. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147366. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147367. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147368. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147369. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147370. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147371. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147372. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147373. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147374. 15,15,15,15,15,15,15,15,15,
  147375. };
  147376. static float _vq_quantthresh__44u1__p7_1[] = {
  147377. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147378. 32.5, 45.5, 58.5, 71.5,
  147379. };
  147380. static long _vq_quantmap__44u1__p7_1[] = {
  147381. 11, 9, 7, 5, 3, 1, 0, 2,
  147382. 4, 6, 8, 10, 12,
  147383. };
  147384. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147385. _vq_quantthresh__44u1__p7_1,
  147386. _vq_quantmap__44u1__p7_1,
  147387. 13,
  147388. 13
  147389. };
  147390. static static_codebook _44u1__p7_1 = {
  147391. 2, 169,
  147392. _vq_lengthlist__44u1__p7_1,
  147393. 1, -523010048, 1618608128, 4, 0,
  147394. _vq_quantlist__44u1__p7_1,
  147395. NULL,
  147396. &_vq_auxt__44u1__p7_1,
  147397. NULL,
  147398. 0
  147399. };
  147400. static long _vq_quantlist__44u1__p7_2[] = {
  147401. 6,
  147402. 5,
  147403. 7,
  147404. 4,
  147405. 8,
  147406. 3,
  147407. 9,
  147408. 2,
  147409. 10,
  147410. 1,
  147411. 11,
  147412. 0,
  147413. 12,
  147414. };
  147415. static long _vq_lengthlist__44u1__p7_2[] = {
  147416. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147417. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147418. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147419. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147420. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147421. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147422. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147423. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147424. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147425. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147426. 9, 9, 9,10, 9, 9,10,10, 9,
  147427. };
  147428. static float _vq_quantthresh__44u1__p7_2[] = {
  147429. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147430. 2.5, 3.5, 4.5, 5.5,
  147431. };
  147432. static long _vq_quantmap__44u1__p7_2[] = {
  147433. 11, 9, 7, 5, 3, 1, 0, 2,
  147434. 4, 6, 8, 10, 12,
  147435. };
  147436. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147437. _vq_quantthresh__44u1__p7_2,
  147438. _vq_quantmap__44u1__p7_2,
  147439. 13,
  147440. 13
  147441. };
  147442. static static_codebook _44u1__p7_2 = {
  147443. 2, 169,
  147444. _vq_lengthlist__44u1__p7_2,
  147445. 1, -531103744, 1611661312, 4, 0,
  147446. _vq_quantlist__44u1__p7_2,
  147447. NULL,
  147448. &_vq_auxt__44u1__p7_2,
  147449. NULL,
  147450. 0
  147451. };
  147452. static long _huff_lengthlist__44u1__short[] = {
  147453. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147454. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147455. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147456. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147457. };
  147458. static static_codebook _huff_book__44u1__short = {
  147459. 2, 64,
  147460. _huff_lengthlist__44u1__short,
  147461. 0, 0, 0, 0, 0,
  147462. NULL,
  147463. NULL,
  147464. NULL,
  147465. NULL,
  147466. 0
  147467. };
  147468. static long _huff_lengthlist__44u2__long[] = {
  147469. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147470. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147471. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147472. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147473. };
  147474. static static_codebook _huff_book__44u2__long = {
  147475. 2, 64,
  147476. _huff_lengthlist__44u2__long,
  147477. 0, 0, 0, 0, 0,
  147478. NULL,
  147479. NULL,
  147480. NULL,
  147481. NULL,
  147482. 0
  147483. };
  147484. static long _vq_quantlist__44u2__p1_0[] = {
  147485. 1,
  147486. 0,
  147487. 2,
  147488. };
  147489. static long _vq_lengthlist__44u2__p1_0[] = {
  147490. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147491. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147492. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147493. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147494. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147495. 13,
  147496. };
  147497. static float _vq_quantthresh__44u2__p1_0[] = {
  147498. -0.5, 0.5,
  147499. };
  147500. static long _vq_quantmap__44u2__p1_0[] = {
  147501. 1, 0, 2,
  147502. };
  147503. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147504. _vq_quantthresh__44u2__p1_0,
  147505. _vq_quantmap__44u2__p1_0,
  147506. 3,
  147507. 3
  147508. };
  147509. static static_codebook _44u2__p1_0 = {
  147510. 4, 81,
  147511. _vq_lengthlist__44u2__p1_0,
  147512. 1, -535822336, 1611661312, 2, 0,
  147513. _vq_quantlist__44u2__p1_0,
  147514. NULL,
  147515. &_vq_auxt__44u2__p1_0,
  147516. NULL,
  147517. 0
  147518. };
  147519. static long _vq_quantlist__44u2__p2_0[] = {
  147520. 1,
  147521. 0,
  147522. 2,
  147523. };
  147524. static long _vq_lengthlist__44u2__p2_0[] = {
  147525. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147526. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147527. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147528. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147529. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147530. 9,
  147531. };
  147532. static float _vq_quantthresh__44u2__p2_0[] = {
  147533. -0.5, 0.5,
  147534. };
  147535. static long _vq_quantmap__44u2__p2_0[] = {
  147536. 1, 0, 2,
  147537. };
  147538. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147539. _vq_quantthresh__44u2__p2_0,
  147540. _vq_quantmap__44u2__p2_0,
  147541. 3,
  147542. 3
  147543. };
  147544. static static_codebook _44u2__p2_0 = {
  147545. 4, 81,
  147546. _vq_lengthlist__44u2__p2_0,
  147547. 1, -535822336, 1611661312, 2, 0,
  147548. _vq_quantlist__44u2__p2_0,
  147549. NULL,
  147550. &_vq_auxt__44u2__p2_0,
  147551. NULL,
  147552. 0
  147553. };
  147554. static long _vq_quantlist__44u2__p3_0[] = {
  147555. 2,
  147556. 1,
  147557. 3,
  147558. 0,
  147559. 4,
  147560. };
  147561. static long _vq_lengthlist__44u2__p3_0[] = {
  147562. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147563. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147564. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147565. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147566. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147567. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147568. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147569. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147570. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147571. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147572. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147573. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147574. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147575. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147576. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147577. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147578. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147579. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147580. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147581. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147582. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147583. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147584. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147585. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147586. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147587. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147588. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147589. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147590. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147591. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147592. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147593. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147594. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147595. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147596. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147597. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147598. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147599. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147600. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147601. 0,
  147602. };
  147603. static float _vq_quantthresh__44u2__p3_0[] = {
  147604. -1.5, -0.5, 0.5, 1.5,
  147605. };
  147606. static long _vq_quantmap__44u2__p3_0[] = {
  147607. 3, 1, 0, 2, 4,
  147608. };
  147609. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147610. _vq_quantthresh__44u2__p3_0,
  147611. _vq_quantmap__44u2__p3_0,
  147612. 5,
  147613. 5
  147614. };
  147615. static static_codebook _44u2__p3_0 = {
  147616. 4, 625,
  147617. _vq_lengthlist__44u2__p3_0,
  147618. 1, -533725184, 1611661312, 3, 0,
  147619. _vq_quantlist__44u2__p3_0,
  147620. NULL,
  147621. &_vq_auxt__44u2__p3_0,
  147622. NULL,
  147623. 0
  147624. };
  147625. static long _vq_quantlist__44u2__p4_0[] = {
  147626. 2,
  147627. 1,
  147628. 3,
  147629. 0,
  147630. 4,
  147631. };
  147632. static long _vq_lengthlist__44u2__p4_0[] = {
  147633. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147634. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147635. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147636. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147637. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147638. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147639. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147640. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147641. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147642. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147643. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147644. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147645. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147646. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147647. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147648. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147649. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147650. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147651. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147652. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147653. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147654. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147655. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147656. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147657. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147658. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147659. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147660. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147661. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147662. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147663. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147664. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147665. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147666. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147667. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147668. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147669. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147670. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147671. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147672. 13,
  147673. };
  147674. static float _vq_quantthresh__44u2__p4_0[] = {
  147675. -1.5, -0.5, 0.5, 1.5,
  147676. };
  147677. static long _vq_quantmap__44u2__p4_0[] = {
  147678. 3, 1, 0, 2, 4,
  147679. };
  147680. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147681. _vq_quantthresh__44u2__p4_0,
  147682. _vq_quantmap__44u2__p4_0,
  147683. 5,
  147684. 5
  147685. };
  147686. static static_codebook _44u2__p4_0 = {
  147687. 4, 625,
  147688. _vq_lengthlist__44u2__p4_0,
  147689. 1, -533725184, 1611661312, 3, 0,
  147690. _vq_quantlist__44u2__p4_0,
  147691. NULL,
  147692. &_vq_auxt__44u2__p4_0,
  147693. NULL,
  147694. 0
  147695. };
  147696. static long _vq_quantlist__44u2__p5_0[] = {
  147697. 4,
  147698. 3,
  147699. 5,
  147700. 2,
  147701. 6,
  147702. 1,
  147703. 7,
  147704. 0,
  147705. 8,
  147706. };
  147707. static long _vq_lengthlist__44u2__p5_0[] = {
  147708. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147709. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147710. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147711. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147712. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147713. 13,
  147714. };
  147715. static float _vq_quantthresh__44u2__p5_0[] = {
  147716. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147717. };
  147718. static long _vq_quantmap__44u2__p5_0[] = {
  147719. 7, 5, 3, 1, 0, 2, 4, 6,
  147720. 8,
  147721. };
  147722. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147723. _vq_quantthresh__44u2__p5_0,
  147724. _vq_quantmap__44u2__p5_0,
  147725. 9,
  147726. 9
  147727. };
  147728. static static_codebook _44u2__p5_0 = {
  147729. 2, 81,
  147730. _vq_lengthlist__44u2__p5_0,
  147731. 1, -531628032, 1611661312, 4, 0,
  147732. _vq_quantlist__44u2__p5_0,
  147733. NULL,
  147734. &_vq_auxt__44u2__p5_0,
  147735. NULL,
  147736. 0
  147737. };
  147738. static long _vq_quantlist__44u2__p6_0[] = {
  147739. 6,
  147740. 5,
  147741. 7,
  147742. 4,
  147743. 8,
  147744. 3,
  147745. 9,
  147746. 2,
  147747. 10,
  147748. 1,
  147749. 11,
  147750. 0,
  147751. 12,
  147752. };
  147753. static long _vq_lengthlist__44u2__p6_0[] = {
  147754. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147755. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147756. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147757. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147758. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147759. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147760. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147761. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147762. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147763. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147764. 15,17,17,16,18,17,18, 0, 0,
  147765. };
  147766. static float _vq_quantthresh__44u2__p6_0[] = {
  147767. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147768. 12.5, 17.5, 22.5, 27.5,
  147769. };
  147770. static long _vq_quantmap__44u2__p6_0[] = {
  147771. 11, 9, 7, 5, 3, 1, 0, 2,
  147772. 4, 6, 8, 10, 12,
  147773. };
  147774. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147775. _vq_quantthresh__44u2__p6_0,
  147776. _vq_quantmap__44u2__p6_0,
  147777. 13,
  147778. 13
  147779. };
  147780. static static_codebook _44u2__p6_0 = {
  147781. 2, 169,
  147782. _vq_lengthlist__44u2__p6_0,
  147783. 1, -526516224, 1616117760, 4, 0,
  147784. _vq_quantlist__44u2__p6_0,
  147785. NULL,
  147786. &_vq_auxt__44u2__p6_0,
  147787. NULL,
  147788. 0
  147789. };
  147790. static long _vq_quantlist__44u2__p6_1[] = {
  147791. 2,
  147792. 1,
  147793. 3,
  147794. 0,
  147795. 4,
  147796. };
  147797. static long _vq_lengthlist__44u2__p6_1[] = {
  147798. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147799. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147800. };
  147801. static float _vq_quantthresh__44u2__p6_1[] = {
  147802. -1.5, -0.5, 0.5, 1.5,
  147803. };
  147804. static long _vq_quantmap__44u2__p6_1[] = {
  147805. 3, 1, 0, 2, 4,
  147806. };
  147807. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147808. _vq_quantthresh__44u2__p6_1,
  147809. _vq_quantmap__44u2__p6_1,
  147810. 5,
  147811. 5
  147812. };
  147813. static static_codebook _44u2__p6_1 = {
  147814. 2, 25,
  147815. _vq_lengthlist__44u2__p6_1,
  147816. 1, -533725184, 1611661312, 3, 0,
  147817. _vq_quantlist__44u2__p6_1,
  147818. NULL,
  147819. &_vq_auxt__44u2__p6_1,
  147820. NULL,
  147821. 0
  147822. };
  147823. static long _vq_quantlist__44u2__p7_0[] = {
  147824. 4,
  147825. 3,
  147826. 5,
  147827. 2,
  147828. 6,
  147829. 1,
  147830. 7,
  147831. 0,
  147832. 8,
  147833. };
  147834. static long _vq_lengthlist__44u2__p7_0[] = {
  147835. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147836. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147837. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147838. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147840. 11,
  147841. };
  147842. static float _vq_quantthresh__44u2__p7_0[] = {
  147843. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147844. };
  147845. static long _vq_quantmap__44u2__p7_0[] = {
  147846. 7, 5, 3, 1, 0, 2, 4, 6,
  147847. 8,
  147848. };
  147849. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147850. _vq_quantthresh__44u2__p7_0,
  147851. _vq_quantmap__44u2__p7_0,
  147852. 9,
  147853. 9
  147854. };
  147855. static static_codebook _44u2__p7_0 = {
  147856. 2, 81,
  147857. _vq_lengthlist__44u2__p7_0,
  147858. 1, -516612096, 1626677248, 4, 0,
  147859. _vq_quantlist__44u2__p7_0,
  147860. NULL,
  147861. &_vq_auxt__44u2__p7_0,
  147862. NULL,
  147863. 0
  147864. };
  147865. static long _vq_quantlist__44u2__p7_1[] = {
  147866. 6,
  147867. 5,
  147868. 7,
  147869. 4,
  147870. 8,
  147871. 3,
  147872. 9,
  147873. 2,
  147874. 10,
  147875. 1,
  147876. 11,
  147877. 0,
  147878. 12,
  147879. };
  147880. static long _vq_lengthlist__44u2__p7_1[] = {
  147881. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147882. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147883. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147884. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147885. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147886. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147887. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147888. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147889. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147890. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147891. 14,14,14,17,15,17,17,17,17,
  147892. };
  147893. static float _vq_quantthresh__44u2__p7_1[] = {
  147894. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147895. 32.5, 45.5, 58.5, 71.5,
  147896. };
  147897. static long _vq_quantmap__44u2__p7_1[] = {
  147898. 11, 9, 7, 5, 3, 1, 0, 2,
  147899. 4, 6, 8, 10, 12,
  147900. };
  147901. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147902. _vq_quantthresh__44u2__p7_1,
  147903. _vq_quantmap__44u2__p7_1,
  147904. 13,
  147905. 13
  147906. };
  147907. static static_codebook _44u2__p7_1 = {
  147908. 2, 169,
  147909. _vq_lengthlist__44u2__p7_1,
  147910. 1, -523010048, 1618608128, 4, 0,
  147911. _vq_quantlist__44u2__p7_1,
  147912. NULL,
  147913. &_vq_auxt__44u2__p7_1,
  147914. NULL,
  147915. 0
  147916. };
  147917. static long _vq_quantlist__44u2__p7_2[] = {
  147918. 6,
  147919. 5,
  147920. 7,
  147921. 4,
  147922. 8,
  147923. 3,
  147924. 9,
  147925. 2,
  147926. 10,
  147927. 1,
  147928. 11,
  147929. 0,
  147930. 12,
  147931. };
  147932. static long _vq_lengthlist__44u2__p7_2[] = {
  147933. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147934. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147935. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147936. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147937. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147938. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147939. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147940. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147941. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147942. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147943. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147944. };
  147945. static float _vq_quantthresh__44u2__p7_2[] = {
  147946. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147947. 2.5, 3.5, 4.5, 5.5,
  147948. };
  147949. static long _vq_quantmap__44u2__p7_2[] = {
  147950. 11, 9, 7, 5, 3, 1, 0, 2,
  147951. 4, 6, 8, 10, 12,
  147952. };
  147953. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147954. _vq_quantthresh__44u2__p7_2,
  147955. _vq_quantmap__44u2__p7_2,
  147956. 13,
  147957. 13
  147958. };
  147959. static static_codebook _44u2__p7_2 = {
  147960. 2, 169,
  147961. _vq_lengthlist__44u2__p7_2,
  147962. 1, -531103744, 1611661312, 4, 0,
  147963. _vq_quantlist__44u2__p7_2,
  147964. NULL,
  147965. &_vq_auxt__44u2__p7_2,
  147966. NULL,
  147967. 0
  147968. };
  147969. static long _huff_lengthlist__44u2__short[] = {
  147970. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147971. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147972. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147973. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147974. };
  147975. static static_codebook _huff_book__44u2__short = {
  147976. 2, 64,
  147977. _huff_lengthlist__44u2__short,
  147978. 0, 0, 0, 0, 0,
  147979. NULL,
  147980. NULL,
  147981. NULL,
  147982. NULL,
  147983. 0
  147984. };
  147985. static long _huff_lengthlist__44u3__long[] = {
  147986. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147987. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147988. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147989. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147990. };
  147991. static static_codebook _huff_book__44u3__long = {
  147992. 2, 64,
  147993. _huff_lengthlist__44u3__long,
  147994. 0, 0, 0, 0, 0,
  147995. NULL,
  147996. NULL,
  147997. NULL,
  147998. NULL,
  147999. 0
  148000. };
  148001. static long _vq_quantlist__44u3__p1_0[] = {
  148002. 1,
  148003. 0,
  148004. 2,
  148005. };
  148006. static long _vq_lengthlist__44u3__p1_0[] = {
  148007. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148008. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148009. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  148010. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148011. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  148012. 13,
  148013. };
  148014. static float _vq_quantthresh__44u3__p1_0[] = {
  148015. -0.5, 0.5,
  148016. };
  148017. static long _vq_quantmap__44u3__p1_0[] = {
  148018. 1, 0, 2,
  148019. };
  148020. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  148021. _vq_quantthresh__44u3__p1_0,
  148022. _vq_quantmap__44u3__p1_0,
  148023. 3,
  148024. 3
  148025. };
  148026. static static_codebook _44u3__p1_0 = {
  148027. 4, 81,
  148028. _vq_lengthlist__44u3__p1_0,
  148029. 1, -535822336, 1611661312, 2, 0,
  148030. _vq_quantlist__44u3__p1_0,
  148031. NULL,
  148032. &_vq_auxt__44u3__p1_0,
  148033. NULL,
  148034. 0
  148035. };
  148036. static long _vq_quantlist__44u3__p2_0[] = {
  148037. 1,
  148038. 0,
  148039. 2,
  148040. };
  148041. static long _vq_lengthlist__44u3__p2_0[] = {
  148042. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148043. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  148044. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148045. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148046. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  148047. 9,
  148048. };
  148049. static float _vq_quantthresh__44u3__p2_0[] = {
  148050. -0.5, 0.5,
  148051. };
  148052. static long _vq_quantmap__44u3__p2_0[] = {
  148053. 1, 0, 2,
  148054. };
  148055. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  148056. _vq_quantthresh__44u3__p2_0,
  148057. _vq_quantmap__44u3__p2_0,
  148058. 3,
  148059. 3
  148060. };
  148061. static static_codebook _44u3__p2_0 = {
  148062. 4, 81,
  148063. _vq_lengthlist__44u3__p2_0,
  148064. 1, -535822336, 1611661312, 2, 0,
  148065. _vq_quantlist__44u3__p2_0,
  148066. NULL,
  148067. &_vq_auxt__44u3__p2_0,
  148068. NULL,
  148069. 0
  148070. };
  148071. static long _vq_quantlist__44u3__p3_0[] = {
  148072. 2,
  148073. 1,
  148074. 3,
  148075. 0,
  148076. 4,
  148077. };
  148078. static long _vq_lengthlist__44u3__p3_0[] = {
  148079. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148080. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148081. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148082. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148083. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  148084. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  148085. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  148086. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  148087. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148088. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148089. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  148090. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148091. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  148092. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  148093. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  148094. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  148095. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  148096. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  148097. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  148098. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  148099. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  148100. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  148101. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  148102. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  148103. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  148104. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  148105. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148106. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148107. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148108. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148109. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148110. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148111. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148112. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148113. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148114. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148115. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148116. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148117. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148118. 0,
  148119. };
  148120. static float _vq_quantthresh__44u3__p3_0[] = {
  148121. -1.5, -0.5, 0.5, 1.5,
  148122. };
  148123. static long _vq_quantmap__44u3__p3_0[] = {
  148124. 3, 1, 0, 2, 4,
  148125. };
  148126. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148127. _vq_quantthresh__44u3__p3_0,
  148128. _vq_quantmap__44u3__p3_0,
  148129. 5,
  148130. 5
  148131. };
  148132. static static_codebook _44u3__p3_0 = {
  148133. 4, 625,
  148134. _vq_lengthlist__44u3__p3_0,
  148135. 1, -533725184, 1611661312, 3, 0,
  148136. _vq_quantlist__44u3__p3_0,
  148137. NULL,
  148138. &_vq_auxt__44u3__p3_0,
  148139. NULL,
  148140. 0
  148141. };
  148142. static long _vq_quantlist__44u3__p4_0[] = {
  148143. 2,
  148144. 1,
  148145. 3,
  148146. 0,
  148147. 4,
  148148. };
  148149. static long _vq_lengthlist__44u3__p4_0[] = {
  148150. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148151. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148152. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148153. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148154. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148155. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148156. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148157. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148158. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148159. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148160. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148161. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148162. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148163. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148164. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148165. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148166. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148167. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148168. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148169. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148170. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148171. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148172. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148173. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148174. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148175. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148176. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148177. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148178. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148179. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148180. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148181. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148182. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148183. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148184. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148185. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148186. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148187. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148188. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148189. 13,
  148190. };
  148191. static float _vq_quantthresh__44u3__p4_0[] = {
  148192. -1.5, -0.5, 0.5, 1.5,
  148193. };
  148194. static long _vq_quantmap__44u3__p4_0[] = {
  148195. 3, 1, 0, 2, 4,
  148196. };
  148197. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148198. _vq_quantthresh__44u3__p4_0,
  148199. _vq_quantmap__44u3__p4_0,
  148200. 5,
  148201. 5
  148202. };
  148203. static static_codebook _44u3__p4_0 = {
  148204. 4, 625,
  148205. _vq_lengthlist__44u3__p4_0,
  148206. 1, -533725184, 1611661312, 3, 0,
  148207. _vq_quantlist__44u3__p4_0,
  148208. NULL,
  148209. &_vq_auxt__44u3__p4_0,
  148210. NULL,
  148211. 0
  148212. };
  148213. static long _vq_quantlist__44u3__p5_0[] = {
  148214. 4,
  148215. 3,
  148216. 5,
  148217. 2,
  148218. 6,
  148219. 1,
  148220. 7,
  148221. 0,
  148222. 8,
  148223. };
  148224. static long _vq_lengthlist__44u3__p5_0[] = {
  148225. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148226. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148227. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148228. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148229. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148230. 12,
  148231. };
  148232. static float _vq_quantthresh__44u3__p5_0[] = {
  148233. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148234. };
  148235. static long _vq_quantmap__44u3__p5_0[] = {
  148236. 7, 5, 3, 1, 0, 2, 4, 6,
  148237. 8,
  148238. };
  148239. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148240. _vq_quantthresh__44u3__p5_0,
  148241. _vq_quantmap__44u3__p5_0,
  148242. 9,
  148243. 9
  148244. };
  148245. static static_codebook _44u3__p5_0 = {
  148246. 2, 81,
  148247. _vq_lengthlist__44u3__p5_0,
  148248. 1, -531628032, 1611661312, 4, 0,
  148249. _vq_quantlist__44u3__p5_0,
  148250. NULL,
  148251. &_vq_auxt__44u3__p5_0,
  148252. NULL,
  148253. 0
  148254. };
  148255. static long _vq_quantlist__44u3__p6_0[] = {
  148256. 6,
  148257. 5,
  148258. 7,
  148259. 4,
  148260. 8,
  148261. 3,
  148262. 9,
  148263. 2,
  148264. 10,
  148265. 1,
  148266. 11,
  148267. 0,
  148268. 12,
  148269. };
  148270. static long _vq_lengthlist__44u3__p6_0[] = {
  148271. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148272. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148273. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148274. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148275. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148276. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148277. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148278. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148279. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148280. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148281. 15,16,16,16,17,18,16,20,18,
  148282. };
  148283. static float _vq_quantthresh__44u3__p6_0[] = {
  148284. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148285. 12.5, 17.5, 22.5, 27.5,
  148286. };
  148287. static long _vq_quantmap__44u3__p6_0[] = {
  148288. 11, 9, 7, 5, 3, 1, 0, 2,
  148289. 4, 6, 8, 10, 12,
  148290. };
  148291. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148292. _vq_quantthresh__44u3__p6_0,
  148293. _vq_quantmap__44u3__p6_0,
  148294. 13,
  148295. 13
  148296. };
  148297. static static_codebook _44u3__p6_0 = {
  148298. 2, 169,
  148299. _vq_lengthlist__44u3__p6_0,
  148300. 1, -526516224, 1616117760, 4, 0,
  148301. _vq_quantlist__44u3__p6_0,
  148302. NULL,
  148303. &_vq_auxt__44u3__p6_0,
  148304. NULL,
  148305. 0
  148306. };
  148307. static long _vq_quantlist__44u3__p6_1[] = {
  148308. 2,
  148309. 1,
  148310. 3,
  148311. 0,
  148312. 4,
  148313. };
  148314. static long _vq_lengthlist__44u3__p6_1[] = {
  148315. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148316. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148317. };
  148318. static float _vq_quantthresh__44u3__p6_1[] = {
  148319. -1.5, -0.5, 0.5, 1.5,
  148320. };
  148321. static long _vq_quantmap__44u3__p6_1[] = {
  148322. 3, 1, 0, 2, 4,
  148323. };
  148324. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148325. _vq_quantthresh__44u3__p6_1,
  148326. _vq_quantmap__44u3__p6_1,
  148327. 5,
  148328. 5
  148329. };
  148330. static static_codebook _44u3__p6_1 = {
  148331. 2, 25,
  148332. _vq_lengthlist__44u3__p6_1,
  148333. 1, -533725184, 1611661312, 3, 0,
  148334. _vq_quantlist__44u3__p6_1,
  148335. NULL,
  148336. &_vq_auxt__44u3__p6_1,
  148337. NULL,
  148338. 0
  148339. };
  148340. static long _vq_quantlist__44u3__p7_0[] = {
  148341. 4,
  148342. 3,
  148343. 5,
  148344. 2,
  148345. 6,
  148346. 1,
  148347. 7,
  148348. 0,
  148349. 8,
  148350. };
  148351. static long _vq_lengthlist__44u3__p7_0[] = {
  148352. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148353. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148354. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148355. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148356. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148357. 9,
  148358. };
  148359. static float _vq_quantthresh__44u3__p7_0[] = {
  148360. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148361. };
  148362. static long _vq_quantmap__44u3__p7_0[] = {
  148363. 7, 5, 3, 1, 0, 2, 4, 6,
  148364. 8,
  148365. };
  148366. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148367. _vq_quantthresh__44u3__p7_0,
  148368. _vq_quantmap__44u3__p7_0,
  148369. 9,
  148370. 9
  148371. };
  148372. static static_codebook _44u3__p7_0 = {
  148373. 2, 81,
  148374. _vq_lengthlist__44u3__p7_0,
  148375. 1, -515907584, 1627381760, 4, 0,
  148376. _vq_quantlist__44u3__p7_0,
  148377. NULL,
  148378. &_vq_auxt__44u3__p7_0,
  148379. NULL,
  148380. 0
  148381. };
  148382. static long _vq_quantlist__44u3__p7_1[] = {
  148383. 7,
  148384. 6,
  148385. 8,
  148386. 5,
  148387. 9,
  148388. 4,
  148389. 10,
  148390. 3,
  148391. 11,
  148392. 2,
  148393. 12,
  148394. 1,
  148395. 13,
  148396. 0,
  148397. 14,
  148398. };
  148399. static long _vq_lengthlist__44u3__p7_1[] = {
  148400. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148401. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148402. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148403. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148404. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148405. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148406. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148407. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148408. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148409. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148410. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148411. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148412. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148413. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148414. 17,
  148415. };
  148416. static float _vq_quantthresh__44u3__p7_1[] = {
  148417. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148418. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148419. };
  148420. static long _vq_quantmap__44u3__p7_1[] = {
  148421. 13, 11, 9, 7, 5, 3, 1, 0,
  148422. 2, 4, 6, 8, 10, 12, 14,
  148423. };
  148424. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148425. _vq_quantthresh__44u3__p7_1,
  148426. _vq_quantmap__44u3__p7_1,
  148427. 15,
  148428. 15
  148429. };
  148430. static static_codebook _44u3__p7_1 = {
  148431. 2, 225,
  148432. _vq_lengthlist__44u3__p7_1,
  148433. 1, -522338304, 1620115456, 4, 0,
  148434. _vq_quantlist__44u3__p7_1,
  148435. NULL,
  148436. &_vq_auxt__44u3__p7_1,
  148437. NULL,
  148438. 0
  148439. };
  148440. static long _vq_quantlist__44u3__p7_2[] = {
  148441. 8,
  148442. 7,
  148443. 9,
  148444. 6,
  148445. 10,
  148446. 5,
  148447. 11,
  148448. 4,
  148449. 12,
  148450. 3,
  148451. 13,
  148452. 2,
  148453. 14,
  148454. 1,
  148455. 15,
  148456. 0,
  148457. 16,
  148458. };
  148459. static long _vq_lengthlist__44u3__p7_2[] = {
  148460. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148461. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148462. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148463. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148464. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148465. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148466. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148467. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148468. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148469. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148470. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148471. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148472. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148473. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148474. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148475. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148476. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148477. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148478. 11,
  148479. };
  148480. static float _vq_quantthresh__44u3__p7_2[] = {
  148481. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148482. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148483. };
  148484. static long _vq_quantmap__44u3__p7_2[] = {
  148485. 15, 13, 11, 9, 7, 5, 3, 1,
  148486. 0, 2, 4, 6, 8, 10, 12, 14,
  148487. 16,
  148488. };
  148489. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148490. _vq_quantthresh__44u3__p7_2,
  148491. _vq_quantmap__44u3__p7_2,
  148492. 17,
  148493. 17
  148494. };
  148495. static static_codebook _44u3__p7_2 = {
  148496. 2, 289,
  148497. _vq_lengthlist__44u3__p7_2,
  148498. 1, -529530880, 1611661312, 5, 0,
  148499. _vq_quantlist__44u3__p7_2,
  148500. NULL,
  148501. &_vq_auxt__44u3__p7_2,
  148502. NULL,
  148503. 0
  148504. };
  148505. static long _huff_lengthlist__44u3__short[] = {
  148506. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148507. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148508. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148509. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148510. };
  148511. static static_codebook _huff_book__44u3__short = {
  148512. 2, 64,
  148513. _huff_lengthlist__44u3__short,
  148514. 0, 0, 0, 0, 0,
  148515. NULL,
  148516. NULL,
  148517. NULL,
  148518. NULL,
  148519. 0
  148520. };
  148521. static long _huff_lengthlist__44u4__long[] = {
  148522. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148523. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148524. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148525. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148526. };
  148527. static static_codebook _huff_book__44u4__long = {
  148528. 2, 64,
  148529. _huff_lengthlist__44u4__long,
  148530. 0, 0, 0, 0, 0,
  148531. NULL,
  148532. NULL,
  148533. NULL,
  148534. NULL,
  148535. 0
  148536. };
  148537. static long _vq_quantlist__44u4__p1_0[] = {
  148538. 1,
  148539. 0,
  148540. 2,
  148541. };
  148542. static long _vq_lengthlist__44u4__p1_0[] = {
  148543. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148544. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148545. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148546. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148547. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148548. 13,
  148549. };
  148550. static float _vq_quantthresh__44u4__p1_0[] = {
  148551. -0.5, 0.5,
  148552. };
  148553. static long _vq_quantmap__44u4__p1_0[] = {
  148554. 1, 0, 2,
  148555. };
  148556. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148557. _vq_quantthresh__44u4__p1_0,
  148558. _vq_quantmap__44u4__p1_0,
  148559. 3,
  148560. 3
  148561. };
  148562. static static_codebook _44u4__p1_0 = {
  148563. 4, 81,
  148564. _vq_lengthlist__44u4__p1_0,
  148565. 1, -535822336, 1611661312, 2, 0,
  148566. _vq_quantlist__44u4__p1_0,
  148567. NULL,
  148568. &_vq_auxt__44u4__p1_0,
  148569. NULL,
  148570. 0
  148571. };
  148572. static long _vq_quantlist__44u4__p2_0[] = {
  148573. 1,
  148574. 0,
  148575. 2,
  148576. };
  148577. static long _vq_lengthlist__44u4__p2_0[] = {
  148578. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148579. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148580. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148581. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148582. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148583. 9,
  148584. };
  148585. static float _vq_quantthresh__44u4__p2_0[] = {
  148586. -0.5, 0.5,
  148587. };
  148588. static long _vq_quantmap__44u4__p2_0[] = {
  148589. 1, 0, 2,
  148590. };
  148591. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148592. _vq_quantthresh__44u4__p2_0,
  148593. _vq_quantmap__44u4__p2_0,
  148594. 3,
  148595. 3
  148596. };
  148597. static static_codebook _44u4__p2_0 = {
  148598. 4, 81,
  148599. _vq_lengthlist__44u4__p2_0,
  148600. 1, -535822336, 1611661312, 2, 0,
  148601. _vq_quantlist__44u4__p2_0,
  148602. NULL,
  148603. &_vq_auxt__44u4__p2_0,
  148604. NULL,
  148605. 0
  148606. };
  148607. static long _vq_quantlist__44u4__p3_0[] = {
  148608. 2,
  148609. 1,
  148610. 3,
  148611. 0,
  148612. 4,
  148613. };
  148614. static long _vq_lengthlist__44u4__p3_0[] = {
  148615. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148616. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148617. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148618. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148619. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148620. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148621. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148622. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148623. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148624. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148625. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148626. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148627. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148628. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148629. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148630. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148631. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148632. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148633. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148634. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148635. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148636. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148637. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148638. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148639. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148640. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148641. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148642. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148643. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148644. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148645. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148646. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148647. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148648. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148649. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148650. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148651. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148652. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148653. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148654. 0,
  148655. };
  148656. static float _vq_quantthresh__44u4__p3_0[] = {
  148657. -1.5, -0.5, 0.5, 1.5,
  148658. };
  148659. static long _vq_quantmap__44u4__p3_0[] = {
  148660. 3, 1, 0, 2, 4,
  148661. };
  148662. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148663. _vq_quantthresh__44u4__p3_0,
  148664. _vq_quantmap__44u4__p3_0,
  148665. 5,
  148666. 5
  148667. };
  148668. static static_codebook _44u4__p3_0 = {
  148669. 4, 625,
  148670. _vq_lengthlist__44u4__p3_0,
  148671. 1, -533725184, 1611661312, 3, 0,
  148672. _vq_quantlist__44u4__p3_0,
  148673. NULL,
  148674. &_vq_auxt__44u4__p3_0,
  148675. NULL,
  148676. 0
  148677. };
  148678. static long _vq_quantlist__44u4__p4_0[] = {
  148679. 2,
  148680. 1,
  148681. 3,
  148682. 0,
  148683. 4,
  148684. };
  148685. static long _vq_lengthlist__44u4__p4_0[] = {
  148686. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148687. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148688. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148689. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148690. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148691. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148692. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148693. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148694. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148695. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148696. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148697. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148698. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148699. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148700. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148701. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148702. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148703. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148704. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148705. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148706. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148707. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148708. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148709. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148710. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148711. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148712. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148713. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148714. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148715. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148716. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148717. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148718. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148719. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148720. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148721. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148722. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148723. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148724. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148725. 13,
  148726. };
  148727. static float _vq_quantthresh__44u4__p4_0[] = {
  148728. -1.5, -0.5, 0.5, 1.5,
  148729. };
  148730. static long _vq_quantmap__44u4__p4_0[] = {
  148731. 3, 1, 0, 2, 4,
  148732. };
  148733. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148734. _vq_quantthresh__44u4__p4_0,
  148735. _vq_quantmap__44u4__p4_0,
  148736. 5,
  148737. 5
  148738. };
  148739. static static_codebook _44u4__p4_0 = {
  148740. 4, 625,
  148741. _vq_lengthlist__44u4__p4_0,
  148742. 1, -533725184, 1611661312, 3, 0,
  148743. _vq_quantlist__44u4__p4_0,
  148744. NULL,
  148745. &_vq_auxt__44u4__p4_0,
  148746. NULL,
  148747. 0
  148748. };
  148749. static long _vq_quantlist__44u4__p5_0[] = {
  148750. 4,
  148751. 3,
  148752. 5,
  148753. 2,
  148754. 6,
  148755. 1,
  148756. 7,
  148757. 0,
  148758. 8,
  148759. };
  148760. static long _vq_lengthlist__44u4__p5_0[] = {
  148761. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148762. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148763. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148764. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148765. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148766. 12,
  148767. };
  148768. static float _vq_quantthresh__44u4__p5_0[] = {
  148769. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148770. };
  148771. static long _vq_quantmap__44u4__p5_0[] = {
  148772. 7, 5, 3, 1, 0, 2, 4, 6,
  148773. 8,
  148774. };
  148775. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148776. _vq_quantthresh__44u4__p5_0,
  148777. _vq_quantmap__44u4__p5_0,
  148778. 9,
  148779. 9
  148780. };
  148781. static static_codebook _44u4__p5_0 = {
  148782. 2, 81,
  148783. _vq_lengthlist__44u4__p5_0,
  148784. 1, -531628032, 1611661312, 4, 0,
  148785. _vq_quantlist__44u4__p5_0,
  148786. NULL,
  148787. &_vq_auxt__44u4__p5_0,
  148788. NULL,
  148789. 0
  148790. };
  148791. static long _vq_quantlist__44u4__p6_0[] = {
  148792. 6,
  148793. 5,
  148794. 7,
  148795. 4,
  148796. 8,
  148797. 3,
  148798. 9,
  148799. 2,
  148800. 10,
  148801. 1,
  148802. 11,
  148803. 0,
  148804. 12,
  148805. };
  148806. static long _vq_lengthlist__44u4__p6_0[] = {
  148807. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148808. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148809. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148810. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148811. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148812. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148813. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148814. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148815. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148816. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148817. 16,16,16,17,17,18,17,20,21,
  148818. };
  148819. static float _vq_quantthresh__44u4__p6_0[] = {
  148820. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148821. 12.5, 17.5, 22.5, 27.5,
  148822. };
  148823. static long _vq_quantmap__44u4__p6_0[] = {
  148824. 11, 9, 7, 5, 3, 1, 0, 2,
  148825. 4, 6, 8, 10, 12,
  148826. };
  148827. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148828. _vq_quantthresh__44u4__p6_0,
  148829. _vq_quantmap__44u4__p6_0,
  148830. 13,
  148831. 13
  148832. };
  148833. static static_codebook _44u4__p6_0 = {
  148834. 2, 169,
  148835. _vq_lengthlist__44u4__p6_0,
  148836. 1, -526516224, 1616117760, 4, 0,
  148837. _vq_quantlist__44u4__p6_0,
  148838. NULL,
  148839. &_vq_auxt__44u4__p6_0,
  148840. NULL,
  148841. 0
  148842. };
  148843. static long _vq_quantlist__44u4__p6_1[] = {
  148844. 2,
  148845. 1,
  148846. 3,
  148847. 0,
  148848. 4,
  148849. };
  148850. static long _vq_lengthlist__44u4__p6_1[] = {
  148851. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148852. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148853. };
  148854. static float _vq_quantthresh__44u4__p6_1[] = {
  148855. -1.5, -0.5, 0.5, 1.5,
  148856. };
  148857. static long _vq_quantmap__44u4__p6_1[] = {
  148858. 3, 1, 0, 2, 4,
  148859. };
  148860. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148861. _vq_quantthresh__44u4__p6_1,
  148862. _vq_quantmap__44u4__p6_1,
  148863. 5,
  148864. 5
  148865. };
  148866. static static_codebook _44u4__p6_1 = {
  148867. 2, 25,
  148868. _vq_lengthlist__44u4__p6_1,
  148869. 1, -533725184, 1611661312, 3, 0,
  148870. _vq_quantlist__44u4__p6_1,
  148871. NULL,
  148872. &_vq_auxt__44u4__p6_1,
  148873. NULL,
  148874. 0
  148875. };
  148876. static long _vq_quantlist__44u4__p7_0[] = {
  148877. 6,
  148878. 5,
  148879. 7,
  148880. 4,
  148881. 8,
  148882. 3,
  148883. 9,
  148884. 2,
  148885. 10,
  148886. 1,
  148887. 11,
  148888. 0,
  148889. 12,
  148890. };
  148891. static long _vq_lengthlist__44u4__p7_0[] = {
  148892. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148893. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148894. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148895. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148896. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148897. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148898. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148899. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148900. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148901. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148902. 11,11,11,11,11,11,11,11,11,
  148903. };
  148904. static float _vq_quantthresh__44u4__p7_0[] = {
  148905. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148906. 637.5, 892.5, 1147.5, 1402.5,
  148907. };
  148908. static long _vq_quantmap__44u4__p7_0[] = {
  148909. 11, 9, 7, 5, 3, 1, 0, 2,
  148910. 4, 6, 8, 10, 12,
  148911. };
  148912. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148913. _vq_quantthresh__44u4__p7_0,
  148914. _vq_quantmap__44u4__p7_0,
  148915. 13,
  148916. 13
  148917. };
  148918. static static_codebook _44u4__p7_0 = {
  148919. 2, 169,
  148920. _vq_lengthlist__44u4__p7_0,
  148921. 1, -514332672, 1627381760, 4, 0,
  148922. _vq_quantlist__44u4__p7_0,
  148923. NULL,
  148924. &_vq_auxt__44u4__p7_0,
  148925. NULL,
  148926. 0
  148927. };
  148928. static long _vq_quantlist__44u4__p7_1[] = {
  148929. 7,
  148930. 6,
  148931. 8,
  148932. 5,
  148933. 9,
  148934. 4,
  148935. 10,
  148936. 3,
  148937. 11,
  148938. 2,
  148939. 12,
  148940. 1,
  148941. 13,
  148942. 0,
  148943. 14,
  148944. };
  148945. static long _vq_lengthlist__44u4__p7_1[] = {
  148946. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148947. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148948. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148949. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148950. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148951. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148952. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148953. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148954. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148955. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148956. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148957. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148958. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148959. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148960. 16,
  148961. };
  148962. static float _vq_quantthresh__44u4__p7_1[] = {
  148963. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148964. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148965. };
  148966. static long _vq_quantmap__44u4__p7_1[] = {
  148967. 13, 11, 9, 7, 5, 3, 1, 0,
  148968. 2, 4, 6, 8, 10, 12, 14,
  148969. };
  148970. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148971. _vq_quantthresh__44u4__p7_1,
  148972. _vq_quantmap__44u4__p7_1,
  148973. 15,
  148974. 15
  148975. };
  148976. static static_codebook _44u4__p7_1 = {
  148977. 2, 225,
  148978. _vq_lengthlist__44u4__p7_1,
  148979. 1, -522338304, 1620115456, 4, 0,
  148980. _vq_quantlist__44u4__p7_1,
  148981. NULL,
  148982. &_vq_auxt__44u4__p7_1,
  148983. NULL,
  148984. 0
  148985. };
  148986. static long _vq_quantlist__44u4__p7_2[] = {
  148987. 8,
  148988. 7,
  148989. 9,
  148990. 6,
  148991. 10,
  148992. 5,
  148993. 11,
  148994. 4,
  148995. 12,
  148996. 3,
  148997. 13,
  148998. 2,
  148999. 14,
  149000. 1,
  149001. 15,
  149002. 0,
  149003. 16,
  149004. };
  149005. static long _vq_lengthlist__44u4__p7_2[] = {
  149006. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149007. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149008. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149009. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149010. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  149011. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149012. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149013. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149014. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149015. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  149016. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  149017. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  149018. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149019. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  149020. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149021. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149022. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149023. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  149024. 10,
  149025. };
  149026. static float _vq_quantthresh__44u4__p7_2[] = {
  149027. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149028. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149029. };
  149030. static long _vq_quantmap__44u4__p7_2[] = {
  149031. 15, 13, 11, 9, 7, 5, 3, 1,
  149032. 0, 2, 4, 6, 8, 10, 12, 14,
  149033. 16,
  149034. };
  149035. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  149036. _vq_quantthresh__44u4__p7_2,
  149037. _vq_quantmap__44u4__p7_2,
  149038. 17,
  149039. 17
  149040. };
  149041. static static_codebook _44u4__p7_2 = {
  149042. 2, 289,
  149043. _vq_lengthlist__44u4__p7_2,
  149044. 1, -529530880, 1611661312, 5, 0,
  149045. _vq_quantlist__44u4__p7_2,
  149046. NULL,
  149047. &_vq_auxt__44u4__p7_2,
  149048. NULL,
  149049. 0
  149050. };
  149051. static long _huff_lengthlist__44u4__short[] = {
  149052. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  149053. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  149054. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  149055. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  149056. };
  149057. static static_codebook _huff_book__44u4__short = {
  149058. 2, 64,
  149059. _huff_lengthlist__44u4__short,
  149060. 0, 0, 0, 0, 0,
  149061. NULL,
  149062. NULL,
  149063. NULL,
  149064. NULL,
  149065. 0
  149066. };
  149067. static long _huff_lengthlist__44u5__long[] = {
  149068. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  149069. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  149070. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  149071. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  149072. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  149073. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  149074. 14, 8, 7, 8,
  149075. };
  149076. static static_codebook _huff_book__44u5__long = {
  149077. 2, 100,
  149078. _huff_lengthlist__44u5__long,
  149079. 0, 0, 0, 0, 0,
  149080. NULL,
  149081. NULL,
  149082. NULL,
  149083. NULL,
  149084. 0
  149085. };
  149086. static long _vq_quantlist__44u5__p1_0[] = {
  149087. 1,
  149088. 0,
  149089. 2,
  149090. };
  149091. static long _vq_lengthlist__44u5__p1_0[] = {
  149092. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149093. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149094. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149095. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  149096. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149097. 12,
  149098. };
  149099. static float _vq_quantthresh__44u5__p1_0[] = {
  149100. -0.5, 0.5,
  149101. };
  149102. static long _vq_quantmap__44u5__p1_0[] = {
  149103. 1, 0, 2,
  149104. };
  149105. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149106. _vq_quantthresh__44u5__p1_0,
  149107. _vq_quantmap__44u5__p1_0,
  149108. 3,
  149109. 3
  149110. };
  149111. static static_codebook _44u5__p1_0 = {
  149112. 4, 81,
  149113. _vq_lengthlist__44u5__p1_0,
  149114. 1, -535822336, 1611661312, 2, 0,
  149115. _vq_quantlist__44u5__p1_0,
  149116. NULL,
  149117. &_vq_auxt__44u5__p1_0,
  149118. NULL,
  149119. 0
  149120. };
  149121. static long _vq_quantlist__44u5__p2_0[] = {
  149122. 1,
  149123. 0,
  149124. 2,
  149125. };
  149126. static long _vq_lengthlist__44u5__p2_0[] = {
  149127. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149128. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149129. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149130. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149131. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149132. 9,
  149133. };
  149134. static float _vq_quantthresh__44u5__p2_0[] = {
  149135. -0.5, 0.5,
  149136. };
  149137. static long _vq_quantmap__44u5__p2_0[] = {
  149138. 1, 0, 2,
  149139. };
  149140. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149141. _vq_quantthresh__44u5__p2_0,
  149142. _vq_quantmap__44u5__p2_0,
  149143. 3,
  149144. 3
  149145. };
  149146. static static_codebook _44u5__p2_0 = {
  149147. 4, 81,
  149148. _vq_lengthlist__44u5__p2_0,
  149149. 1, -535822336, 1611661312, 2, 0,
  149150. _vq_quantlist__44u5__p2_0,
  149151. NULL,
  149152. &_vq_auxt__44u5__p2_0,
  149153. NULL,
  149154. 0
  149155. };
  149156. static long _vq_quantlist__44u5__p3_0[] = {
  149157. 2,
  149158. 1,
  149159. 3,
  149160. 0,
  149161. 4,
  149162. };
  149163. static long _vq_lengthlist__44u5__p3_0[] = {
  149164. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149165. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149166. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149167. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149168. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149169. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149170. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149171. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149172. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149173. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149174. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149175. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149176. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149177. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149178. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149179. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149180. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149181. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149182. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149183. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149184. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149185. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149186. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149187. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149188. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149189. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149190. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149191. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149192. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149193. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149194. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149195. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149196. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149197. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149198. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149199. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149200. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149201. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149202. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149203. 0,
  149204. };
  149205. static float _vq_quantthresh__44u5__p3_0[] = {
  149206. -1.5, -0.5, 0.5, 1.5,
  149207. };
  149208. static long _vq_quantmap__44u5__p3_0[] = {
  149209. 3, 1, 0, 2, 4,
  149210. };
  149211. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149212. _vq_quantthresh__44u5__p3_0,
  149213. _vq_quantmap__44u5__p3_0,
  149214. 5,
  149215. 5
  149216. };
  149217. static static_codebook _44u5__p3_0 = {
  149218. 4, 625,
  149219. _vq_lengthlist__44u5__p3_0,
  149220. 1, -533725184, 1611661312, 3, 0,
  149221. _vq_quantlist__44u5__p3_0,
  149222. NULL,
  149223. &_vq_auxt__44u5__p3_0,
  149224. NULL,
  149225. 0
  149226. };
  149227. static long _vq_quantlist__44u5__p4_0[] = {
  149228. 2,
  149229. 1,
  149230. 3,
  149231. 0,
  149232. 4,
  149233. };
  149234. static long _vq_lengthlist__44u5__p4_0[] = {
  149235. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149236. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149237. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149238. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149239. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149240. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149241. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149242. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149243. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149244. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149245. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149246. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149247. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149248. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149249. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149250. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149251. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149252. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149253. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149254. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149255. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149256. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149257. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149258. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149259. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149260. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149261. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149262. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149263. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149264. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149265. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149266. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149267. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149268. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149269. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149270. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149271. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149272. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149273. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149274. 12,
  149275. };
  149276. static float _vq_quantthresh__44u5__p4_0[] = {
  149277. -1.5, -0.5, 0.5, 1.5,
  149278. };
  149279. static long _vq_quantmap__44u5__p4_0[] = {
  149280. 3, 1, 0, 2, 4,
  149281. };
  149282. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149283. _vq_quantthresh__44u5__p4_0,
  149284. _vq_quantmap__44u5__p4_0,
  149285. 5,
  149286. 5
  149287. };
  149288. static static_codebook _44u5__p4_0 = {
  149289. 4, 625,
  149290. _vq_lengthlist__44u5__p4_0,
  149291. 1, -533725184, 1611661312, 3, 0,
  149292. _vq_quantlist__44u5__p4_0,
  149293. NULL,
  149294. &_vq_auxt__44u5__p4_0,
  149295. NULL,
  149296. 0
  149297. };
  149298. static long _vq_quantlist__44u5__p5_0[] = {
  149299. 4,
  149300. 3,
  149301. 5,
  149302. 2,
  149303. 6,
  149304. 1,
  149305. 7,
  149306. 0,
  149307. 8,
  149308. };
  149309. static long _vq_lengthlist__44u5__p5_0[] = {
  149310. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149311. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149312. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149313. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149314. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149315. 14,
  149316. };
  149317. static float _vq_quantthresh__44u5__p5_0[] = {
  149318. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149319. };
  149320. static long _vq_quantmap__44u5__p5_0[] = {
  149321. 7, 5, 3, 1, 0, 2, 4, 6,
  149322. 8,
  149323. };
  149324. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149325. _vq_quantthresh__44u5__p5_0,
  149326. _vq_quantmap__44u5__p5_0,
  149327. 9,
  149328. 9
  149329. };
  149330. static static_codebook _44u5__p5_0 = {
  149331. 2, 81,
  149332. _vq_lengthlist__44u5__p5_0,
  149333. 1, -531628032, 1611661312, 4, 0,
  149334. _vq_quantlist__44u5__p5_0,
  149335. NULL,
  149336. &_vq_auxt__44u5__p5_0,
  149337. NULL,
  149338. 0
  149339. };
  149340. static long _vq_quantlist__44u5__p6_0[] = {
  149341. 4,
  149342. 3,
  149343. 5,
  149344. 2,
  149345. 6,
  149346. 1,
  149347. 7,
  149348. 0,
  149349. 8,
  149350. };
  149351. static long _vq_lengthlist__44u5__p6_0[] = {
  149352. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149353. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149354. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149355. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149356. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149357. 11,
  149358. };
  149359. static float _vq_quantthresh__44u5__p6_0[] = {
  149360. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149361. };
  149362. static long _vq_quantmap__44u5__p6_0[] = {
  149363. 7, 5, 3, 1, 0, 2, 4, 6,
  149364. 8,
  149365. };
  149366. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149367. _vq_quantthresh__44u5__p6_0,
  149368. _vq_quantmap__44u5__p6_0,
  149369. 9,
  149370. 9
  149371. };
  149372. static static_codebook _44u5__p6_0 = {
  149373. 2, 81,
  149374. _vq_lengthlist__44u5__p6_0,
  149375. 1, -531628032, 1611661312, 4, 0,
  149376. _vq_quantlist__44u5__p6_0,
  149377. NULL,
  149378. &_vq_auxt__44u5__p6_0,
  149379. NULL,
  149380. 0
  149381. };
  149382. static long _vq_quantlist__44u5__p7_0[] = {
  149383. 1,
  149384. 0,
  149385. 2,
  149386. };
  149387. static long _vq_lengthlist__44u5__p7_0[] = {
  149388. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149389. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149390. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149391. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149392. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149393. 12,
  149394. };
  149395. static float _vq_quantthresh__44u5__p7_0[] = {
  149396. -5.5, 5.5,
  149397. };
  149398. static long _vq_quantmap__44u5__p7_0[] = {
  149399. 1, 0, 2,
  149400. };
  149401. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149402. _vq_quantthresh__44u5__p7_0,
  149403. _vq_quantmap__44u5__p7_0,
  149404. 3,
  149405. 3
  149406. };
  149407. static static_codebook _44u5__p7_0 = {
  149408. 4, 81,
  149409. _vq_lengthlist__44u5__p7_0,
  149410. 1, -529137664, 1618345984, 2, 0,
  149411. _vq_quantlist__44u5__p7_0,
  149412. NULL,
  149413. &_vq_auxt__44u5__p7_0,
  149414. NULL,
  149415. 0
  149416. };
  149417. static long _vq_quantlist__44u5__p7_1[] = {
  149418. 5,
  149419. 4,
  149420. 6,
  149421. 3,
  149422. 7,
  149423. 2,
  149424. 8,
  149425. 1,
  149426. 9,
  149427. 0,
  149428. 10,
  149429. };
  149430. static long _vq_lengthlist__44u5__p7_1[] = {
  149431. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149432. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149433. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149434. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149435. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149436. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149437. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149438. 9, 9, 9, 9, 9,10,10,10,10,
  149439. };
  149440. static float _vq_quantthresh__44u5__p7_1[] = {
  149441. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149442. 3.5, 4.5,
  149443. };
  149444. static long _vq_quantmap__44u5__p7_1[] = {
  149445. 9, 7, 5, 3, 1, 0, 2, 4,
  149446. 6, 8, 10,
  149447. };
  149448. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149449. _vq_quantthresh__44u5__p7_1,
  149450. _vq_quantmap__44u5__p7_1,
  149451. 11,
  149452. 11
  149453. };
  149454. static static_codebook _44u5__p7_1 = {
  149455. 2, 121,
  149456. _vq_lengthlist__44u5__p7_1,
  149457. 1, -531365888, 1611661312, 4, 0,
  149458. _vq_quantlist__44u5__p7_1,
  149459. NULL,
  149460. &_vq_auxt__44u5__p7_1,
  149461. NULL,
  149462. 0
  149463. };
  149464. static long _vq_quantlist__44u5__p8_0[] = {
  149465. 5,
  149466. 4,
  149467. 6,
  149468. 3,
  149469. 7,
  149470. 2,
  149471. 8,
  149472. 1,
  149473. 9,
  149474. 0,
  149475. 10,
  149476. };
  149477. static long _vq_lengthlist__44u5__p8_0[] = {
  149478. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149479. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149480. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149481. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149482. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149483. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149484. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149485. 12,13,13,14,14,14,14,15,15,
  149486. };
  149487. static float _vq_quantthresh__44u5__p8_0[] = {
  149488. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149489. 38.5, 49.5,
  149490. };
  149491. static long _vq_quantmap__44u5__p8_0[] = {
  149492. 9, 7, 5, 3, 1, 0, 2, 4,
  149493. 6, 8, 10,
  149494. };
  149495. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149496. _vq_quantthresh__44u5__p8_0,
  149497. _vq_quantmap__44u5__p8_0,
  149498. 11,
  149499. 11
  149500. };
  149501. static static_codebook _44u5__p8_0 = {
  149502. 2, 121,
  149503. _vq_lengthlist__44u5__p8_0,
  149504. 1, -524582912, 1618345984, 4, 0,
  149505. _vq_quantlist__44u5__p8_0,
  149506. NULL,
  149507. &_vq_auxt__44u5__p8_0,
  149508. NULL,
  149509. 0
  149510. };
  149511. static long _vq_quantlist__44u5__p8_1[] = {
  149512. 5,
  149513. 4,
  149514. 6,
  149515. 3,
  149516. 7,
  149517. 2,
  149518. 8,
  149519. 1,
  149520. 9,
  149521. 0,
  149522. 10,
  149523. };
  149524. static long _vq_lengthlist__44u5__p8_1[] = {
  149525. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149526. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149527. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149528. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149529. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149530. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149531. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149532. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149533. };
  149534. static float _vq_quantthresh__44u5__p8_1[] = {
  149535. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149536. 3.5, 4.5,
  149537. };
  149538. static long _vq_quantmap__44u5__p8_1[] = {
  149539. 9, 7, 5, 3, 1, 0, 2, 4,
  149540. 6, 8, 10,
  149541. };
  149542. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149543. _vq_quantthresh__44u5__p8_1,
  149544. _vq_quantmap__44u5__p8_1,
  149545. 11,
  149546. 11
  149547. };
  149548. static static_codebook _44u5__p8_1 = {
  149549. 2, 121,
  149550. _vq_lengthlist__44u5__p8_1,
  149551. 1, -531365888, 1611661312, 4, 0,
  149552. _vq_quantlist__44u5__p8_1,
  149553. NULL,
  149554. &_vq_auxt__44u5__p8_1,
  149555. NULL,
  149556. 0
  149557. };
  149558. static long _vq_quantlist__44u5__p9_0[] = {
  149559. 6,
  149560. 5,
  149561. 7,
  149562. 4,
  149563. 8,
  149564. 3,
  149565. 9,
  149566. 2,
  149567. 10,
  149568. 1,
  149569. 11,
  149570. 0,
  149571. 12,
  149572. };
  149573. static long _vq_lengthlist__44u5__p9_0[] = {
  149574. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149575. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149576. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149577. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149578. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149579. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149580. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149581. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149582. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149583. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149584. 12,12,12,12,12,12,12,12,12,
  149585. };
  149586. static float _vq_quantthresh__44u5__p9_0[] = {
  149587. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149588. 637.5, 892.5, 1147.5, 1402.5,
  149589. };
  149590. static long _vq_quantmap__44u5__p9_0[] = {
  149591. 11, 9, 7, 5, 3, 1, 0, 2,
  149592. 4, 6, 8, 10, 12,
  149593. };
  149594. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149595. _vq_quantthresh__44u5__p9_0,
  149596. _vq_quantmap__44u5__p9_0,
  149597. 13,
  149598. 13
  149599. };
  149600. static static_codebook _44u5__p9_0 = {
  149601. 2, 169,
  149602. _vq_lengthlist__44u5__p9_0,
  149603. 1, -514332672, 1627381760, 4, 0,
  149604. _vq_quantlist__44u5__p9_0,
  149605. NULL,
  149606. &_vq_auxt__44u5__p9_0,
  149607. NULL,
  149608. 0
  149609. };
  149610. static long _vq_quantlist__44u5__p9_1[] = {
  149611. 7,
  149612. 6,
  149613. 8,
  149614. 5,
  149615. 9,
  149616. 4,
  149617. 10,
  149618. 3,
  149619. 11,
  149620. 2,
  149621. 12,
  149622. 1,
  149623. 13,
  149624. 0,
  149625. 14,
  149626. };
  149627. static long _vq_lengthlist__44u5__p9_1[] = {
  149628. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149629. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149630. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149631. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149632. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149633. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149634. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149635. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149636. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149637. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149638. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149639. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149640. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149641. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149642. 14,
  149643. };
  149644. static float _vq_quantthresh__44u5__p9_1[] = {
  149645. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149646. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149647. };
  149648. static long _vq_quantmap__44u5__p9_1[] = {
  149649. 13, 11, 9, 7, 5, 3, 1, 0,
  149650. 2, 4, 6, 8, 10, 12, 14,
  149651. };
  149652. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149653. _vq_quantthresh__44u5__p9_1,
  149654. _vq_quantmap__44u5__p9_1,
  149655. 15,
  149656. 15
  149657. };
  149658. static static_codebook _44u5__p9_1 = {
  149659. 2, 225,
  149660. _vq_lengthlist__44u5__p9_1,
  149661. 1, -522338304, 1620115456, 4, 0,
  149662. _vq_quantlist__44u5__p9_1,
  149663. NULL,
  149664. &_vq_auxt__44u5__p9_1,
  149665. NULL,
  149666. 0
  149667. };
  149668. static long _vq_quantlist__44u5__p9_2[] = {
  149669. 8,
  149670. 7,
  149671. 9,
  149672. 6,
  149673. 10,
  149674. 5,
  149675. 11,
  149676. 4,
  149677. 12,
  149678. 3,
  149679. 13,
  149680. 2,
  149681. 14,
  149682. 1,
  149683. 15,
  149684. 0,
  149685. 16,
  149686. };
  149687. static long _vq_lengthlist__44u5__p9_2[] = {
  149688. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149689. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149690. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149691. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149692. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149693. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149694. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149695. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149696. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149697. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149698. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149699. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149700. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149701. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149702. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149703. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149704. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149705. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149706. 10,
  149707. };
  149708. static float _vq_quantthresh__44u5__p9_2[] = {
  149709. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149710. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149711. };
  149712. static long _vq_quantmap__44u5__p9_2[] = {
  149713. 15, 13, 11, 9, 7, 5, 3, 1,
  149714. 0, 2, 4, 6, 8, 10, 12, 14,
  149715. 16,
  149716. };
  149717. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149718. _vq_quantthresh__44u5__p9_2,
  149719. _vq_quantmap__44u5__p9_2,
  149720. 17,
  149721. 17
  149722. };
  149723. static static_codebook _44u5__p9_2 = {
  149724. 2, 289,
  149725. _vq_lengthlist__44u5__p9_2,
  149726. 1, -529530880, 1611661312, 5, 0,
  149727. _vq_quantlist__44u5__p9_2,
  149728. NULL,
  149729. &_vq_auxt__44u5__p9_2,
  149730. NULL,
  149731. 0
  149732. };
  149733. static long _huff_lengthlist__44u5__short[] = {
  149734. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149735. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149736. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149737. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149738. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149739. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149740. 6, 8,15,17,
  149741. };
  149742. static static_codebook _huff_book__44u5__short = {
  149743. 2, 100,
  149744. _huff_lengthlist__44u5__short,
  149745. 0, 0, 0, 0, 0,
  149746. NULL,
  149747. NULL,
  149748. NULL,
  149749. NULL,
  149750. 0
  149751. };
  149752. static long _huff_lengthlist__44u6__long[] = {
  149753. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149754. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149755. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149756. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149757. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149758. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149759. 13, 8, 7, 7,
  149760. };
  149761. static static_codebook _huff_book__44u6__long = {
  149762. 2, 100,
  149763. _huff_lengthlist__44u6__long,
  149764. 0, 0, 0, 0, 0,
  149765. NULL,
  149766. NULL,
  149767. NULL,
  149768. NULL,
  149769. 0
  149770. };
  149771. static long _vq_quantlist__44u6__p1_0[] = {
  149772. 1,
  149773. 0,
  149774. 2,
  149775. };
  149776. static long _vq_lengthlist__44u6__p1_0[] = {
  149777. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149778. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149779. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149780. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149781. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149782. 12,
  149783. };
  149784. static float _vq_quantthresh__44u6__p1_0[] = {
  149785. -0.5, 0.5,
  149786. };
  149787. static long _vq_quantmap__44u6__p1_0[] = {
  149788. 1, 0, 2,
  149789. };
  149790. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149791. _vq_quantthresh__44u6__p1_0,
  149792. _vq_quantmap__44u6__p1_0,
  149793. 3,
  149794. 3
  149795. };
  149796. static static_codebook _44u6__p1_0 = {
  149797. 4, 81,
  149798. _vq_lengthlist__44u6__p1_0,
  149799. 1, -535822336, 1611661312, 2, 0,
  149800. _vq_quantlist__44u6__p1_0,
  149801. NULL,
  149802. &_vq_auxt__44u6__p1_0,
  149803. NULL,
  149804. 0
  149805. };
  149806. static long _vq_quantlist__44u6__p2_0[] = {
  149807. 1,
  149808. 0,
  149809. 2,
  149810. };
  149811. static long _vq_lengthlist__44u6__p2_0[] = {
  149812. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149813. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149814. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149815. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149816. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149817. 9,
  149818. };
  149819. static float _vq_quantthresh__44u6__p2_0[] = {
  149820. -0.5, 0.5,
  149821. };
  149822. static long _vq_quantmap__44u6__p2_0[] = {
  149823. 1, 0, 2,
  149824. };
  149825. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149826. _vq_quantthresh__44u6__p2_0,
  149827. _vq_quantmap__44u6__p2_0,
  149828. 3,
  149829. 3
  149830. };
  149831. static static_codebook _44u6__p2_0 = {
  149832. 4, 81,
  149833. _vq_lengthlist__44u6__p2_0,
  149834. 1, -535822336, 1611661312, 2, 0,
  149835. _vq_quantlist__44u6__p2_0,
  149836. NULL,
  149837. &_vq_auxt__44u6__p2_0,
  149838. NULL,
  149839. 0
  149840. };
  149841. static long _vq_quantlist__44u6__p3_0[] = {
  149842. 2,
  149843. 1,
  149844. 3,
  149845. 0,
  149846. 4,
  149847. };
  149848. static long _vq_lengthlist__44u6__p3_0[] = {
  149849. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149850. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149851. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149852. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149853. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149854. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149855. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149856. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149857. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149858. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149859. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149860. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149861. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149862. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149863. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149864. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149865. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149866. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149867. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149868. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149869. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149870. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149871. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149872. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149873. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149874. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149875. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149876. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149877. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149878. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149879. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149880. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149881. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149882. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149883. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149884. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149885. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149886. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149887. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149888. 19,
  149889. };
  149890. static float _vq_quantthresh__44u6__p3_0[] = {
  149891. -1.5, -0.5, 0.5, 1.5,
  149892. };
  149893. static long _vq_quantmap__44u6__p3_0[] = {
  149894. 3, 1, 0, 2, 4,
  149895. };
  149896. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149897. _vq_quantthresh__44u6__p3_0,
  149898. _vq_quantmap__44u6__p3_0,
  149899. 5,
  149900. 5
  149901. };
  149902. static static_codebook _44u6__p3_0 = {
  149903. 4, 625,
  149904. _vq_lengthlist__44u6__p3_0,
  149905. 1, -533725184, 1611661312, 3, 0,
  149906. _vq_quantlist__44u6__p3_0,
  149907. NULL,
  149908. &_vq_auxt__44u6__p3_0,
  149909. NULL,
  149910. 0
  149911. };
  149912. static long _vq_quantlist__44u6__p4_0[] = {
  149913. 2,
  149914. 1,
  149915. 3,
  149916. 0,
  149917. 4,
  149918. };
  149919. static long _vq_lengthlist__44u6__p4_0[] = {
  149920. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149921. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149922. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149923. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149924. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149925. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149926. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149927. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149928. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149929. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149930. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149931. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149932. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149933. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149934. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149935. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149936. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149937. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149938. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149939. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149940. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149941. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149942. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149943. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149944. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149945. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149946. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149947. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149948. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149949. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149950. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149951. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149952. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149953. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149954. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149955. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149956. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149957. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149958. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149959. 13,
  149960. };
  149961. static float _vq_quantthresh__44u6__p4_0[] = {
  149962. -1.5, -0.5, 0.5, 1.5,
  149963. };
  149964. static long _vq_quantmap__44u6__p4_0[] = {
  149965. 3, 1, 0, 2, 4,
  149966. };
  149967. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149968. _vq_quantthresh__44u6__p4_0,
  149969. _vq_quantmap__44u6__p4_0,
  149970. 5,
  149971. 5
  149972. };
  149973. static static_codebook _44u6__p4_0 = {
  149974. 4, 625,
  149975. _vq_lengthlist__44u6__p4_0,
  149976. 1, -533725184, 1611661312, 3, 0,
  149977. _vq_quantlist__44u6__p4_0,
  149978. NULL,
  149979. &_vq_auxt__44u6__p4_0,
  149980. NULL,
  149981. 0
  149982. };
  149983. static long _vq_quantlist__44u6__p5_0[] = {
  149984. 4,
  149985. 3,
  149986. 5,
  149987. 2,
  149988. 6,
  149989. 1,
  149990. 7,
  149991. 0,
  149992. 8,
  149993. };
  149994. static long _vq_lengthlist__44u6__p5_0[] = {
  149995. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149996. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149997. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149998. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149999. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  150000. 14,
  150001. };
  150002. static float _vq_quantthresh__44u6__p5_0[] = {
  150003. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150004. };
  150005. static long _vq_quantmap__44u6__p5_0[] = {
  150006. 7, 5, 3, 1, 0, 2, 4, 6,
  150007. 8,
  150008. };
  150009. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  150010. _vq_quantthresh__44u6__p5_0,
  150011. _vq_quantmap__44u6__p5_0,
  150012. 9,
  150013. 9
  150014. };
  150015. static static_codebook _44u6__p5_0 = {
  150016. 2, 81,
  150017. _vq_lengthlist__44u6__p5_0,
  150018. 1, -531628032, 1611661312, 4, 0,
  150019. _vq_quantlist__44u6__p5_0,
  150020. NULL,
  150021. &_vq_auxt__44u6__p5_0,
  150022. NULL,
  150023. 0
  150024. };
  150025. static long _vq_quantlist__44u6__p6_0[] = {
  150026. 4,
  150027. 3,
  150028. 5,
  150029. 2,
  150030. 6,
  150031. 1,
  150032. 7,
  150033. 0,
  150034. 8,
  150035. };
  150036. static long _vq_lengthlist__44u6__p6_0[] = {
  150037. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150038. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  150039. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150040. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  150041. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  150042. 12,
  150043. };
  150044. static float _vq_quantthresh__44u6__p6_0[] = {
  150045. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150046. };
  150047. static long _vq_quantmap__44u6__p6_0[] = {
  150048. 7, 5, 3, 1, 0, 2, 4, 6,
  150049. 8,
  150050. };
  150051. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  150052. _vq_quantthresh__44u6__p6_0,
  150053. _vq_quantmap__44u6__p6_0,
  150054. 9,
  150055. 9
  150056. };
  150057. static static_codebook _44u6__p6_0 = {
  150058. 2, 81,
  150059. _vq_lengthlist__44u6__p6_0,
  150060. 1, -531628032, 1611661312, 4, 0,
  150061. _vq_quantlist__44u6__p6_0,
  150062. NULL,
  150063. &_vq_auxt__44u6__p6_0,
  150064. NULL,
  150065. 0
  150066. };
  150067. static long _vq_quantlist__44u6__p7_0[] = {
  150068. 1,
  150069. 0,
  150070. 2,
  150071. };
  150072. static long _vq_lengthlist__44u6__p7_0[] = {
  150073. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  150074. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  150075. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  150076. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  150077. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  150078. 10,
  150079. };
  150080. static float _vq_quantthresh__44u6__p7_0[] = {
  150081. -5.5, 5.5,
  150082. };
  150083. static long _vq_quantmap__44u6__p7_0[] = {
  150084. 1, 0, 2,
  150085. };
  150086. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  150087. _vq_quantthresh__44u6__p7_0,
  150088. _vq_quantmap__44u6__p7_0,
  150089. 3,
  150090. 3
  150091. };
  150092. static static_codebook _44u6__p7_0 = {
  150093. 4, 81,
  150094. _vq_lengthlist__44u6__p7_0,
  150095. 1, -529137664, 1618345984, 2, 0,
  150096. _vq_quantlist__44u6__p7_0,
  150097. NULL,
  150098. &_vq_auxt__44u6__p7_0,
  150099. NULL,
  150100. 0
  150101. };
  150102. static long _vq_quantlist__44u6__p7_1[] = {
  150103. 5,
  150104. 4,
  150105. 6,
  150106. 3,
  150107. 7,
  150108. 2,
  150109. 8,
  150110. 1,
  150111. 9,
  150112. 0,
  150113. 10,
  150114. };
  150115. static long _vq_lengthlist__44u6__p7_1[] = {
  150116. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150117. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150118. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150119. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150120. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150121. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150122. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150123. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150124. };
  150125. static float _vq_quantthresh__44u6__p7_1[] = {
  150126. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150127. 3.5, 4.5,
  150128. };
  150129. static long _vq_quantmap__44u6__p7_1[] = {
  150130. 9, 7, 5, 3, 1, 0, 2, 4,
  150131. 6, 8, 10,
  150132. };
  150133. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150134. _vq_quantthresh__44u6__p7_1,
  150135. _vq_quantmap__44u6__p7_1,
  150136. 11,
  150137. 11
  150138. };
  150139. static static_codebook _44u6__p7_1 = {
  150140. 2, 121,
  150141. _vq_lengthlist__44u6__p7_1,
  150142. 1, -531365888, 1611661312, 4, 0,
  150143. _vq_quantlist__44u6__p7_1,
  150144. NULL,
  150145. &_vq_auxt__44u6__p7_1,
  150146. NULL,
  150147. 0
  150148. };
  150149. static long _vq_quantlist__44u6__p8_0[] = {
  150150. 5,
  150151. 4,
  150152. 6,
  150153. 3,
  150154. 7,
  150155. 2,
  150156. 8,
  150157. 1,
  150158. 9,
  150159. 0,
  150160. 10,
  150161. };
  150162. static long _vq_lengthlist__44u6__p8_0[] = {
  150163. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150164. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150165. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150166. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150167. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150168. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150169. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150170. 12,13,13,14,14,14,15,15,15,
  150171. };
  150172. static float _vq_quantthresh__44u6__p8_0[] = {
  150173. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150174. 38.5, 49.5,
  150175. };
  150176. static long _vq_quantmap__44u6__p8_0[] = {
  150177. 9, 7, 5, 3, 1, 0, 2, 4,
  150178. 6, 8, 10,
  150179. };
  150180. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150181. _vq_quantthresh__44u6__p8_0,
  150182. _vq_quantmap__44u6__p8_0,
  150183. 11,
  150184. 11
  150185. };
  150186. static static_codebook _44u6__p8_0 = {
  150187. 2, 121,
  150188. _vq_lengthlist__44u6__p8_0,
  150189. 1, -524582912, 1618345984, 4, 0,
  150190. _vq_quantlist__44u6__p8_0,
  150191. NULL,
  150192. &_vq_auxt__44u6__p8_0,
  150193. NULL,
  150194. 0
  150195. };
  150196. static long _vq_quantlist__44u6__p8_1[] = {
  150197. 5,
  150198. 4,
  150199. 6,
  150200. 3,
  150201. 7,
  150202. 2,
  150203. 8,
  150204. 1,
  150205. 9,
  150206. 0,
  150207. 10,
  150208. };
  150209. static long _vq_lengthlist__44u6__p8_1[] = {
  150210. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150211. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150212. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150213. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150214. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150215. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150216. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150217. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150218. };
  150219. static float _vq_quantthresh__44u6__p8_1[] = {
  150220. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150221. 3.5, 4.5,
  150222. };
  150223. static long _vq_quantmap__44u6__p8_1[] = {
  150224. 9, 7, 5, 3, 1, 0, 2, 4,
  150225. 6, 8, 10,
  150226. };
  150227. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150228. _vq_quantthresh__44u6__p8_1,
  150229. _vq_quantmap__44u6__p8_1,
  150230. 11,
  150231. 11
  150232. };
  150233. static static_codebook _44u6__p8_1 = {
  150234. 2, 121,
  150235. _vq_lengthlist__44u6__p8_1,
  150236. 1, -531365888, 1611661312, 4, 0,
  150237. _vq_quantlist__44u6__p8_1,
  150238. NULL,
  150239. &_vq_auxt__44u6__p8_1,
  150240. NULL,
  150241. 0
  150242. };
  150243. static long _vq_quantlist__44u6__p9_0[] = {
  150244. 7,
  150245. 6,
  150246. 8,
  150247. 5,
  150248. 9,
  150249. 4,
  150250. 10,
  150251. 3,
  150252. 11,
  150253. 2,
  150254. 12,
  150255. 1,
  150256. 13,
  150257. 0,
  150258. 14,
  150259. };
  150260. static long _vq_lengthlist__44u6__p9_0[] = {
  150261. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150262. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150263. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150264. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150265. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150266. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150267. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150268. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150269. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150270. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150271. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150272. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150273. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150274. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150275. 14,
  150276. };
  150277. static float _vq_quantthresh__44u6__p9_0[] = {
  150278. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150279. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150280. };
  150281. static long _vq_quantmap__44u6__p9_0[] = {
  150282. 13, 11, 9, 7, 5, 3, 1, 0,
  150283. 2, 4, 6, 8, 10, 12, 14,
  150284. };
  150285. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150286. _vq_quantthresh__44u6__p9_0,
  150287. _vq_quantmap__44u6__p9_0,
  150288. 15,
  150289. 15
  150290. };
  150291. static static_codebook _44u6__p9_0 = {
  150292. 2, 225,
  150293. _vq_lengthlist__44u6__p9_0,
  150294. 1, -514071552, 1627381760, 4, 0,
  150295. _vq_quantlist__44u6__p9_0,
  150296. NULL,
  150297. &_vq_auxt__44u6__p9_0,
  150298. NULL,
  150299. 0
  150300. };
  150301. static long _vq_quantlist__44u6__p9_1[] = {
  150302. 7,
  150303. 6,
  150304. 8,
  150305. 5,
  150306. 9,
  150307. 4,
  150308. 10,
  150309. 3,
  150310. 11,
  150311. 2,
  150312. 12,
  150313. 1,
  150314. 13,
  150315. 0,
  150316. 14,
  150317. };
  150318. static long _vq_lengthlist__44u6__p9_1[] = {
  150319. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150320. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150321. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150322. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150323. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150324. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150325. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150326. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150327. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150328. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150329. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150330. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150331. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150332. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150333. 13,
  150334. };
  150335. static float _vq_quantthresh__44u6__p9_1[] = {
  150336. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150337. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150338. };
  150339. static long _vq_quantmap__44u6__p9_1[] = {
  150340. 13, 11, 9, 7, 5, 3, 1, 0,
  150341. 2, 4, 6, 8, 10, 12, 14,
  150342. };
  150343. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150344. _vq_quantthresh__44u6__p9_1,
  150345. _vq_quantmap__44u6__p9_1,
  150346. 15,
  150347. 15
  150348. };
  150349. static static_codebook _44u6__p9_1 = {
  150350. 2, 225,
  150351. _vq_lengthlist__44u6__p9_1,
  150352. 1, -522338304, 1620115456, 4, 0,
  150353. _vq_quantlist__44u6__p9_1,
  150354. NULL,
  150355. &_vq_auxt__44u6__p9_1,
  150356. NULL,
  150357. 0
  150358. };
  150359. static long _vq_quantlist__44u6__p9_2[] = {
  150360. 8,
  150361. 7,
  150362. 9,
  150363. 6,
  150364. 10,
  150365. 5,
  150366. 11,
  150367. 4,
  150368. 12,
  150369. 3,
  150370. 13,
  150371. 2,
  150372. 14,
  150373. 1,
  150374. 15,
  150375. 0,
  150376. 16,
  150377. };
  150378. static long _vq_lengthlist__44u6__p9_2[] = {
  150379. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150380. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150381. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150382. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150383. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150384. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150385. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150386. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150387. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150388. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150389. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150390. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150391. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150392. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150393. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150394. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150395. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150396. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150397. 10,
  150398. };
  150399. static float _vq_quantthresh__44u6__p9_2[] = {
  150400. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150401. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150402. };
  150403. static long _vq_quantmap__44u6__p9_2[] = {
  150404. 15, 13, 11, 9, 7, 5, 3, 1,
  150405. 0, 2, 4, 6, 8, 10, 12, 14,
  150406. 16,
  150407. };
  150408. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150409. _vq_quantthresh__44u6__p9_2,
  150410. _vq_quantmap__44u6__p9_2,
  150411. 17,
  150412. 17
  150413. };
  150414. static static_codebook _44u6__p9_2 = {
  150415. 2, 289,
  150416. _vq_lengthlist__44u6__p9_2,
  150417. 1, -529530880, 1611661312, 5, 0,
  150418. _vq_quantlist__44u6__p9_2,
  150419. NULL,
  150420. &_vq_auxt__44u6__p9_2,
  150421. NULL,
  150422. 0
  150423. };
  150424. static long _huff_lengthlist__44u6__short[] = {
  150425. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150426. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150427. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150428. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150429. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150430. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150431. 7, 6, 9,16,
  150432. };
  150433. static static_codebook _huff_book__44u6__short = {
  150434. 2, 100,
  150435. _huff_lengthlist__44u6__short,
  150436. 0, 0, 0, 0, 0,
  150437. NULL,
  150438. NULL,
  150439. NULL,
  150440. NULL,
  150441. 0
  150442. };
  150443. static long _huff_lengthlist__44u7__long[] = {
  150444. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150445. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150446. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150447. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150448. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150449. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150450. 12, 8, 6, 7,
  150451. };
  150452. static static_codebook _huff_book__44u7__long = {
  150453. 2, 100,
  150454. _huff_lengthlist__44u7__long,
  150455. 0, 0, 0, 0, 0,
  150456. NULL,
  150457. NULL,
  150458. NULL,
  150459. NULL,
  150460. 0
  150461. };
  150462. static long _vq_quantlist__44u7__p1_0[] = {
  150463. 1,
  150464. 0,
  150465. 2,
  150466. };
  150467. static long _vq_lengthlist__44u7__p1_0[] = {
  150468. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150469. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150470. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150471. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150472. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150473. 12,
  150474. };
  150475. static float _vq_quantthresh__44u7__p1_0[] = {
  150476. -0.5, 0.5,
  150477. };
  150478. static long _vq_quantmap__44u7__p1_0[] = {
  150479. 1, 0, 2,
  150480. };
  150481. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150482. _vq_quantthresh__44u7__p1_0,
  150483. _vq_quantmap__44u7__p1_0,
  150484. 3,
  150485. 3
  150486. };
  150487. static static_codebook _44u7__p1_0 = {
  150488. 4, 81,
  150489. _vq_lengthlist__44u7__p1_0,
  150490. 1, -535822336, 1611661312, 2, 0,
  150491. _vq_quantlist__44u7__p1_0,
  150492. NULL,
  150493. &_vq_auxt__44u7__p1_0,
  150494. NULL,
  150495. 0
  150496. };
  150497. static long _vq_quantlist__44u7__p2_0[] = {
  150498. 1,
  150499. 0,
  150500. 2,
  150501. };
  150502. static long _vq_lengthlist__44u7__p2_0[] = {
  150503. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150504. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150505. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150506. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150507. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150508. 9,
  150509. };
  150510. static float _vq_quantthresh__44u7__p2_0[] = {
  150511. -0.5, 0.5,
  150512. };
  150513. static long _vq_quantmap__44u7__p2_0[] = {
  150514. 1, 0, 2,
  150515. };
  150516. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150517. _vq_quantthresh__44u7__p2_0,
  150518. _vq_quantmap__44u7__p2_0,
  150519. 3,
  150520. 3
  150521. };
  150522. static static_codebook _44u7__p2_0 = {
  150523. 4, 81,
  150524. _vq_lengthlist__44u7__p2_0,
  150525. 1, -535822336, 1611661312, 2, 0,
  150526. _vq_quantlist__44u7__p2_0,
  150527. NULL,
  150528. &_vq_auxt__44u7__p2_0,
  150529. NULL,
  150530. 0
  150531. };
  150532. static long _vq_quantlist__44u7__p3_0[] = {
  150533. 2,
  150534. 1,
  150535. 3,
  150536. 0,
  150537. 4,
  150538. };
  150539. static long _vq_lengthlist__44u7__p3_0[] = {
  150540. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150541. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150542. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150543. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150544. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150545. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150546. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150547. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150548. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150549. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150550. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150551. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150552. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150553. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150554. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150555. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150556. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150557. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150558. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150559. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150560. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150561. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150562. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150563. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150564. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150565. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150566. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150567. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150568. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150569. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150570. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150571. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150572. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150573. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150574. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150575. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150576. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150577. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150578. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150579. 0,
  150580. };
  150581. static float _vq_quantthresh__44u7__p3_0[] = {
  150582. -1.5, -0.5, 0.5, 1.5,
  150583. };
  150584. static long _vq_quantmap__44u7__p3_0[] = {
  150585. 3, 1, 0, 2, 4,
  150586. };
  150587. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150588. _vq_quantthresh__44u7__p3_0,
  150589. _vq_quantmap__44u7__p3_0,
  150590. 5,
  150591. 5
  150592. };
  150593. static static_codebook _44u7__p3_0 = {
  150594. 4, 625,
  150595. _vq_lengthlist__44u7__p3_0,
  150596. 1, -533725184, 1611661312, 3, 0,
  150597. _vq_quantlist__44u7__p3_0,
  150598. NULL,
  150599. &_vq_auxt__44u7__p3_0,
  150600. NULL,
  150601. 0
  150602. };
  150603. static long _vq_quantlist__44u7__p4_0[] = {
  150604. 2,
  150605. 1,
  150606. 3,
  150607. 0,
  150608. 4,
  150609. };
  150610. static long _vq_lengthlist__44u7__p4_0[] = {
  150611. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150612. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150613. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150614. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150615. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150616. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150617. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150618. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150619. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150620. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150621. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150622. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150623. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150624. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150625. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150626. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150627. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150628. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150629. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150630. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150631. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150632. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150633. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150634. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150635. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150636. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150637. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150638. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150639. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150640. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150641. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150642. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150643. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150644. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150645. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150646. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150647. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150648. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150649. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150650. 14,
  150651. };
  150652. static float _vq_quantthresh__44u7__p4_0[] = {
  150653. -1.5, -0.5, 0.5, 1.5,
  150654. };
  150655. static long _vq_quantmap__44u7__p4_0[] = {
  150656. 3, 1, 0, 2, 4,
  150657. };
  150658. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150659. _vq_quantthresh__44u7__p4_0,
  150660. _vq_quantmap__44u7__p4_0,
  150661. 5,
  150662. 5
  150663. };
  150664. static static_codebook _44u7__p4_0 = {
  150665. 4, 625,
  150666. _vq_lengthlist__44u7__p4_0,
  150667. 1, -533725184, 1611661312, 3, 0,
  150668. _vq_quantlist__44u7__p4_0,
  150669. NULL,
  150670. &_vq_auxt__44u7__p4_0,
  150671. NULL,
  150672. 0
  150673. };
  150674. static long _vq_quantlist__44u7__p5_0[] = {
  150675. 4,
  150676. 3,
  150677. 5,
  150678. 2,
  150679. 6,
  150680. 1,
  150681. 7,
  150682. 0,
  150683. 8,
  150684. };
  150685. static long _vq_lengthlist__44u7__p5_0[] = {
  150686. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150687. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150688. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150689. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150690. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150691. 14,
  150692. };
  150693. static float _vq_quantthresh__44u7__p5_0[] = {
  150694. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150695. };
  150696. static long _vq_quantmap__44u7__p5_0[] = {
  150697. 7, 5, 3, 1, 0, 2, 4, 6,
  150698. 8,
  150699. };
  150700. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150701. _vq_quantthresh__44u7__p5_0,
  150702. _vq_quantmap__44u7__p5_0,
  150703. 9,
  150704. 9
  150705. };
  150706. static static_codebook _44u7__p5_0 = {
  150707. 2, 81,
  150708. _vq_lengthlist__44u7__p5_0,
  150709. 1, -531628032, 1611661312, 4, 0,
  150710. _vq_quantlist__44u7__p5_0,
  150711. NULL,
  150712. &_vq_auxt__44u7__p5_0,
  150713. NULL,
  150714. 0
  150715. };
  150716. static long _vq_quantlist__44u7__p6_0[] = {
  150717. 4,
  150718. 3,
  150719. 5,
  150720. 2,
  150721. 6,
  150722. 1,
  150723. 7,
  150724. 0,
  150725. 8,
  150726. };
  150727. static long _vq_lengthlist__44u7__p6_0[] = {
  150728. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150729. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150730. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150731. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150732. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150733. 12,
  150734. };
  150735. static float _vq_quantthresh__44u7__p6_0[] = {
  150736. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150737. };
  150738. static long _vq_quantmap__44u7__p6_0[] = {
  150739. 7, 5, 3, 1, 0, 2, 4, 6,
  150740. 8,
  150741. };
  150742. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150743. _vq_quantthresh__44u7__p6_0,
  150744. _vq_quantmap__44u7__p6_0,
  150745. 9,
  150746. 9
  150747. };
  150748. static static_codebook _44u7__p6_0 = {
  150749. 2, 81,
  150750. _vq_lengthlist__44u7__p6_0,
  150751. 1, -531628032, 1611661312, 4, 0,
  150752. _vq_quantlist__44u7__p6_0,
  150753. NULL,
  150754. &_vq_auxt__44u7__p6_0,
  150755. NULL,
  150756. 0
  150757. };
  150758. static long _vq_quantlist__44u7__p7_0[] = {
  150759. 1,
  150760. 0,
  150761. 2,
  150762. };
  150763. static long _vq_lengthlist__44u7__p7_0[] = {
  150764. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150765. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150766. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150767. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150768. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150769. 10,
  150770. };
  150771. static float _vq_quantthresh__44u7__p7_0[] = {
  150772. -5.5, 5.5,
  150773. };
  150774. static long _vq_quantmap__44u7__p7_0[] = {
  150775. 1, 0, 2,
  150776. };
  150777. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150778. _vq_quantthresh__44u7__p7_0,
  150779. _vq_quantmap__44u7__p7_0,
  150780. 3,
  150781. 3
  150782. };
  150783. static static_codebook _44u7__p7_0 = {
  150784. 4, 81,
  150785. _vq_lengthlist__44u7__p7_0,
  150786. 1, -529137664, 1618345984, 2, 0,
  150787. _vq_quantlist__44u7__p7_0,
  150788. NULL,
  150789. &_vq_auxt__44u7__p7_0,
  150790. NULL,
  150791. 0
  150792. };
  150793. static long _vq_quantlist__44u7__p7_1[] = {
  150794. 5,
  150795. 4,
  150796. 6,
  150797. 3,
  150798. 7,
  150799. 2,
  150800. 8,
  150801. 1,
  150802. 9,
  150803. 0,
  150804. 10,
  150805. };
  150806. static long _vq_lengthlist__44u7__p7_1[] = {
  150807. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150808. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150809. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150810. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150811. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150812. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150813. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150814. 8, 9, 9, 9, 9, 9,10,10,10,
  150815. };
  150816. static float _vq_quantthresh__44u7__p7_1[] = {
  150817. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150818. 3.5, 4.5,
  150819. };
  150820. static long _vq_quantmap__44u7__p7_1[] = {
  150821. 9, 7, 5, 3, 1, 0, 2, 4,
  150822. 6, 8, 10,
  150823. };
  150824. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150825. _vq_quantthresh__44u7__p7_1,
  150826. _vq_quantmap__44u7__p7_1,
  150827. 11,
  150828. 11
  150829. };
  150830. static static_codebook _44u7__p7_1 = {
  150831. 2, 121,
  150832. _vq_lengthlist__44u7__p7_1,
  150833. 1, -531365888, 1611661312, 4, 0,
  150834. _vq_quantlist__44u7__p7_1,
  150835. NULL,
  150836. &_vq_auxt__44u7__p7_1,
  150837. NULL,
  150838. 0
  150839. };
  150840. static long _vq_quantlist__44u7__p8_0[] = {
  150841. 5,
  150842. 4,
  150843. 6,
  150844. 3,
  150845. 7,
  150846. 2,
  150847. 8,
  150848. 1,
  150849. 9,
  150850. 0,
  150851. 10,
  150852. };
  150853. static long _vq_lengthlist__44u7__p8_0[] = {
  150854. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150855. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150856. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150857. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150858. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150859. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150860. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150861. 12,13,13,14,14,15,15,15,16,
  150862. };
  150863. static float _vq_quantthresh__44u7__p8_0[] = {
  150864. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150865. 38.5, 49.5,
  150866. };
  150867. static long _vq_quantmap__44u7__p8_0[] = {
  150868. 9, 7, 5, 3, 1, 0, 2, 4,
  150869. 6, 8, 10,
  150870. };
  150871. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150872. _vq_quantthresh__44u7__p8_0,
  150873. _vq_quantmap__44u7__p8_0,
  150874. 11,
  150875. 11
  150876. };
  150877. static static_codebook _44u7__p8_0 = {
  150878. 2, 121,
  150879. _vq_lengthlist__44u7__p8_0,
  150880. 1, -524582912, 1618345984, 4, 0,
  150881. _vq_quantlist__44u7__p8_0,
  150882. NULL,
  150883. &_vq_auxt__44u7__p8_0,
  150884. NULL,
  150885. 0
  150886. };
  150887. static long _vq_quantlist__44u7__p8_1[] = {
  150888. 5,
  150889. 4,
  150890. 6,
  150891. 3,
  150892. 7,
  150893. 2,
  150894. 8,
  150895. 1,
  150896. 9,
  150897. 0,
  150898. 10,
  150899. };
  150900. static long _vq_lengthlist__44u7__p8_1[] = {
  150901. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150902. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150903. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150904. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150905. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150906. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150907. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150908. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150909. };
  150910. static float _vq_quantthresh__44u7__p8_1[] = {
  150911. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150912. 3.5, 4.5,
  150913. };
  150914. static long _vq_quantmap__44u7__p8_1[] = {
  150915. 9, 7, 5, 3, 1, 0, 2, 4,
  150916. 6, 8, 10,
  150917. };
  150918. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150919. _vq_quantthresh__44u7__p8_1,
  150920. _vq_quantmap__44u7__p8_1,
  150921. 11,
  150922. 11
  150923. };
  150924. static static_codebook _44u7__p8_1 = {
  150925. 2, 121,
  150926. _vq_lengthlist__44u7__p8_1,
  150927. 1, -531365888, 1611661312, 4, 0,
  150928. _vq_quantlist__44u7__p8_1,
  150929. NULL,
  150930. &_vq_auxt__44u7__p8_1,
  150931. NULL,
  150932. 0
  150933. };
  150934. static long _vq_quantlist__44u7__p9_0[] = {
  150935. 5,
  150936. 4,
  150937. 6,
  150938. 3,
  150939. 7,
  150940. 2,
  150941. 8,
  150942. 1,
  150943. 9,
  150944. 0,
  150945. 10,
  150946. };
  150947. static long _vq_lengthlist__44u7__p9_0[] = {
  150948. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150949. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150950. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150951. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150952. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150953. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150954. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150955. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150956. };
  150957. static float _vq_quantthresh__44u7__p9_0[] = {
  150958. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150959. 2229.5, 2866.5,
  150960. };
  150961. static long _vq_quantmap__44u7__p9_0[] = {
  150962. 9, 7, 5, 3, 1, 0, 2, 4,
  150963. 6, 8, 10,
  150964. };
  150965. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150966. _vq_quantthresh__44u7__p9_0,
  150967. _vq_quantmap__44u7__p9_0,
  150968. 11,
  150969. 11
  150970. };
  150971. static static_codebook _44u7__p9_0 = {
  150972. 2, 121,
  150973. _vq_lengthlist__44u7__p9_0,
  150974. 1, -512171520, 1630791680, 4, 0,
  150975. _vq_quantlist__44u7__p9_0,
  150976. NULL,
  150977. &_vq_auxt__44u7__p9_0,
  150978. NULL,
  150979. 0
  150980. };
  150981. static long _vq_quantlist__44u7__p9_1[] = {
  150982. 6,
  150983. 5,
  150984. 7,
  150985. 4,
  150986. 8,
  150987. 3,
  150988. 9,
  150989. 2,
  150990. 10,
  150991. 1,
  150992. 11,
  150993. 0,
  150994. 12,
  150995. };
  150996. static long _vq_lengthlist__44u7__p9_1[] = {
  150997. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150998. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150999. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  151000. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  151001. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  151002. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  151003. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  151004. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  151005. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  151006. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  151007. 15,15,15,15,17,17,16,17,16,
  151008. };
  151009. static float _vq_quantthresh__44u7__p9_1[] = {
  151010. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  151011. 122.5, 171.5, 220.5, 269.5,
  151012. };
  151013. static long _vq_quantmap__44u7__p9_1[] = {
  151014. 11, 9, 7, 5, 3, 1, 0, 2,
  151015. 4, 6, 8, 10, 12,
  151016. };
  151017. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  151018. _vq_quantthresh__44u7__p9_1,
  151019. _vq_quantmap__44u7__p9_1,
  151020. 13,
  151021. 13
  151022. };
  151023. static static_codebook _44u7__p9_1 = {
  151024. 2, 169,
  151025. _vq_lengthlist__44u7__p9_1,
  151026. 1, -518889472, 1622704128, 4, 0,
  151027. _vq_quantlist__44u7__p9_1,
  151028. NULL,
  151029. &_vq_auxt__44u7__p9_1,
  151030. NULL,
  151031. 0
  151032. };
  151033. static long _vq_quantlist__44u7__p9_2[] = {
  151034. 24,
  151035. 23,
  151036. 25,
  151037. 22,
  151038. 26,
  151039. 21,
  151040. 27,
  151041. 20,
  151042. 28,
  151043. 19,
  151044. 29,
  151045. 18,
  151046. 30,
  151047. 17,
  151048. 31,
  151049. 16,
  151050. 32,
  151051. 15,
  151052. 33,
  151053. 14,
  151054. 34,
  151055. 13,
  151056. 35,
  151057. 12,
  151058. 36,
  151059. 11,
  151060. 37,
  151061. 10,
  151062. 38,
  151063. 9,
  151064. 39,
  151065. 8,
  151066. 40,
  151067. 7,
  151068. 41,
  151069. 6,
  151070. 42,
  151071. 5,
  151072. 43,
  151073. 4,
  151074. 44,
  151075. 3,
  151076. 45,
  151077. 2,
  151078. 46,
  151079. 1,
  151080. 47,
  151081. 0,
  151082. 48,
  151083. };
  151084. static long _vq_lengthlist__44u7__p9_2[] = {
  151085. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151086. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151087. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  151088. 8,
  151089. };
  151090. static float _vq_quantthresh__44u7__p9_2[] = {
  151091. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151092. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151093. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151094. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151095. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151096. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151097. };
  151098. static long _vq_quantmap__44u7__p9_2[] = {
  151099. 47, 45, 43, 41, 39, 37, 35, 33,
  151100. 31, 29, 27, 25, 23, 21, 19, 17,
  151101. 15, 13, 11, 9, 7, 5, 3, 1,
  151102. 0, 2, 4, 6, 8, 10, 12, 14,
  151103. 16, 18, 20, 22, 24, 26, 28, 30,
  151104. 32, 34, 36, 38, 40, 42, 44, 46,
  151105. 48,
  151106. };
  151107. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151108. _vq_quantthresh__44u7__p9_2,
  151109. _vq_quantmap__44u7__p9_2,
  151110. 49,
  151111. 49
  151112. };
  151113. static static_codebook _44u7__p9_2 = {
  151114. 1, 49,
  151115. _vq_lengthlist__44u7__p9_2,
  151116. 1, -526909440, 1611661312, 6, 0,
  151117. _vq_quantlist__44u7__p9_2,
  151118. NULL,
  151119. &_vq_auxt__44u7__p9_2,
  151120. NULL,
  151121. 0
  151122. };
  151123. static long _huff_lengthlist__44u7__short[] = {
  151124. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151125. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151126. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151127. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151128. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151129. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151130. 6, 8, 5, 9,
  151131. };
  151132. static static_codebook _huff_book__44u7__short = {
  151133. 2, 100,
  151134. _huff_lengthlist__44u7__short,
  151135. 0, 0, 0, 0, 0,
  151136. NULL,
  151137. NULL,
  151138. NULL,
  151139. NULL,
  151140. 0
  151141. };
  151142. static long _huff_lengthlist__44u8__long[] = {
  151143. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151144. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151145. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151146. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151147. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151148. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151149. 10, 8, 8, 9,
  151150. };
  151151. static static_codebook _huff_book__44u8__long = {
  151152. 2, 100,
  151153. _huff_lengthlist__44u8__long,
  151154. 0, 0, 0, 0, 0,
  151155. NULL,
  151156. NULL,
  151157. NULL,
  151158. NULL,
  151159. 0
  151160. };
  151161. static long _huff_lengthlist__44u8__short[] = {
  151162. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151163. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151164. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151165. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151166. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151167. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151168. 10,10,15,17,
  151169. };
  151170. static static_codebook _huff_book__44u8__short = {
  151171. 2, 100,
  151172. _huff_lengthlist__44u8__short,
  151173. 0, 0, 0, 0, 0,
  151174. NULL,
  151175. NULL,
  151176. NULL,
  151177. NULL,
  151178. 0
  151179. };
  151180. static long _vq_quantlist__44u8_p1_0[] = {
  151181. 1,
  151182. 0,
  151183. 2,
  151184. };
  151185. static long _vq_lengthlist__44u8_p1_0[] = {
  151186. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151187. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151188. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151189. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151190. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151191. 10,
  151192. };
  151193. static float _vq_quantthresh__44u8_p1_0[] = {
  151194. -0.5, 0.5,
  151195. };
  151196. static long _vq_quantmap__44u8_p1_0[] = {
  151197. 1, 0, 2,
  151198. };
  151199. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151200. _vq_quantthresh__44u8_p1_0,
  151201. _vq_quantmap__44u8_p1_0,
  151202. 3,
  151203. 3
  151204. };
  151205. static static_codebook _44u8_p1_0 = {
  151206. 4, 81,
  151207. _vq_lengthlist__44u8_p1_0,
  151208. 1, -535822336, 1611661312, 2, 0,
  151209. _vq_quantlist__44u8_p1_0,
  151210. NULL,
  151211. &_vq_auxt__44u8_p1_0,
  151212. NULL,
  151213. 0
  151214. };
  151215. static long _vq_quantlist__44u8_p2_0[] = {
  151216. 2,
  151217. 1,
  151218. 3,
  151219. 0,
  151220. 4,
  151221. };
  151222. static long _vq_lengthlist__44u8_p2_0[] = {
  151223. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151224. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151225. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151226. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151227. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151228. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151229. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151230. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151231. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151232. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151233. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151234. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151235. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151236. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151237. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151238. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151239. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151240. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151241. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151242. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151243. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151244. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151245. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151246. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151247. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151248. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151249. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151250. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151251. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151252. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151253. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151254. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151255. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151256. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151257. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151258. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151259. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151260. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151261. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151262. 14,
  151263. };
  151264. static float _vq_quantthresh__44u8_p2_0[] = {
  151265. -1.5, -0.5, 0.5, 1.5,
  151266. };
  151267. static long _vq_quantmap__44u8_p2_0[] = {
  151268. 3, 1, 0, 2, 4,
  151269. };
  151270. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151271. _vq_quantthresh__44u8_p2_0,
  151272. _vq_quantmap__44u8_p2_0,
  151273. 5,
  151274. 5
  151275. };
  151276. static static_codebook _44u8_p2_0 = {
  151277. 4, 625,
  151278. _vq_lengthlist__44u8_p2_0,
  151279. 1, -533725184, 1611661312, 3, 0,
  151280. _vq_quantlist__44u8_p2_0,
  151281. NULL,
  151282. &_vq_auxt__44u8_p2_0,
  151283. NULL,
  151284. 0
  151285. };
  151286. static long _vq_quantlist__44u8_p3_0[] = {
  151287. 4,
  151288. 3,
  151289. 5,
  151290. 2,
  151291. 6,
  151292. 1,
  151293. 7,
  151294. 0,
  151295. 8,
  151296. };
  151297. static long _vq_lengthlist__44u8_p3_0[] = {
  151298. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151299. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151300. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151301. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151302. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151303. 12,
  151304. };
  151305. static float _vq_quantthresh__44u8_p3_0[] = {
  151306. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151307. };
  151308. static long _vq_quantmap__44u8_p3_0[] = {
  151309. 7, 5, 3, 1, 0, 2, 4, 6,
  151310. 8,
  151311. };
  151312. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151313. _vq_quantthresh__44u8_p3_0,
  151314. _vq_quantmap__44u8_p3_0,
  151315. 9,
  151316. 9
  151317. };
  151318. static static_codebook _44u8_p3_0 = {
  151319. 2, 81,
  151320. _vq_lengthlist__44u8_p3_0,
  151321. 1, -531628032, 1611661312, 4, 0,
  151322. _vq_quantlist__44u8_p3_0,
  151323. NULL,
  151324. &_vq_auxt__44u8_p3_0,
  151325. NULL,
  151326. 0
  151327. };
  151328. static long _vq_quantlist__44u8_p4_0[] = {
  151329. 8,
  151330. 7,
  151331. 9,
  151332. 6,
  151333. 10,
  151334. 5,
  151335. 11,
  151336. 4,
  151337. 12,
  151338. 3,
  151339. 13,
  151340. 2,
  151341. 14,
  151342. 1,
  151343. 15,
  151344. 0,
  151345. 16,
  151346. };
  151347. static long _vq_lengthlist__44u8_p4_0[] = {
  151348. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151349. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151350. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151351. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151352. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151353. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151354. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151355. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151356. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151357. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151358. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151359. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151360. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151361. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151362. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151363. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151364. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151365. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151366. 14,
  151367. };
  151368. static float _vq_quantthresh__44u8_p4_0[] = {
  151369. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151370. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151371. };
  151372. static long _vq_quantmap__44u8_p4_0[] = {
  151373. 15, 13, 11, 9, 7, 5, 3, 1,
  151374. 0, 2, 4, 6, 8, 10, 12, 14,
  151375. 16,
  151376. };
  151377. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151378. _vq_quantthresh__44u8_p4_0,
  151379. _vq_quantmap__44u8_p4_0,
  151380. 17,
  151381. 17
  151382. };
  151383. static static_codebook _44u8_p4_0 = {
  151384. 2, 289,
  151385. _vq_lengthlist__44u8_p4_0,
  151386. 1, -529530880, 1611661312, 5, 0,
  151387. _vq_quantlist__44u8_p4_0,
  151388. NULL,
  151389. &_vq_auxt__44u8_p4_0,
  151390. NULL,
  151391. 0
  151392. };
  151393. static long _vq_quantlist__44u8_p5_0[] = {
  151394. 1,
  151395. 0,
  151396. 2,
  151397. };
  151398. static long _vq_lengthlist__44u8_p5_0[] = {
  151399. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151400. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151401. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151402. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151403. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151404. 10,
  151405. };
  151406. static float _vq_quantthresh__44u8_p5_0[] = {
  151407. -5.5, 5.5,
  151408. };
  151409. static long _vq_quantmap__44u8_p5_0[] = {
  151410. 1, 0, 2,
  151411. };
  151412. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151413. _vq_quantthresh__44u8_p5_0,
  151414. _vq_quantmap__44u8_p5_0,
  151415. 3,
  151416. 3
  151417. };
  151418. static static_codebook _44u8_p5_0 = {
  151419. 4, 81,
  151420. _vq_lengthlist__44u8_p5_0,
  151421. 1, -529137664, 1618345984, 2, 0,
  151422. _vq_quantlist__44u8_p5_0,
  151423. NULL,
  151424. &_vq_auxt__44u8_p5_0,
  151425. NULL,
  151426. 0
  151427. };
  151428. static long _vq_quantlist__44u8_p5_1[] = {
  151429. 5,
  151430. 4,
  151431. 6,
  151432. 3,
  151433. 7,
  151434. 2,
  151435. 8,
  151436. 1,
  151437. 9,
  151438. 0,
  151439. 10,
  151440. };
  151441. static long _vq_lengthlist__44u8_p5_1[] = {
  151442. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151443. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151444. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151445. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151446. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151447. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151448. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151449. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151450. };
  151451. static float _vq_quantthresh__44u8_p5_1[] = {
  151452. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151453. 3.5, 4.5,
  151454. };
  151455. static long _vq_quantmap__44u8_p5_1[] = {
  151456. 9, 7, 5, 3, 1, 0, 2, 4,
  151457. 6, 8, 10,
  151458. };
  151459. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151460. _vq_quantthresh__44u8_p5_1,
  151461. _vq_quantmap__44u8_p5_1,
  151462. 11,
  151463. 11
  151464. };
  151465. static static_codebook _44u8_p5_1 = {
  151466. 2, 121,
  151467. _vq_lengthlist__44u8_p5_1,
  151468. 1, -531365888, 1611661312, 4, 0,
  151469. _vq_quantlist__44u8_p5_1,
  151470. NULL,
  151471. &_vq_auxt__44u8_p5_1,
  151472. NULL,
  151473. 0
  151474. };
  151475. static long _vq_quantlist__44u8_p6_0[] = {
  151476. 6,
  151477. 5,
  151478. 7,
  151479. 4,
  151480. 8,
  151481. 3,
  151482. 9,
  151483. 2,
  151484. 10,
  151485. 1,
  151486. 11,
  151487. 0,
  151488. 12,
  151489. };
  151490. static long _vq_lengthlist__44u8_p6_0[] = {
  151491. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151492. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151493. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151494. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151495. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151496. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151497. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151498. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151499. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151500. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151501. 11,11,11,11,11,12,11,12,12,
  151502. };
  151503. static float _vq_quantthresh__44u8_p6_0[] = {
  151504. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151505. 12.5, 17.5, 22.5, 27.5,
  151506. };
  151507. static long _vq_quantmap__44u8_p6_0[] = {
  151508. 11, 9, 7, 5, 3, 1, 0, 2,
  151509. 4, 6, 8, 10, 12,
  151510. };
  151511. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151512. _vq_quantthresh__44u8_p6_0,
  151513. _vq_quantmap__44u8_p6_0,
  151514. 13,
  151515. 13
  151516. };
  151517. static static_codebook _44u8_p6_0 = {
  151518. 2, 169,
  151519. _vq_lengthlist__44u8_p6_0,
  151520. 1, -526516224, 1616117760, 4, 0,
  151521. _vq_quantlist__44u8_p6_0,
  151522. NULL,
  151523. &_vq_auxt__44u8_p6_0,
  151524. NULL,
  151525. 0
  151526. };
  151527. static long _vq_quantlist__44u8_p6_1[] = {
  151528. 2,
  151529. 1,
  151530. 3,
  151531. 0,
  151532. 4,
  151533. };
  151534. static long _vq_lengthlist__44u8_p6_1[] = {
  151535. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151536. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151537. };
  151538. static float _vq_quantthresh__44u8_p6_1[] = {
  151539. -1.5, -0.5, 0.5, 1.5,
  151540. };
  151541. static long _vq_quantmap__44u8_p6_1[] = {
  151542. 3, 1, 0, 2, 4,
  151543. };
  151544. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151545. _vq_quantthresh__44u8_p6_1,
  151546. _vq_quantmap__44u8_p6_1,
  151547. 5,
  151548. 5
  151549. };
  151550. static static_codebook _44u8_p6_1 = {
  151551. 2, 25,
  151552. _vq_lengthlist__44u8_p6_1,
  151553. 1, -533725184, 1611661312, 3, 0,
  151554. _vq_quantlist__44u8_p6_1,
  151555. NULL,
  151556. &_vq_auxt__44u8_p6_1,
  151557. NULL,
  151558. 0
  151559. };
  151560. static long _vq_quantlist__44u8_p7_0[] = {
  151561. 6,
  151562. 5,
  151563. 7,
  151564. 4,
  151565. 8,
  151566. 3,
  151567. 9,
  151568. 2,
  151569. 10,
  151570. 1,
  151571. 11,
  151572. 0,
  151573. 12,
  151574. };
  151575. static long _vq_lengthlist__44u8_p7_0[] = {
  151576. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151577. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151578. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151579. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151580. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151581. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151582. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151583. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151584. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151585. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151586. 13,13,14,14,14,15,15,15,16,
  151587. };
  151588. static float _vq_quantthresh__44u8_p7_0[] = {
  151589. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151590. 27.5, 38.5, 49.5, 60.5,
  151591. };
  151592. static long _vq_quantmap__44u8_p7_0[] = {
  151593. 11, 9, 7, 5, 3, 1, 0, 2,
  151594. 4, 6, 8, 10, 12,
  151595. };
  151596. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151597. _vq_quantthresh__44u8_p7_0,
  151598. _vq_quantmap__44u8_p7_0,
  151599. 13,
  151600. 13
  151601. };
  151602. static static_codebook _44u8_p7_0 = {
  151603. 2, 169,
  151604. _vq_lengthlist__44u8_p7_0,
  151605. 1, -523206656, 1618345984, 4, 0,
  151606. _vq_quantlist__44u8_p7_0,
  151607. NULL,
  151608. &_vq_auxt__44u8_p7_0,
  151609. NULL,
  151610. 0
  151611. };
  151612. static long _vq_quantlist__44u8_p7_1[] = {
  151613. 5,
  151614. 4,
  151615. 6,
  151616. 3,
  151617. 7,
  151618. 2,
  151619. 8,
  151620. 1,
  151621. 9,
  151622. 0,
  151623. 10,
  151624. };
  151625. static long _vq_lengthlist__44u8_p7_1[] = {
  151626. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151627. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151628. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151629. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151630. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151631. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151632. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151633. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151634. };
  151635. static float _vq_quantthresh__44u8_p7_1[] = {
  151636. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151637. 3.5, 4.5,
  151638. };
  151639. static long _vq_quantmap__44u8_p7_1[] = {
  151640. 9, 7, 5, 3, 1, 0, 2, 4,
  151641. 6, 8, 10,
  151642. };
  151643. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151644. _vq_quantthresh__44u8_p7_1,
  151645. _vq_quantmap__44u8_p7_1,
  151646. 11,
  151647. 11
  151648. };
  151649. static static_codebook _44u8_p7_1 = {
  151650. 2, 121,
  151651. _vq_lengthlist__44u8_p7_1,
  151652. 1, -531365888, 1611661312, 4, 0,
  151653. _vq_quantlist__44u8_p7_1,
  151654. NULL,
  151655. &_vq_auxt__44u8_p7_1,
  151656. NULL,
  151657. 0
  151658. };
  151659. static long _vq_quantlist__44u8_p8_0[] = {
  151660. 7,
  151661. 6,
  151662. 8,
  151663. 5,
  151664. 9,
  151665. 4,
  151666. 10,
  151667. 3,
  151668. 11,
  151669. 2,
  151670. 12,
  151671. 1,
  151672. 13,
  151673. 0,
  151674. 14,
  151675. };
  151676. static long _vq_lengthlist__44u8_p8_0[] = {
  151677. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151678. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151679. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151680. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151681. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151682. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151683. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151684. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151685. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151686. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151687. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151688. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151689. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151690. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151691. 17,
  151692. };
  151693. static float _vq_quantthresh__44u8_p8_0[] = {
  151694. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151695. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151696. };
  151697. static long _vq_quantmap__44u8_p8_0[] = {
  151698. 13, 11, 9, 7, 5, 3, 1, 0,
  151699. 2, 4, 6, 8, 10, 12, 14,
  151700. };
  151701. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151702. _vq_quantthresh__44u8_p8_0,
  151703. _vq_quantmap__44u8_p8_0,
  151704. 15,
  151705. 15
  151706. };
  151707. static static_codebook _44u8_p8_0 = {
  151708. 2, 225,
  151709. _vq_lengthlist__44u8_p8_0,
  151710. 1, -520986624, 1620377600, 4, 0,
  151711. _vq_quantlist__44u8_p8_0,
  151712. NULL,
  151713. &_vq_auxt__44u8_p8_0,
  151714. NULL,
  151715. 0
  151716. };
  151717. static long _vq_quantlist__44u8_p8_1[] = {
  151718. 10,
  151719. 9,
  151720. 11,
  151721. 8,
  151722. 12,
  151723. 7,
  151724. 13,
  151725. 6,
  151726. 14,
  151727. 5,
  151728. 15,
  151729. 4,
  151730. 16,
  151731. 3,
  151732. 17,
  151733. 2,
  151734. 18,
  151735. 1,
  151736. 19,
  151737. 0,
  151738. 20,
  151739. };
  151740. static long _vq_lengthlist__44u8_p8_1[] = {
  151741. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151742. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151743. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151744. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151745. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151746. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151747. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151748. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151749. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151750. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151751. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151752. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151753. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151754. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151755. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151756. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151757. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151758. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151759. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151760. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151761. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151762. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151763. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151764. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151765. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151766. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151767. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151768. 10,10,10,10,10,10,10,10,10,
  151769. };
  151770. static float _vq_quantthresh__44u8_p8_1[] = {
  151771. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151772. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151773. 6.5, 7.5, 8.5, 9.5,
  151774. };
  151775. static long _vq_quantmap__44u8_p8_1[] = {
  151776. 19, 17, 15, 13, 11, 9, 7, 5,
  151777. 3, 1, 0, 2, 4, 6, 8, 10,
  151778. 12, 14, 16, 18, 20,
  151779. };
  151780. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151781. _vq_quantthresh__44u8_p8_1,
  151782. _vq_quantmap__44u8_p8_1,
  151783. 21,
  151784. 21
  151785. };
  151786. static static_codebook _44u8_p8_1 = {
  151787. 2, 441,
  151788. _vq_lengthlist__44u8_p8_1,
  151789. 1, -529268736, 1611661312, 5, 0,
  151790. _vq_quantlist__44u8_p8_1,
  151791. NULL,
  151792. &_vq_auxt__44u8_p8_1,
  151793. NULL,
  151794. 0
  151795. };
  151796. static long _vq_quantlist__44u8_p9_0[] = {
  151797. 4,
  151798. 3,
  151799. 5,
  151800. 2,
  151801. 6,
  151802. 1,
  151803. 7,
  151804. 0,
  151805. 8,
  151806. };
  151807. static long _vq_lengthlist__44u8_p9_0[] = {
  151808. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151809. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151810. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151811. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151812. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151813. 8,
  151814. };
  151815. static float _vq_quantthresh__44u8_p9_0[] = {
  151816. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151817. };
  151818. static long _vq_quantmap__44u8_p9_0[] = {
  151819. 7, 5, 3, 1, 0, 2, 4, 6,
  151820. 8,
  151821. };
  151822. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151823. _vq_quantthresh__44u8_p9_0,
  151824. _vq_quantmap__44u8_p9_0,
  151825. 9,
  151826. 9
  151827. };
  151828. static static_codebook _44u8_p9_0 = {
  151829. 2, 81,
  151830. _vq_lengthlist__44u8_p9_0,
  151831. 1, -511895552, 1631393792, 4, 0,
  151832. _vq_quantlist__44u8_p9_0,
  151833. NULL,
  151834. &_vq_auxt__44u8_p9_0,
  151835. NULL,
  151836. 0
  151837. };
  151838. static long _vq_quantlist__44u8_p9_1[] = {
  151839. 9,
  151840. 8,
  151841. 10,
  151842. 7,
  151843. 11,
  151844. 6,
  151845. 12,
  151846. 5,
  151847. 13,
  151848. 4,
  151849. 14,
  151850. 3,
  151851. 15,
  151852. 2,
  151853. 16,
  151854. 1,
  151855. 17,
  151856. 0,
  151857. 18,
  151858. };
  151859. static long _vq_lengthlist__44u8_p9_1[] = {
  151860. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151861. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151862. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151863. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151864. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151865. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151866. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151867. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151868. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151869. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151870. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151871. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151872. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151873. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151874. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151875. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151876. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151877. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151878. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151879. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151880. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151881. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151882. 16,15,16,16,16,16,16,16,16,
  151883. };
  151884. static float _vq_quantthresh__44u8_p9_1[] = {
  151885. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151886. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151887. 367.5, 416.5,
  151888. };
  151889. static long _vq_quantmap__44u8_p9_1[] = {
  151890. 17, 15, 13, 11, 9, 7, 5, 3,
  151891. 1, 0, 2, 4, 6, 8, 10, 12,
  151892. 14, 16, 18,
  151893. };
  151894. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151895. _vq_quantthresh__44u8_p9_1,
  151896. _vq_quantmap__44u8_p9_1,
  151897. 19,
  151898. 19
  151899. };
  151900. static static_codebook _44u8_p9_1 = {
  151901. 2, 361,
  151902. _vq_lengthlist__44u8_p9_1,
  151903. 1, -518287360, 1622704128, 5, 0,
  151904. _vq_quantlist__44u8_p9_1,
  151905. NULL,
  151906. &_vq_auxt__44u8_p9_1,
  151907. NULL,
  151908. 0
  151909. };
  151910. static long _vq_quantlist__44u8_p9_2[] = {
  151911. 24,
  151912. 23,
  151913. 25,
  151914. 22,
  151915. 26,
  151916. 21,
  151917. 27,
  151918. 20,
  151919. 28,
  151920. 19,
  151921. 29,
  151922. 18,
  151923. 30,
  151924. 17,
  151925. 31,
  151926. 16,
  151927. 32,
  151928. 15,
  151929. 33,
  151930. 14,
  151931. 34,
  151932. 13,
  151933. 35,
  151934. 12,
  151935. 36,
  151936. 11,
  151937. 37,
  151938. 10,
  151939. 38,
  151940. 9,
  151941. 39,
  151942. 8,
  151943. 40,
  151944. 7,
  151945. 41,
  151946. 6,
  151947. 42,
  151948. 5,
  151949. 43,
  151950. 4,
  151951. 44,
  151952. 3,
  151953. 45,
  151954. 2,
  151955. 46,
  151956. 1,
  151957. 47,
  151958. 0,
  151959. 48,
  151960. };
  151961. static long _vq_lengthlist__44u8_p9_2[] = {
  151962. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151963. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151964. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151965. 7,
  151966. };
  151967. static float _vq_quantthresh__44u8_p9_2[] = {
  151968. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151969. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151970. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151971. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151972. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151973. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151974. };
  151975. static long _vq_quantmap__44u8_p9_2[] = {
  151976. 47, 45, 43, 41, 39, 37, 35, 33,
  151977. 31, 29, 27, 25, 23, 21, 19, 17,
  151978. 15, 13, 11, 9, 7, 5, 3, 1,
  151979. 0, 2, 4, 6, 8, 10, 12, 14,
  151980. 16, 18, 20, 22, 24, 26, 28, 30,
  151981. 32, 34, 36, 38, 40, 42, 44, 46,
  151982. 48,
  151983. };
  151984. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151985. _vq_quantthresh__44u8_p9_2,
  151986. _vq_quantmap__44u8_p9_2,
  151987. 49,
  151988. 49
  151989. };
  151990. static static_codebook _44u8_p9_2 = {
  151991. 1, 49,
  151992. _vq_lengthlist__44u8_p9_2,
  151993. 1, -526909440, 1611661312, 6, 0,
  151994. _vq_quantlist__44u8_p9_2,
  151995. NULL,
  151996. &_vq_auxt__44u8_p9_2,
  151997. NULL,
  151998. 0
  151999. };
  152000. static long _huff_lengthlist__44u9__long[] = {
  152001. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  152002. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  152003. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  152004. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  152005. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  152006. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  152007. 10, 8, 8, 9,
  152008. };
  152009. static static_codebook _huff_book__44u9__long = {
  152010. 2, 100,
  152011. _huff_lengthlist__44u9__long,
  152012. 0, 0, 0, 0, 0,
  152013. NULL,
  152014. NULL,
  152015. NULL,
  152016. NULL,
  152017. 0
  152018. };
  152019. static long _huff_lengthlist__44u9__short[] = {
  152020. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  152021. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  152022. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  152023. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  152024. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  152025. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  152026. 9, 9,12,15,
  152027. };
  152028. static static_codebook _huff_book__44u9__short = {
  152029. 2, 100,
  152030. _huff_lengthlist__44u9__short,
  152031. 0, 0, 0, 0, 0,
  152032. NULL,
  152033. NULL,
  152034. NULL,
  152035. NULL,
  152036. 0
  152037. };
  152038. static long _vq_quantlist__44u9_p1_0[] = {
  152039. 1,
  152040. 0,
  152041. 2,
  152042. };
  152043. static long _vq_lengthlist__44u9_p1_0[] = {
  152044. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  152045. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  152046. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  152047. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  152048. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  152049. 10,
  152050. };
  152051. static float _vq_quantthresh__44u9_p1_0[] = {
  152052. -0.5, 0.5,
  152053. };
  152054. static long _vq_quantmap__44u9_p1_0[] = {
  152055. 1, 0, 2,
  152056. };
  152057. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  152058. _vq_quantthresh__44u9_p1_0,
  152059. _vq_quantmap__44u9_p1_0,
  152060. 3,
  152061. 3
  152062. };
  152063. static static_codebook _44u9_p1_0 = {
  152064. 4, 81,
  152065. _vq_lengthlist__44u9_p1_0,
  152066. 1, -535822336, 1611661312, 2, 0,
  152067. _vq_quantlist__44u9_p1_0,
  152068. NULL,
  152069. &_vq_auxt__44u9_p1_0,
  152070. NULL,
  152071. 0
  152072. };
  152073. static long _vq_quantlist__44u9_p2_0[] = {
  152074. 2,
  152075. 1,
  152076. 3,
  152077. 0,
  152078. 4,
  152079. };
  152080. static long _vq_lengthlist__44u9_p2_0[] = {
  152081. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  152082. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  152083. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  152084. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  152085. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  152086. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  152087. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  152088. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  152089. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  152090. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  152091. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  152092. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  152093. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  152094. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  152095. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  152096. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  152097. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  152098. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  152099. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  152100. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  152101. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  152102. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  152103. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  152104. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  152105. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152106. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152107. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152108. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152109. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152110. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152111. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152112. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152113. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152114. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152115. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152116. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152117. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152118. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152119. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152120. 14,
  152121. };
  152122. static float _vq_quantthresh__44u9_p2_0[] = {
  152123. -1.5, -0.5, 0.5, 1.5,
  152124. };
  152125. static long _vq_quantmap__44u9_p2_0[] = {
  152126. 3, 1, 0, 2, 4,
  152127. };
  152128. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152129. _vq_quantthresh__44u9_p2_0,
  152130. _vq_quantmap__44u9_p2_0,
  152131. 5,
  152132. 5
  152133. };
  152134. static static_codebook _44u9_p2_0 = {
  152135. 4, 625,
  152136. _vq_lengthlist__44u9_p2_0,
  152137. 1, -533725184, 1611661312, 3, 0,
  152138. _vq_quantlist__44u9_p2_0,
  152139. NULL,
  152140. &_vq_auxt__44u9_p2_0,
  152141. NULL,
  152142. 0
  152143. };
  152144. static long _vq_quantlist__44u9_p3_0[] = {
  152145. 4,
  152146. 3,
  152147. 5,
  152148. 2,
  152149. 6,
  152150. 1,
  152151. 7,
  152152. 0,
  152153. 8,
  152154. };
  152155. static long _vq_lengthlist__44u9_p3_0[] = {
  152156. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152157. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152158. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152159. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152160. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152161. 11,
  152162. };
  152163. static float _vq_quantthresh__44u9_p3_0[] = {
  152164. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152165. };
  152166. static long _vq_quantmap__44u9_p3_0[] = {
  152167. 7, 5, 3, 1, 0, 2, 4, 6,
  152168. 8,
  152169. };
  152170. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152171. _vq_quantthresh__44u9_p3_0,
  152172. _vq_quantmap__44u9_p3_0,
  152173. 9,
  152174. 9
  152175. };
  152176. static static_codebook _44u9_p3_0 = {
  152177. 2, 81,
  152178. _vq_lengthlist__44u9_p3_0,
  152179. 1, -531628032, 1611661312, 4, 0,
  152180. _vq_quantlist__44u9_p3_0,
  152181. NULL,
  152182. &_vq_auxt__44u9_p3_0,
  152183. NULL,
  152184. 0
  152185. };
  152186. static long _vq_quantlist__44u9_p4_0[] = {
  152187. 8,
  152188. 7,
  152189. 9,
  152190. 6,
  152191. 10,
  152192. 5,
  152193. 11,
  152194. 4,
  152195. 12,
  152196. 3,
  152197. 13,
  152198. 2,
  152199. 14,
  152200. 1,
  152201. 15,
  152202. 0,
  152203. 16,
  152204. };
  152205. static long _vq_lengthlist__44u9_p4_0[] = {
  152206. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152207. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152208. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152209. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152210. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152211. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152212. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152213. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152214. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152215. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152216. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152217. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152218. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152219. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152220. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152221. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152222. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152223. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152224. 14,
  152225. };
  152226. static float _vq_quantthresh__44u9_p4_0[] = {
  152227. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152228. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152229. };
  152230. static long _vq_quantmap__44u9_p4_0[] = {
  152231. 15, 13, 11, 9, 7, 5, 3, 1,
  152232. 0, 2, 4, 6, 8, 10, 12, 14,
  152233. 16,
  152234. };
  152235. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152236. _vq_quantthresh__44u9_p4_0,
  152237. _vq_quantmap__44u9_p4_0,
  152238. 17,
  152239. 17
  152240. };
  152241. static static_codebook _44u9_p4_0 = {
  152242. 2, 289,
  152243. _vq_lengthlist__44u9_p4_0,
  152244. 1, -529530880, 1611661312, 5, 0,
  152245. _vq_quantlist__44u9_p4_0,
  152246. NULL,
  152247. &_vq_auxt__44u9_p4_0,
  152248. NULL,
  152249. 0
  152250. };
  152251. static long _vq_quantlist__44u9_p5_0[] = {
  152252. 1,
  152253. 0,
  152254. 2,
  152255. };
  152256. static long _vq_lengthlist__44u9_p5_0[] = {
  152257. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152258. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152259. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152260. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152261. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152262. 10,
  152263. };
  152264. static float _vq_quantthresh__44u9_p5_0[] = {
  152265. -5.5, 5.5,
  152266. };
  152267. static long _vq_quantmap__44u9_p5_0[] = {
  152268. 1, 0, 2,
  152269. };
  152270. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152271. _vq_quantthresh__44u9_p5_0,
  152272. _vq_quantmap__44u9_p5_0,
  152273. 3,
  152274. 3
  152275. };
  152276. static static_codebook _44u9_p5_0 = {
  152277. 4, 81,
  152278. _vq_lengthlist__44u9_p5_0,
  152279. 1, -529137664, 1618345984, 2, 0,
  152280. _vq_quantlist__44u9_p5_0,
  152281. NULL,
  152282. &_vq_auxt__44u9_p5_0,
  152283. NULL,
  152284. 0
  152285. };
  152286. static long _vq_quantlist__44u9_p5_1[] = {
  152287. 5,
  152288. 4,
  152289. 6,
  152290. 3,
  152291. 7,
  152292. 2,
  152293. 8,
  152294. 1,
  152295. 9,
  152296. 0,
  152297. 10,
  152298. };
  152299. static long _vq_lengthlist__44u9_p5_1[] = {
  152300. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152301. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152302. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152303. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152304. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152305. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152306. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152307. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152308. };
  152309. static float _vq_quantthresh__44u9_p5_1[] = {
  152310. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152311. 3.5, 4.5,
  152312. };
  152313. static long _vq_quantmap__44u9_p5_1[] = {
  152314. 9, 7, 5, 3, 1, 0, 2, 4,
  152315. 6, 8, 10,
  152316. };
  152317. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152318. _vq_quantthresh__44u9_p5_1,
  152319. _vq_quantmap__44u9_p5_1,
  152320. 11,
  152321. 11
  152322. };
  152323. static static_codebook _44u9_p5_1 = {
  152324. 2, 121,
  152325. _vq_lengthlist__44u9_p5_1,
  152326. 1, -531365888, 1611661312, 4, 0,
  152327. _vq_quantlist__44u9_p5_1,
  152328. NULL,
  152329. &_vq_auxt__44u9_p5_1,
  152330. NULL,
  152331. 0
  152332. };
  152333. static long _vq_quantlist__44u9_p6_0[] = {
  152334. 6,
  152335. 5,
  152336. 7,
  152337. 4,
  152338. 8,
  152339. 3,
  152340. 9,
  152341. 2,
  152342. 10,
  152343. 1,
  152344. 11,
  152345. 0,
  152346. 12,
  152347. };
  152348. static long _vq_lengthlist__44u9_p6_0[] = {
  152349. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152350. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152351. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152352. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152353. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152354. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152355. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152356. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152357. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152358. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152359. 10,11,11,11,11,12,11,12,12,
  152360. };
  152361. static float _vq_quantthresh__44u9_p6_0[] = {
  152362. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152363. 12.5, 17.5, 22.5, 27.5,
  152364. };
  152365. static long _vq_quantmap__44u9_p6_0[] = {
  152366. 11, 9, 7, 5, 3, 1, 0, 2,
  152367. 4, 6, 8, 10, 12,
  152368. };
  152369. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152370. _vq_quantthresh__44u9_p6_0,
  152371. _vq_quantmap__44u9_p6_0,
  152372. 13,
  152373. 13
  152374. };
  152375. static static_codebook _44u9_p6_0 = {
  152376. 2, 169,
  152377. _vq_lengthlist__44u9_p6_0,
  152378. 1, -526516224, 1616117760, 4, 0,
  152379. _vq_quantlist__44u9_p6_0,
  152380. NULL,
  152381. &_vq_auxt__44u9_p6_0,
  152382. NULL,
  152383. 0
  152384. };
  152385. static long _vq_quantlist__44u9_p6_1[] = {
  152386. 2,
  152387. 1,
  152388. 3,
  152389. 0,
  152390. 4,
  152391. };
  152392. static long _vq_lengthlist__44u9_p6_1[] = {
  152393. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152394. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152395. };
  152396. static float _vq_quantthresh__44u9_p6_1[] = {
  152397. -1.5, -0.5, 0.5, 1.5,
  152398. };
  152399. static long _vq_quantmap__44u9_p6_1[] = {
  152400. 3, 1, 0, 2, 4,
  152401. };
  152402. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152403. _vq_quantthresh__44u9_p6_1,
  152404. _vq_quantmap__44u9_p6_1,
  152405. 5,
  152406. 5
  152407. };
  152408. static static_codebook _44u9_p6_1 = {
  152409. 2, 25,
  152410. _vq_lengthlist__44u9_p6_1,
  152411. 1, -533725184, 1611661312, 3, 0,
  152412. _vq_quantlist__44u9_p6_1,
  152413. NULL,
  152414. &_vq_auxt__44u9_p6_1,
  152415. NULL,
  152416. 0
  152417. };
  152418. static long _vq_quantlist__44u9_p7_0[] = {
  152419. 6,
  152420. 5,
  152421. 7,
  152422. 4,
  152423. 8,
  152424. 3,
  152425. 9,
  152426. 2,
  152427. 10,
  152428. 1,
  152429. 11,
  152430. 0,
  152431. 12,
  152432. };
  152433. static long _vq_lengthlist__44u9_p7_0[] = {
  152434. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152435. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152436. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152437. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152438. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152439. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152440. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152441. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152442. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152443. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152444. 12,13,13,14,14,14,15,15,15,
  152445. };
  152446. static float _vq_quantthresh__44u9_p7_0[] = {
  152447. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152448. 27.5, 38.5, 49.5, 60.5,
  152449. };
  152450. static long _vq_quantmap__44u9_p7_0[] = {
  152451. 11, 9, 7, 5, 3, 1, 0, 2,
  152452. 4, 6, 8, 10, 12,
  152453. };
  152454. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152455. _vq_quantthresh__44u9_p7_0,
  152456. _vq_quantmap__44u9_p7_0,
  152457. 13,
  152458. 13
  152459. };
  152460. static static_codebook _44u9_p7_0 = {
  152461. 2, 169,
  152462. _vq_lengthlist__44u9_p7_0,
  152463. 1, -523206656, 1618345984, 4, 0,
  152464. _vq_quantlist__44u9_p7_0,
  152465. NULL,
  152466. &_vq_auxt__44u9_p7_0,
  152467. NULL,
  152468. 0
  152469. };
  152470. static long _vq_quantlist__44u9_p7_1[] = {
  152471. 5,
  152472. 4,
  152473. 6,
  152474. 3,
  152475. 7,
  152476. 2,
  152477. 8,
  152478. 1,
  152479. 9,
  152480. 0,
  152481. 10,
  152482. };
  152483. static long _vq_lengthlist__44u9_p7_1[] = {
  152484. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152485. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152486. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152487. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152488. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152489. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152490. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152491. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152492. };
  152493. static float _vq_quantthresh__44u9_p7_1[] = {
  152494. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152495. 3.5, 4.5,
  152496. };
  152497. static long _vq_quantmap__44u9_p7_1[] = {
  152498. 9, 7, 5, 3, 1, 0, 2, 4,
  152499. 6, 8, 10,
  152500. };
  152501. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152502. _vq_quantthresh__44u9_p7_1,
  152503. _vq_quantmap__44u9_p7_1,
  152504. 11,
  152505. 11
  152506. };
  152507. static static_codebook _44u9_p7_1 = {
  152508. 2, 121,
  152509. _vq_lengthlist__44u9_p7_1,
  152510. 1, -531365888, 1611661312, 4, 0,
  152511. _vq_quantlist__44u9_p7_1,
  152512. NULL,
  152513. &_vq_auxt__44u9_p7_1,
  152514. NULL,
  152515. 0
  152516. };
  152517. static long _vq_quantlist__44u9_p8_0[] = {
  152518. 7,
  152519. 6,
  152520. 8,
  152521. 5,
  152522. 9,
  152523. 4,
  152524. 10,
  152525. 3,
  152526. 11,
  152527. 2,
  152528. 12,
  152529. 1,
  152530. 13,
  152531. 0,
  152532. 14,
  152533. };
  152534. static long _vq_lengthlist__44u9_p8_0[] = {
  152535. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152536. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152537. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152538. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152539. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152540. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152541. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152542. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152543. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152544. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152545. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152546. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152547. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152548. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152549. 15,
  152550. };
  152551. static float _vq_quantthresh__44u9_p8_0[] = {
  152552. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152553. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152554. };
  152555. static long _vq_quantmap__44u9_p8_0[] = {
  152556. 13, 11, 9, 7, 5, 3, 1, 0,
  152557. 2, 4, 6, 8, 10, 12, 14,
  152558. };
  152559. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152560. _vq_quantthresh__44u9_p8_0,
  152561. _vq_quantmap__44u9_p8_0,
  152562. 15,
  152563. 15
  152564. };
  152565. static static_codebook _44u9_p8_0 = {
  152566. 2, 225,
  152567. _vq_lengthlist__44u9_p8_0,
  152568. 1, -520986624, 1620377600, 4, 0,
  152569. _vq_quantlist__44u9_p8_0,
  152570. NULL,
  152571. &_vq_auxt__44u9_p8_0,
  152572. NULL,
  152573. 0
  152574. };
  152575. static long _vq_quantlist__44u9_p8_1[] = {
  152576. 10,
  152577. 9,
  152578. 11,
  152579. 8,
  152580. 12,
  152581. 7,
  152582. 13,
  152583. 6,
  152584. 14,
  152585. 5,
  152586. 15,
  152587. 4,
  152588. 16,
  152589. 3,
  152590. 17,
  152591. 2,
  152592. 18,
  152593. 1,
  152594. 19,
  152595. 0,
  152596. 20,
  152597. };
  152598. static long _vq_lengthlist__44u9_p8_1[] = {
  152599. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152600. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152601. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152602. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152603. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152604. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152605. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152606. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152607. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152608. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152609. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152610. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152611. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152612. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152613. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152614. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152615. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152616. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152617. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152618. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152620. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152621. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152622. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152623. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152624. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152625. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152626. 10,10,10,10,10,10,10,10,10,
  152627. };
  152628. static float _vq_quantthresh__44u9_p8_1[] = {
  152629. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152630. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152631. 6.5, 7.5, 8.5, 9.5,
  152632. };
  152633. static long _vq_quantmap__44u9_p8_1[] = {
  152634. 19, 17, 15, 13, 11, 9, 7, 5,
  152635. 3, 1, 0, 2, 4, 6, 8, 10,
  152636. 12, 14, 16, 18, 20,
  152637. };
  152638. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152639. _vq_quantthresh__44u9_p8_1,
  152640. _vq_quantmap__44u9_p8_1,
  152641. 21,
  152642. 21
  152643. };
  152644. static static_codebook _44u9_p8_1 = {
  152645. 2, 441,
  152646. _vq_lengthlist__44u9_p8_1,
  152647. 1, -529268736, 1611661312, 5, 0,
  152648. _vq_quantlist__44u9_p8_1,
  152649. NULL,
  152650. &_vq_auxt__44u9_p8_1,
  152651. NULL,
  152652. 0
  152653. };
  152654. static long _vq_quantlist__44u9_p9_0[] = {
  152655. 7,
  152656. 6,
  152657. 8,
  152658. 5,
  152659. 9,
  152660. 4,
  152661. 10,
  152662. 3,
  152663. 11,
  152664. 2,
  152665. 12,
  152666. 1,
  152667. 13,
  152668. 0,
  152669. 14,
  152670. };
  152671. static long _vq_lengthlist__44u9_p9_0[] = {
  152672. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152673. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152674. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152676. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152684. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152685. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152686. 10,
  152687. };
  152688. static float _vq_quantthresh__44u9_p9_0[] = {
  152689. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152690. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152691. };
  152692. static long _vq_quantmap__44u9_p9_0[] = {
  152693. 13, 11, 9, 7, 5, 3, 1, 0,
  152694. 2, 4, 6, 8, 10, 12, 14,
  152695. };
  152696. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152697. _vq_quantthresh__44u9_p9_0,
  152698. _vq_quantmap__44u9_p9_0,
  152699. 15,
  152700. 15
  152701. };
  152702. static static_codebook _44u9_p9_0 = {
  152703. 2, 225,
  152704. _vq_lengthlist__44u9_p9_0,
  152705. 1, -510036736, 1631393792, 4, 0,
  152706. _vq_quantlist__44u9_p9_0,
  152707. NULL,
  152708. &_vq_auxt__44u9_p9_0,
  152709. NULL,
  152710. 0
  152711. };
  152712. static long _vq_quantlist__44u9_p9_1[] = {
  152713. 9,
  152714. 8,
  152715. 10,
  152716. 7,
  152717. 11,
  152718. 6,
  152719. 12,
  152720. 5,
  152721. 13,
  152722. 4,
  152723. 14,
  152724. 3,
  152725. 15,
  152726. 2,
  152727. 16,
  152728. 1,
  152729. 17,
  152730. 0,
  152731. 18,
  152732. };
  152733. static long _vq_lengthlist__44u9_p9_1[] = {
  152734. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152735. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152736. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152737. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152738. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152739. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152740. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152741. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152742. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152743. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152744. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152745. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152746. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152747. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152748. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152749. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152750. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152751. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152752. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152753. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152754. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152755. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152756. 17,17,15,17,15,17,16,16,17,
  152757. };
  152758. static float _vq_quantthresh__44u9_p9_1[] = {
  152759. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152760. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152761. 367.5, 416.5,
  152762. };
  152763. static long _vq_quantmap__44u9_p9_1[] = {
  152764. 17, 15, 13, 11, 9, 7, 5, 3,
  152765. 1, 0, 2, 4, 6, 8, 10, 12,
  152766. 14, 16, 18,
  152767. };
  152768. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152769. _vq_quantthresh__44u9_p9_1,
  152770. _vq_quantmap__44u9_p9_1,
  152771. 19,
  152772. 19
  152773. };
  152774. static static_codebook _44u9_p9_1 = {
  152775. 2, 361,
  152776. _vq_lengthlist__44u9_p9_1,
  152777. 1, -518287360, 1622704128, 5, 0,
  152778. _vq_quantlist__44u9_p9_1,
  152779. NULL,
  152780. &_vq_auxt__44u9_p9_1,
  152781. NULL,
  152782. 0
  152783. };
  152784. static long _vq_quantlist__44u9_p9_2[] = {
  152785. 24,
  152786. 23,
  152787. 25,
  152788. 22,
  152789. 26,
  152790. 21,
  152791. 27,
  152792. 20,
  152793. 28,
  152794. 19,
  152795. 29,
  152796. 18,
  152797. 30,
  152798. 17,
  152799. 31,
  152800. 16,
  152801. 32,
  152802. 15,
  152803. 33,
  152804. 14,
  152805. 34,
  152806. 13,
  152807. 35,
  152808. 12,
  152809. 36,
  152810. 11,
  152811. 37,
  152812. 10,
  152813. 38,
  152814. 9,
  152815. 39,
  152816. 8,
  152817. 40,
  152818. 7,
  152819. 41,
  152820. 6,
  152821. 42,
  152822. 5,
  152823. 43,
  152824. 4,
  152825. 44,
  152826. 3,
  152827. 45,
  152828. 2,
  152829. 46,
  152830. 1,
  152831. 47,
  152832. 0,
  152833. 48,
  152834. };
  152835. static long _vq_lengthlist__44u9_p9_2[] = {
  152836. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152837. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152838. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152839. 7,
  152840. };
  152841. static float _vq_quantthresh__44u9_p9_2[] = {
  152842. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152843. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152844. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152845. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152846. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152847. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152848. };
  152849. static long _vq_quantmap__44u9_p9_2[] = {
  152850. 47, 45, 43, 41, 39, 37, 35, 33,
  152851. 31, 29, 27, 25, 23, 21, 19, 17,
  152852. 15, 13, 11, 9, 7, 5, 3, 1,
  152853. 0, 2, 4, 6, 8, 10, 12, 14,
  152854. 16, 18, 20, 22, 24, 26, 28, 30,
  152855. 32, 34, 36, 38, 40, 42, 44, 46,
  152856. 48,
  152857. };
  152858. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152859. _vq_quantthresh__44u9_p9_2,
  152860. _vq_quantmap__44u9_p9_2,
  152861. 49,
  152862. 49
  152863. };
  152864. static static_codebook _44u9_p9_2 = {
  152865. 1, 49,
  152866. _vq_lengthlist__44u9_p9_2,
  152867. 1, -526909440, 1611661312, 6, 0,
  152868. _vq_quantlist__44u9_p9_2,
  152869. NULL,
  152870. &_vq_auxt__44u9_p9_2,
  152871. NULL,
  152872. 0
  152873. };
  152874. static long _huff_lengthlist__44un1__long[] = {
  152875. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152876. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152877. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152878. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152879. };
  152880. static static_codebook _huff_book__44un1__long = {
  152881. 2, 64,
  152882. _huff_lengthlist__44un1__long,
  152883. 0, 0, 0, 0, 0,
  152884. NULL,
  152885. NULL,
  152886. NULL,
  152887. NULL,
  152888. 0
  152889. };
  152890. static long _vq_quantlist__44un1__p1_0[] = {
  152891. 1,
  152892. 0,
  152893. 2,
  152894. };
  152895. static long _vq_lengthlist__44un1__p1_0[] = {
  152896. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152897. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152898. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152899. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152900. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152901. 12,
  152902. };
  152903. static float _vq_quantthresh__44un1__p1_0[] = {
  152904. -0.5, 0.5,
  152905. };
  152906. static long _vq_quantmap__44un1__p1_0[] = {
  152907. 1, 0, 2,
  152908. };
  152909. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152910. _vq_quantthresh__44un1__p1_0,
  152911. _vq_quantmap__44un1__p1_0,
  152912. 3,
  152913. 3
  152914. };
  152915. static static_codebook _44un1__p1_0 = {
  152916. 4, 81,
  152917. _vq_lengthlist__44un1__p1_0,
  152918. 1, -535822336, 1611661312, 2, 0,
  152919. _vq_quantlist__44un1__p1_0,
  152920. NULL,
  152921. &_vq_auxt__44un1__p1_0,
  152922. NULL,
  152923. 0
  152924. };
  152925. static long _vq_quantlist__44un1__p2_0[] = {
  152926. 1,
  152927. 0,
  152928. 2,
  152929. };
  152930. static long _vq_lengthlist__44un1__p2_0[] = {
  152931. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152932. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152933. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152934. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152935. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152936. 8,
  152937. };
  152938. static float _vq_quantthresh__44un1__p2_0[] = {
  152939. -0.5, 0.5,
  152940. };
  152941. static long _vq_quantmap__44un1__p2_0[] = {
  152942. 1, 0, 2,
  152943. };
  152944. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152945. _vq_quantthresh__44un1__p2_0,
  152946. _vq_quantmap__44un1__p2_0,
  152947. 3,
  152948. 3
  152949. };
  152950. static static_codebook _44un1__p2_0 = {
  152951. 4, 81,
  152952. _vq_lengthlist__44un1__p2_0,
  152953. 1, -535822336, 1611661312, 2, 0,
  152954. _vq_quantlist__44un1__p2_0,
  152955. NULL,
  152956. &_vq_auxt__44un1__p2_0,
  152957. NULL,
  152958. 0
  152959. };
  152960. static long _vq_quantlist__44un1__p3_0[] = {
  152961. 2,
  152962. 1,
  152963. 3,
  152964. 0,
  152965. 4,
  152966. };
  152967. static long _vq_lengthlist__44un1__p3_0[] = {
  152968. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152969. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152970. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152971. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152972. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152973. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152974. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152975. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152976. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152977. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152978. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152979. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152980. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152981. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152982. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152983. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152984. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152985. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152986. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152987. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152988. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152989. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152990. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152991. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152992. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152993. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152994. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152995. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152996. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152997. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152998. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152999. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  153000. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  153001. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  153002. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  153003. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  153004. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  153005. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  153006. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  153007. 17,
  153008. };
  153009. static float _vq_quantthresh__44un1__p3_0[] = {
  153010. -1.5, -0.5, 0.5, 1.5,
  153011. };
  153012. static long _vq_quantmap__44un1__p3_0[] = {
  153013. 3, 1, 0, 2, 4,
  153014. };
  153015. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  153016. _vq_quantthresh__44un1__p3_0,
  153017. _vq_quantmap__44un1__p3_0,
  153018. 5,
  153019. 5
  153020. };
  153021. static static_codebook _44un1__p3_0 = {
  153022. 4, 625,
  153023. _vq_lengthlist__44un1__p3_0,
  153024. 1, -533725184, 1611661312, 3, 0,
  153025. _vq_quantlist__44un1__p3_0,
  153026. NULL,
  153027. &_vq_auxt__44un1__p3_0,
  153028. NULL,
  153029. 0
  153030. };
  153031. static long _vq_quantlist__44un1__p4_0[] = {
  153032. 2,
  153033. 1,
  153034. 3,
  153035. 0,
  153036. 4,
  153037. };
  153038. static long _vq_lengthlist__44un1__p4_0[] = {
  153039. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  153040. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  153041. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  153042. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  153043. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  153044. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  153045. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  153046. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  153047. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  153048. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  153049. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  153050. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  153051. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  153052. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  153053. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  153054. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  153055. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  153056. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  153057. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  153058. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  153059. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  153060. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  153061. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  153062. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  153063. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  153064. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  153065. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  153066. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  153067. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  153068. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  153069. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  153070. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  153071. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  153072. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  153073. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  153074. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  153075. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  153076. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  153077. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  153078. 12,
  153079. };
  153080. static float _vq_quantthresh__44un1__p4_0[] = {
  153081. -1.5, -0.5, 0.5, 1.5,
  153082. };
  153083. static long _vq_quantmap__44un1__p4_0[] = {
  153084. 3, 1, 0, 2, 4,
  153085. };
  153086. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  153087. _vq_quantthresh__44un1__p4_0,
  153088. _vq_quantmap__44un1__p4_0,
  153089. 5,
  153090. 5
  153091. };
  153092. static static_codebook _44un1__p4_0 = {
  153093. 4, 625,
  153094. _vq_lengthlist__44un1__p4_0,
  153095. 1, -533725184, 1611661312, 3, 0,
  153096. _vq_quantlist__44un1__p4_0,
  153097. NULL,
  153098. &_vq_auxt__44un1__p4_0,
  153099. NULL,
  153100. 0
  153101. };
  153102. static long _vq_quantlist__44un1__p5_0[] = {
  153103. 4,
  153104. 3,
  153105. 5,
  153106. 2,
  153107. 6,
  153108. 1,
  153109. 7,
  153110. 0,
  153111. 8,
  153112. };
  153113. static long _vq_lengthlist__44un1__p5_0[] = {
  153114. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153115. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153116. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153117. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153118. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153119. 12,
  153120. };
  153121. static float _vq_quantthresh__44un1__p5_0[] = {
  153122. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153123. };
  153124. static long _vq_quantmap__44un1__p5_0[] = {
  153125. 7, 5, 3, 1, 0, 2, 4, 6,
  153126. 8,
  153127. };
  153128. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153129. _vq_quantthresh__44un1__p5_0,
  153130. _vq_quantmap__44un1__p5_0,
  153131. 9,
  153132. 9
  153133. };
  153134. static static_codebook _44un1__p5_0 = {
  153135. 2, 81,
  153136. _vq_lengthlist__44un1__p5_0,
  153137. 1, -531628032, 1611661312, 4, 0,
  153138. _vq_quantlist__44un1__p5_0,
  153139. NULL,
  153140. &_vq_auxt__44un1__p5_0,
  153141. NULL,
  153142. 0
  153143. };
  153144. static long _vq_quantlist__44un1__p6_0[] = {
  153145. 6,
  153146. 5,
  153147. 7,
  153148. 4,
  153149. 8,
  153150. 3,
  153151. 9,
  153152. 2,
  153153. 10,
  153154. 1,
  153155. 11,
  153156. 0,
  153157. 12,
  153158. };
  153159. static long _vq_lengthlist__44un1__p6_0[] = {
  153160. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153161. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153162. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153163. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153164. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153165. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153166. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153167. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153168. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153169. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153170. 16, 0,15,18,18, 0,16, 0, 0,
  153171. };
  153172. static float _vq_quantthresh__44un1__p6_0[] = {
  153173. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153174. 12.5, 17.5, 22.5, 27.5,
  153175. };
  153176. static long _vq_quantmap__44un1__p6_0[] = {
  153177. 11, 9, 7, 5, 3, 1, 0, 2,
  153178. 4, 6, 8, 10, 12,
  153179. };
  153180. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153181. _vq_quantthresh__44un1__p6_0,
  153182. _vq_quantmap__44un1__p6_0,
  153183. 13,
  153184. 13
  153185. };
  153186. static static_codebook _44un1__p6_0 = {
  153187. 2, 169,
  153188. _vq_lengthlist__44un1__p6_0,
  153189. 1, -526516224, 1616117760, 4, 0,
  153190. _vq_quantlist__44un1__p6_0,
  153191. NULL,
  153192. &_vq_auxt__44un1__p6_0,
  153193. NULL,
  153194. 0
  153195. };
  153196. static long _vq_quantlist__44un1__p6_1[] = {
  153197. 2,
  153198. 1,
  153199. 3,
  153200. 0,
  153201. 4,
  153202. };
  153203. static long _vq_lengthlist__44un1__p6_1[] = {
  153204. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153205. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153206. };
  153207. static float _vq_quantthresh__44un1__p6_1[] = {
  153208. -1.5, -0.5, 0.5, 1.5,
  153209. };
  153210. static long _vq_quantmap__44un1__p6_1[] = {
  153211. 3, 1, 0, 2, 4,
  153212. };
  153213. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153214. _vq_quantthresh__44un1__p6_1,
  153215. _vq_quantmap__44un1__p6_1,
  153216. 5,
  153217. 5
  153218. };
  153219. static static_codebook _44un1__p6_1 = {
  153220. 2, 25,
  153221. _vq_lengthlist__44un1__p6_1,
  153222. 1, -533725184, 1611661312, 3, 0,
  153223. _vq_quantlist__44un1__p6_1,
  153224. NULL,
  153225. &_vq_auxt__44un1__p6_1,
  153226. NULL,
  153227. 0
  153228. };
  153229. static long _vq_quantlist__44un1__p7_0[] = {
  153230. 2,
  153231. 1,
  153232. 3,
  153233. 0,
  153234. 4,
  153235. };
  153236. static long _vq_lengthlist__44un1__p7_0[] = {
  153237. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153238. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153239. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153240. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153242. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153243. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153244. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153245. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153246. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153247. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153249. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153250. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153252. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153254. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153256. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153273. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153274. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153275. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153276. 10,
  153277. };
  153278. static float _vq_quantthresh__44un1__p7_0[] = {
  153279. -253.5, -84.5, 84.5, 253.5,
  153280. };
  153281. static long _vq_quantmap__44un1__p7_0[] = {
  153282. 3, 1, 0, 2, 4,
  153283. };
  153284. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153285. _vq_quantthresh__44un1__p7_0,
  153286. _vq_quantmap__44un1__p7_0,
  153287. 5,
  153288. 5
  153289. };
  153290. static static_codebook _44un1__p7_0 = {
  153291. 4, 625,
  153292. _vq_lengthlist__44un1__p7_0,
  153293. 1, -518709248, 1626677248, 3, 0,
  153294. _vq_quantlist__44un1__p7_0,
  153295. NULL,
  153296. &_vq_auxt__44un1__p7_0,
  153297. NULL,
  153298. 0
  153299. };
  153300. static long _vq_quantlist__44un1__p7_1[] = {
  153301. 6,
  153302. 5,
  153303. 7,
  153304. 4,
  153305. 8,
  153306. 3,
  153307. 9,
  153308. 2,
  153309. 10,
  153310. 1,
  153311. 11,
  153312. 0,
  153313. 12,
  153314. };
  153315. static long _vq_lengthlist__44un1__p7_1[] = {
  153316. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153317. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153318. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153319. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153320. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153321. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153322. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153323. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153324. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153325. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153326. 12,13,13,12,13,13,14,14,14,
  153327. };
  153328. static float _vq_quantthresh__44un1__p7_1[] = {
  153329. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153330. 32.5, 45.5, 58.5, 71.5,
  153331. };
  153332. static long _vq_quantmap__44un1__p7_1[] = {
  153333. 11, 9, 7, 5, 3, 1, 0, 2,
  153334. 4, 6, 8, 10, 12,
  153335. };
  153336. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153337. _vq_quantthresh__44un1__p7_1,
  153338. _vq_quantmap__44un1__p7_1,
  153339. 13,
  153340. 13
  153341. };
  153342. static static_codebook _44un1__p7_1 = {
  153343. 2, 169,
  153344. _vq_lengthlist__44un1__p7_1,
  153345. 1, -523010048, 1618608128, 4, 0,
  153346. _vq_quantlist__44un1__p7_1,
  153347. NULL,
  153348. &_vq_auxt__44un1__p7_1,
  153349. NULL,
  153350. 0
  153351. };
  153352. static long _vq_quantlist__44un1__p7_2[] = {
  153353. 6,
  153354. 5,
  153355. 7,
  153356. 4,
  153357. 8,
  153358. 3,
  153359. 9,
  153360. 2,
  153361. 10,
  153362. 1,
  153363. 11,
  153364. 0,
  153365. 12,
  153366. };
  153367. static long _vq_lengthlist__44un1__p7_2[] = {
  153368. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153369. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153370. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153371. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153372. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153373. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153374. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153375. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153376. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153377. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153378. 9, 9, 9,10,10,10,10,10,10,
  153379. };
  153380. static float _vq_quantthresh__44un1__p7_2[] = {
  153381. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153382. 2.5, 3.5, 4.5, 5.5,
  153383. };
  153384. static long _vq_quantmap__44un1__p7_2[] = {
  153385. 11, 9, 7, 5, 3, 1, 0, 2,
  153386. 4, 6, 8, 10, 12,
  153387. };
  153388. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153389. _vq_quantthresh__44un1__p7_2,
  153390. _vq_quantmap__44un1__p7_2,
  153391. 13,
  153392. 13
  153393. };
  153394. static static_codebook _44un1__p7_2 = {
  153395. 2, 169,
  153396. _vq_lengthlist__44un1__p7_2,
  153397. 1, -531103744, 1611661312, 4, 0,
  153398. _vq_quantlist__44un1__p7_2,
  153399. NULL,
  153400. &_vq_auxt__44un1__p7_2,
  153401. NULL,
  153402. 0
  153403. };
  153404. static long _huff_lengthlist__44un1__short[] = {
  153405. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153406. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153407. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153408. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153409. };
  153410. static static_codebook _huff_book__44un1__short = {
  153411. 2, 64,
  153412. _huff_lengthlist__44un1__short,
  153413. 0, 0, 0, 0, 0,
  153414. NULL,
  153415. NULL,
  153416. NULL,
  153417. NULL,
  153418. 0
  153419. };
  153420. /*** End of inlined file: res_books_uncoupled.h ***/
  153421. /***** residue backends *********************************************/
  153422. static vorbis_info_residue0 _residue_44_low_un={
  153423. 0,-1, -1, 8,-1,
  153424. {0},
  153425. {-1},
  153426. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153427. { -1, 25, -1, 45, -1, -1, -1}
  153428. };
  153429. static vorbis_info_residue0 _residue_44_mid_un={
  153430. 0,-1, -1, 10,-1,
  153431. /* 0 1 2 3 4 5 6 7 8 9 */
  153432. {0},
  153433. {-1},
  153434. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153435. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153436. };
  153437. static vorbis_info_residue0 _residue_44_hi_un={
  153438. 0,-1, -1, 10,-1,
  153439. /* 0 1 2 3 4 5 6 7 8 9 */
  153440. {0},
  153441. {-1},
  153442. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153443. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153444. };
  153445. /* mapping conventions:
  153446. only one submap (this would change for efficient 5.1 support for example)*/
  153447. /* Four psychoacoustic profiles are used, one for each blocktype */
  153448. static vorbis_info_mapping0 _map_nominal_u[2]={
  153449. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153450. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153451. };
  153452. static static_bookblock _resbook_44u_n1={
  153453. {
  153454. {0},
  153455. {0,0,&_44un1__p1_0},
  153456. {0,0,&_44un1__p2_0},
  153457. {0,0,&_44un1__p3_0},
  153458. {0,0,&_44un1__p4_0},
  153459. {0,0,&_44un1__p5_0},
  153460. {&_44un1__p6_0,&_44un1__p6_1},
  153461. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153462. }
  153463. };
  153464. static static_bookblock _resbook_44u_0={
  153465. {
  153466. {0},
  153467. {0,0,&_44u0__p1_0},
  153468. {0,0,&_44u0__p2_0},
  153469. {0,0,&_44u0__p3_0},
  153470. {0,0,&_44u0__p4_0},
  153471. {0,0,&_44u0__p5_0},
  153472. {&_44u0__p6_0,&_44u0__p6_1},
  153473. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153474. }
  153475. };
  153476. static static_bookblock _resbook_44u_1={
  153477. {
  153478. {0},
  153479. {0,0,&_44u1__p1_0},
  153480. {0,0,&_44u1__p2_0},
  153481. {0,0,&_44u1__p3_0},
  153482. {0,0,&_44u1__p4_0},
  153483. {0,0,&_44u1__p5_0},
  153484. {&_44u1__p6_0,&_44u1__p6_1},
  153485. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153486. }
  153487. };
  153488. static static_bookblock _resbook_44u_2={
  153489. {
  153490. {0},
  153491. {0,0,&_44u2__p1_0},
  153492. {0,0,&_44u2__p2_0},
  153493. {0,0,&_44u2__p3_0},
  153494. {0,0,&_44u2__p4_0},
  153495. {0,0,&_44u2__p5_0},
  153496. {&_44u2__p6_0,&_44u2__p6_1},
  153497. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153498. }
  153499. };
  153500. static static_bookblock _resbook_44u_3={
  153501. {
  153502. {0},
  153503. {0,0,&_44u3__p1_0},
  153504. {0,0,&_44u3__p2_0},
  153505. {0,0,&_44u3__p3_0},
  153506. {0,0,&_44u3__p4_0},
  153507. {0,0,&_44u3__p5_0},
  153508. {&_44u3__p6_0,&_44u3__p6_1},
  153509. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153510. }
  153511. };
  153512. static static_bookblock _resbook_44u_4={
  153513. {
  153514. {0},
  153515. {0,0,&_44u4__p1_0},
  153516. {0,0,&_44u4__p2_0},
  153517. {0,0,&_44u4__p3_0},
  153518. {0,0,&_44u4__p4_0},
  153519. {0,0,&_44u4__p5_0},
  153520. {&_44u4__p6_0,&_44u4__p6_1},
  153521. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153522. }
  153523. };
  153524. static static_bookblock _resbook_44u_5={
  153525. {
  153526. {0},
  153527. {0,0,&_44u5__p1_0},
  153528. {0,0,&_44u5__p2_0},
  153529. {0,0,&_44u5__p3_0},
  153530. {0,0,&_44u5__p4_0},
  153531. {0,0,&_44u5__p5_0},
  153532. {0,0,&_44u5__p6_0},
  153533. {&_44u5__p7_0,&_44u5__p7_1},
  153534. {&_44u5__p8_0,&_44u5__p8_1},
  153535. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153536. }
  153537. };
  153538. static static_bookblock _resbook_44u_6={
  153539. {
  153540. {0},
  153541. {0,0,&_44u6__p1_0},
  153542. {0,0,&_44u6__p2_0},
  153543. {0,0,&_44u6__p3_0},
  153544. {0,0,&_44u6__p4_0},
  153545. {0,0,&_44u6__p5_0},
  153546. {0,0,&_44u6__p6_0},
  153547. {&_44u6__p7_0,&_44u6__p7_1},
  153548. {&_44u6__p8_0,&_44u6__p8_1},
  153549. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153550. }
  153551. };
  153552. static static_bookblock _resbook_44u_7={
  153553. {
  153554. {0},
  153555. {0,0,&_44u7__p1_0},
  153556. {0,0,&_44u7__p2_0},
  153557. {0,0,&_44u7__p3_0},
  153558. {0,0,&_44u7__p4_0},
  153559. {0,0,&_44u7__p5_0},
  153560. {0,0,&_44u7__p6_0},
  153561. {&_44u7__p7_0,&_44u7__p7_1},
  153562. {&_44u7__p8_0,&_44u7__p8_1},
  153563. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153564. }
  153565. };
  153566. static static_bookblock _resbook_44u_8={
  153567. {
  153568. {0},
  153569. {0,0,&_44u8_p1_0},
  153570. {0,0,&_44u8_p2_0},
  153571. {0,0,&_44u8_p3_0},
  153572. {0,0,&_44u8_p4_0},
  153573. {&_44u8_p5_0,&_44u8_p5_1},
  153574. {&_44u8_p6_0,&_44u8_p6_1},
  153575. {&_44u8_p7_0,&_44u8_p7_1},
  153576. {&_44u8_p8_0,&_44u8_p8_1},
  153577. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153578. }
  153579. };
  153580. static static_bookblock _resbook_44u_9={
  153581. {
  153582. {0},
  153583. {0,0,&_44u9_p1_0},
  153584. {0,0,&_44u9_p2_0},
  153585. {0,0,&_44u9_p3_0},
  153586. {0,0,&_44u9_p4_0},
  153587. {&_44u9_p5_0,&_44u9_p5_1},
  153588. {&_44u9_p6_0,&_44u9_p6_1},
  153589. {&_44u9_p7_0,&_44u9_p7_1},
  153590. {&_44u9_p8_0,&_44u9_p8_1},
  153591. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153592. }
  153593. };
  153594. static vorbis_residue_template _res_44u_n1[]={
  153595. {1,0, &_residue_44_low_un,
  153596. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153597. &_resbook_44u_n1,&_resbook_44u_n1},
  153598. {1,0, &_residue_44_low_un,
  153599. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153600. &_resbook_44u_n1,&_resbook_44u_n1}
  153601. };
  153602. static vorbis_residue_template _res_44u_0[]={
  153603. {1,0, &_residue_44_low_un,
  153604. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153605. &_resbook_44u_0,&_resbook_44u_0},
  153606. {1,0, &_residue_44_low_un,
  153607. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153608. &_resbook_44u_0,&_resbook_44u_0}
  153609. };
  153610. static vorbis_residue_template _res_44u_1[]={
  153611. {1,0, &_residue_44_low_un,
  153612. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153613. &_resbook_44u_1,&_resbook_44u_1},
  153614. {1,0, &_residue_44_low_un,
  153615. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153616. &_resbook_44u_1,&_resbook_44u_1}
  153617. };
  153618. static vorbis_residue_template _res_44u_2[]={
  153619. {1,0, &_residue_44_low_un,
  153620. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153621. &_resbook_44u_2,&_resbook_44u_2},
  153622. {1,0, &_residue_44_low_un,
  153623. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153624. &_resbook_44u_2,&_resbook_44u_2}
  153625. };
  153626. static vorbis_residue_template _res_44u_3[]={
  153627. {1,0, &_residue_44_low_un,
  153628. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153629. &_resbook_44u_3,&_resbook_44u_3},
  153630. {1,0, &_residue_44_low_un,
  153631. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153632. &_resbook_44u_3,&_resbook_44u_3}
  153633. };
  153634. static vorbis_residue_template _res_44u_4[]={
  153635. {1,0, &_residue_44_low_un,
  153636. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153637. &_resbook_44u_4,&_resbook_44u_4},
  153638. {1,0, &_residue_44_low_un,
  153639. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153640. &_resbook_44u_4,&_resbook_44u_4}
  153641. };
  153642. static vorbis_residue_template _res_44u_5[]={
  153643. {1,0, &_residue_44_mid_un,
  153644. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153645. &_resbook_44u_5,&_resbook_44u_5},
  153646. {1,0, &_residue_44_mid_un,
  153647. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153648. &_resbook_44u_5,&_resbook_44u_5}
  153649. };
  153650. static vorbis_residue_template _res_44u_6[]={
  153651. {1,0, &_residue_44_mid_un,
  153652. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153653. &_resbook_44u_6,&_resbook_44u_6},
  153654. {1,0, &_residue_44_mid_un,
  153655. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153656. &_resbook_44u_6,&_resbook_44u_6}
  153657. };
  153658. static vorbis_residue_template _res_44u_7[]={
  153659. {1,0, &_residue_44_mid_un,
  153660. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153661. &_resbook_44u_7,&_resbook_44u_7},
  153662. {1,0, &_residue_44_mid_un,
  153663. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153664. &_resbook_44u_7,&_resbook_44u_7}
  153665. };
  153666. static vorbis_residue_template _res_44u_8[]={
  153667. {1,0, &_residue_44_hi_un,
  153668. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153669. &_resbook_44u_8,&_resbook_44u_8},
  153670. {1,0, &_residue_44_hi_un,
  153671. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153672. &_resbook_44u_8,&_resbook_44u_8}
  153673. };
  153674. static vorbis_residue_template _res_44u_9[]={
  153675. {1,0, &_residue_44_hi_un,
  153676. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153677. &_resbook_44u_9,&_resbook_44u_9},
  153678. {1,0, &_residue_44_hi_un,
  153679. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153680. &_resbook_44u_9,&_resbook_44u_9}
  153681. };
  153682. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153683. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153684. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153685. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153686. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153687. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153688. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153689. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153690. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153691. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153692. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153693. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153694. };
  153695. /*** End of inlined file: residue_44u.h ***/
  153696. static double rate_mapping_44_un[12]={
  153697. 32000.,48000.,60000.,70000.,80000.,86000.,
  153698. 96000.,110000.,120000.,140000.,160000.,240001.
  153699. };
  153700. ve_setup_data_template ve_setup_44_uncoupled={
  153701. 11,
  153702. rate_mapping_44_un,
  153703. quality_mapping_44,
  153704. -1,
  153705. 40000,
  153706. 50000,
  153707. blocksize_short_44,
  153708. blocksize_long_44,
  153709. _psy_tone_masteratt_44,
  153710. _psy_tone_0dB,
  153711. _psy_tone_suppress,
  153712. _vp_tonemask_adj_otherblock,
  153713. _vp_tonemask_adj_longblock,
  153714. _vp_tonemask_adj_otherblock,
  153715. _psy_noiseguards_44,
  153716. _psy_noisebias_impulse,
  153717. _psy_noisebias_padding,
  153718. _psy_noisebias_trans,
  153719. _psy_noisebias_long,
  153720. _psy_noise_suppress,
  153721. _psy_compand_44,
  153722. _psy_compand_short_mapping,
  153723. _psy_compand_long_mapping,
  153724. {_noise_start_short_44,_noise_start_long_44},
  153725. {_noise_part_short_44,_noise_part_long_44},
  153726. _noise_thresh_44,
  153727. _psy_ath_floater,
  153728. _psy_ath_abs,
  153729. _psy_lowpass_44,
  153730. _psy_global_44,
  153731. _global_mapping_44,
  153732. NULL,
  153733. _floor_books,
  153734. _floor,
  153735. _floor_short_mapping_44,
  153736. _floor_long_mapping_44,
  153737. _mapres_template_44_uncoupled
  153738. };
  153739. /*** End of inlined file: setup_44u.h ***/
  153740. /*** Start of inlined file: setup_32.h ***/
  153741. static double rate_mapping_32[12]={
  153742. 18000.,28000.,35000.,45000.,56000.,60000.,
  153743. 75000.,90000.,100000.,115000.,150000.,190000.,
  153744. };
  153745. static double rate_mapping_32_un[12]={
  153746. 30000.,42000.,52000.,64000.,72000.,78000.,
  153747. 86000.,92000.,110000.,120000.,140000.,190000.,
  153748. };
  153749. static double _psy_lowpass_32[12]={
  153750. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153751. };
  153752. ve_setup_data_template ve_setup_32_stereo={
  153753. 11,
  153754. rate_mapping_32,
  153755. quality_mapping_44,
  153756. 2,
  153757. 26000,
  153758. 40000,
  153759. blocksize_short_44,
  153760. blocksize_long_44,
  153761. _psy_tone_masteratt_44,
  153762. _psy_tone_0dB,
  153763. _psy_tone_suppress,
  153764. _vp_tonemask_adj_otherblock,
  153765. _vp_tonemask_adj_longblock,
  153766. _vp_tonemask_adj_otherblock,
  153767. _psy_noiseguards_44,
  153768. _psy_noisebias_impulse,
  153769. _psy_noisebias_padding,
  153770. _psy_noisebias_trans,
  153771. _psy_noisebias_long,
  153772. _psy_noise_suppress,
  153773. _psy_compand_44,
  153774. _psy_compand_short_mapping,
  153775. _psy_compand_long_mapping,
  153776. {_noise_start_short_44,_noise_start_long_44},
  153777. {_noise_part_short_44,_noise_part_long_44},
  153778. _noise_thresh_44,
  153779. _psy_ath_floater,
  153780. _psy_ath_abs,
  153781. _psy_lowpass_32,
  153782. _psy_global_44,
  153783. _global_mapping_44,
  153784. _psy_stereo_modes_44,
  153785. _floor_books,
  153786. _floor,
  153787. _floor_short_mapping_44,
  153788. _floor_long_mapping_44,
  153789. _mapres_template_44_stereo
  153790. };
  153791. ve_setup_data_template ve_setup_32_uncoupled={
  153792. 11,
  153793. rate_mapping_32_un,
  153794. quality_mapping_44,
  153795. -1,
  153796. 26000,
  153797. 40000,
  153798. blocksize_short_44,
  153799. blocksize_long_44,
  153800. _psy_tone_masteratt_44,
  153801. _psy_tone_0dB,
  153802. _psy_tone_suppress,
  153803. _vp_tonemask_adj_otherblock,
  153804. _vp_tonemask_adj_longblock,
  153805. _vp_tonemask_adj_otherblock,
  153806. _psy_noiseguards_44,
  153807. _psy_noisebias_impulse,
  153808. _psy_noisebias_padding,
  153809. _psy_noisebias_trans,
  153810. _psy_noisebias_long,
  153811. _psy_noise_suppress,
  153812. _psy_compand_44,
  153813. _psy_compand_short_mapping,
  153814. _psy_compand_long_mapping,
  153815. {_noise_start_short_44,_noise_start_long_44},
  153816. {_noise_part_short_44,_noise_part_long_44},
  153817. _noise_thresh_44,
  153818. _psy_ath_floater,
  153819. _psy_ath_abs,
  153820. _psy_lowpass_32,
  153821. _psy_global_44,
  153822. _global_mapping_44,
  153823. NULL,
  153824. _floor_books,
  153825. _floor,
  153826. _floor_short_mapping_44,
  153827. _floor_long_mapping_44,
  153828. _mapres_template_44_uncoupled
  153829. };
  153830. /*** End of inlined file: setup_32.h ***/
  153831. /*** Start of inlined file: setup_8.h ***/
  153832. /*** Start of inlined file: psych_8.h ***/
  153833. static att3 _psy_tone_masteratt_8[3]={
  153834. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153835. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153836. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153837. };
  153838. static vp_adjblock _vp_tonemask_adj_8[3]={
  153839. /* adjust for mode zero */
  153840. /* 63 125 250 500 1 2 4 8 16 */
  153841. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153842. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153843. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153844. };
  153845. static noise3 _psy_noisebias_8[3]={
  153846. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153847. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153848. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153849. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153850. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153851. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153852. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153853. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153854. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153855. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153856. };
  153857. /* stereo mode by base quality level */
  153858. static adj_stereo _psy_stereo_modes_8[3]={
  153859. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153860. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153861. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153862. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153863. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153864. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153865. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153866. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153867. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153868. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153869. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153870. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153871. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153872. };
  153873. static noiseguard _psy_noiseguards_8[2]={
  153874. {10,10,-1},
  153875. {10,10,-1},
  153876. };
  153877. static compandblock _psy_compand_8[2]={
  153878. {{
  153879. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153880. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153881. 12,12,13,13,14,14,15, 15, /* 23dB */
  153882. 16,16,17,17,17,18,18, 19, /* 31dB */
  153883. 19,19,20,21,22,23,24, 25, /* 39dB */
  153884. }},
  153885. {{
  153886. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153887. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153888. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153889. 9,10,11,12,13,14,15, 16, /* 31dB */
  153890. 17,18,19,20,21,22,23, 24, /* 39dB */
  153891. }},
  153892. };
  153893. static double _psy_lowpass_8[3]={3.,4.,4.};
  153894. static int _noise_start_8[2]={
  153895. 64,64,
  153896. };
  153897. static int _noise_part_8[2]={
  153898. 8,8,
  153899. };
  153900. static int _psy_ath_floater_8[3]={
  153901. -100,-100,-105,
  153902. };
  153903. static int _psy_ath_abs_8[3]={
  153904. -130,-130,-140,
  153905. };
  153906. /*** End of inlined file: psych_8.h ***/
  153907. /*** Start of inlined file: residue_8.h ***/
  153908. /***** residue backends *********************************************/
  153909. static static_bookblock _resbook_8s_0={
  153910. {
  153911. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153912. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153913. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153914. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153915. }
  153916. };
  153917. static static_bookblock _resbook_8s_1={
  153918. {
  153919. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153920. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153921. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153922. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153923. }
  153924. };
  153925. static vorbis_residue_template _res_8s_0[]={
  153926. {2,0, &_residue_44_mid,
  153927. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153928. &_resbook_8s_0,&_resbook_8s_0},
  153929. };
  153930. static vorbis_residue_template _res_8s_1[]={
  153931. {2,0, &_residue_44_mid,
  153932. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153933. &_resbook_8s_1,&_resbook_8s_1},
  153934. };
  153935. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153936. { _map_nominal, _res_8s_0 }, /* 0 */
  153937. { _map_nominal, _res_8s_1 }, /* 1 */
  153938. };
  153939. static static_bookblock _resbook_8u_0={
  153940. {
  153941. {0},
  153942. {0,0,&_8u0__p1_0},
  153943. {0,0,&_8u0__p2_0},
  153944. {0,0,&_8u0__p3_0},
  153945. {0,0,&_8u0__p4_0},
  153946. {0,0,&_8u0__p5_0},
  153947. {&_8u0__p6_0,&_8u0__p6_1},
  153948. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153949. }
  153950. };
  153951. static static_bookblock _resbook_8u_1={
  153952. {
  153953. {0},
  153954. {0,0,&_8u1__p1_0},
  153955. {0,0,&_8u1__p2_0},
  153956. {0,0,&_8u1__p3_0},
  153957. {0,0,&_8u1__p4_0},
  153958. {0,0,&_8u1__p5_0},
  153959. {0,0,&_8u1__p6_0},
  153960. {&_8u1__p7_0,&_8u1__p7_1},
  153961. {&_8u1__p8_0,&_8u1__p8_1},
  153962. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153963. }
  153964. };
  153965. static vorbis_residue_template _res_8u_0[]={
  153966. {1,0, &_residue_44_low_un,
  153967. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153968. &_resbook_8u_0,&_resbook_8u_0},
  153969. };
  153970. static vorbis_residue_template _res_8u_1[]={
  153971. {1,0, &_residue_44_mid_un,
  153972. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153973. &_resbook_8u_1,&_resbook_8u_1},
  153974. };
  153975. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153976. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153977. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153978. };
  153979. /*** End of inlined file: residue_8.h ***/
  153980. static int blocksize_8[2]={
  153981. 512,512
  153982. };
  153983. static int _floor_mapping_8[2]={
  153984. 6,6,
  153985. };
  153986. static double rate_mapping_8[3]={
  153987. 6000.,9000.,32000.,
  153988. };
  153989. static double rate_mapping_8_uncoupled[3]={
  153990. 8000.,14000.,42000.,
  153991. };
  153992. static double quality_mapping_8[3]={
  153993. -.1,.0,1.
  153994. };
  153995. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153996. static double _global_mapping_8[3]={ 1., 2., 3. };
  153997. ve_setup_data_template ve_setup_8_stereo={
  153998. 2,
  153999. rate_mapping_8,
  154000. quality_mapping_8,
  154001. 2,
  154002. 8000,
  154003. 9000,
  154004. blocksize_8,
  154005. blocksize_8,
  154006. _psy_tone_masteratt_8,
  154007. _psy_tone_0dB,
  154008. _psy_tone_suppress,
  154009. _vp_tonemask_adj_8,
  154010. NULL,
  154011. _vp_tonemask_adj_8,
  154012. _psy_noiseguards_8,
  154013. _psy_noisebias_8,
  154014. _psy_noisebias_8,
  154015. NULL,
  154016. NULL,
  154017. _psy_noise_suppress,
  154018. _psy_compand_8,
  154019. _psy_compand_8_mapping,
  154020. NULL,
  154021. {_noise_start_8,_noise_start_8},
  154022. {_noise_part_8,_noise_part_8},
  154023. _noise_thresh_5only,
  154024. _psy_ath_floater_8,
  154025. _psy_ath_abs_8,
  154026. _psy_lowpass_8,
  154027. _psy_global_44,
  154028. _global_mapping_8,
  154029. _psy_stereo_modes_8,
  154030. _floor_books,
  154031. _floor,
  154032. _floor_mapping_8,
  154033. NULL,
  154034. _mapres_template_8_stereo
  154035. };
  154036. ve_setup_data_template ve_setup_8_uncoupled={
  154037. 2,
  154038. rate_mapping_8_uncoupled,
  154039. quality_mapping_8,
  154040. -1,
  154041. 8000,
  154042. 9000,
  154043. blocksize_8,
  154044. blocksize_8,
  154045. _psy_tone_masteratt_8,
  154046. _psy_tone_0dB,
  154047. _psy_tone_suppress,
  154048. _vp_tonemask_adj_8,
  154049. NULL,
  154050. _vp_tonemask_adj_8,
  154051. _psy_noiseguards_8,
  154052. _psy_noisebias_8,
  154053. _psy_noisebias_8,
  154054. NULL,
  154055. NULL,
  154056. _psy_noise_suppress,
  154057. _psy_compand_8,
  154058. _psy_compand_8_mapping,
  154059. NULL,
  154060. {_noise_start_8,_noise_start_8},
  154061. {_noise_part_8,_noise_part_8},
  154062. _noise_thresh_5only,
  154063. _psy_ath_floater_8,
  154064. _psy_ath_abs_8,
  154065. _psy_lowpass_8,
  154066. _psy_global_44,
  154067. _global_mapping_8,
  154068. _psy_stereo_modes_8,
  154069. _floor_books,
  154070. _floor,
  154071. _floor_mapping_8,
  154072. NULL,
  154073. _mapres_template_8_uncoupled
  154074. };
  154075. /*** End of inlined file: setup_8.h ***/
  154076. /*** Start of inlined file: setup_11.h ***/
  154077. /*** Start of inlined file: psych_11.h ***/
  154078. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  154079. static att3 _psy_tone_masteratt_11[3]={
  154080. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154081. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154082. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154083. };
  154084. static vp_adjblock _vp_tonemask_adj_11[3]={
  154085. /* adjust for mode zero */
  154086. /* 63 125 250 500 1 2 4 8 16 */
  154087. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  154088. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  154089. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  154090. };
  154091. static noise3 _psy_noisebias_11[3]={
  154092. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154093. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154094. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  154095. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154096. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154097. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154098. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154099. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154100. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154101. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154102. };
  154103. static double _noise_thresh_11[3]={ .3,.5,.5 };
  154104. /*** End of inlined file: psych_11.h ***/
  154105. static int blocksize_11[2]={
  154106. 512,512
  154107. };
  154108. static int _floor_mapping_11[2]={
  154109. 6,6,
  154110. };
  154111. static double rate_mapping_11[3]={
  154112. 8000.,13000.,44000.,
  154113. };
  154114. static double rate_mapping_11_uncoupled[3]={
  154115. 12000.,20000.,50000.,
  154116. };
  154117. static double quality_mapping_11[3]={
  154118. -.1,.0,1.
  154119. };
  154120. ve_setup_data_template ve_setup_11_stereo={
  154121. 2,
  154122. rate_mapping_11,
  154123. quality_mapping_11,
  154124. 2,
  154125. 9000,
  154126. 15000,
  154127. blocksize_11,
  154128. blocksize_11,
  154129. _psy_tone_masteratt_11,
  154130. _psy_tone_0dB,
  154131. _psy_tone_suppress,
  154132. _vp_tonemask_adj_11,
  154133. NULL,
  154134. _vp_tonemask_adj_11,
  154135. _psy_noiseguards_8,
  154136. _psy_noisebias_11,
  154137. _psy_noisebias_11,
  154138. NULL,
  154139. NULL,
  154140. _psy_noise_suppress,
  154141. _psy_compand_8,
  154142. _psy_compand_8_mapping,
  154143. NULL,
  154144. {_noise_start_8,_noise_start_8},
  154145. {_noise_part_8,_noise_part_8},
  154146. _noise_thresh_11,
  154147. _psy_ath_floater_8,
  154148. _psy_ath_abs_8,
  154149. _psy_lowpass_11,
  154150. _psy_global_44,
  154151. _global_mapping_8,
  154152. _psy_stereo_modes_8,
  154153. _floor_books,
  154154. _floor,
  154155. _floor_mapping_11,
  154156. NULL,
  154157. _mapres_template_8_stereo
  154158. };
  154159. ve_setup_data_template ve_setup_11_uncoupled={
  154160. 2,
  154161. rate_mapping_11_uncoupled,
  154162. quality_mapping_11,
  154163. -1,
  154164. 9000,
  154165. 15000,
  154166. blocksize_11,
  154167. blocksize_11,
  154168. _psy_tone_masteratt_11,
  154169. _psy_tone_0dB,
  154170. _psy_tone_suppress,
  154171. _vp_tonemask_adj_11,
  154172. NULL,
  154173. _vp_tonemask_adj_11,
  154174. _psy_noiseguards_8,
  154175. _psy_noisebias_11,
  154176. _psy_noisebias_11,
  154177. NULL,
  154178. NULL,
  154179. _psy_noise_suppress,
  154180. _psy_compand_8,
  154181. _psy_compand_8_mapping,
  154182. NULL,
  154183. {_noise_start_8,_noise_start_8},
  154184. {_noise_part_8,_noise_part_8},
  154185. _noise_thresh_11,
  154186. _psy_ath_floater_8,
  154187. _psy_ath_abs_8,
  154188. _psy_lowpass_11,
  154189. _psy_global_44,
  154190. _global_mapping_8,
  154191. _psy_stereo_modes_8,
  154192. _floor_books,
  154193. _floor,
  154194. _floor_mapping_11,
  154195. NULL,
  154196. _mapres_template_8_uncoupled
  154197. };
  154198. /*** End of inlined file: setup_11.h ***/
  154199. /*** Start of inlined file: setup_16.h ***/
  154200. /*** Start of inlined file: psych_16.h ***/
  154201. /* stereo mode by base quality level */
  154202. static adj_stereo _psy_stereo_modes_16[4]={
  154203. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154204. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154205. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154206. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154207. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154208. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154209. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154210. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154211. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154212. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154213. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154214. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154215. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154216. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154217. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154218. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154219. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154220. };
  154221. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154222. static att3 _psy_tone_masteratt_16[4]={
  154223. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154224. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154225. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154226. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154227. };
  154228. static vp_adjblock _vp_tonemask_adj_16[4]={
  154229. /* adjust for mode zero */
  154230. /* 63 125 250 500 1 2 4 8 16 */
  154231. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154232. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154233. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154234. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154235. };
  154236. static noise3 _psy_noisebias_16_short[4]={
  154237. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154238. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154239. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154240. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154241. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154242. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154243. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154244. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154245. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154246. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154247. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154248. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154249. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154250. };
  154251. static noise3 _psy_noisebias_16_impulse[4]={
  154252. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154253. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154254. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154255. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154256. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154257. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154258. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154259. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154260. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154261. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154262. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154263. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154264. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154265. };
  154266. static noise3 _psy_noisebias_16[4]={
  154267. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154268. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154269. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154270. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154271. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154272. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154273. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154274. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154275. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154276. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154277. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154278. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154279. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154280. };
  154281. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154282. static int _noise_start_16[3]={ 256,256,9999 };
  154283. static int _noise_part_16[4]={ 8,8,8,8 };
  154284. static int _psy_ath_floater_16[4]={
  154285. -100,-100,-100,-105,
  154286. };
  154287. static int _psy_ath_abs_16[4]={
  154288. -130,-130,-130,-140,
  154289. };
  154290. /*** End of inlined file: psych_16.h ***/
  154291. /*** Start of inlined file: residue_16.h ***/
  154292. /***** residue backends *********************************************/
  154293. static static_bookblock _resbook_16s_0={
  154294. {
  154295. {0},
  154296. {0,0,&_16c0_s_p1_0},
  154297. {0,0,&_16c0_s_p2_0},
  154298. {0,0,&_16c0_s_p3_0},
  154299. {0,0,&_16c0_s_p4_0},
  154300. {0,0,&_16c0_s_p5_0},
  154301. {0,0,&_16c0_s_p6_0},
  154302. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154303. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154304. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154305. }
  154306. };
  154307. static static_bookblock _resbook_16s_1={
  154308. {
  154309. {0},
  154310. {0,0,&_16c1_s_p1_0},
  154311. {0,0,&_16c1_s_p2_0},
  154312. {0,0,&_16c1_s_p3_0},
  154313. {0,0,&_16c1_s_p4_0},
  154314. {0,0,&_16c1_s_p5_0},
  154315. {0,0,&_16c1_s_p6_0},
  154316. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154317. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154318. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154319. }
  154320. };
  154321. static static_bookblock _resbook_16s_2={
  154322. {
  154323. {0},
  154324. {0,0,&_16c2_s_p1_0},
  154325. {0,0,&_16c2_s_p2_0},
  154326. {0,0,&_16c2_s_p3_0},
  154327. {0,0,&_16c2_s_p4_0},
  154328. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154329. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154330. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154331. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154332. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154333. }
  154334. };
  154335. static vorbis_residue_template _res_16s_0[]={
  154336. {2,0, &_residue_44_mid,
  154337. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154338. &_resbook_16s_0,&_resbook_16s_0},
  154339. };
  154340. static vorbis_residue_template _res_16s_1[]={
  154341. {2,0, &_residue_44_mid,
  154342. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154343. &_resbook_16s_1,&_resbook_16s_1},
  154344. {2,0, &_residue_44_mid,
  154345. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154346. &_resbook_16s_1,&_resbook_16s_1}
  154347. };
  154348. static vorbis_residue_template _res_16s_2[]={
  154349. {2,0, &_residue_44_high,
  154350. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154351. &_resbook_16s_2,&_resbook_16s_2},
  154352. {2,0, &_residue_44_high,
  154353. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154354. &_resbook_16s_2,&_resbook_16s_2}
  154355. };
  154356. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154357. { _map_nominal, _res_16s_0 }, /* 0 */
  154358. { _map_nominal, _res_16s_1 }, /* 1 */
  154359. { _map_nominal, _res_16s_2 }, /* 2 */
  154360. };
  154361. static static_bookblock _resbook_16u_0={
  154362. {
  154363. {0},
  154364. {0,0,&_16u0__p1_0},
  154365. {0,0,&_16u0__p2_0},
  154366. {0,0,&_16u0__p3_0},
  154367. {0,0,&_16u0__p4_0},
  154368. {0,0,&_16u0__p5_0},
  154369. {&_16u0__p6_0,&_16u0__p6_1},
  154370. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154371. }
  154372. };
  154373. static static_bookblock _resbook_16u_1={
  154374. {
  154375. {0},
  154376. {0,0,&_16u1__p1_0},
  154377. {0,0,&_16u1__p2_0},
  154378. {0,0,&_16u1__p3_0},
  154379. {0,0,&_16u1__p4_0},
  154380. {0,0,&_16u1__p5_0},
  154381. {0,0,&_16u1__p6_0},
  154382. {&_16u1__p7_0,&_16u1__p7_1},
  154383. {&_16u1__p8_0,&_16u1__p8_1},
  154384. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154385. }
  154386. };
  154387. static static_bookblock _resbook_16u_2={
  154388. {
  154389. {0},
  154390. {0,0,&_16u2_p1_0},
  154391. {0,0,&_16u2_p2_0},
  154392. {0,0,&_16u2_p3_0},
  154393. {0,0,&_16u2_p4_0},
  154394. {&_16u2_p5_0,&_16u2_p5_1},
  154395. {&_16u2_p6_0,&_16u2_p6_1},
  154396. {&_16u2_p7_0,&_16u2_p7_1},
  154397. {&_16u2_p8_0,&_16u2_p8_1},
  154398. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154399. }
  154400. };
  154401. static vorbis_residue_template _res_16u_0[]={
  154402. {1,0, &_residue_44_low_un,
  154403. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154404. &_resbook_16u_0,&_resbook_16u_0},
  154405. };
  154406. static vorbis_residue_template _res_16u_1[]={
  154407. {1,0, &_residue_44_mid_un,
  154408. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154409. &_resbook_16u_1,&_resbook_16u_1},
  154410. {1,0, &_residue_44_mid_un,
  154411. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154412. &_resbook_16u_1,&_resbook_16u_1}
  154413. };
  154414. static vorbis_residue_template _res_16u_2[]={
  154415. {1,0, &_residue_44_hi_un,
  154416. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154417. &_resbook_16u_2,&_resbook_16u_2},
  154418. {1,0, &_residue_44_hi_un,
  154419. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154420. &_resbook_16u_2,&_resbook_16u_2}
  154421. };
  154422. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154423. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154424. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154425. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154426. };
  154427. /*** End of inlined file: residue_16.h ***/
  154428. static int blocksize_16_short[3]={
  154429. 1024,512,512
  154430. };
  154431. static int blocksize_16_long[3]={
  154432. 1024,1024,1024
  154433. };
  154434. static int _floor_mapping_16_short[3]={
  154435. 9,3,3
  154436. };
  154437. static int _floor_mapping_16[3]={
  154438. 9,9,9
  154439. };
  154440. static double rate_mapping_16[4]={
  154441. 12000.,20000.,44000.,86000.
  154442. };
  154443. static double rate_mapping_16_uncoupled[4]={
  154444. 16000.,28000.,64000.,100000.
  154445. };
  154446. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154447. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154448. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154449. ve_setup_data_template ve_setup_16_stereo={
  154450. 3,
  154451. rate_mapping_16,
  154452. quality_mapping_16,
  154453. 2,
  154454. 15000,
  154455. 19000,
  154456. blocksize_16_short,
  154457. blocksize_16_long,
  154458. _psy_tone_masteratt_16,
  154459. _psy_tone_0dB,
  154460. _psy_tone_suppress,
  154461. _vp_tonemask_adj_16,
  154462. _vp_tonemask_adj_16,
  154463. _vp_tonemask_adj_16,
  154464. _psy_noiseguards_8,
  154465. _psy_noisebias_16_impulse,
  154466. _psy_noisebias_16_short,
  154467. _psy_noisebias_16_short,
  154468. _psy_noisebias_16,
  154469. _psy_noise_suppress,
  154470. _psy_compand_8,
  154471. _psy_compand_16_mapping,
  154472. _psy_compand_16_mapping,
  154473. {_noise_start_16,_noise_start_16},
  154474. { _noise_part_16, _noise_part_16},
  154475. _noise_thresh_16,
  154476. _psy_ath_floater_16,
  154477. _psy_ath_abs_16,
  154478. _psy_lowpass_16,
  154479. _psy_global_44,
  154480. _global_mapping_16,
  154481. _psy_stereo_modes_16,
  154482. _floor_books,
  154483. _floor,
  154484. _floor_mapping_16_short,
  154485. _floor_mapping_16,
  154486. _mapres_template_16_stereo
  154487. };
  154488. ve_setup_data_template ve_setup_16_uncoupled={
  154489. 3,
  154490. rate_mapping_16_uncoupled,
  154491. quality_mapping_16,
  154492. -1,
  154493. 15000,
  154494. 19000,
  154495. blocksize_16_short,
  154496. blocksize_16_long,
  154497. _psy_tone_masteratt_16,
  154498. _psy_tone_0dB,
  154499. _psy_tone_suppress,
  154500. _vp_tonemask_adj_16,
  154501. _vp_tonemask_adj_16,
  154502. _vp_tonemask_adj_16,
  154503. _psy_noiseguards_8,
  154504. _psy_noisebias_16_impulse,
  154505. _psy_noisebias_16_short,
  154506. _psy_noisebias_16_short,
  154507. _psy_noisebias_16,
  154508. _psy_noise_suppress,
  154509. _psy_compand_8,
  154510. _psy_compand_16_mapping,
  154511. _psy_compand_16_mapping,
  154512. {_noise_start_16,_noise_start_16},
  154513. { _noise_part_16, _noise_part_16},
  154514. _noise_thresh_16,
  154515. _psy_ath_floater_16,
  154516. _psy_ath_abs_16,
  154517. _psy_lowpass_16,
  154518. _psy_global_44,
  154519. _global_mapping_16,
  154520. _psy_stereo_modes_16,
  154521. _floor_books,
  154522. _floor,
  154523. _floor_mapping_16_short,
  154524. _floor_mapping_16,
  154525. _mapres_template_16_uncoupled
  154526. };
  154527. /*** End of inlined file: setup_16.h ***/
  154528. /*** Start of inlined file: setup_22.h ***/
  154529. static double rate_mapping_22[4]={
  154530. 15000.,20000.,44000.,86000.
  154531. };
  154532. static double rate_mapping_22_uncoupled[4]={
  154533. 16000.,28000.,50000.,90000.
  154534. };
  154535. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154536. ve_setup_data_template ve_setup_22_stereo={
  154537. 3,
  154538. rate_mapping_22,
  154539. quality_mapping_16,
  154540. 2,
  154541. 19000,
  154542. 26000,
  154543. blocksize_16_short,
  154544. blocksize_16_long,
  154545. _psy_tone_masteratt_16,
  154546. _psy_tone_0dB,
  154547. _psy_tone_suppress,
  154548. _vp_tonemask_adj_16,
  154549. _vp_tonemask_adj_16,
  154550. _vp_tonemask_adj_16,
  154551. _psy_noiseguards_8,
  154552. _psy_noisebias_16_impulse,
  154553. _psy_noisebias_16_short,
  154554. _psy_noisebias_16_short,
  154555. _psy_noisebias_16,
  154556. _psy_noise_suppress,
  154557. _psy_compand_8,
  154558. _psy_compand_8_mapping,
  154559. _psy_compand_8_mapping,
  154560. {_noise_start_16,_noise_start_16},
  154561. { _noise_part_16, _noise_part_16},
  154562. _noise_thresh_16,
  154563. _psy_ath_floater_16,
  154564. _psy_ath_abs_16,
  154565. _psy_lowpass_22,
  154566. _psy_global_44,
  154567. _global_mapping_16,
  154568. _psy_stereo_modes_16,
  154569. _floor_books,
  154570. _floor,
  154571. _floor_mapping_16_short,
  154572. _floor_mapping_16,
  154573. _mapres_template_16_stereo
  154574. };
  154575. ve_setup_data_template ve_setup_22_uncoupled={
  154576. 3,
  154577. rate_mapping_22_uncoupled,
  154578. quality_mapping_16,
  154579. -1,
  154580. 19000,
  154581. 26000,
  154582. blocksize_16_short,
  154583. blocksize_16_long,
  154584. _psy_tone_masteratt_16,
  154585. _psy_tone_0dB,
  154586. _psy_tone_suppress,
  154587. _vp_tonemask_adj_16,
  154588. _vp_tonemask_adj_16,
  154589. _vp_tonemask_adj_16,
  154590. _psy_noiseguards_8,
  154591. _psy_noisebias_16_impulse,
  154592. _psy_noisebias_16_short,
  154593. _psy_noisebias_16_short,
  154594. _psy_noisebias_16,
  154595. _psy_noise_suppress,
  154596. _psy_compand_8,
  154597. _psy_compand_8_mapping,
  154598. _psy_compand_8_mapping,
  154599. {_noise_start_16,_noise_start_16},
  154600. { _noise_part_16, _noise_part_16},
  154601. _noise_thresh_16,
  154602. _psy_ath_floater_16,
  154603. _psy_ath_abs_16,
  154604. _psy_lowpass_22,
  154605. _psy_global_44,
  154606. _global_mapping_16,
  154607. _psy_stereo_modes_16,
  154608. _floor_books,
  154609. _floor,
  154610. _floor_mapping_16_short,
  154611. _floor_mapping_16,
  154612. _mapres_template_16_uncoupled
  154613. };
  154614. /*** End of inlined file: setup_22.h ***/
  154615. /*** Start of inlined file: setup_X.h ***/
  154616. static double rate_mapping_X[12]={
  154617. -1.,-1.,-1.,-1.,-1.,-1.,
  154618. -1.,-1.,-1.,-1.,-1.,-1.
  154619. };
  154620. ve_setup_data_template ve_setup_X_stereo={
  154621. 11,
  154622. rate_mapping_X,
  154623. quality_mapping_44,
  154624. 2,
  154625. 50000,
  154626. 200000,
  154627. blocksize_short_44,
  154628. blocksize_long_44,
  154629. _psy_tone_masteratt_44,
  154630. _psy_tone_0dB,
  154631. _psy_tone_suppress,
  154632. _vp_tonemask_adj_otherblock,
  154633. _vp_tonemask_adj_longblock,
  154634. _vp_tonemask_adj_otherblock,
  154635. _psy_noiseguards_44,
  154636. _psy_noisebias_impulse,
  154637. _psy_noisebias_padding,
  154638. _psy_noisebias_trans,
  154639. _psy_noisebias_long,
  154640. _psy_noise_suppress,
  154641. _psy_compand_44,
  154642. _psy_compand_short_mapping,
  154643. _psy_compand_long_mapping,
  154644. {_noise_start_short_44,_noise_start_long_44},
  154645. {_noise_part_short_44,_noise_part_long_44},
  154646. _noise_thresh_44,
  154647. _psy_ath_floater,
  154648. _psy_ath_abs,
  154649. _psy_lowpass_44,
  154650. _psy_global_44,
  154651. _global_mapping_44,
  154652. _psy_stereo_modes_44,
  154653. _floor_books,
  154654. _floor,
  154655. _floor_short_mapping_44,
  154656. _floor_long_mapping_44,
  154657. _mapres_template_44_stereo
  154658. };
  154659. ve_setup_data_template ve_setup_X_uncoupled={
  154660. 11,
  154661. rate_mapping_X,
  154662. quality_mapping_44,
  154663. -1,
  154664. 50000,
  154665. 200000,
  154666. blocksize_short_44,
  154667. blocksize_long_44,
  154668. _psy_tone_masteratt_44,
  154669. _psy_tone_0dB,
  154670. _psy_tone_suppress,
  154671. _vp_tonemask_adj_otherblock,
  154672. _vp_tonemask_adj_longblock,
  154673. _vp_tonemask_adj_otherblock,
  154674. _psy_noiseguards_44,
  154675. _psy_noisebias_impulse,
  154676. _psy_noisebias_padding,
  154677. _psy_noisebias_trans,
  154678. _psy_noisebias_long,
  154679. _psy_noise_suppress,
  154680. _psy_compand_44,
  154681. _psy_compand_short_mapping,
  154682. _psy_compand_long_mapping,
  154683. {_noise_start_short_44,_noise_start_long_44},
  154684. {_noise_part_short_44,_noise_part_long_44},
  154685. _noise_thresh_44,
  154686. _psy_ath_floater,
  154687. _psy_ath_abs,
  154688. _psy_lowpass_44,
  154689. _psy_global_44,
  154690. _global_mapping_44,
  154691. NULL,
  154692. _floor_books,
  154693. _floor,
  154694. _floor_short_mapping_44,
  154695. _floor_long_mapping_44,
  154696. _mapres_template_44_uncoupled
  154697. };
  154698. ve_setup_data_template ve_setup_XX_stereo={
  154699. 2,
  154700. rate_mapping_X,
  154701. quality_mapping_8,
  154702. 2,
  154703. 0,
  154704. 8000,
  154705. blocksize_8,
  154706. blocksize_8,
  154707. _psy_tone_masteratt_8,
  154708. _psy_tone_0dB,
  154709. _psy_tone_suppress,
  154710. _vp_tonemask_adj_8,
  154711. NULL,
  154712. _vp_tonemask_adj_8,
  154713. _psy_noiseguards_8,
  154714. _psy_noisebias_8,
  154715. _psy_noisebias_8,
  154716. NULL,
  154717. NULL,
  154718. _psy_noise_suppress,
  154719. _psy_compand_8,
  154720. _psy_compand_8_mapping,
  154721. NULL,
  154722. {_noise_start_8,_noise_start_8},
  154723. {_noise_part_8,_noise_part_8},
  154724. _noise_thresh_5only,
  154725. _psy_ath_floater_8,
  154726. _psy_ath_abs_8,
  154727. _psy_lowpass_8,
  154728. _psy_global_44,
  154729. _global_mapping_8,
  154730. _psy_stereo_modes_8,
  154731. _floor_books,
  154732. _floor,
  154733. _floor_mapping_8,
  154734. NULL,
  154735. _mapres_template_8_stereo
  154736. };
  154737. ve_setup_data_template ve_setup_XX_uncoupled={
  154738. 2,
  154739. rate_mapping_X,
  154740. quality_mapping_8,
  154741. -1,
  154742. 0,
  154743. 8000,
  154744. blocksize_8,
  154745. blocksize_8,
  154746. _psy_tone_masteratt_8,
  154747. _psy_tone_0dB,
  154748. _psy_tone_suppress,
  154749. _vp_tonemask_adj_8,
  154750. NULL,
  154751. _vp_tonemask_adj_8,
  154752. _psy_noiseguards_8,
  154753. _psy_noisebias_8,
  154754. _psy_noisebias_8,
  154755. NULL,
  154756. NULL,
  154757. _psy_noise_suppress,
  154758. _psy_compand_8,
  154759. _psy_compand_8_mapping,
  154760. NULL,
  154761. {_noise_start_8,_noise_start_8},
  154762. {_noise_part_8,_noise_part_8},
  154763. _noise_thresh_5only,
  154764. _psy_ath_floater_8,
  154765. _psy_ath_abs_8,
  154766. _psy_lowpass_8,
  154767. _psy_global_44,
  154768. _global_mapping_8,
  154769. _psy_stereo_modes_8,
  154770. _floor_books,
  154771. _floor,
  154772. _floor_mapping_8,
  154773. NULL,
  154774. _mapres_template_8_uncoupled
  154775. };
  154776. /*** End of inlined file: setup_X.h ***/
  154777. static ve_setup_data_template *setup_list[]={
  154778. &ve_setup_44_stereo,
  154779. &ve_setup_44_uncoupled,
  154780. &ve_setup_32_stereo,
  154781. &ve_setup_32_uncoupled,
  154782. &ve_setup_22_stereo,
  154783. &ve_setup_22_uncoupled,
  154784. &ve_setup_16_stereo,
  154785. &ve_setup_16_uncoupled,
  154786. &ve_setup_11_stereo,
  154787. &ve_setup_11_uncoupled,
  154788. &ve_setup_8_stereo,
  154789. &ve_setup_8_uncoupled,
  154790. &ve_setup_X_stereo,
  154791. &ve_setup_X_uncoupled,
  154792. &ve_setup_XX_stereo,
  154793. &ve_setup_XX_uncoupled,
  154794. 0
  154795. };
  154796. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154797. if(vi && vi->codec_setup){
  154798. vi->version=0;
  154799. vi->channels=ch;
  154800. vi->rate=rate;
  154801. return(0);
  154802. }
  154803. return(OV_EINVAL);
  154804. }
  154805. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154806. static_codebook ***books,
  154807. vorbis_info_floor1 *in,
  154808. int *x){
  154809. int i,k,is=s;
  154810. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154811. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154812. memcpy(f,in+x[is],sizeof(*f));
  154813. /* fill in the lowpass field, even if it's temporary */
  154814. f->n=ci->blocksizes[block]>>1;
  154815. /* books */
  154816. {
  154817. int partitions=f->partitions;
  154818. int maxclass=-1;
  154819. int maxbook=-1;
  154820. for(i=0;i<partitions;i++)
  154821. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154822. for(i=0;i<=maxclass;i++){
  154823. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154824. f->class_book[i]+=ci->books;
  154825. for(k=0;k<(1<<f->class_subs[i]);k++){
  154826. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154827. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154828. }
  154829. }
  154830. for(i=0;i<=maxbook;i++)
  154831. ci->book_param[ci->books++]=books[x[is]][i];
  154832. }
  154833. /* for now, we're only using floor 1 */
  154834. ci->floor_type[ci->floors]=1;
  154835. ci->floor_param[ci->floors]=f;
  154836. ci->floors++;
  154837. return;
  154838. }
  154839. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154840. vorbis_info_psy_global *in,
  154841. double *x){
  154842. int i,is=s;
  154843. double ds=s-is;
  154844. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154845. vorbis_info_psy_global *g=&ci->psy_g_param;
  154846. memcpy(g,in+(int)x[is],sizeof(*g));
  154847. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154848. is=(int)ds;
  154849. ds-=is;
  154850. if(ds==0 && is>0){
  154851. is--;
  154852. ds=1.;
  154853. }
  154854. /* interpolate the trigger threshholds */
  154855. for(i=0;i<4;i++){
  154856. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154857. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154858. }
  154859. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154860. return;
  154861. }
  154862. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154863. highlevel_encode_setup *hi,
  154864. adj_stereo *p){
  154865. float s=hi->stereo_point_setting;
  154866. int i,is=s;
  154867. double ds=s-is;
  154868. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154869. vorbis_info_psy_global *g=&ci->psy_g_param;
  154870. if(p){
  154871. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154872. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154873. if(hi->managed){
  154874. /* interpolate the kHz threshholds */
  154875. for(i=0;i<PACKETBLOBS;i++){
  154876. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154877. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154878. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154879. g->coupling_pkHz[i]=kHz;
  154880. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154881. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154882. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154883. }
  154884. }else{
  154885. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154886. for(i=0;i<PACKETBLOBS;i++){
  154887. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154888. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154889. g->coupling_pkHz[i]=kHz;
  154890. }
  154891. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154892. for(i=0;i<PACKETBLOBS;i++){
  154893. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154894. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154895. }
  154896. }
  154897. }else{
  154898. for(i=0;i<PACKETBLOBS;i++){
  154899. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154900. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154901. }
  154902. }
  154903. return;
  154904. }
  154905. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154906. int *nn_start,
  154907. int *nn_partition,
  154908. double *nn_thresh,
  154909. int block){
  154910. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154911. vorbis_info_psy *p=ci->psy_param[block];
  154912. highlevel_encode_setup *hi=&ci->hi;
  154913. int is=s;
  154914. if(block>=ci->psys)
  154915. ci->psys=block+1;
  154916. if(!p){
  154917. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154918. ci->psy_param[block]=p;
  154919. }
  154920. memcpy(p,&_psy_info_template,sizeof(*p));
  154921. p->blockflag=block>>1;
  154922. if(hi->noise_normalize_p){
  154923. p->normal_channel_p=1;
  154924. p->normal_point_p=1;
  154925. p->normal_start=nn_start[is];
  154926. p->normal_partition=nn_partition[is];
  154927. p->normal_thresh=nn_thresh[is];
  154928. }
  154929. return;
  154930. }
  154931. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154932. att3 *att,
  154933. int *max,
  154934. vp_adjblock *in){
  154935. int i,is=s;
  154936. double ds=s-is;
  154937. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154938. vorbis_info_psy *p=ci->psy_param[block];
  154939. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154940. filling the values in here */
  154941. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154942. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154943. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154944. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154945. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154946. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154947. for(i=0;i<P_BANDS;i++)
  154948. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154949. return;
  154950. }
  154951. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154952. compandblock *in, double *x){
  154953. int i,is=s;
  154954. double ds=s-is;
  154955. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154956. vorbis_info_psy *p=ci->psy_param[block];
  154957. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154958. is=(int)ds;
  154959. ds-=is;
  154960. if(ds==0 && is>0){
  154961. is--;
  154962. ds=1.;
  154963. }
  154964. /* interpolate the compander settings */
  154965. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154966. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154967. return;
  154968. }
  154969. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154970. int *suppress){
  154971. int is=s;
  154972. double ds=s-is;
  154973. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154974. vorbis_info_psy *p=ci->psy_param[block];
  154975. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154976. return;
  154977. }
  154978. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154979. int *suppress,
  154980. noise3 *in,
  154981. noiseguard *guard,
  154982. double userbias){
  154983. int i,is=s,j;
  154984. double ds=s-is;
  154985. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154986. vorbis_info_psy *p=ci->psy_param[block];
  154987. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154988. p->noisewindowlomin=guard[block].lo;
  154989. p->noisewindowhimin=guard[block].hi;
  154990. p->noisewindowfixed=guard[block].fixed;
  154991. for(j=0;j<P_NOISECURVES;j++)
  154992. for(i=0;i<P_BANDS;i++)
  154993. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154994. /* impulse blocks may take a user specified bias to boost the
  154995. nominal/high noise encoding depth */
  154996. for(j=0;j<P_NOISECURVES;j++){
  154997. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154998. for(i=0;i<P_BANDS;i++){
  154999. p->noiseoff[j][i]+=userbias;
  155000. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  155001. }
  155002. }
  155003. return;
  155004. }
  155005. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  155006. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155007. vorbis_info_psy *p=ci->psy_param[block];
  155008. p->ath_adjatt=ci->hi.ath_floating_dB;
  155009. p->ath_maxatt=ci->hi.ath_absolute_dB;
  155010. return;
  155011. }
  155012. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  155013. int i;
  155014. for(i=0;i<ci->books;i++)
  155015. if(ci->book_param[i]==book)return(i);
  155016. return(ci->books++);
  155017. }
  155018. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  155019. int *shortb,int *longb){
  155020. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155021. int is=s;
  155022. int blockshort=shortb[is];
  155023. int blocklong=longb[is];
  155024. ci->blocksizes[0]=blockshort;
  155025. ci->blocksizes[1]=blocklong;
  155026. }
  155027. static void vorbis_encode_residue_setup(vorbis_info *vi,
  155028. int number, int block,
  155029. vorbis_residue_template *res){
  155030. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155031. int i,n;
  155032. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  155033. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  155034. memcpy(r,res->res,sizeof(*r));
  155035. if(ci->residues<=number)ci->residues=number+1;
  155036. switch(ci->blocksizes[block]){
  155037. case 64:case 128:case 256:
  155038. r->grouping=16;
  155039. break;
  155040. default:
  155041. r->grouping=32;
  155042. break;
  155043. }
  155044. ci->residue_type[number]=res->res_type;
  155045. /* to be adjusted by lowpass/pointlimit later */
  155046. n=r->end=ci->blocksizes[block]>>1;
  155047. if(res->res_type==2)
  155048. n=r->end*=vi->channels;
  155049. /* fill in all the books */
  155050. {
  155051. int booklist=0,k;
  155052. if(ci->hi.managed){
  155053. for(i=0;i<r->partitions;i++)
  155054. for(k=0;k<3;k++)
  155055. if(res->books_base_managed->books[i][k])
  155056. r->secondstages[i]|=(1<<k);
  155057. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  155058. ci->book_param[r->groupbook]=res->book_aux_managed;
  155059. for(i=0;i<r->partitions;i++){
  155060. for(k=0;k<3;k++){
  155061. if(res->books_base_managed->books[i][k]){
  155062. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  155063. r->booklist[booklist++]=bookid;
  155064. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  155065. }
  155066. }
  155067. }
  155068. }else{
  155069. for(i=0;i<r->partitions;i++)
  155070. for(k=0;k<3;k++)
  155071. if(res->books_base->books[i][k])
  155072. r->secondstages[i]|=(1<<k);
  155073. r->groupbook=book_dup_or_new(ci,res->book_aux);
  155074. ci->book_param[r->groupbook]=res->book_aux;
  155075. for(i=0;i<r->partitions;i++){
  155076. for(k=0;k<3;k++){
  155077. if(res->books_base->books[i][k]){
  155078. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  155079. r->booklist[booklist++]=bookid;
  155080. ci->book_param[bookid]=res->books_base->books[i][k];
  155081. }
  155082. }
  155083. }
  155084. }
  155085. }
  155086. /* lowpass setup/pointlimit */
  155087. {
  155088. double freq=ci->hi.lowpass_kHz*1000.;
  155089. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  155090. double nyq=vi->rate/2.;
  155091. long blocksize=ci->blocksizes[block]>>1;
  155092. /* lowpass needs to be set in the floor and the residue. */
  155093. if(freq>nyq)freq=nyq;
  155094. /* in the floor, the granularity can be very fine; it doesn't alter
  155095. the encoding structure, only the samples used to fit the floor
  155096. approximation */
  155097. f->n=freq/nyq*blocksize;
  155098. /* this res may by limited by the maximum pointlimit of the mode,
  155099. not the lowpass. the floor is always lowpass limited. */
  155100. if(res->limit_type){
  155101. if(ci->hi.managed)
  155102. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  155103. else
  155104. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  155105. if(freq>nyq)freq=nyq;
  155106. }
  155107. /* in the residue, we're constrained, physically, by partition
  155108. boundaries. We still lowpass 'wherever', but we have to round up
  155109. here to next boundary, or the vorbis spec will round it *down* to
  155110. previous boundary in encode/decode */
  155111. if(ci->residue_type[block]==2)
  155112. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155113. r->grouping;
  155114. else
  155115. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155116. r->grouping;
  155117. }
  155118. }
  155119. /* we assume two maps in this encoder */
  155120. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155121. vorbis_mapping_template *maps){
  155122. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155123. int i,j,is=s,modes=2;
  155124. vorbis_info_mapping0 *map=maps[is].map;
  155125. vorbis_info_mode *mode=_mode_template;
  155126. vorbis_residue_template *res=maps[is].res;
  155127. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155128. for(i=0;i<modes;i++){
  155129. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155130. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155131. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155132. if(i>=ci->modes)ci->modes=i+1;
  155133. ci->map_type[i]=0;
  155134. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155135. if(i>=ci->maps)ci->maps=i+1;
  155136. for(j=0;j<map[i].submaps;j++)
  155137. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155138. ,res+map[i].residuesubmap[j]);
  155139. }
  155140. }
  155141. static double setting_to_approx_bitrate(vorbis_info *vi){
  155142. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155143. highlevel_encode_setup *hi=&ci->hi;
  155144. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155145. int is=hi->base_setting;
  155146. double ds=hi->base_setting-is;
  155147. int ch=vi->channels;
  155148. double *r=setup->rate_mapping;
  155149. if(r==NULL)
  155150. return(-1);
  155151. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155152. }
  155153. static void get_setup_template(vorbis_info *vi,
  155154. long ch,long srate,
  155155. double req,int q_or_bitrate){
  155156. int i=0,j;
  155157. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155158. highlevel_encode_setup *hi=&ci->hi;
  155159. if(q_or_bitrate)req/=ch;
  155160. while(setup_list[i]){
  155161. if(setup_list[i]->coupling_restriction==-1 ||
  155162. setup_list[i]->coupling_restriction==ch){
  155163. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155164. srate<=setup_list[i]->samplerate_max_restriction){
  155165. int mappings=setup_list[i]->mappings;
  155166. double *map=(q_or_bitrate?
  155167. setup_list[i]->rate_mapping:
  155168. setup_list[i]->quality_mapping);
  155169. /* the template matches. Does the requested quality mode
  155170. fall within this template's modes? */
  155171. if(req<map[0]){++i;continue;}
  155172. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155173. for(j=0;j<mappings;j++)
  155174. if(req>=map[j] && req<map[j+1])break;
  155175. /* an all-points match */
  155176. hi->setup=setup_list[i];
  155177. if(j==mappings)
  155178. hi->base_setting=j-.001;
  155179. else{
  155180. float low=map[j];
  155181. float high=map[j+1];
  155182. float del=(req-low)/(high-low);
  155183. hi->base_setting=j+del;
  155184. }
  155185. return;
  155186. }
  155187. }
  155188. i++;
  155189. }
  155190. hi->setup=NULL;
  155191. }
  155192. /* encoders will need to use vorbis_info_init beforehand and call
  155193. vorbis_info clear when all done */
  155194. /* two interfaces; this, more detailed one, and later a convenience
  155195. layer on top */
  155196. /* the final setup call */
  155197. int vorbis_encode_setup_init(vorbis_info *vi){
  155198. int i0=0,singleblock=0;
  155199. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155200. ve_setup_data_template *setup=NULL;
  155201. highlevel_encode_setup *hi=&ci->hi;
  155202. if(ci==NULL)return(OV_EINVAL);
  155203. if(!hi->impulse_block_p)i0=1;
  155204. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155205. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155206. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155207. /* again, bound this to avoid the app shooting itself int he foot
  155208. too badly */
  155209. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155210. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155211. /* get the appropriate setup template; matches the fetch in previous
  155212. stages */
  155213. setup=(ve_setup_data_template *)hi->setup;
  155214. if(setup==NULL)return(OV_EINVAL);
  155215. hi->set_in_stone=1;
  155216. /* choose block sizes from configured sizes as well as paying
  155217. attention to long_block_p and short_block_p. If the configured
  155218. short and long blocks are the same length, we set long_block_p
  155219. and unset short_block_p */
  155220. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155221. setup->blocksize_short,
  155222. setup->blocksize_long);
  155223. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155224. /* floor setup; choose proper floor params. Allocated on the floor
  155225. stack in order; if we alloc only long floor, it's 0 */
  155226. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155227. setup->floor_books,
  155228. setup->floor_params,
  155229. setup->floor_short_mapping);
  155230. if(!singleblock)
  155231. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155232. setup->floor_books,
  155233. setup->floor_params,
  155234. setup->floor_long_mapping);
  155235. /* setup of [mostly] short block detection and stereo*/
  155236. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155237. setup->global_params,
  155238. setup->global_mapping);
  155239. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155240. /* basic psych setup and noise normalization */
  155241. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155242. setup->psy_noise_normal_start[0],
  155243. setup->psy_noise_normal_partition[0],
  155244. setup->psy_noise_normal_thresh,
  155245. 0);
  155246. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155247. setup->psy_noise_normal_start[0],
  155248. setup->psy_noise_normal_partition[0],
  155249. setup->psy_noise_normal_thresh,
  155250. 1);
  155251. if(!singleblock){
  155252. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155253. setup->psy_noise_normal_start[1],
  155254. setup->psy_noise_normal_partition[1],
  155255. setup->psy_noise_normal_thresh,
  155256. 2);
  155257. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155258. setup->psy_noise_normal_start[1],
  155259. setup->psy_noise_normal_partition[1],
  155260. setup->psy_noise_normal_thresh,
  155261. 3);
  155262. }
  155263. /* tone masking setup */
  155264. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155265. setup->psy_tone_masteratt,
  155266. setup->psy_tone_0dB,
  155267. setup->psy_tone_adj_impulse);
  155268. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155269. setup->psy_tone_masteratt,
  155270. setup->psy_tone_0dB,
  155271. setup->psy_tone_adj_other);
  155272. if(!singleblock){
  155273. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155274. setup->psy_tone_masteratt,
  155275. setup->psy_tone_0dB,
  155276. setup->psy_tone_adj_other);
  155277. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155278. setup->psy_tone_masteratt,
  155279. setup->psy_tone_0dB,
  155280. setup->psy_tone_adj_long);
  155281. }
  155282. /* noise companding setup */
  155283. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155284. setup->psy_noise_compand,
  155285. setup->psy_noise_compand_short_mapping);
  155286. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155287. setup->psy_noise_compand,
  155288. setup->psy_noise_compand_short_mapping);
  155289. if(!singleblock){
  155290. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155291. setup->psy_noise_compand,
  155292. setup->psy_noise_compand_long_mapping);
  155293. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155294. setup->psy_noise_compand,
  155295. setup->psy_noise_compand_long_mapping);
  155296. }
  155297. /* peak guarding setup */
  155298. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155299. setup->psy_tone_dBsuppress);
  155300. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155301. setup->psy_tone_dBsuppress);
  155302. if(!singleblock){
  155303. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155304. setup->psy_tone_dBsuppress);
  155305. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155306. setup->psy_tone_dBsuppress);
  155307. }
  155308. /* noise bias setup */
  155309. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155310. setup->psy_noise_dBsuppress,
  155311. setup->psy_noise_bias_impulse,
  155312. setup->psy_noiseguards,
  155313. (i0==0?hi->impulse_noisetune:0.));
  155314. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155315. setup->psy_noise_dBsuppress,
  155316. setup->psy_noise_bias_padding,
  155317. setup->psy_noiseguards,0.);
  155318. if(!singleblock){
  155319. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155320. setup->psy_noise_dBsuppress,
  155321. setup->psy_noise_bias_trans,
  155322. setup->psy_noiseguards,0.);
  155323. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155324. setup->psy_noise_dBsuppress,
  155325. setup->psy_noise_bias_long,
  155326. setup->psy_noiseguards,0.);
  155327. }
  155328. vorbis_encode_ath_setup(vi,0);
  155329. vorbis_encode_ath_setup(vi,1);
  155330. if(!singleblock){
  155331. vorbis_encode_ath_setup(vi,2);
  155332. vorbis_encode_ath_setup(vi,3);
  155333. }
  155334. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155335. /* set bitrate readonlies and management */
  155336. if(hi->bitrate_av>0)
  155337. vi->bitrate_nominal=hi->bitrate_av;
  155338. else{
  155339. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155340. }
  155341. vi->bitrate_lower=hi->bitrate_min;
  155342. vi->bitrate_upper=hi->bitrate_max;
  155343. if(hi->bitrate_av)
  155344. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155345. else
  155346. vi->bitrate_window=0.;
  155347. if(hi->managed){
  155348. ci->bi.avg_rate=hi->bitrate_av;
  155349. ci->bi.min_rate=hi->bitrate_min;
  155350. ci->bi.max_rate=hi->bitrate_max;
  155351. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155352. ci->bi.reservoir_bias=
  155353. hi->bitrate_reservoir_bias;
  155354. ci->bi.slew_damp=hi->bitrate_av_damp;
  155355. }
  155356. return(0);
  155357. }
  155358. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155359. long channels,
  155360. long rate){
  155361. int ret=0,i,is;
  155362. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155363. highlevel_encode_setup *hi=&ci->hi;
  155364. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155365. double ds;
  155366. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155367. if(ret)return(ret);
  155368. is=hi->base_setting;
  155369. ds=hi->base_setting-is;
  155370. hi->short_setting=hi->base_setting;
  155371. hi->long_setting=hi->base_setting;
  155372. hi->managed=0;
  155373. hi->impulse_block_p=1;
  155374. hi->noise_normalize_p=1;
  155375. hi->stereo_point_setting=hi->base_setting;
  155376. hi->lowpass_kHz=
  155377. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155378. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155379. setup->psy_ath_float[is+1]*ds;
  155380. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155381. setup->psy_ath_abs[is+1]*ds;
  155382. hi->amplitude_track_dBpersec=-6.;
  155383. hi->trigger_setting=hi->base_setting;
  155384. for(i=0;i<4;i++){
  155385. hi->block[i].tone_mask_setting=hi->base_setting;
  155386. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155387. hi->block[i].noise_bias_setting=hi->base_setting;
  155388. hi->block[i].noise_compand_setting=hi->base_setting;
  155389. }
  155390. return(ret);
  155391. }
  155392. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155393. long channels,
  155394. long rate,
  155395. float quality){
  155396. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155397. highlevel_encode_setup *hi=&ci->hi;
  155398. quality+=.0000001;
  155399. if(quality>=1.)quality=.9999;
  155400. get_setup_template(vi,channels,rate,quality,0);
  155401. if(!hi->setup)return OV_EIMPL;
  155402. return vorbis_encode_setup_setting(vi,channels,rate);
  155403. }
  155404. int vorbis_encode_init_vbr(vorbis_info *vi,
  155405. long channels,
  155406. long rate,
  155407. float base_quality /* 0. to 1. */
  155408. ){
  155409. int ret=0;
  155410. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155411. if(ret){
  155412. vorbis_info_clear(vi);
  155413. return ret;
  155414. }
  155415. ret=vorbis_encode_setup_init(vi);
  155416. if(ret)
  155417. vorbis_info_clear(vi);
  155418. return(ret);
  155419. }
  155420. int vorbis_encode_setup_managed(vorbis_info *vi,
  155421. long channels,
  155422. long rate,
  155423. long max_bitrate,
  155424. long nominal_bitrate,
  155425. long min_bitrate){
  155426. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155427. highlevel_encode_setup *hi=&ci->hi;
  155428. double tnominal=nominal_bitrate;
  155429. int ret=0;
  155430. if(nominal_bitrate<=0.){
  155431. if(max_bitrate>0.){
  155432. if(min_bitrate>0.)
  155433. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155434. else
  155435. nominal_bitrate=max_bitrate*.875;
  155436. }else{
  155437. if(min_bitrate>0.){
  155438. nominal_bitrate=min_bitrate;
  155439. }else{
  155440. return(OV_EINVAL);
  155441. }
  155442. }
  155443. }
  155444. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155445. if(!hi->setup)return OV_EIMPL;
  155446. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155447. if(ret){
  155448. vorbis_info_clear(vi);
  155449. return ret;
  155450. }
  155451. /* initialize management with sane defaults */
  155452. hi->managed=1;
  155453. hi->bitrate_min=min_bitrate;
  155454. hi->bitrate_max=max_bitrate;
  155455. hi->bitrate_av=tnominal;
  155456. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155457. hi->bitrate_reservoir=nominal_bitrate*2;
  155458. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155459. return(ret);
  155460. }
  155461. int vorbis_encode_init(vorbis_info *vi,
  155462. long channels,
  155463. long rate,
  155464. long max_bitrate,
  155465. long nominal_bitrate,
  155466. long min_bitrate){
  155467. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155468. max_bitrate,
  155469. nominal_bitrate,
  155470. min_bitrate);
  155471. if(ret){
  155472. vorbis_info_clear(vi);
  155473. return(ret);
  155474. }
  155475. ret=vorbis_encode_setup_init(vi);
  155476. if(ret)
  155477. vorbis_info_clear(vi);
  155478. return(ret);
  155479. }
  155480. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155481. if(vi){
  155482. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155483. highlevel_encode_setup *hi=&ci->hi;
  155484. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155485. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155486. switch(number){
  155487. /* now deprecated *****************/
  155488. case OV_ECTL_RATEMANAGE_GET:
  155489. {
  155490. struct ovectl_ratemanage_arg *ai=
  155491. (struct ovectl_ratemanage_arg *)arg;
  155492. ai->management_active=hi->managed;
  155493. ai->bitrate_hard_window=ai->bitrate_av_window=
  155494. (double)hi->bitrate_reservoir/vi->rate;
  155495. ai->bitrate_av_window_center=1.;
  155496. ai->bitrate_hard_min=hi->bitrate_min;
  155497. ai->bitrate_hard_max=hi->bitrate_max;
  155498. ai->bitrate_av_lo=hi->bitrate_av;
  155499. ai->bitrate_av_hi=hi->bitrate_av;
  155500. }
  155501. return(0);
  155502. /* now deprecated *****************/
  155503. case OV_ECTL_RATEMANAGE_SET:
  155504. {
  155505. struct ovectl_ratemanage_arg *ai=
  155506. (struct ovectl_ratemanage_arg *)arg;
  155507. if(ai==NULL){
  155508. hi->managed=0;
  155509. }else{
  155510. hi->managed=ai->management_active;
  155511. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155512. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155513. }
  155514. }
  155515. return 0;
  155516. /* now deprecated *****************/
  155517. case OV_ECTL_RATEMANAGE_AVG:
  155518. {
  155519. struct ovectl_ratemanage_arg *ai=
  155520. (struct ovectl_ratemanage_arg *)arg;
  155521. if(ai==NULL){
  155522. hi->bitrate_av=0;
  155523. }else{
  155524. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155525. }
  155526. }
  155527. return(0);
  155528. /* now deprecated *****************/
  155529. case OV_ECTL_RATEMANAGE_HARD:
  155530. {
  155531. struct ovectl_ratemanage_arg *ai=
  155532. (struct ovectl_ratemanage_arg *)arg;
  155533. if(ai==NULL){
  155534. hi->bitrate_min=0;
  155535. hi->bitrate_max=0;
  155536. }else{
  155537. hi->bitrate_min=ai->bitrate_hard_min;
  155538. hi->bitrate_max=ai->bitrate_hard_max;
  155539. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155540. (hi->bitrate_max+hi->bitrate_min)*.5;
  155541. }
  155542. if(hi->bitrate_reservoir<128.)
  155543. hi->bitrate_reservoir=128.;
  155544. }
  155545. return(0);
  155546. /* replacement ratemanage interface */
  155547. case OV_ECTL_RATEMANAGE2_GET:
  155548. {
  155549. struct ovectl_ratemanage2_arg *ai=
  155550. (struct ovectl_ratemanage2_arg *)arg;
  155551. if(ai==NULL)return OV_EINVAL;
  155552. ai->management_active=hi->managed;
  155553. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155554. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155555. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155556. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155557. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155558. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155559. }
  155560. return (0);
  155561. case OV_ECTL_RATEMANAGE2_SET:
  155562. {
  155563. struct ovectl_ratemanage2_arg *ai=
  155564. (struct ovectl_ratemanage2_arg *)arg;
  155565. if(ai==NULL){
  155566. hi->managed=0;
  155567. }else{
  155568. /* sanity check; only catch invariant violations */
  155569. if(ai->bitrate_limit_min_kbps>0 &&
  155570. ai->bitrate_average_kbps>0 &&
  155571. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155572. return OV_EINVAL;
  155573. if(ai->bitrate_limit_max_kbps>0 &&
  155574. ai->bitrate_average_kbps>0 &&
  155575. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155576. return OV_EINVAL;
  155577. if(ai->bitrate_limit_min_kbps>0 &&
  155578. ai->bitrate_limit_max_kbps>0 &&
  155579. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155580. return OV_EINVAL;
  155581. if(ai->bitrate_average_damping <= 0.)
  155582. return OV_EINVAL;
  155583. if(ai->bitrate_limit_reservoir_bits < 0)
  155584. return OV_EINVAL;
  155585. if(ai->bitrate_limit_reservoir_bias < 0.)
  155586. return OV_EINVAL;
  155587. if(ai->bitrate_limit_reservoir_bias > 1.)
  155588. return OV_EINVAL;
  155589. hi->managed=ai->management_active;
  155590. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155591. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155592. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155593. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155594. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155595. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155596. }
  155597. }
  155598. return 0;
  155599. case OV_ECTL_LOWPASS_GET:
  155600. {
  155601. double *farg=(double *)arg;
  155602. *farg=hi->lowpass_kHz;
  155603. }
  155604. return(0);
  155605. case OV_ECTL_LOWPASS_SET:
  155606. {
  155607. double *farg=(double *)arg;
  155608. hi->lowpass_kHz=*farg;
  155609. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155610. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155611. }
  155612. return(0);
  155613. case OV_ECTL_IBLOCK_GET:
  155614. {
  155615. double *farg=(double *)arg;
  155616. *farg=hi->impulse_noisetune;
  155617. }
  155618. return(0);
  155619. case OV_ECTL_IBLOCK_SET:
  155620. {
  155621. double *farg=(double *)arg;
  155622. hi->impulse_noisetune=*farg;
  155623. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155624. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155625. }
  155626. return(0);
  155627. }
  155628. return(OV_EIMPL);
  155629. }
  155630. return(OV_EINVAL);
  155631. }
  155632. #endif
  155633. /*** End of inlined file: vorbisenc.c ***/
  155634. /*** Start of inlined file: vorbisfile.c ***/
  155635. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155636. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155637. // tasks..
  155638. #if JUCE_MSVC
  155639. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155640. #endif
  155641. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155642. #if JUCE_USE_OGGVORBIS
  155643. #include <stdlib.h>
  155644. #include <stdio.h>
  155645. #include <errno.h>
  155646. #include <string.h>
  155647. #include <math.h>
  155648. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155649. one logical bitstream arranged end to end (the only form of Ogg
  155650. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155651. multiplexing] is not allowed in Vorbis) */
  155652. /* A Vorbis file can be played beginning to end (streamed) without
  155653. worrying ahead of time about chaining (see decoder_example.c). If
  155654. we have the whole file, however, and want random access
  155655. (seeking/scrubbing) or desire to know the total length/time of a
  155656. file, we need to account for the possibility of chaining. */
  155657. /* We can handle things a number of ways; we can determine the entire
  155658. bitstream structure right off the bat, or find pieces on demand.
  155659. This example determines and caches structure for the entire
  155660. bitstream, but builds a virtual decoder on the fly when moving
  155661. between links in the chain. */
  155662. /* There are also different ways to implement seeking. Enough
  155663. information exists in an Ogg bitstream to seek to
  155664. sample-granularity positions in the output. Or, one can seek by
  155665. picking some portion of the stream roughly in the desired area if
  155666. we only want coarse navigation through the stream. */
  155667. /*************************************************************************
  155668. * Many, many internal helpers. The intention is not to be confusing;
  155669. * rampant duplication and monolithic function implementation would be
  155670. * harder to understand anyway. The high level functions are last. Begin
  155671. * grokking near the end of the file */
  155672. /* read a little more data from the file/pipe into the ogg_sync framer
  155673. */
  155674. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155675. over 8k gets what they deserve */
  155676. static long _get_data(OggVorbis_File *vf){
  155677. errno=0;
  155678. if(vf->datasource){
  155679. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155680. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155681. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155682. if(bytes==0 && errno)return(-1);
  155683. return(bytes);
  155684. }else
  155685. return(0);
  155686. }
  155687. /* save a tiny smidge of verbosity to make the code more readable */
  155688. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155689. if(vf->datasource){
  155690. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155691. vf->offset=offset;
  155692. ogg_sync_reset(&vf->oy);
  155693. }else{
  155694. /* shouldn't happen unless someone writes a broken callback */
  155695. return;
  155696. }
  155697. }
  155698. /* The read/seek functions track absolute position within the stream */
  155699. /* from the head of the stream, get the next page. boundary specifies
  155700. if the function is allowed to fetch more data from the stream (and
  155701. how much) or only use internally buffered data.
  155702. boundary: -1) unbounded search
  155703. 0) read no additional data; use cached only
  155704. n) search for a new page beginning for n bytes
  155705. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155706. n) found a page at absolute offset n */
  155707. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155708. ogg_int64_t boundary){
  155709. if(boundary>0)boundary+=vf->offset;
  155710. while(1){
  155711. long more;
  155712. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155713. more=ogg_sync_pageseek(&vf->oy,og);
  155714. if(more<0){
  155715. /* skipped n bytes */
  155716. vf->offset-=more;
  155717. }else{
  155718. if(more==0){
  155719. /* send more paramedics */
  155720. if(!boundary)return(OV_FALSE);
  155721. {
  155722. long ret=_get_data(vf);
  155723. if(ret==0)return(OV_EOF);
  155724. if(ret<0)return(OV_EREAD);
  155725. }
  155726. }else{
  155727. /* got a page. Return the offset at the page beginning,
  155728. advance the internal offset past the page end */
  155729. ogg_int64_t ret=vf->offset;
  155730. vf->offset+=more;
  155731. return(ret);
  155732. }
  155733. }
  155734. }
  155735. }
  155736. /* find the latest page beginning before the current stream cursor
  155737. position. Much dirtier than the above as Ogg doesn't have any
  155738. backward search linkage. no 'readp' as it will certainly have to
  155739. read. */
  155740. /* returns offset or OV_EREAD, OV_FAULT */
  155741. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155742. ogg_int64_t begin=vf->offset;
  155743. ogg_int64_t end=begin;
  155744. ogg_int64_t ret;
  155745. ogg_int64_t offset=-1;
  155746. while(offset==-1){
  155747. begin-=CHUNKSIZE;
  155748. if(begin<0)
  155749. begin=0;
  155750. _seek_helper(vf,begin);
  155751. while(vf->offset<end){
  155752. ret=_get_next_page(vf,og,end-vf->offset);
  155753. if(ret==OV_EREAD)return(OV_EREAD);
  155754. if(ret<0){
  155755. break;
  155756. }else{
  155757. offset=ret;
  155758. }
  155759. }
  155760. }
  155761. /* we have the offset. Actually snork and hold the page now */
  155762. _seek_helper(vf,offset);
  155763. ret=_get_next_page(vf,og,CHUNKSIZE);
  155764. if(ret<0)
  155765. /* this shouldn't be possible */
  155766. return(OV_EFAULT);
  155767. return(offset);
  155768. }
  155769. /* finds each bitstream link one at a time using a bisection search
  155770. (has to begin by knowing the offset of the lb's initial page).
  155771. Recurses for each link so it can alloc the link storage after
  155772. finding them all, then unroll and fill the cache at the same time */
  155773. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155774. ogg_int64_t begin,
  155775. ogg_int64_t searched,
  155776. ogg_int64_t end,
  155777. long currentno,
  155778. long m){
  155779. ogg_int64_t endsearched=end;
  155780. ogg_int64_t next=end;
  155781. ogg_page og;
  155782. ogg_int64_t ret;
  155783. /* the below guards against garbage seperating the last and
  155784. first pages of two links. */
  155785. while(searched<endsearched){
  155786. ogg_int64_t bisect;
  155787. if(endsearched-searched<CHUNKSIZE){
  155788. bisect=searched;
  155789. }else{
  155790. bisect=(searched+endsearched)/2;
  155791. }
  155792. _seek_helper(vf,bisect);
  155793. ret=_get_next_page(vf,&og,-1);
  155794. if(ret==OV_EREAD)return(OV_EREAD);
  155795. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155796. endsearched=bisect;
  155797. if(ret>=0)next=ret;
  155798. }else{
  155799. searched=ret+og.header_len+og.body_len;
  155800. }
  155801. }
  155802. _seek_helper(vf,next);
  155803. ret=_get_next_page(vf,&og,-1);
  155804. if(ret==OV_EREAD)return(OV_EREAD);
  155805. if(searched>=end || ret<0){
  155806. vf->links=m+1;
  155807. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155808. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155809. vf->offsets[m+1]=searched;
  155810. }else{
  155811. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155812. end,ogg_page_serialno(&og),m+1);
  155813. if(ret==OV_EREAD)return(OV_EREAD);
  155814. }
  155815. vf->offsets[m]=begin;
  155816. vf->serialnos[m]=currentno;
  155817. return(0);
  155818. }
  155819. /* uses the local ogg_stream storage in vf; this is important for
  155820. non-streaming input sources */
  155821. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155822. long *serialno,ogg_page *og_ptr){
  155823. ogg_page og;
  155824. ogg_packet op;
  155825. int i,ret;
  155826. if(!og_ptr){
  155827. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155828. if(llret==OV_EREAD)return(OV_EREAD);
  155829. if(llret<0)return OV_ENOTVORBIS;
  155830. og_ptr=&og;
  155831. }
  155832. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155833. if(serialno)*serialno=vf->os.serialno;
  155834. vf->ready_state=STREAMSET;
  155835. /* extract the initial header from the first page and verify that the
  155836. Ogg bitstream is in fact Vorbis data */
  155837. vorbis_info_init(vi);
  155838. vorbis_comment_init(vc);
  155839. i=0;
  155840. while(i<3){
  155841. ogg_stream_pagein(&vf->os,og_ptr);
  155842. while(i<3){
  155843. int result=ogg_stream_packetout(&vf->os,&op);
  155844. if(result==0)break;
  155845. if(result==-1){
  155846. ret=OV_EBADHEADER;
  155847. goto bail_header;
  155848. }
  155849. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155850. goto bail_header;
  155851. }
  155852. i++;
  155853. }
  155854. if(i<3)
  155855. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155856. ret=OV_EBADHEADER;
  155857. goto bail_header;
  155858. }
  155859. }
  155860. return 0;
  155861. bail_header:
  155862. vorbis_info_clear(vi);
  155863. vorbis_comment_clear(vc);
  155864. vf->ready_state=OPENED;
  155865. return ret;
  155866. }
  155867. /* last step of the OggVorbis_File initialization; get all the
  155868. vorbis_info structs and PCM positions. Only called by the seekable
  155869. initialization (local stream storage is hacked slightly; pay
  155870. attention to how that's done) */
  155871. /* this is void and does not propogate errors up because we want to be
  155872. able to open and use damaged bitstreams as well as we can. Just
  155873. watch out for missing information for links in the OggVorbis_File
  155874. struct */
  155875. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155876. ogg_page og;
  155877. int i;
  155878. ogg_int64_t ret;
  155879. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155880. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155881. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155882. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155883. for(i=0;i<vf->links;i++){
  155884. if(i==0){
  155885. /* we already grabbed the initial header earlier. Just set the offset */
  155886. vf->dataoffsets[i]=dataoffset;
  155887. _seek_helper(vf,dataoffset);
  155888. }else{
  155889. /* seek to the location of the initial header */
  155890. _seek_helper(vf,vf->offsets[i]);
  155891. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155892. vf->dataoffsets[i]=-1;
  155893. }else{
  155894. vf->dataoffsets[i]=vf->offset;
  155895. }
  155896. }
  155897. /* fetch beginning PCM offset */
  155898. if(vf->dataoffsets[i]!=-1){
  155899. ogg_int64_t accumulated=0;
  155900. long lastblock=-1;
  155901. int result;
  155902. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155903. while(1){
  155904. ogg_packet op;
  155905. ret=_get_next_page(vf,&og,-1);
  155906. if(ret<0)
  155907. /* this should not be possible unless the file is
  155908. truncated/mangled */
  155909. break;
  155910. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155911. break;
  155912. /* count blocksizes of all frames in the page */
  155913. ogg_stream_pagein(&vf->os,&og);
  155914. while((result=ogg_stream_packetout(&vf->os,&op))){
  155915. if(result>0){ /* ignore holes */
  155916. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155917. if(lastblock!=-1)
  155918. accumulated+=(lastblock+thisblock)>>2;
  155919. lastblock=thisblock;
  155920. }
  155921. }
  155922. if(ogg_page_granulepos(&og)!=-1){
  155923. /* pcm offset of last packet on the first audio page */
  155924. accumulated= ogg_page_granulepos(&og)-accumulated;
  155925. break;
  155926. }
  155927. }
  155928. /* less than zero? This is a stream with samples trimmed off
  155929. the beginning, a normal occurrence; set the offset to zero */
  155930. if(accumulated<0)accumulated=0;
  155931. vf->pcmlengths[i*2]=accumulated;
  155932. }
  155933. /* get the PCM length of this link. To do this,
  155934. get the last page of the stream */
  155935. {
  155936. ogg_int64_t end=vf->offsets[i+1];
  155937. _seek_helper(vf,end);
  155938. while(1){
  155939. ret=_get_prev_page(vf,&og);
  155940. if(ret<0){
  155941. /* this should not be possible */
  155942. vorbis_info_clear(vf->vi+i);
  155943. vorbis_comment_clear(vf->vc+i);
  155944. break;
  155945. }
  155946. if(ogg_page_granulepos(&og)!=-1){
  155947. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155948. break;
  155949. }
  155950. vf->offset=ret;
  155951. }
  155952. }
  155953. }
  155954. }
  155955. static int _make_decode_ready(OggVorbis_File *vf){
  155956. if(vf->ready_state>STREAMSET)return 0;
  155957. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155958. if(vf->seekable){
  155959. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155960. return OV_EBADLINK;
  155961. }else{
  155962. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155963. return OV_EBADLINK;
  155964. }
  155965. vorbis_block_init(&vf->vd,&vf->vb);
  155966. vf->ready_state=INITSET;
  155967. vf->bittrack=0.f;
  155968. vf->samptrack=0.f;
  155969. return 0;
  155970. }
  155971. static int _open_seekable2(OggVorbis_File *vf){
  155972. long serialno=vf->current_serialno;
  155973. ogg_int64_t dataoffset=vf->offset, end;
  155974. ogg_page og;
  155975. /* we're partially open and have a first link header state in
  155976. storage in vf */
  155977. /* we can seek, so set out learning all about this file */
  155978. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155979. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155980. /* We get the offset for the last page of the physical bitstream.
  155981. Most OggVorbis files will contain a single logical bitstream */
  155982. end=_get_prev_page(vf,&og);
  155983. if(end<0)return(end);
  155984. /* more than one logical bitstream? */
  155985. if(ogg_page_serialno(&og)!=serialno){
  155986. /* Chained bitstream. Bisect-search each logical bitstream
  155987. section. Do so based on serial number only */
  155988. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155989. }else{
  155990. /* Only one logical bitstream */
  155991. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155992. }
  155993. /* the initial header memory is referenced by vf after; don't free it */
  155994. _prefetch_all_headers(vf,dataoffset);
  155995. return(ov_raw_seek(vf,0));
  155996. }
  155997. /* clear out the current logical bitstream decoder */
  155998. static void _decode_clear(OggVorbis_File *vf){
  155999. vorbis_dsp_clear(&vf->vd);
  156000. vorbis_block_clear(&vf->vb);
  156001. vf->ready_state=OPENED;
  156002. }
  156003. /* fetch and process a packet. Handles the case where we're at a
  156004. bitstream boundary and dumps the decoding machine. If the decoding
  156005. machine is unloaded, it loads it. It also keeps pcm_offset up to
  156006. date (seek and read both use this. seek uses a special hack with
  156007. readp).
  156008. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  156009. 0) need more data (only if readp==0)
  156010. 1) got a packet
  156011. */
  156012. static int _fetch_and_process_packet(OggVorbis_File *vf,
  156013. ogg_packet *op_in,
  156014. int readp,
  156015. int spanp){
  156016. ogg_page og;
  156017. /* handle one packet. Try to fetch it from current stream state */
  156018. /* extract packets from page */
  156019. while(1){
  156020. /* process a packet if we can. If the machine isn't loaded,
  156021. neither is a page */
  156022. if(vf->ready_state==INITSET){
  156023. while(1) {
  156024. ogg_packet op;
  156025. ogg_packet *op_ptr=(op_in?op_in:&op);
  156026. int result=ogg_stream_packetout(&vf->os,op_ptr);
  156027. ogg_int64_t granulepos;
  156028. op_in=NULL;
  156029. if(result==-1)return(OV_HOLE); /* hole in the data. */
  156030. if(result>0){
  156031. /* got a packet. process it */
  156032. granulepos=op_ptr->granulepos;
  156033. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  156034. header handling. The
  156035. header packets aren't
  156036. audio, so if/when we
  156037. submit them,
  156038. vorbis_synthesis will
  156039. reject them */
  156040. /* suck in the synthesis data and track bitrate */
  156041. {
  156042. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156043. /* for proper use of libvorbis within libvorbisfile,
  156044. oldsamples will always be zero. */
  156045. if(oldsamples)return(OV_EFAULT);
  156046. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156047. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  156048. vf->bittrack+=op_ptr->bytes*8;
  156049. }
  156050. /* update the pcm offset. */
  156051. if(granulepos!=-1 && !op_ptr->e_o_s){
  156052. int link=(vf->seekable?vf->current_link:0);
  156053. int i,samples;
  156054. /* this packet has a pcm_offset on it (the last packet
  156055. completed on a page carries the offset) After processing
  156056. (above), we know the pcm position of the *last* sample
  156057. ready to be returned. Find the offset of the *first*
  156058. As an aside, this trick is inaccurate if we begin
  156059. reading anew right at the last page; the end-of-stream
  156060. granulepos declares the last frame in the stream, and the
  156061. last packet of the last page may be a partial frame.
  156062. So, we need a previous granulepos from an in-sequence page
  156063. to have a reference point. Thus the !op_ptr->e_o_s clause
  156064. above */
  156065. if(vf->seekable && link>0)
  156066. granulepos-=vf->pcmlengths[link*2];
  156067. if(granulepos<0)granulepos=0; /* actually, this
  156068. shouldn't be possible
  156069. here unless the stream
  156070. is very broken */
  156071. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156072. granulepos-=samples;
  156073. for(i=0;i<link;i++)
  156074. granulepos+=vf->pcmlengths[i*2+1];
  156075. vf->pcm_offset=granulepos;
  156076. }
  156077. return(1);
  156078. }
  156079. }
  156080. else
  156081. break;
  156082. }
  156083. }
  156084. if(vf->ready_state>=OPENED){
  156085. ogg_int64_t ret;
  156086. if(!readp)return(0);
  156087. if((ret=_get_next_page(vf,&og,-1))<0){
  156088. return(OV_EOF); /* eof.
  156089. leave unitialized */
  156090. }
  156091. /* bitrate tracking; add the header's bytes here, the body bytes
  156092. are done by packet above */
  156093. vf->bittrack+=og.header_len*8;
  156094. /* has our decoding just traversed a bitstream boundary? */
  156095. if(vf->ready_state==INITSET){
  156096. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156097. if(!spanp)
  156098. return(OV_EOF);
  156099. _decode_clear(vf);
  156100. if(!vf->seekable){
  156101. vorbis_info_clear(vf->vi);
  156102. vorbis_comment_clear(vf->vc);
  156103. }
  156104. }
  156105. }
  156106. }
  156107. /* Do we need to load a new machine before submitting the page? */
  156108. /* This is different in the seekable and non-seekable cases.
  156109. In the seekable case, we already have all the header
  156110. information loaded and cached; we just initialize the machine
  156111. with it and continue on our merry way.
  156112. In the non-seekable (streaming) case, we'll only be at a
  156113. boundary if we just left the previous logical bitstream and
  156114. we're now nominally at the header of the next bitstream
  156115. */
  156116. if(vf->ready_state!=INITSET){
  156117. int link;
  156118. if(vf->ready_state<STREAMSET){
  156119. if(vf->seekable){
  156120. vf->current_serialno=ogg_page_serialno(&og);
  156121. /* match the serialno to bitstream section. We use this rather than
  156122. offset positions to avoid problems near logical bitstream
  156123. boundaries */
  156124. for(link=0;link<vf->links;link++)
  156125. if(vf->serialnos[link]==vf->current_serialno)break;
  156126. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156127. stream. error out,
  156128. leave machine
  156129. uninitialized */
  156130. vf->current_link=link;
  156131. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156132. vf->ready_state=STREAMSET;
  156133. }else{
  156134. /* we're streaming */
  156135. /* fetch the three header packets, build the info struct */
  156136. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156137. if(ret)return(ret);
  156138. vf->current_link++;
  156139. link=0;
  156140. }
  156141. }
  156142. {
  156143. int ret=_make_decode_ready(vf);
  156144. if(ret<0)return ret;
  156145. }
  156146. }
  156147. ogg_stream_pagein(&vf->os,&og);
  156148. }
  156149. }
  156150. /* if, eg, 64 bit stdio is configured by default, this will build with
  156151. fseek64 */
  156152. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156153. if(f==NULL)return(-1);
  156154. return fseek(f,off,whence);
  156155. }
  156156. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156157. long ibytes, ov_callbacks callbacks){
  156158. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156159. int ret;
  156160. memset(vf,0,sizeof(*vf));
  156161. vf->datasource=f;
  156162. vf->callbacks = callbacks;
  156163. /* init the framing state */
  156164. ogg_sync_init(&vf->oy);
  156165. /* perhaps some data was previously read into a buffer for testing
  156166. against other stream types. Allow initialization from this
  156167. previously read data (as we may be reading from a non-seekable
  156168. stream) */
  156169. if(initial){
  156170. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156171. memcpy(buffer,initial,ibytes);
  156172. ogg_sync_wrote(&vf->oy,ibytes);
  156173. }
  156174. /* can we seek? Stevens suggests the seek test was portable */
  156175. if(offsettest!=-1)vf->seekable=1;
  156176. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156177. entry for partial open */
  156178. vf->links=1;
  156179. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156180. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156181. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156182. /* Try to fetch the headers, maintaining all the storage */
  156183. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156184. vf->datasource=NULL;
  156185. ov_clear(vf);
  156186. }else
  156187. vf->ready_state=PARTOPEN;
  156188. return(ret);
  156189. }
  156190. static int _ov_open2(OggVorbis_File *vf){
  156191. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156192. vf->ready_state=OPENED;
  156193. if(vf->seekable){
  156194. int ret=_open_seekable2(vf);
  156195. if(ret){
  156196. vf->datasource=NULL;
  156197. ov_clear(vf);
  156198. }
  156199. return(ret);
  156200. }else
  156201. vf->ready_state=STREAMSET;
  156202. return 0;
  156203. }
  156204. /* clear out the OggVorbis_File struct */
  156205. int ov_clear(OggVorbis_File *vf){
  156206. if(vf){
  156207. vorbis_block_clear(&vf->vb);
  156208. vorbis_dsp_clear(&vf->vd);
  156209. ogg_stream_clear(&vf->os);
  156210. if(vf->vi && vf->links){
  156211. int i;
  156212. for(i=0;i<vf->links;i++){
  156213. vorbis_info_clear(vf->vi+i);
  156214. vorbis_comment_clear(vf->vc+i);
  156215. }
  156216. _ogg_free(vf->vi);
  156217. _ogg_free(vf->vc);
  156218. }
  156219. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156220. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156221. if(vf->serialnos)_ogg_free(vf->serialnos);
  156222. if(vf->offsets)_ogg_free(vf->offsets);
  156223. ogg_sync_clear(&vf->oy);
  156224. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156225. memset(vf,0,sizeof(*vf));
  156226. }
  156227. #ifdef DEBUG_LEAKS
  156228. _VDBG_dump();
  156229. #endif
  156230. return(0);
  156231. }
  156232. /* inspects the OggVorbis file and finds/documents all the logical
  156233. bitstreams contained in it. Tries to be tolerant of logical
  156234. bitstream sections that are truncated/woogie.
  156235. return: -1) error
  156236. 0) OK
  156237. */
  156238. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156239. ov_callbacks callbacks){
  156240. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156241. if(ret)return ret;
  156242. return _ov_open2(vf);
  156243. }
  156244. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156245. ov_callbacks callbacks = {
  156246. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156247. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156248. (int (*)(void *)) fclose,
  156249. (long (*)(void *)) ftell
  156250. };
  156251. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156252. }
  156253. /* cheap hack for game usage where downsampling is desirable; there's
  156254. no need for SRC as we can just do it cheaply in libvorbis. */
  156255. int ov_halfrate(OggVorbis_File *vf,int flag){
  156256. int i;
  156257. if(vf->vi==NULL)return OV_EINVAL;
  156258. if(!vf->seekable)return OV_EINVAL;
  156259. if(vf->ready_state>=STREAMSET)
  156260. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156261. will be able to swap this on the fly, but
  156262. for now dumping the decode machine is needed
  156263. to reinit the MDCT lookups. 1.1 libvorbis
  156264. is planned to be able to switch on the fly */
  156265. for(i=0;i<vf->links;i++){
  156266. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156267. ov_halfrate(vf,0);
  156268. return OV_EINVAL;
  156269. }
  156270. }
  156271. return 0;
  156272. }
  156273. int ov_halfrate_p(OggVorbis_File *vf){
  156274. if(vf->vi==NULL)return OV_EINVAL;
  156275. return vorbis_synthesis_halfrate_p(vf->vi);
  156276. }
  156277. /* Only partially open the vorbis file; test for Vorbisness, and load
  156278. the headers for the first chain. Do not seek (although test for
  156279. seekability). Use ov_test_open to finish opening the file, else
  156280. ov_clear to close/free it. Same return codes as open. */
  156281. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156282. ov_callbacks callbacks)
  156283. {
  156284. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156285. }
  156286. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156287. ov_callbacks callbacks = {
  156288. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156289. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156290. (int (*)(void *)) fclose,
  156291. (long (*)(void *)) ftell
  156292. };
  156293. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156294. }
  156295. int ov_test_open(OggVorbis_File *vf){
  156296. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156297. return _ov_open2(vf);
  156298. }
  156299. /* How many logical bitstreams in this physical bitstream? */
  156300. long ov_streams(OggVorbis_File *vf){
  156301. return vf->links;
  156302. }
  156303. /* Is the FILE * associated with vf seekable? */
  156304. long ov_seekable(OggVorbis_File *vf){
  156305. return vf->seekable;
  156306. }
  156307. /* returns the bitrate for a given logical bitstream or the entire
  156308. physical bitstream. If the file is open for random access, it will
  156309. find the *actual* average bitrate. If the file is streaming, it
  156310. returns the nominal bitrate (if set) else the average of the
  156311. upper/lower bounds (if set) else -1 (unset).
  156312. If you want the actual bitrate field settings, get them from the
  156313. vorbis_info structs */
  156314. long ov_bitrate(OggVorbis_File *vf,int i){
  156315. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156316. if(i>=vf->links)return(OV_EINVAL);
  156317. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156318. if(i<0){
  156319. ogg_int64_t bits=0;
  156320. int i;
  156321. float br;
  156322. for(i=0;i<vf->links;i++)
  156323. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156324. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156325. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156326. * so this is slightly transformed to make it work.
  156327. */
  156328. br = bits/ov_time_total(vf,-1);
  156329. return(rint(br));
  156330. }else{
  156331. if(vf->seekable){
  156332. /* return the actual bitrate */
  156333. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156334. }else{
  156335. /* return nominal if set */
  156336. if(vf->vi[i].bitrate_nominal>0){
  156337. return vf->vi[i].bitrate_nominal;
  156338. }else{
  156339. if(vf->vi[i].bitrate_upper>0){
  156340. if(vf->vi[i].bitrate_lower>0){
  156341. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156342. }else{
  156343. return vf->vi[i].bitrate_upper;
  156344. }
  156345. }
  156346. return(OV_FALSE);
  156347. }
  156348. }
  156349. }
  156350. }
  156351. /* returns the actual bitrate since last call. returns -1 if no
  156352. additional data to offer since last call (or at beginning of stream),
  156353. EINVAL if stream is only partially open
  156354. */
  156355. long ov_bitrate_instant(OggVorbis_File *vf){
  156356. int link=(vf->seekable?vf->current_link:0);
  156357. long ret;
  156358. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156359. if(vf->samptrack==0)return(OV_FALSE);
  156360. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156361. vf->bittrack=0.f;
  156362. vf->samptrack=0.f;
  156363. return(ret);
  156364. }
  156365. /* Guess */
  156366. long ov_serialnumber(OggVorbis_File *vf,int i){
  156367. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156368. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156369. if(i<0){
  156370. return(vf->current_serialno);
  156371. }else{
  156372. return(vf->serialnos[i]);
  156373. }
  156374. }
  156375. /* returns: total raw (compressed) length of content if i==-1
  156376. raw (compressed) length of that logical bitstream for i==0 to n
  156377. OV_EINVAL if the stream is not seekable (we can't know the length)
  156378. or if stream is only partially open
  156379. */
  156380. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156381. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156382. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156383. if(i<0){
  156384. ogg_int64_t acc=0;
  156385. int i;
  156386. for(i=0;i<vf->links;i++)
  156387. acc+=ov_raw_total(vf,i);
  156388. return(acc);
  156389. }else{
  156390. return(vf->offsets[i+1]-vf->offsets[i]);
  156391. }
  156392. }
  156393. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156394. (samples) of that logical bitstream for i==0 to n
  156395. OV_EINVAL if the stream is not seekable (we can't know the
  156396. length) or only partially open
  156397. */
  156398. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156399. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156400. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156401. if(i<0){
  156402. ogg_int64_t acc=0;
  156403. int i;
  156404. for(i=0;i<vf->links;i++)
  156405. acc+=ov_pcm_total(vf,i);
  156406. return(acc);
  156407. }else{
  156408. return(vf->pcmlengths[i*2+1]);
  156409. }
  156410. }
  156411. /* returns: total seconds of content if i==-1
  156412. seconds in that logical bitstream for i==0 to n
  156413. OV_EINVAL if the stream is not seekable (we can't know the
  156414. length) or only partially open
  156415. */
  156416. double ov_time_total(OggVorbis_File *vf,int i){
  156417. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156418. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156419. if(i<0){
  156420. double acc=0;
  156421. int i;
  156422. for(i=0;i<vf->links;i++)
  156423. acc+=ov_time_total(vf,i);
  156424. return(acc);
  156425. }else{
  156426. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156427. }
  156428. }
  156429. /* seek to an offset relative to the *compressed* data. This also
  156430. scans packets to update the PCM cursor. It will cross a logical
  156431. bitstream boundary, but only if it can't get any packets out of the
  156432. tail of the bitstream we seek to (so no surprises).
  156433. returns zero on success, nonzero on failure */
  156434. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156435. ogg_stream_state work_os;
  156436. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156437. if(!vf->seekable)
  156438. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156439. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156440. /* don't yet clear out decoding machine (if it's initialized), in
  156441. the case we're in the same link. Restart the decode lapping, and
  156442. let _fetch_and_process_packet deal with a potential bitstream
  156443. boundary */
  156444. vf->pcm_offset=-1;
  156445. ogg_stream_reset_serialno(&vf->os,
  156446. vf->current_serialno); /* must set serialno */
  156447. vorbis_synthesis_restart(&vf->vd);
  156448. _seek_helper(vf,pos);
  156449. /* we need to make sure the pcm_offset is set, but we don't want to
  156450. advance the raw cursor past good packets just to get to the first
  156451. with a granulepos. That's not equivalent behavior to beginning
  156452. decoding as immediately after the seek position as possible.
  156453. So, a hack. We use two stream states; a local scratch state and
  156454. the shared vf->os stream state. We use the local state to
  156455. scan, and the shared state as a buffer for later decode.
  156456. Unfortuantely, on the last page we still advance to last packet
  156457. because the granulepos on the last page is not necessarily on a
  156458. packet boundary, and we need to make sure the granpos is
  156459. correct.
  156460. */
  156461. {
  156462. ogg_page og;
  156463. ogg_packet op;
  156464. int lastblock=0;
  156465. int accblock=0;
  156466. int thisblock;
  156467. int eosflag;
  156468. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156469. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156470. return from not necessarily
  156471. starting from the beginning */
  156472. while(1){
  156473. if(vf->ready_state>=STREAMSET){
  156474. /* snarf/scan a packet if we can */
  156475. int result=ogg_stream_packetout(&work_os,&op);
  156476. if(result>0){
  156477. if(vf->vi[vf->current_link].codec_setup){
  156478. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156479. if(thisblock<0){
  156480. ogg_stream_packetout(&vf->os,NULL);
  156481. thisblock=0;
  156482. }else{
  156483. if(eosflag)
  156484. ogg_stream_packetout(&vf->os,NULL);
  156485. else
  156486. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156487. }
  156488. if(op.granulepos!=-1){
  156489. int i,link=vf->current_link;
  156490. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156491. if(granulepos<0)granulepos=0;
  156492. for(i=0;i<link;i++)
  156493. granulepos+=vf->pcmlengths[i*2+1];
  156494. vf->pcm_offset=granulepos-accblock;
  156495. break;
  156496. }
  156497. lastblock=thisblock;
  156498. continue;
  156499. }else
  156500. ogg_stream_packetout(&vf->os,NULL);
  156501. }
  156502. }
  156503. if(!lastblock){
  156504. if(_get_next_page(vf,&og,-1)<0){
  156505. vf->pcm_offset=ov_pcm_total(vf,-1);
  156506. break;
  156507. }
  156508. }else{
  156509. /* huh? Bogus stream with packets but no granulepos */
  156510. vf->pcm_offset=-1;
  156511. break;
  156512. }
  156513. /* has our decoding just traversed a bitstream boundary? */
  156514. if(vf->ready_state>=STREAMSET)
  156515. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156516. _decode_clear(vf); /* clear out stream state */
  156517. ogg_stream_clear(&work_os);
  156518. }
  156519. if(vf->ready_state<STREAMSET){
  156520. int link;
  156521. vf->current_serialno=ogg_page_serialno(&og);
  156522. for(link=0;link<vf->links;link++)
  156523. if(vf->serialnos[link]==vf->current_serialno)break;
  156524. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156525. error out, leave
  156526. machine uninitialized */
  156527. vf->current_link=link;
  156528. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156529. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156530. vf->ready_state=STREAMSET;
  156531. }
  156532. ogg_stream_pagein(&vf->os,&og);
  156533. ogg_stream_pagein(&work_os,&og);
  156534. eosflag=ogg_page_eos(&og);
  156535. }
  156536. }
  156537. ogg_stream_clear(&work_os);
  156538. vf->bittrack=0.f;
  156539. vf->samptrack=0.f;
  156540. return(0);
  156541. seek_error:
  156542. /* dump the machine so we're in a known state */
  156543. vf->pcm_offset=-1;
  156544. ogg_stream_clear(&work_os);
  156545. _decode_clear(vf);
  156546. return OV_EBADLINK;
  156547. }
  156548. /* Page granularity seek (faster than sample granularity because we
  156549. don't do the last bit of decode to find a specific sample).
  156550. Seek to the last [granule marked] page preceeding the specified pos
  156551. location, such that decoding past the returned point will quickly
  156552. arrive at the requested position. */
  156553. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156554. int link=-1;
  156555. ogg_int64_t result=0;
  156556. ogg_int64_t total=ov_pcm_total(vf,-1);
  156557. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156558. if(!vf->seekable)return(OV_ENOSEEK);
  156559. if(pos<0 || pos>total)return(OV_EINVAL);
  156560. /* which bitstream section does this pcm offset occur in? */
  156561. for(link=vf->links-1;link>=0;link--){
  156562. total-=vf->pcmlengths[link*2+1];
  156563. if(pos>=total)break;
  156564. }
  156565. /* search within the logical bitstream for the page with the highest
  156566. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156567. missing pages or incorrect frame number information in the
  156568. bitstream could make our task impossible. Account for that (it
  156569. would be an error condition) */
  156570. /* new search algorithm by HB (Nicholas Vinen) */
  156571. {
  156572. ogg_int64_t end=vf->offsets[link+1];
  156573. ogg_int64_t begin=vf->offsets[link];
  156574. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156575. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156576. ogg_int64_t target=pos-total+begintime;
  156577. ogg_int64_t best=begin;
  156578. ogg_page og;
  156579. while(begin<end){
  156580. ogg_int64_t bisect;
  156581. if(end-begin<CHUNKSIZE){
  156582. bisect=begin;
  156583. }else{
  156584. /* take a (pretty decent) guess. */
  156585. bisect=begin +
  156586. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156587. if(bisect<=begin)
  156588. bisect=begin+1;
  156589. }
  156590. _seek_helper(vf,bisect);
  156591. while(begin<end){
  156592. result=_get_next_page(vf,&og,end-vf->offset);
  156593. if(result==OV_EREAD) goto seek_error;
  156594. if(result<0){
  156595. if(bisect<=begin+1)
  156596. end=begin; /* found it */
  156597. else{
  156598. if(bisect==0) goto seek_error;
  156599. bisect-=CHUNKSIZE;
  156600. if(bisect<=begin)bisect=begin+1;
  156601. _seek_helper(vf,bisect);
  156602. }
  156603. }else{
  156604. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156605. if(granulepos==-1)continue;
  156606. if(granulepos<target){
  156607. best=result; /* raw offset of packet with granulepos */
  156608. begin=vf->offset; /* raw offset of next page */
  156609. begintime=granulepos;
  156610. if(target-begintime>44100)break;
  156611. bisect=begin; /* *not* begin + 1 */
  156612. }else{
  156613. if(bisect<=begin+1)
  156614. end=begin; /* found it */
  156615. else{
  156616. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156617. end=result;
  156618. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156619. if(bisect<=begin)bisect=begin+1;
  156620. _seek_helper(vf,bisect);
  156621. }else{
  156622. end=result;
  156623. endtime=granulepos;
  156624. break;
  156625. }
  156626. }
  156627. }
  156628. }
  156629. }
  156630. }
  156631. /* found our page. seek to it, update pcm offset. Easier case than
  156632. raw_seek, don't keep packets preceeding granulepos. */
  156633. {
  156634. ogg_page og;
  156635. ogg_packet op;
  156636. /* seek */
  156637. _seek_helper(vf,best);
  156638. vf->pcm_offset=-1;
  156639. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156640. if(link!=vf->current_link){
  156641. /* Different link; dump entire decode machine */
  156642. _decode_clear(vf);
  156643. vf->current_link=link;
  156644. vf->current_serialno=ogg_page_serialno(&og);
  156645. vf->ready_state=STREAMSET;
  156646. }else{
  156647. vorbis_synthesis_restart(&vf->vd);
  156648. }
  156649. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156650. ogg_stream_pagein(&vf->os,&og);
  156651. /* pull out all but last packet; the one with granulepos */
  156652. while(1){
  156653. result=ogg_stream_packetpeek(&vf->os,&op);
  156654. if(result==0){
  156655. /* !!! the packet finishing this page originated on a
  156656. preceeding page. Keep fetching previous pages until we
  156657. get one with a granulepos or without the 'continued' flag
  156658. set. Then just use raw_seek for simplicity. */
  156659. _seek_helper(vf,best);
  156660. while(1){
  156661. result=_get_prev_page(vf,&og);
  156662. if(result<0) goto seek_error;
  156663. if(ogg_page_granulepos(&og)>-1 ||
  156664. !ogg_page_continued(&og)){
  156665. return ov_raw_seek(vf,result);
  156666. }
  156667. vf->offset=result;
  156668. }
  156669. }
  156670. if(result<0){
  156671. result = OV_EBADPACKET;
  156672. goto seek_error;
  156673. }
  156674. if(op.granulepos!=-1){
  156675. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156676. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156677. vf->pcm_offset+=total;
  156678. break;
  156679. }else
  156680. result=ogg_stream_packetout(&vf->os,NULL);
  156681. }
  156682. }
  156683. }
  156684. /* verify result */
  156685. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156686. result=OV_EFAULT;
  156687. goto seek_error;
  156688. }
  156689. vf->bittrack=0.f;
  156690. vf->samptrack=0.f;
  156691. return(0);
  156692. seek_error:
  156693. /* dump machine so we're in a known state */
  156694. vf->pcm_offset=-1;
  156695. _decode_clear(vf);
  156696. return (int)result;
  156697. }
  156698. /* seek to a sample offset relative to the decompressed pcm stream
  156699. returns zero on success, nonzero on failure */
  156700. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156701. int thisblock,lastblock=0;
  156702. int ret=ov_pcm_seek_page(vf,pos);
  156703. if(ret<0)return(ret);
  156704. if((ret=_make_decode_ready(vf)))return ret;
  156705. /* discard leading packets we don't need for the lapping of the
  156706. position we want; don't decode them */
  156707. while(1){
  156708. ogg_packet op;
  156709. ogg_page og;
  156710. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156711. if(ret>0){
  156712. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156713. if(thisblock<0){
  156714. ogg_stream_packetout(&vf->os,NULL);
  156715. continue; /* non audio packet */
  156716. }
  156717. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156718. if(vf->pcm_offset+((thisblock+
  156719. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156720. /* remove the packet from packet queue and track its granulepos */
  156721. ogg_stream_packetout(&vf->os,NULL);
  156722. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156723. only tracking, no
  156724. pcm_decode */
  156725. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156726. /* end of logical stream case is hard, especially with exact
  156727. length positioning. */
  156728. if(op.granulepos>-1){
  156729. int i;
  156730. /* always believe the stream markers */
  156731. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156732. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156733. for(i=0;i<vf->current_link;i++)
  156734. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156735. }
  156736. lastblock=thisblock;
  156737. }else{
  156738. if(ret<0 && ret!=OV_HOLE)break;
  156739. /* suck in a new page */
  156740. if(_get_next_page(vf,&og,-1)<0)break;
  156741. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156742. if(vf->ready_state<STREAMSET){
  156743. int link;
  156744. vf->current_serialno=ogg_page_serialno(&og);
  156745. for(link=0;link<vf->links;link++)
  156746. if(vf->serialnos[link]==vf->current_serialno)break;
  156747. if(link==vf->links)return(OV_EBADLINK);
  156748. vf->current_link=link;
  156749. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156750. vf->ready_state=STREAMSET;
  156751. ret=_make_decode_ready(vf);
  156752. if(ret)return ret;
  156753. lastblock=0;
  156754. }
  156755. ogg_stream_pagein(&vf->os,&og);
  156756. }
  156757. }
  156758. vf->bittrack=0.f;
  156759. vf->samptrack=0.f;
  156760. /* discard samples until we reach the desired position. Crossing a
  156761. logical bitstream boundary with abandon is OK. */
  156762. while(vf->pcm_offset<pos){
  156763. ogg_int64_t target=pos-vf->pcm_offset;
  156764. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156765. if(samples>target)samples=target;
  156766. vorbis_synthesis_read(&vf->vd,samples);
  156767. vf->pcm_offset+=samples;
  156768. if(samples<target)
  156769. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156770. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156771. }
  156772. return 0;
  156773. }
  156774. /* seek to a playback time relative to the decompressed pcm stream
  156775. returns zero on success, nonzero on failure */
  156776. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156777. /* translate time to PCM position and call ov_pcm_seek */
  156778. int link=-1;
  156779. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156780. double time_total=ov_time_total(vf,-1);
  156781. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156782. if(!vf->seekable)return(OV_ENOSEEK);
  156783. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156784. /* which bitstream section does this time offset occur in? */
  156785. for(link=vf->links-1;link>=0;link--){
  156786. pcm_total-=vf->pcmlengths[link*2+1];
  156787. time_total-=ov_time_total(vf,link);
  156788. if(seconds>=time_total)break;
  156789. }
  156790. /* enough information to convert time offset to pcm offset */
  156791. {
  156792. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156793. return(ov_pcm_seek(vf,target));
  156794. }
  156795. }
  156796. /* page-granularity version of ov_time_seek
  156797. returns zero on success, nonzero on failure */
  156798. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156799. /* translate time to PCM position and call ov_pcm_seek */
  156800. int link=-1;
  156801. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156802. double time_total=ov_time_total(vf,-1);
  156803. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156804. if(!vf->seekable)return(OV_ENOSEEK);
  156805. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156806. /* which bitstream section does this time offset occur in? */
  156807. for(link=vf->links-1;link>=0;link--){
  156808. pcm_total-=vf->pcmlengths[link*2+1];
  156809. time_total-=ov_time_total(vf,link);
  156810. if(seconds>=time_total)break;
  156811. }
  156812. /* enough information to convert time offset to pcm offset */
  156813. {
  156814. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156815. return(ov_pcm_seek_page(vf,target));
  156816. }
  156817. }
  156818. /* tell the current stream offset cursor. Note that seek followed by
  156819. tell will likely not give the set offset due to caching */
  156820. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156821. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156822. return(vf->offset);
  156823. }
  156824. /* return PCM offset (sample) of next PCM sample to be read */
  156825. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156826. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156827. return(vf->pcm_offset);
  156828. }
  156829. /* return time offset (seconds) of next PCM sample to be read */
  156830. double ov_time_tell(OggVorbis_File *vf){
  156831. int link=0;
  156832. ogg_int64_t pcm_total=0;
  156833. double time_total=0.f;
  156834. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156835. if(vf->seekable){
  156836. pcm_total=ov_pcm_total(vf,-1);
  156837. time_total=ov_time_total(vf,-1);
  156838. /* which bitstream section does this time offset occur in? */
  156839. for(link=vf->links-1;link>=0;link--){
  156840. pcm_total-=vf->pcmlengths[link*2+1];
  156841. time_total-=ov_time_total(vf,link);
  156842. if(vf->pcm_offset>=pcm_total)break;
  156843. }
  156844. }
  156845. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156846. }
  156847. /* link: -1) return the vorbis_info struct for the bitstream section
  156848. currently being decoded
  156849. 0-n) to request information for a specific bitstream section
  156850. In the case of a non-seekable bitstream, any call returns the
  156851. current bitstream. NULL in the case that the machine is not
  156852. initialized */
  156853. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156854. if(vf->seekable){
  156855. if(link<0)
  156856. if(vf->ready_state>=STREAMSET)
  156857. return vf->vi+vf->current_link;
  156858. else
  156859. return vf->vi;
  156860. else
  156861. if(link>=vf->links)
  156862. return NULL;
  156863. else
  156864. return vf->vi+link;
  156865. }else{
  156866. return vf->vi;
  156867. }
  156868. }
  156869. /* grr, strong typing, grr, no templates/inheritence, grr */
  156870. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156871. if(vf->seekable){
  156872. if(link<0)
  156873. if(vf->ready_state>=STREAMSET)
  156874. return vf->vc+vf->current_link;
  156875. else
  156876. return vf->vc;
  156877. else
  156878. if(link>=vf->links)
  156879. return NULL;
  156880. else
  156881. return vf->vc+link;
  156882. }else{
  156883. return vf->vc;
  156884. }
  156885. }
  156886. static int host_is_big_endian() {
  156887. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156888. unsigned char *bytewise = (unsigned char *)&pattern;
  156889. if (bytewise[0] == 0xfe) return 1;
  156890. return 0;
  156891. }
  156892. /* up to this point, everything could more or less hide the multiple
  156893. logical bitstream nature of chaining from the toplevel application
  156894. if the toplevel application didn't particularly care. However, at
  156895. the point that we actually read audio back, the multiple-section
  156896. nature must surface: Multiple bitstream sections do not necessarily
  156897. have to have the same number of channels or sampling rate.
  156898. ov_read returns the sequential logical bitstream number currently
  156899. being decoded along with the PCM data in order that the toplevel
  156900. application can take action on channel/sample rate changes. This
  156901. number will be incremented even for streamed (non-seekable) streams
  156902. (for seekable streams, it represents the actual logical bitstream
  156903. index within the physical bitstream. Note that the accessor
  156904. functions above are aware of this dichotomy).
  156905. input values: buffer) a buffer to hold packed PCM data for return
  156906. length) the byte length requested to be placed into buffer
  156907. bigendianp) should the data be packed LSB first (0) or
  156908. MSB first (1)
  156909. word) word size for output. currently 1 (byte) or
  156910. 2 (16 bit short)
  156911. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156912. 0) EOF
  156913. n) number of bytes of PCM actually returned. The
  156914. below works on a packet-by-packet basis, so the
  156915. return length is not related to the 'length' passed
  156916. in, just guaranteed to fit.
  156917. *section) set to the logical bitstream number */
  156918. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156919. int bigendianp,int word,int sgned,int *bitstream){
  156920. int i,j;
  156921. int host_endian = host_is_big_endian();
  156922. float **pcm;
  156923. long samples;
  156924. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156925. while(1){
  156926. if(vf->ready_state==INITSET){
  156927. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156928. if(samples)break;
  156929. }
  156930. /* suck in another packet */
  156931. {
  156932. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156933. if(ret==OV_EOF)
  156934. return(0);
  156935. if(ret<=0)
  156936. return(ret);
  156937. }
  156938. }
  156939. if(samples>0){
  156940. /* yay! proceed to pack data into the byte buffer */
  156941. long channels=ov_info(vf,-1)->channels;
  156942. long bytespersample=word * channels;
  156943. vorbis_fpu_control fpu;
  156944. (void) fpu; // (to avoid a warning about it being unused)
  156945. if(samples>length/bytespersample)samples=length/bytespersample;
  156946. if(samples <= 0)
  156947. return OV_EINVAL;
  156948. /* a tight loop to pack each size */
  156949. {
  156950. int val;
  156951. if(word==1){
  156952. int off=(sgned?0:128);
  156953. vorbis_fpu_setround(&fpu);
  156954. for(j=0;j<samples;j++)
  156955. for(i=0;i<channels;i++){
  156956. val=vorbis_ftoi(pcm[i][j]*128.f);
  156957. if(val>127)val=127;
  156958. else if(val<-128)val=-128;
  156959. *buffer++=val+off;
  156960. }
  156961. vorbis_fpu_restore(fpu);
  156962. }else{
  156963. int off=(sgned?0:32768);
  156964. if(host_endian==bigendianp){
  156965. if(sgned){
  156966. vorbis_fpu_setround(&fpu);
  156967. for(i=0;i<channels;i++) { /* It's faster in this order */
  156968. float *src=pcm[i];
  156969. short *dest=((short *)buffer)+i;
  156970. for(j=0;j<samples;j++) {
  156971. val=vorbis_ftoi(src[j]*32768.f);
  156972. if(val>32767)val=32767;
  156973. else if(val<-32768)val=-32768;
  156974. *dest=val;
  156975. dest+=channels;
  156976. }
  156977. }
  156978. vorbis_fpu_restore(fpu);
  156979. }else{
  156980. vorbis_fpu_setround(&fpu);
  156981. for(i=0;i<channels;i++) {
  156982. float *src=pcm[i];
  156983. short *dest=((short *)buffer)+i;
  156984. for(j=0;j<samples;j++) {
  156985. val=vorbis_ftoi(src[j]*32768.f);
  156986. if(val>32767)val=32767;
  156987. else if(val<-32768)val=-32768;
  156988. *dest=val+off;
  156989. dest+=channels;
  156990. }
  156991. }
  156992. vorbis_fpu_restore(fpu);
  156993. }
  156994. }else if(bigendianp){
  156995. vorbis_fpu_setround(&fpu);
  156996. for(j=0;j<samples;j++)
  156997. for(i=0;i<channels;i++){
  156998. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156999. if(val>32767)val=32767;
  157000. else if(val<-32768)val=-32768;
  157001. val+=off;
  157002. *buffer++=(val>>8);
  157003. *buffer++=(val&0xff);
  157004. }
  157005. vorbis_fpu_restore(fpu);
  157006. }else{
  157007. int val;
  157008. vorbis_fpu_setround(&fpu);
  157009. for(j=0;j<samples;j++)
  157010. for(i=0;i<channels;i++){
  157011. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157012. if(val>32767)val=32767;
  157013. else if(val<-32768)val=-32768;
  157014. val+=off;
  157015. *buffer++=(val&0xff);
  157016. *buffer++=(val>>8);
  157017. }
  157018. vorbis_fpu_restore(fpu);
  157019. }
  157020. }
  157021. }
  157022. vorbis_synthesis_read(&vf->vd,samples);
  157023. vf->pcm_offset+=samples;
  157024. if(bitstream)*bitstream=vf->current_link;
  157025. return(samples*bytespersample);
  157026. }else{
  157027. return(samples);
  157028. }
  157029. }
  157030. /* input values: pcm_channels) a float vector per channel of output
  157031. length) the sample length being read by the app
  157032. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  157033. 0) EOF
  157034. n) number of samples of PCM actually returned. The
  157035. below works on a packet-by-packet basis, so the
  157036. return length is not related to the 'length' passed
  157037. in, just guaranteed to fit.
  157038. *section) set to the logical bitstream number */
  157039. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  157040. int *bitstream){
  157041. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157042. while(1){
  157043. if(vf->ready_state==INITSET){
  157044. float **pcm;
  157045. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157046. if(samples){
  157047. if(pcm_channels)*pcm_channels=pcm;
  157048. if(samples>length)samples=length;
  157049. vorbis_synthesis_read(&vf->vd,samples);
  157050. vf->pcm_offset+=samples;
  157051. if(bitstream)*bitstream=vf->current_link;
  157052. return samples;
  157053. }
  157054. }
  157055. /* suck in another packet */
  157056. {
  157057. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157058. if(ret==OV_EOF)return(0);
  157059. if(ret<=0)return(ret);
  157060. }
  157061. }
  157062. }
  157063. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  157064. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  157065. ogg_int64_t off);
  157066. static void _ov_splice(float **pcm,float **lappcm,
  157067. int n1, int n2,
  157068. int ch1, int ch2,
  157069. float *w1, float *w2){
  157070. int i,j;
  157071. float *w=w1;
  157072. int n=n1;
  157073. if(n1>n2){
  157074. n=n2;
  157075. w=w2;
  157076. }
  157077. /* splice */
  157078. for(j=0;j<ch1 && j<ch2;j++){
  157079. float *s=lappcm[j];
  157080. float *d=pcm[j];
  157081. for(i=0;i<n;i++){
  157082. float wd=w[i]*w[i];
  157083. float ws=1.-wd;
  157084. d[i]=d[i]*wd + s[i]*ws;
  157085. }
  157086. }
  157087. /* window from zero */
  157088. for(;j<ch2;j++){
  157089. float *d=pcm[j];
  157090. for(i=0;i<n;i++){
  157091. float wd=w[i]*w[i];
  157092. d[i]=d[i]*wd;
  157093. }
  157094. }
  157095. }
  157096. /* make sure vf is INITSET */
  157097. static int _ov_initset(OggVorbis_File *vf){
  157098. while(1){
  157099. if(vf->ready_state==INITSET)break;
  157100. /* suck in another packet */
  157101. {
  157102. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157103. if(ret<0 && ret!=OV_HOLE)return(ret);
  157104. }
  157105. }
  157106. return 0;
  157107. }
  157108. /* make sure vf is INITSET and that we have a primed buffer; if
  157109. we're crosslapping at a stream section boundary, this also makes
  157110. sure we're sanity checking against the right stream information */
  157111. static int _ov_initprime(OggVorbis_File *vf){
  157112. vorbis_dsp_state *vd=&vf->vd;
  157113. while(1){
  157114. if(vf->ready_state==INITSET)
  157115. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157116. /* suck in another packet */
  157117. {
  157118. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157119. if(ret<0 && ret!=OV_HOLE)return(ret);
  157120. }
  157121. }
  157122. return 0;
  157123. }
  157124. /* grab enough data for lapping from vf; this may be in the form of
  157125. unreturned, already-decoded pcm, remaining PCM we will need to
  157126. decode, or synthetic postextrapolation from last packets. */
  157127. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157128. float **lappcm,int lapsize){
  157129. int lapcount=0,i;
  157130. float **pcm;
  157131. /* try first to decode the lapping data */
  157132. while(lapcount<lapsize){
  157133. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157134. if(samples){
  157135. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157136. for(i=0;i<vi->channels;i++)
  157137. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157138. lapcount+=samples;
  157139. vorbis_synthesis_read(vd,samples);
  157140. }else{
  157141. /* suck in another packet */
  157142. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157143. if(ret==OV_EOF)break;
  157144. }
  157145. }
  157146. if(lapcount<lapsize){
  157147. /* failed to get lapping data from normal decode; pry it from the
  157148. postextrapolation buffering, or the second half of the MDCT
  157149. from the last packet */
  157150. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157151. if(samples==0){
  157152. for(i=0;i<vi->channels;i++)
  157153. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157154. lapcount=lapsize;
  157155. }else{
  157156. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157157. for(i=0;i<vi->channels;i++)
  157158. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157159. lapcount+=samples;
  157160. }
  157161. }
  157162. }
  157163. /* this sets up crosslapping of a sample by using trailing data from
  157164. sample 1 and lapping it into the windowing buffer of sample 2 */
  157165. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157166. vorbis_info *vi1,*vi2;
  157167. float **lappcm;
  157168. float **pcm;
  157169. float *w1,*w2;
  157170. int n1,n2,i,ret,hs1,hs2;
  157171. if(vf1==vf2)return(0); /* degenerate case */
  157172. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157173. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157174. /* the relevant overlap buffers must be pre-checked and pre-primed
  157175. before looking at settings in the event that priming would cross
  157176. a bitstream boundary. So, do it now */
  157177. ret=_ov_initset(vf1);
  157178. if(ret)return(ret);
  157179. ret=_ov_initprime(vf2);
  157180. if(ret)return(ret);
  157181. vi1=ov_info(vf1,-1);
  157182. vi2=ov_info(vf2,-1);
  157183. hs1=ov_halfrate_p(vf1);
  157184. hs2=ov_halfrate_p(vf2);
  157185. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157186. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157187. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157188. w1=vorbis_window(&vf1->vd,0);
  157189. w2=vorbis_window(&vf2->vd,0);
  157190. for(i=0;i<vi1->channels;i++)
  157191. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157192. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157193. /* have a lapping buffer from vf1; now to splice it into the lapping
  157194. buffer of vf2 */
  157195. /* consolidate and expose the buffer. */
  157196. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157197. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157198. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157199. /* splice */
  157200. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157201. /* done */
  157202. return(0);
  157203. }
  157204. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157205. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157206. vorbis_info *vi;
  157207. float **lappcm;
  157208. float **pcm;
  157209. float *w1,*w2;
  157210. int n1,n2,ch1,ch2,hs;
  157211. int i,ret;
  157212. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157213. ret=_ov_initset(vf);
  157214. if(ret)return(ret);
  157215. vi=ov_info(vf,-1);
  157216. hs=ov_halfrate_p(vf);
  157217. ch1=vi->channels;
  157218. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157219. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157220. persistent; even if the decode state
  157221. from this link gets dumped, this
  157222. window array continues to exist */
  157223. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157224. for(i=0;i<ch1;i++)
  157225. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157226. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157227. /* have lapping data; seek and prime the buffer */
  157228. ret=localseek(vf,pos);
  157229. if(ret)return ret;
  157230. ret=_ov_initprime(vf);
  157231. if(ret)return(ret);
  157232. /* Guard against cross-link changes; they're perfectly legal */
  157233. vi=ov_info(vf,-1);
  157234. ch2=vi->channels;
  157235. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157236. w2=vorbis_window(&vf->vd,0);
  157237. /* consolidate and expose the buffer. */
  157238. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157239. /* splice */
  157240. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157241. /* done */
  157242. return(0);
  157243. }
  157244. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157245. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157246. }
  157247. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157248. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157249. }
  157250. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157251. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157252. }
  157253. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157254. int (*localseek)(OggVorbis_File *,double)){
  157255. vorbis_info *vi;
  157256. float **lappcm;
  157257. float **pcm;
  157258. float *w1,*w2;
  157259. int n1,n2,ch1,ch2,hs;
  157260. int i,ret;
  157261. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157262. ret=_ov_initset(vf);
  157263. if(ret)return(ret);
  157264. vi=ov_info(vf,-1);
  157265. hs=ov_halfrate_p(vf);
  157266. ch1=vi->channels;
  157267. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157268. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157269. persistent; even if the decode state
  157270. from this link gets dumped, this
  157271. window array continues to exist */
  157272. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157273. for(i=0;i<ch1;i++)
  157274. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157275. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157276. /* have lapping data; seek and prime the buffer */
  157277. ret=localseek(vf,pos);
  157278. if(ret)return ret;
  157279. ret=_ov_initprime(vf);
  157280. if(ret)return(ret);
  157281. /* Guard against cross-link changes; they're perfectly legal */
  157282. vi=ov_info(vf,-1);
  157283. ch2=vi->channels;
  157284. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157285. w2=vorbis_window(&vf->vd,0);
  157286. /* consolidate and expose the buffer. */
  157287. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157288. /* splice */
  157289. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157290. /* done */
  157291. return(0);
  157292. }
  157293. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157294. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157295. }
  157296. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157297. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157298. }
  157299. #endif
  157300. /*** End of inlined file: vorbisfile.c ***/
  157301. /*** Start of inlined file: window.c ***/
  157302. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157303. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157304. // tasks..
  157305. #if JUCE_MSVC
  157306. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157307. #endif
  157308. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157309. #if JUCE_USE_OGGVORBIS
  157310. #include <stdlib.h>
  157311. #include <math.h>
  157312. static float vwin64[32] = {
  157313. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157314. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157315. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157316. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157317. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157318. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157319. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157320. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157321. };
  157322. static float vwin128[64] = {
  157323. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157324. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157325. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157326. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157327. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157328. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157329. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157330. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157331. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157332. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157333. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157334. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157335. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157336. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157337. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157338. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157339. };
  157340. static float vwin256[128] = {
  157341. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157342. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157343. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157344. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157345. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157346. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157347. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157348. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157349. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157350. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157351. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157352. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157353. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157354. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157355. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157356. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157357. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157358. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157359. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157360. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157361. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157362. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157363. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157364. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157365. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157366. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157367. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157368. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157369. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157370. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157371. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157372. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157373. };
  157374. static float vwin512[256] = {
  157375. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157376. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157377. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157378. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157379. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157380. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157381. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157382. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157383. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157384. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157385. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157386. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157387. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157388. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157389. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157390. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157391. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157392. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157393. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157394. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157395. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157396. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157397. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157398. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157399. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157400. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157401. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157402. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157403. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157404. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157405. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157406. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157407. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157408. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157409. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157410. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157411. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157412. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157413. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157414. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157415. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157416. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157417. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157418. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157419. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157420. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157421. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157422. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157423. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157424. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157425. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157426. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157427. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157428. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157429. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157430. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157431. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157432. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157433. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157434. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157435. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157436. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157437. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157438. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157439. };
  157440. static float vwin1024[512] = {
  157441. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157442. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157443. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157444. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157445. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157446. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157447. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157448. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157449. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157450. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157451. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157452. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157453. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157454. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157455. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157456. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157457. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157458. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157459. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157460. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157461. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157462. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157463. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157464. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157465. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157466. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157467. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157468. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157469. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157470. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157471. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157472. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157473. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157474. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157475. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157476. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157477. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157478. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157479. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157480. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157481. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157482. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157483. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157484. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157485. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157486. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157487. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157488. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157489. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157490. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157491. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157492. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157493. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157494. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157495. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157496. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157497. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157498. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157499. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157500. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157501. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157502. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157503. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157504. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157505. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157506. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157507. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157508. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157509. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157510. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157511. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157512. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157513. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157514. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157515. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157516. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157517. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157518. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157519. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157520. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157521. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157522. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157523. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157524. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157525. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157526. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157527. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157528. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157529. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157530. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157531. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157532. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157533. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157534. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157535. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157536. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157537. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157538. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157539. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157540. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157541. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157542. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157543. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157544. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157545. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157546. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157547. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157548. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157549. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157550. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157551. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157552. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157553. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157554. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157555. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157556. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157557. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157558. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157559. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157560. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157561. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157562. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157563. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157564. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157565. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157566. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157567. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157568. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157569. };
  157570. static float vwin2048[1024] = {
  157571. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157572. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157573. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157574. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157575. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157576. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157577. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157578. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157579. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157580. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157581. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157582. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157583. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157584. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157585. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157586. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157587. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157588. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157589. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157590. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157591. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157592. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157593. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157594. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157595. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157596. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157597. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157598. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157599. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157600. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157601. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157602. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157603. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157604. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157605. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157606. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157607. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157608. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157609. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157610. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157611. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157612. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157613. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157614. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157615. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157616. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157617. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157618. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157619. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157620. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157621. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157622. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157623. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157624. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157625. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157626. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157627. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157628. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157629. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157630. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157631. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157632. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157633. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157634. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157635. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157636. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157637. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157638. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157639. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157640. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157641. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157642. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157643. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157644. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157645. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157646. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157647. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157648. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157649. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157650. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157651. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157652. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157653. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157654. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157655. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157656. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157657. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157658. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157659. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157660. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157661. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157662. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157663. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157664. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157665. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157666. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157667. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157668. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157669. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157670. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157671. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157672. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157673. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157674. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157675. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157676. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157677. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157678. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157679. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157680. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157681. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157682. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157683. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157684. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157685. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157686. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157687. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157688. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157689. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157690. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157691. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157692. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157693. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157694. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157695. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157696. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157697. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157698. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157699. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157700. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157701. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157702. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157703. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157704. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157705. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157706. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157707. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157708. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157709. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157710. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157711. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157712. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157713. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157714. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157715. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157716. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157717. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157718. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157719. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157720. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157721. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157722. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157723. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157724. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157725. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157726. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157727. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157728. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157729. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157730. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157731. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157732. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157733. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157734. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157735. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157736. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157737. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157738. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157739. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157740. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157741. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157742. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157743. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157744. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157745. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157746. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157747. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157748. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157749. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157750. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157751. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157752. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157753. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157754. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157755. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157756. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157757. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157758. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157759. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157760. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157761. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157762. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157763. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157764. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157765. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157766. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157767. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157768. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157769. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157770. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157771. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157772. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157773. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157774. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157775. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157776. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157777. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157778. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157779. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157780. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157781. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157782. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157783. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157784. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157785. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157786. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157787. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157788. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157789. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157790. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157791. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157792. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157793. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157794. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157795. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157796. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157797. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157798. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157799. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157800. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157801. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157802. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157803. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157804. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157805. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157806. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157807. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157808. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157809. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157810. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157811. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157812. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157813. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157814. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157815. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157816. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157817. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157818. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157819. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157820. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157821. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157822. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157823. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157824. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157825. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157826. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157827. };
  157828. static float vwin4096[2048] = {
  157829. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157830. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157831. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157832. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157833. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157834. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157835. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157836. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157837. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157838. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157839. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157840. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157841. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157842. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157843. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157844. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157845. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157846. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157847. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157848. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157849. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157850. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157851. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157852. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157853. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157854. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157855. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157856. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157857. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157858. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157859. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157860. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157861. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157862. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157863. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157864. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157865. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157866. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157867. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157868. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157869. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157870. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157871. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157872. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157873. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157874. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157875. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157876. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157877. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157878. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157879. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157880. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157881. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157882. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157883. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157884. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157885. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157886. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157887. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157888. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157889. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157890. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157891. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157892. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157893. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157894. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157895. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157896. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157897. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157898. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157899. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157900. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157901. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157902. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157903. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157904. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157905. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157906. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157907. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157908. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157909. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157910. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157911. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157912. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157913. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157914. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157915. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157916. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157917. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157918. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157919. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157920. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157921. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157922. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157923. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157924. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157925. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157926. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157927. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157928. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157929. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157930. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157931. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157932. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157933. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157934. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157935. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157936. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157937. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157938. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157939. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157940. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157941. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157942. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157943. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157944. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157945. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157946. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157947. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157948. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157949. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157950. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157951. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157952. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157953. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157954. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157955. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157956. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157957. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157958. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157959. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157960. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157961. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157962. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157963. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157964. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157965. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157966. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157967. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157968. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157969. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157970. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157971. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157972. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157973. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157974. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157975. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157976. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157977. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157978. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157979. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157980. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157981. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157982. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157983. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157984. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157985. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157986. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157987. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157988. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157989. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157990. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157991. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157992. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157993. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157994. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157995. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157996. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157997. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157998. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157999. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  158000. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  158001. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  158002. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  158003. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  158004. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  158005. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  158006. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  158007. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  158008. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  158009. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  158010. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  158011. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  158012. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  158013. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  158014. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  158015. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  158016. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  158017. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  158018. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  158019. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  158020. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  158021. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  158022. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  158023. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  158024. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  158025. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  158026. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  158027. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  158028. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  158029. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  158030. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  158031. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  158032. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  158033. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  158034. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  158035. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  158036. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  158037. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  158038. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  158039. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  158040. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  158041. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  158042. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  158043. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  158044. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  158045. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  158046. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  158047. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  158048. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  158049. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  158050. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  158051. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  158052. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  158053. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  158054. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  158055. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  158056. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  158057. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  158058. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  158059. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  158060. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  158061. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  158062. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  158063. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  158064. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  158065. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  158066. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  158067. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  158068. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  158069. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  158070. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  158071. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  158072. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  158073. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  158074. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  158075. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  158076. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  158077. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  158078. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  158079. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  158080. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  158081. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  158082. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  158083. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  158084. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  158085. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  158086. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  158087. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  158088. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  158089. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  158090. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  158091. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  158092. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  158093. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  158094. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  158095. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  158096. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  158097. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  158098. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  158099. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  158100. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  158101. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  158102. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  158103. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  158104. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  158105. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158106. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158107. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158108. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158109. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158110. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158111. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158112. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158113. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158114. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158115. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158116. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158117. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158118. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158119. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158120. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158121. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158122. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158123. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158124. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158125. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158126. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158127. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158128. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158129. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158130. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158131. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158132. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158133. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158134. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158135. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158136. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158137. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158138. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158139. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158140. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158141. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158142. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158143. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158144. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158145. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158146. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158147. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158148. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158149. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158150. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158151. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158152. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158153. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158154. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158155. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158156. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158157. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158158. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158159. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158160. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158161. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158162. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158163. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158164. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158165. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158166. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158167. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158168. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158169. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158170. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158171. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158172. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158173. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158174. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158175. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158176. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158177. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158178. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158179. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158180. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158181. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158182. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158183. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158184. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158185. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158186. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158187. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158188. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158189. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158190. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158191. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158192. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158193. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158194. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158195. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158196. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158197. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158198. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158199. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158200. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158201. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158202. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158203. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158204. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158205. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158206. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158207. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158208. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158209. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158210. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158211. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158212. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158213. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158214. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158215. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158216. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158217. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158218. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158219. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158220. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158221. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158222. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158223. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158224. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158225. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158226. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158227. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158228. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158229. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158230. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158231. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158232. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158233. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158234. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158235. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158236. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158237. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158238. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158239. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158240. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158241. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158242. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158243. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158244. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158245. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158246. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158247. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158248. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158249. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158250. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158251. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158252. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158253. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158254. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158255. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158256. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158257. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158258. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158259. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158260. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158261. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158262. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158263. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158264. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158265. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158266. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158267. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158268. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158269. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158270. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158271. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158272. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158273. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158274. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158275. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158276. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158277. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158278. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158279. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158280. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158281. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158282. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158283. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158284. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158285. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158286. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158287. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158288. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158289. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158290. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158291. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158292. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158293. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158294. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158295. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158296. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158297. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158298. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158299. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158300. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158301. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158302. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158303. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158304. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158305. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158306. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158307. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158308. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158309. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158310. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158311. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158312. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158313. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158314. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158315. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158316. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158317. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158318. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158319. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158320. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158321. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158322. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158323. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158324. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158325. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158326. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158327. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158328. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158329. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158330. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158331. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158332. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158333. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158334. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158335. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158336. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158337. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158338. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158339. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158340. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158341. };
  158342. static float vwin8192[4096] = {
  158343. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158344. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158345. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158346. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158347. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158348. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158349. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158350. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158351. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158352. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158353. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158354. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158355. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158356. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158357. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158358. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158359. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158360. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158361. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158362. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158363. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158364. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158365. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158366. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158367. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158368. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158369. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158370. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158371. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158372. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158373. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158374. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158375. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158376. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158377. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158378. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158379. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158380. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158381. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158382. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158383. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158384. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158385. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158386. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158387. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158388. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158389. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158390. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158391. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158392. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158393. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158394. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158395. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158396. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158397. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158398. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158399. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158400. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158401. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158402. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158403. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158404. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158405. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158406. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158407. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158408. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158409. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158410. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158411. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158412. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158413. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158414. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158415. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158416. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158417. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158418. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158419. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158420. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158421. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158422. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158423. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158424. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158425. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158426. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158427. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158428. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158429. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158430. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158431. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158432. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158433. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158434. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158435. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158436. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158437. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158438. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158439. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158440. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158441. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158442. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158443. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158444. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158445. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158446. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158447. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158448. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158449. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158450. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158451. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158452. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158453. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158454. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158455. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158456. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158457. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158458. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158459. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158460. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158461. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158462. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158463. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158464. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158465. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158466. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158467. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158468. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158469. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158470. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158471. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158472. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158473. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158474. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158475. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158476. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158477. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158478. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158479. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158480. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158481. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158482. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158483. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158484. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158485. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158486. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158487. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158488. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158489. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158490. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158491. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158492. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158493. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158494. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158495. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158496. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158497. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158498. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158499. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158500. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158501. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158502. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158503. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158504. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158505. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158506. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158507. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158508. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158509. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158510. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158511. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158512. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158513. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158514. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158515. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158516. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158517. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158518. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158519. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158520. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158521. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158522. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158523. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158524. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158525. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158526. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158527. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158528. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158529. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158530. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158531. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158532. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158533. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158534. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158535. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158536. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158537. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158538. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158539. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158540. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158541. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158542. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158543. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158544. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158545. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158546. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158547. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158548. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158549. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158550. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158551. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158552. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158553. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158554. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158555. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158556. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158557. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158558. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158559. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158560. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158561. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158562. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158563. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158564. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158565. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158566. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158567. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158568. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158569. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158570. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158571. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158572. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158573. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158574. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158575. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158576. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158577. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158578. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158579. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158580. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158581. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158582. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158583. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158584. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158585. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158586. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158587. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158588. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158589. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158590. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158591. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158592. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158593. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158594. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158595. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158596. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158597. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158598. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158599. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158600. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158601. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158602. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158603. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158604. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158605. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158606. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158607. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158608. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158609. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158610. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158611. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158612. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158613. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158614. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158615. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158616. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158617. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158618. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158619. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158620. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158621. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158622. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158623. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158624. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158625. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158626. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158627. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158628. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158629. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158630. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158631. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158632. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158633. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158634. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158635. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158636. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158637. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158638. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158639. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158640. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158641. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158642. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158643. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158644. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158645. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158646. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158647. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158648. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158649. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158650. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158651. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158652. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158653. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158654. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158655. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158656. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158657. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158658. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158659. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158660. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158661. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158662. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158663. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158664. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158665. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158666. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158667. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158668. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158669. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158670. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158671. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158672. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158673. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158674. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158675. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158676. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158677. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158678. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158679. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158680. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158681. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158682. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158683. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158684. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158685. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158686. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158687. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158688. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158689. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158690. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158691. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158692. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158693. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158694. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158695. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158696. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158697. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158698. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158699. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158700. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158701. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158702. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158703. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158704. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158705. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158706. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158707. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158708. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158709. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158710. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158711. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158712. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158713. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158714. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158715. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158716. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158717. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158718. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158719. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158720. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158721. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158722. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158723. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158724. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158725. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158726. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158727. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158728. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158729. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158730. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158731. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158732. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158733. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158734. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158735. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158736. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158737. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158738. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158739. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158740. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158741. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158742. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158743. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158744. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158745. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158746. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158747. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158748. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158749. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158750. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158751. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158752. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158753. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158754. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158755. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158756. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158757. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158758. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158759. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158760. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158761. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158762. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158763. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158764. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158765. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158766. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158767. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158768. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158769. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158770. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158771. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158772. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158773. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158774. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158775. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158776. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158777. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158778. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158779. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158780. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158781. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158782. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158783. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158784. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158785. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158786. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158787. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158788. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158789. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158790. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158791. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158792. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158793. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158794. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158795. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158796. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158797. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158798. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158799. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158800. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158801. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158802. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158803. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158804. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158805. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158806. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158807. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158808. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158809. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158810. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158811. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158812. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158813. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158814. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158815. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158816. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158817. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158818. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158819. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158820. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158821. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158822. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158823. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158824. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158825. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158826. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158827. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158828. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158829. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158830. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158831. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158832. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158833. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158834. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158835. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158836. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158837. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158838. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158839. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158840. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158841. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158842. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158843. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158844. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158845. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158846. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158847. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158848. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158849. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158850. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158851. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158852. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158853. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158854. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158855. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158856. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158857. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158858. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158859. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158860. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158861. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158862. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158863. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158864. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158865. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158866. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158867. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158868. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158869. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158870. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158871. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158872. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158873. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158874. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158875. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158876. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158877. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158878. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158879. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158880. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158881. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158882. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158883. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158884. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158885. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158886. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158887. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158888. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158889. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158890. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158891. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158892. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158893. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158894. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158895. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158896. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158897. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158898. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158899. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158900. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158901. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158902. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158903. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158904. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158905. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158906. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158907. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158908. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158909. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158910. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158911. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158912. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158913. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158914. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158915. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158916. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158917. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158918. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158919. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158920. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158921. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158922. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158923. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158924. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158925. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158926. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158927. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158928. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158929. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158930. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158931. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158932. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158933. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158934. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158935. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158936. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158937. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158938. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158939. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158940. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158941. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158942. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158943. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158944. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158945. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158946. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158947. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158948. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158949. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158950. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158951. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158952. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158953. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158954. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158955. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158956. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158957. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158958. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158959. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158960. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158961. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158962. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158963. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158964. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158965. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158966. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158967. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158968. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158969. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158970. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158971. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158972. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158973. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158974. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158975. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158976. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158977. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158978. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158979. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158980. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158981. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158982. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158983. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158984. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158985. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158986. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158987. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158988. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158989. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158990. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158991. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158992. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158993. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158994. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158995. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158996. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158997. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158998. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158999. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  159000. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  159001. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  159002. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  159003. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  159004. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  159005. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  159006. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  159007. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  159008. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  159009. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  159010. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  159011. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  159012. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  159013. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  159014. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  159015. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  159016. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  159017. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  159018. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  159019. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  159020. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  159021. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  159022. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  159023. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  159024. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  159025. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  159026. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  159027. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  159028. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  159029. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  159030. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  159031. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  159032. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  159033. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  159034. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  159035. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  159036. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  159037. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  159038. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  159039. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  159040. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  159041. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  159042. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  159043. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  159044. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  159045. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  159046. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  159047. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  159048. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  159049. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  159050. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  159051. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  159052. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  159053. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  159054. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  159055. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  159056. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  159057. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  159058. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  159059. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  159060. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  159061. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  159062. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  159063. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  159064. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  159065. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  159066. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  159067. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  159068. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  159069. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  159070. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  159071. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  159072. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  159073. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  159074. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  159075. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  159076. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  159077. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  159078. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  159079. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  159080. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  159081. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  159082. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  159083. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  159084. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  159085. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  159086. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  159087. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  159088. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  159089. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  159090. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  159091. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  159092. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  159093. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  159094. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  159095. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  159096. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  159097. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  159098. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  159099. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  159100. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  159101. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  159102. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  159103. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  159104. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  159105. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159106. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159107. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159108. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159109. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159110. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159111. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159112. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159113. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159114. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159115. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159116. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159117. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159118. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159119. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159120. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159121. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159122. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159123. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159124. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159125. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159126. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159127. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159128. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159129. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159130. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159131. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159132. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159133. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159134. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159135. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159136. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159137. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159138. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159139. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159140. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159141. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159142. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159143. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159144. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159145. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159146. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159147. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159148. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159149. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159150. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159151. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159152. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159153. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159154. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159155. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159156. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159157. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159158. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159159. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159160. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159161. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159162. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159163. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159164. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159165. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159166. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159167. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159168. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159169. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159170. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159171. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159172. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159173. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159174. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159175. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159176. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159177. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159178. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159179. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159180. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159181. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159182. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159183. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159184. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159185. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159186. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159187. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159188. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159189. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159190. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159191. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159192. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159193. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159194. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159195. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159196. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159197. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159198. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159199. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159200. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159201. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159202. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159203. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159204. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159205. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159206. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159207. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159208. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159209. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159210. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159211. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159212. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159213. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159214. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159215. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159216. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159217. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159218. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159219. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159220. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159221. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159222. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159223. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159224. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159225. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159226. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159227. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159228. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159229. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159230. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159231. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159232. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159233. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159234. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159235. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159236. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159237. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159238. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159239. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159240. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159241. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159242. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159243. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159244. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159245. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159246. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159247. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159248. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159249. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159250. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159251. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159252. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159253. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159254. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159255. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159256. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159257. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159258. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159259. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159260. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159261. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159262. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159263. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159264. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159265. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159266. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159267. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159268. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159269. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159270. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159271. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159272. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159273. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159274. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159275. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159276. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159277. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159278. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159279. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159280. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159281. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159282. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159283. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159284. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159285. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159286. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159287. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159288. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159289. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159290. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159291. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159292. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159293. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159294. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159295. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159296. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159297. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159298. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159299. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159300. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159301. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159302. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159303. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159304. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159305. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159306. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159307. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159308. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159309. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159310. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159311. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159312. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159313. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159314. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159315. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159316. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159317. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159318. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159319. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159320. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159321. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159322. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159323. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159324. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159325. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159326. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159327. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159328. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159329. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159330. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159331. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159332. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159333. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159334. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159335. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159336. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159337. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159338. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159339. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159340. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159341. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159342. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159343. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159344. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159345. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159346. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159347. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159348. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159349. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159350. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159351. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159352. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159353. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159354. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159355. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159356. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159357. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159358. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159359. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159360. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159361. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159362. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159363. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159364. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159365. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159366. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159367. };
  159368. static float *vwin[8] = {
  159369. vwin64,
  159370. vwin128,
  159371. vwin256,
  159372. vwin512,
  159373. vwin1024,
  159374. vwin2048,
  159375. vwin4096,
  159376. vwin8192,
  159377. };
  159378. float *_vorbis_window_get(int n){
  159379. return vwin[n];
  159380. }
  159381. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159382. int lW,int W,int nW){
  159383. lW=(W?lW:0);
  159384. nW=(W?nW:0);
  159385. {
  159386. float *windowLW=vwin[winno[lW]];
  159387. float *windowNW=vwin[winno[nW]];
  159388. long n=blocksizes[W];
  159389. long ln=blocksizes[lW];
  159390. long rn=blocksizes[nW];
  159391. long leftbegin=n/4-ln/4;
  159392. long leftend=leftbegin+ln/2;
  159393. long rightbegin=n/2+n/4-rn/4;
  159394. long rightend=rightbegin+rn/2;
  159395. int i,p;
  159396. for(i=0;i<leftbegin;i++)
  159397. d[i]=0.f;
  159398. for(p=0;i<leftend;i++,p++)
  159399. d[i]*=windowLW[p];
  159400. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159401. d[i]*=windowNW[p];
  159402. for(;i<n;i++)
  159403. d[i]=0.f;
  159404. }
  159405. }
  159406. #endif
  159407. /*** End of inlined file: window.c ***/
  159408. #else
  159409. #include <vorbis/vorbisenc.h>
  159410. #include <vorbis/codec.h>
  159411. #include <vorbis/vorbisfile.h>
  159412. #endif
  159413. }
  159414. #undef max
  159415. #undef min
  159416. BEGIN_JUCE_NAMESPACE
  159417. static const char* const oggFormatName = "Ogg-Vorbis file";
  159418. static const char* const oggExtensions[] = { ".ogg", 0 };
  159419. class OggReader : public AudioFormatReader
  159420. {
  159421. OggVorbisNamespace::OggVorbis_File ovFile;
  159422. OggVorbisNamespace::ov_callbacks callbacks;
  159423. AudioSampleBuffer reservoir;
  159424. int reservoirStart, samplesInReservoir;
  159425. public:
  159426. OggReader (InputStream* const inp)
  159427. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159428. reservoir (2, 4096),
  159429. reservoirStart (0),
  159430. samplesInReservoir (0)
  159431. {
  159432. using namespace OggVorbisNamespace;
  159433. sampleRate = 0;
  159434. usesFloatingPointData = true;
  159435. callbacks.read_func = &oggReadCallback;
  159436. callbacks.seek_func = &oggSeekCallback;
  159437. callbacks.close_func = &oggCloseCallback;
  159438. callbacks.tell_func = &oggTellCallback;
  159439. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159440. if (err == 0)
  159441. {
  159442. vorbis_info* info = ov_info (&ovFile, -1);
  159443. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159444. numChannels = info->channels;
  159445. bitsPerSample = 16;
  159446. sampleRate = info->rate;
  159447. reservoir.setSize (numChannels,
  159448. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159449. }
  159450. }
  159451. ~OggReader()
  159452. {
  159453. OggVorbisNamespace::ov_clear (&ovFile);
  159454. }
  159455. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159456. int64 startSampleInFile, int numSamples)
  159457. {
  159458. while (numSamples > 0)
  159459. {
  159460. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159461. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159462. {
  159463. // got a few samples overlapping, so use them before seeking..
  159464. const int numToUse = jmin (numSamples, numAvailable);
  159465. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159466. if (destSamples[i] != 0)
  159467. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159468. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159469. sizeof (float) * numToUse);
  159470. startSampleInFile += numToUse;
  159471. numSamples -= numToUse;
  159472. startOffsetInDestBuffer += numToUse;
  159473. if (numSamples == 0)
  159474. break;
  159475. }
  159476. if (startSampleInFile < reservoirStart
  159477. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159478. {
  159479. // buffer miss, so refill the reservoir
  159480. int bitStream = 0;
  159481. reservoirStart = jmax (0, (int) startSampleInFile);
  159482. samplesInReservoir = reservoir.getNumSamples();
  159483. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159484. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159485. int offset = 0;
  159486. int numToRead = samplesInReservoir;
  159487. while (numToRead > 0)
  159488. {
  159489. float** dataIn = 0;
  159490. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159491. if (samps <= 0)
  159492. break;
  159493. jassert (samps <= numToRead);
  159494. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159495. {
  159496. memcpy (reservoir.getSampleData (i, offset),
  159497. dataIn[i],
  159498. sizeof (float) * samps);
  159499. }
  159500. numToRead -= samps;
  159501. offset += samps;
  159502. }
  159503. if (numToRead > 0)
  159504. reservoir.clear (offset, numToRead);
  159505. }
  159506. }
  159507. if (numSamples > 0)
  159508. {
  159509. for (int i = numDestChannels; --i >= 0;)
  159510. if (destSamples[i] != 0)
  159511. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159512. sizeof (int) * numSamples);
  159513. }
  159514. return true;
  159515. }
  159516. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159517. {
  159518. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159519. }
  159520. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159521. {
  159522. InputStream* const in = static_cast <InputStream*> (datasource);
  159523. if (whence == SEEK_CUR)
  159524. offset += in->getPosition();
  159525. else if (whence == SEEK_END)
  159526. offset += in->getTotalLength();
  159527. in->setPosition (offset);
  159528. return 0;
  159529. }
  159530. static int oggCloseCallback (void*)
  159531. {
  159532. return 0;
  159533. }
  159534. static long oggTellCallback (void* datasource)
  159535. {
  159536. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159537. }
  159538. juce_UseDebuggingNewOperator
  159539. };
  159540. class OggWriter : public AudioFormatWriter
  159541. {
  159542. OggVorbisNamespace::ogg_stream_state os;
  159543. OggVorbisNamespace::ogg_page og;
  159544. OggVorbisNamespace::ogg_packet op;
  159545. OggVorbisNamespace::vorbis_info vi;
  159546. OggVorbisNamespace::vorbis_comment vc;
  159547. OggVorbisNamespace::vorbis_dsp_state vd;
  159548. OggVorbisNamespace::vorbis_block vb;
  159549. public:
  159550. bool ok;
  159551. OggWriter (OutputStream* const out,
  159552. const double sampleRate,
  159553. const int numChannels,
  159554. const int bitsPerSample,
  159555. const int qualityIndex)
  159556. : AudioFormatWriter (out, TRANS (oggFormatName),
  159557. sampleRate,
  159558. numChannels,
  159559. bitsPerSample)
  159560. {
  159561. using namespace OggVorbisNamespace;
  159562. ok = false;
  159563. vorbis_info_init (&vi);
  159564. if (vorbis_encode_init_vbr (&vi,
  159565. numChannels,
  159566. (int) sampleRate,
  159567. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159568. {
  159569. vorbis_comment_init (&vc);
  159570. if (JUCEApplication::getInstance() != 0)
  159571. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159572. vorbis_analysis_init (&vd, &vi);
  159573. vorbis_block_init (&vd, &vb);
  159574. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159575. ogg_packet header;
  159576. ogg_packet header_comm;
  159577. ogg_packet header_code;
  159578. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159579. ogg_stream_packetin (&os, &header);
  159580. ogg_stream_packetin (&os, &header_comm);
  159581. ogg_stream_packetin (&os, &header_code);
  159582. for (;;)
  159583. {
  159584. if (ogg_stream_flush (&os, &og) == 0)
  159585. break;
  159586. output->write (og.header, og.header_len);
  159587. output->write (og.body, og.body_len);
  159588. }
  159589. ok = true;
  159590. }
  159591. }
  159592. ~OggWriter()
  159593. {
  159594. using namespace OggVorbisNamespace;
  159595. if (ok)
  159596. {
  159597. // write a zero-length packet to show ogg that we're finished..
  159598. write (0, 0);
  159599. ogg_stream_clear (&os);
  159600. vorbis_block_clear (&vb);
  159601. vorbis_dsp_clear (&vd);
  159602. vorbis_comment_clear (&vc);
  159603. vorbis_info_clear (&vi);
  159604. output->flush();
  159605. }
  159606. else
  159607. {
  159608. vorbis_info_clear (&vi);
  159609. output = 0; // to stop the base class deleting this, as it needs to be returned
  159610. // to the caller of createWriter()
  159611. }
  159612. }
  159613. bool write (const int** samplesToWrite, int numSamples)
  159614. {
  159615. using namespace OggVorbisNamespace;
  159616. if (! ok)
  159617. return false;
  159618. if (numSamples > 0)
  159619. {
  159620. const double gain = 1.0 / 0x80000000u;
  159621. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159622. for (int i = numChannels; --i >= 0;)
  159623. {
  159624. float* const dst = vorbisBuffer[i];
  159625. const int* const src = samplesToWrite [i];
  159626. if (src != 0 && dst != 0)
  159627. {
  159628. for (int j = 0; j < numSamples; ++j)
  159629. dst[j] = (float) (src[j] * gain);
  159630. }
  159631. }
  159632. }
  159633. vorbis_analysis_wrote (&vd, numSamples);
  159634. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159635. {
  159636. vorbis_analysis (&vb, 0);
  159637. vorbis_bitrate_addblock (&vb);
  159638. while (vorbis_bitrate_flushpacket (&vd, &op))
  159639. {
  159640. ogg_stream_packetin (&os, &op);
  159641. for (;;)
  159642. {
  159643. if (ogg_stream_pageout (&os, &og) == 0)
  159644. break;
  159645. output->write (og.header, og.header_len);
  159646. output->write (og.body, og.body_len);
  159647. if (ogg_page_eos (&og))
  159648. break;
  159649. }
  159650. }
  159651. }
  159652. return true;
  159653. }
  159654. juce_UseDebuggingNewOperator
  159655. };
  159656. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159657. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159658. {
  159659. }
  159660. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159661. {
  159662. }
  159663. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159664. {
  159665. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159666. return Array <int> (rates);
  159667. }
  159668. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159669. {
  159670. Array <int> depths;
  159671. depths.add (32);
  159672. return depths;
  159673. }
  159674. bool OggVorbisAudioFormat::canDoStereo()
  159675. {
  159676. return true;
  159677. }
  159678. bool OggVorbisAudioFormat::canDoMono()
  159679. {
  159680. return true;
  159681. }
  159682. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159683. const bool deleteStreamIfOpeningFails)
  159684. {
  159685. ScopedPointer <OggReader> r (new OggReader (in));
  159686. if (r->sampleRate != 0)
  159687. return r.release();
  159688. if (! deleteStreamIfOpeningFails)
  159689. r->input = 0;
  159690. return 0;
  159691. }
  159692. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159693. double sampleRate,
  159694. unsigned int numChannels,
  159695. int bitsPerSample,
  159696. const StringPairArray& /*metadataValues*/,
  159697. int qualityOptionIndex)
  159698. {
  159699. ScopedPointer <OggWriter> w (new OggWriter (out,
  159700. sampleRate,
  159701. numChannels,
  159702. bitsPerSample,
  159703. qualityOptionIndex));
  159704. return w->ok ? w.release() : 0;
  159705. }
  159706. bool OggVorbisAudioFormat::isCompressed()
  159707. {
  159708. return true;
  159709. }
  159710. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159711. {
  159712. StringArray s;
  159713. s.add ("Low Quality");
  159714. s.add ("Medium Quality");
  159715. s.add ("High Quality");
  159716. return s;
  159717. }
  159718. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159719. {
  159720. FileInputStream* const in = source.createInputStream();
  159721. if (in != 0)
  159722. {
  159723. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159724. if (r != 0)
  159725. {
  159726. const int64 numSamps = r->lengthInSamples;
  159727. r = 0;
  159728. const int64 fileNumSamps = source.getSize() / 4;
  159729. const double ratio = numSamps / (double) fileNumSamps;
  159730. if (ratio > 12.0)
  159731. return 0;
  159732. else if (ratio > 6.0)
  159733. return 1;
  159734. else
  159735. return 2;
  159736. }
  159737. }
  159738. return 1;
  159739. }
  159740. END_JUCE_NAMESPACE
  159741. #endif
  159742. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159743. #endif
  159744. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159745. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159746. #if JUCE_MSVC
  159747. #pragma warning (push)
  159748. #endif
  159749. namespace jpeglibNamespace
  159750. {
  159751. #if JUCE_INCLUDE_JPEGLIB_CODE
  159752. #if JUCE_MINGW
  159753. typedef unsigned char boolean;
  159754. #endif
  159755. #define JPEG_INTERNALS
  159756. #undef FAR
  159757. /*** Start of inlined file: jpeglib.h ***/
  159758. #ifndef JPEGLIB_H
  159759. #define JPEGLIB_H
  159760. /*
  159761. * First we include the configuration files that record how this
  159762. * installation of the JPEG library is set up. jconfig.h can be
  159763. * generated automatically for many systems. jmorecfg.h contains
  159764. * manual configuration options that most people need not worry about.
  159765. */
  159766. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159767. /*** Start of inlined file: jconfig.h ***/
  159768. /* see jconfig.doc for explanations */
  159769. // disable all the warnings under MSVC
  159770. #ifdef _MSC_VER
  159771. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159772. #endif
  159773. #ifdef __BORLANDC__
  159774. #pragma warn -8057
  159775. #pragma warn -8019
  159776. #pragma warn -8004
  159777. #pragma warn -8008
  159778. #endif
  159779. #define HAVE_PROTOTYPES
  159780. #define HAVE_UNSIGNED_CHAR
  159781. #define HAVE_UNSIGNED_SHORT
  159782. /* #define void char */
  159783. /* #define const */
  159784. #undef CHAR_IS_UNSIGNED
  159785. #define HAVE_STDDEF_H
  159786. #define HAVE_STDLIB_H
  159787. #undef NEED_BSD_STRINGS
  159788. #undef NEED_SYS_TYPES_H
  159789. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159790. #undef NEED_SHORT_EXTERNAL_NAMES
  159791. #undef INCOMPLETE_TYPES_BROKEN
  159792. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159793. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159794. typedef unsigned char boolean;
  159795. #endif
  159796. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159797. #ifdef JPEG_INTERNALS
  159798. #undef RIGHT_SHIFT_IS_UNSIGNED
  159799. #endif /* JPEG_INTERNALS */
  159800. #ifdef JPEG_CJPEG_DJPEG
  159801. #define BMP_SUPPORTED /* BMP image file format */
  159802. #define GIF_SUPPORTED /* GIF image file format */
  159803. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159804. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159805. #define TARGA_SUPPORTED /* Targa image file format */
  159806. #define TWO_FILE_COMMANDLINE /* optional */
  159807. #define USE_SETMODE /* Microsoft has setmode() */
  159808. #undef NEED_SIGNAL_CATCHER
  159809. #undef DONT_USE_B_MODE
  159810. #undef PROGRESS_REPORT /* optional */
  159811. #endif /* JPEG_CJPEG_DJPEG */
  159812. /*** End of inlined file: jconfig.h ***/
  159813. /* widely used configuration options */
  159814. #endif
  159815. /*** Start of inlined file: jmorecfg.h ***/
  159816. /*
  159817. * Define BITS_IN_JSAMPLE as either
  159818. * 8 for 8-bit sample values (the usual setting)
  159819. * 12 for 12-bit sample values
  159820. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159821. * JPEG standard, and the IJG code does not support anything else!
  159822. * We do not support run-time selection of data precision, sorry.
  159823. */
  159824. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159825. /*
  159826. * Maximum number of components (color channels) allowed in JPEG image.
  159827. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159828. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159829. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159830. * really short on memory. (Each allowed component costs a hundred or so
  159831. * bytes of storage, whether actually used in an image or not.)
  159832. */
  159833. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159834. /*
  159835. * Basic data types.
  159836. * You may need to change these if you have a machine with unusual data
  159837. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159838. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159839. * but it had better be at least 16.
  159840. */
  159841. /* Representation of a single sample (pixel element value).
  159842. * We frequently allocate large arrays of these, so it's important to keep
  159843. * them small. But if you have memory to burn and access to char or short
  159844. * arrays is very slow on your hardware, you might want to change these.
  159845. */
  159846. #if BITS_IN_JSAMPLE == 8
  159847. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159848. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159849. */
  159850. #ifdef HAVE_UNSIGNED_CHAR
  159851. typedef unsigned char JSAMPLE;
  159852. #define GETJSAMPLE(value) ((int) (value))
  159853. #else /* not HAVE_UNSIGNED_CHAR */
  159854. typedef char JSAMPLE;
  159855. #ifdef CHAR_IS_UNSIGNED
  159856. #define GETJSAMPLE(value) ((int) (value))
  159857. #else
  159858. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159859. #endif /* CHAR_IS_UNSIGNED */
  159860. #endif /* HAVE_UNSIGNED_CHAR */
  159861. #define MAXJSAMPLE 255
  159862. #define CENTERJSAMPLE 128
  159863. #endif /* BITS_IN_JSAMPLE == 8 */
  159864. #if BITS_IN_JSAMPLE == 12
  159865. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159866. * On nearly all machines "short" will do nicely.
  159867. */
  159868. typedef short JSAMPLE;
  159869. #define GETJSAMPLE(value) ((int) (value))
  159870. #define MAXJSAMPLE 4095
  159871. #define CENTERJSAMPLE 2048
  159872. #endif /* BITS_IN_JSAMPLE == 12 */
  159873. /* Representation of a DCT frequency coefficient.
  159874. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159875. * Again, we allocate large arrays of these, but you can change to int
  159876. * if you have memory to burn and "short" is really slow.
  159877. */
  159878. typedef short JCOEF;
  159879. /* Compressed datastreams are represented as arrays of JOCTET.
  159880. * These must be EXACTLY 8 bits wide, at least once they are written to
  159881. * external storage. Note that when using the stdio data source/destination
  159882. * managers, this is also the data type passed to fread/fwrite.
  159883. */
  159884. #ifdef HAVE_UNSIGNED_CHAR
  159885. typedef unsigned char JOCTET;
  159886. #define GETJOCTET(value) (value)
  159887. #else /* not HAVE_UNSIGNED_CHAR */
  159888. typedef char JOCTET;
  159889. #ifdef CHAR_IS_UNSIGNED
  159890. #define GETJOCTET(value) (value)
  159891. #else
  159892. #define GETJOCTET(value) ((value) & 0xFF)
  159893. #endif /* CHAR_IS_UNSIGNED */
  159894. #endif /* HAVE_UNSIGNED_CHAR */
  159895. /* These typedefs are used for various table entries and so forth.
  159896. * They must be at least as wide as specified; but making them too big
  159897. * won't cost a huge amount of memory, so we don't provide special
  159898. * extraction code like we did for JSAMPLE. (In other words, these
  159899. * typedefs live at a different point on the speed/space tradeoff curve.)
  159900. */
  159901. /* UINT8 must hold at least the values 0..255. */
  159902. #ifdef HAVE_UNSIGNED_CHAR
  159903. typedef unsigned char UINT8;
  159904. #else /* not HAVE_UNSIGNED_CHAR */
  159905. #ifdef CHAR_IS_UNSIGNED
  159906. typedef char UINT8;
  159907. #else /* not CHAR_IS_UNSIGNED */
  159908. typedef short UINT8;
  159909. #endif /* CHAR_IS_UNSIGNED */
  159910. #endif /* HAVE_UNSIGNED_CHAR */
  159911. /* UINT16 must hold at least the values 0..65535. */
  159912. #ifdef HAVE_UNSIGNED_SHORT
  159913. typedef unsigned short UINT16;
  159914. #else /* not HAVE_UNSIGNED_SHORT */
  159915. typedef unsigned int UINT16;
  159916. #endif /* HAVE_UNSIGNED_SHORT */
  159917. /* INT16 must hold at least the values -32768..32767. */
  159918. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159919. typedef short INT16;
  159920. #endif
  159921. /* INT32 must hold at least signed 32-bit values. */
  159922. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159923. typedef long INT32;
  159924. #endif
  159925. /* Datatype used for image dimensions. The JPEG standard only supports
  159926. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159927. * "unsigned int" is sufficient on all machines. However, if you need to
  159928. * handle larger images and you don't mind deviating from the spec, you
  159929. * can change this datatype.
  159930. */
  159931. typedef unsigned int JDIMENSION;
  159932. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159933. /* These macros are used in all function definitions and extern declarations.
  159934. * You could modify them if you need to change function linkage conventions;
  159935. * in particular, you'll need to do that to make the library a Windows DLL.
  159936. * Another application is to make all functions global for use with debuggers
  159937. * or code profilers that require it.
  159938. */
  159939. /* a function called through method pointers: */
  159940. #define METHODDEF(type) static type
  159941. /* a function used only in its module: */
  159942. #define LOCAL(type) static type
  159943. /* a function referenced thru EXTERNs: */
  159944. #define GLOBAL(type) type
  159945. /* a reference to a GLOBAL function: */
  159946. #define EXTERN(type) extern type
  159947. /* This macro is used to declare a "method", that is, a function pointer.
  159948. * We want to supply prototype parameters if the compiler can cope.
  159949. * Note that the arglist parameter must be parenthesized!
  159950. * Again, you can customize this if you need special linkage keywords.
  159951. */
  159952. #ifdef HAVE_PROTOTYPES
  159953. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159954. #else
  159955. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159956. #endif
  159957. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159958. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159959. * by just saying "FAR *" where such a pointer is needed. In a few places
  159960. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159961. */
  159962. #ifdef NEED_FAR_POINTERS
  159963. #define FAR far
  159964. #else
  159965. #define FAR
  159966. #endif
  159967. /*
  159968. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159969. * in standard header files. Or you may have conflicts with application-
  159970. * specific header files that you want to include together with these files.
  159971. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159972. */
  159973. #ifndef HAVE_BOOLEAN
  159974. typedef int boolean;
  159975. #endif
  159976. #ifndef FALSE /* in case these macros already exist */
  159977. #define FALSE 0 /* values of boolean */
  159978. #endif
  159979. #ifndef TRUE
  159980. #define TRUE 1
  159981. #endif
  159982. /*
  159983. * The remaining options affect code selection within the JPEG library,
  159984. * but they don't need to be visible to most applications using the library.
  159985. * To minimize application namespace pollution, the symbols won't be
  159986. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159987. */
  159988. #ifdef JPEG_INTERNALS
  159989. #define JPEG_INTERNAL_OPTIONS
  159990. #endif
  159991. #ifdef JPEG_INTERNAL_OPTIONS
  159992. /*
  159993. * These defines indicate whether to include various optional functions.
  159994. * Undefining some of these symbols will produce a smaller but less capable
  159995. * library. Note that you can leave certain source files out of the
  159996. * compilation/linking process if you've #undef'd the corresponding symbols.
  159997. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159998. */
  159999. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  160000. /* Capability options common to encoder and decoder: */
  160001. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  160002. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  160003. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  160004. /* Encoder capability options: */
  160005. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160006. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160007. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160008. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  160009. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  160010. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  160011. * precision, so jchuff.c normally uses entropy optimization to compute
  160012. * usable tables for higher precision. If you don't want to do optimization,
  160013. * you'll have to supply different default Huffman tables.
  160014. * The exact same statements apply for progressive JPEG: the default tables
  160015. * don't work for progressive mode. (This may get fixed, however.)
  160016. */
  160017. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  160018. /* Decoder capability options: */
  160019. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160020. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160021. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160022. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  160023. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  160024. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  160025. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  160026. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  160027. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  160028. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  160029. /* more capability options later, no doubt */
  160030. /*
  160031. * Ordering of RGB data in scanlines passed to or from the application.
  160032. * If your application wants to deal with data in the order B,G,R, just
  160033. * change these macros. You can also deal with formats such as R,G,B,X
  160034. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  160035. * the offsets will also change the order in which colormap data is organized.
  160036. * RESTRICTIONS:
  160037. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  160038. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  160039. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  160040. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  160041. * is not 3 (they don't understand about dummy color components!). So you
  160042. * can't use color quantization if you change that value.
  160043. */
  160044. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  160045. #define RGB_GREEN 1 /* Offset of Green */
  160046. #define RGB_BLUE 2 /* Offset of Blue */
  160047. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  160048. /* Definitions for speed-related optimizations. */
  160049. /* If your compiler supports inline functions, define INLINE
  160050. * as the inline keyword; otherwise define it as empty.
  160051. */
  160052. #ifndef INLINE
  160053. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  160054. #define INLINE __inline__
  160055. #endif
  160056. #ifndef INLINE
  160057. #define INLINE /* default is to define it as empty */
  160058. #endif
  160059. #endif
  160060. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  160061. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  160062. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  160063. */
  160064. #ifndef MULTIPLIER
  160065. #define MULTIPLIER int /* type for fastest integer multiply */
  160066. #endif
  160067. /* FAST_FLOAT should be either float or double, whichever is done faster
  160068. * by your compiler. (Note that this type is only used in the floating point
  160069. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  160070. * Typically, float is faster in ANSI C compilers, while double is faster in
  160071. * pre-ANSI compilers (because they insist on converting to double anyway).
  160072. * The code below therefore chooses float if we have ANSI-style prototypes.
  160073. */
  160074. #ifndef FAST_FLOAT
  160075. #ifdef HAVE_PROTOTYPES
  160076. #define FAST_FLOAT float
  160077. #else
  160078. #define FAST_FLOAT double
  160079. #endif
  160080. #endif
  160081. #endif /* JPEG_INTERNAL_OPTIONS */
  160082. /*** End of inlined file: jmorecfg.h ***/
  160083. /* seldom changed options */
  160084. /* Version ID for the JPEG library.
  160085. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  160086. */
  160087. #define JPEG_LIB_VERSION 62 /* Version 6b */
  160088. /* Various constants determining the sizes of things.
  160089. * All of these are specified by the JPEG standard, so don't change them
  160090. * if you want to be compatible.
  160091. */
  160092. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  160093. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  160094. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  160095. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  160096. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  160097. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  160098. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  160099. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  160100. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  160101. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  160102. * to handle it. We even let you do this from the jconfig.h file. However,
  160103. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  160104. * sometimes emits noncompliant files doesn't mean you should too.
  160105. */
  160106. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  160107. #ifndef D_MAX_BLOCKS_IN_MCU
  160108. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  160109. #endif
  160110. /* Data structures for images (arrays of samples and of DCT coefficients).
  160111. * On 80x86 machines, the image arrays are too big for near pointers,
  160112. * but the pointer arrays can fit in near memory.
  160113. */
  160114. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  160115. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160116. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160117. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160118. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160119. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160120. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160121. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160122. /* Types for JPEG compression parameters and working tables. */
  160123. /* DCT coefficient quantization tables. */
  160124. typedef struct {
  160125. /* This array gives the coefficient quantizers in natural array order
  160126. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160127. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160128. */
  160129. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160130. /* This field is used only during compression. It's initialized FALSE when
  160131. * the table is created, and set TRUE when it's been output to the file.
  160132. * You could suppress output of a table by setting this to TRUE.
  160133. * (See jpeg_suppress_tables for an example.)
  160134. */
  160135. boolean sent_table; /* TRUE when table has been output */
  160136. } JQUANT_TBL;
  160137. /* Huffman coding tables. */
  160138. typedef struct {
  160139. /* These two fields directly represent the contents of a JPEG DHT marker */
  160140. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160141. /* length k bits; bits[0] is unused */
  160142. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160143. /* This field is used only during compression. It's initialized FALSE when
  160144. * the table is created, and set TRUE when it's been output to the file.
  160145. * You could suppress output of a table by setting this to TRUE.
  160146. * (See jpeg_suppress_tables for an example.)
  160147. */
  160148. boolean sent_table; /* TRUE when table has been output */
  160149. } JHUFF_TBL;
  160150. /* Basic info about one component (color channel). */
  160151. typedef struct {
  160152. /* These values are fixed over the whole image. */
  160153. /* For compression, they must be supplied by parameter setup; */
  160154. /* for decompression, they are read from the SOF marker. */
  160155. int component_id; /* identifier for this component (0..255) */
  160156. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160157. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160158. int v_samp_factor; /* vertical sampling factor (1..4) */
  160159. int quant_tbl_no; /* quantization table selector (0..3) */
  160160. /* These values may vary between scans. */
  160161. /* For compression, they must be supplied by parameter setup; */
  160162. /* for decompression, they are read from the SOS marker. */
  160163. /* The decompressor output side may not use these variables. */
  160164. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160165. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160166. /* Remaining fields should be treated as private by applications. */
  160167. /* These values are computed during compression or decompression startup: */
  160168. /* Component's size in DCT blocks.
  160169. * Any dummy blocks added to complete an MCU are not counted; therefore
  160170. * these values do not depend on whether a scan is interleaved or not.
  160171. */
  160172. JDIMENSION width_in_blocks;
  160173. JDIMENSION height_in_blocks;
  160174. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160175. * For decompression this is the size of the output from one DCT block,
  160176. * reflecting any scaling we choose to apply during the IDCT step.
  160177. * Values of 1,2,4,8 are likely to be supported. Note that different
  160178. * components may receive different IDCT scalings.
  160179. */
  160180. int DCT_scaled_size;
  160181. /* The downsampled dimensions are the component's actual, unpadded number
  160182. * of samples at the main buffer (preprocessing/compression interface), thus
  160183. * downsampled_width = ceil(image_width * Hi/Hmax)
  160184. * and similarly for height. For decompression, IDCT scaling is included, so
  160185. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160186. */
  160187. JDIMENSION downsampled_width; /* actual width in samples */
  160188. JDIMENSION downsampled_height; /* actual height in samples */
  160189. /* This flag is used only for decompression. In cases where some of the
  160190. * components will be ignored (eg grayscale output from YCbCr image),
  160191. * we can skip most computations for the unused components.
  160192. */
  160193. boolean component_needed; /* do we need the value of this component? */
  160194. /* These values are computed before starting a scan of the component. */
  160195. /* The decompressor output side may not use these variables. */
  160196. int MCU_width; /* number of blocks per MCU, horizontally */
  160197. int MCU_height; /* number of blocks per MCU, vertically */
  160198. int MCU_blocks; /* MCU_width * MCU_height */
  160199. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160200. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160201. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160202. /* Saved quantization table for component; NULL if none yet saved.
  160203. * See jdinput.c comments about the need for this information.
  160204. * This field is currently used only for decompression.
  160205. */
  160206. JQUANT_TBL * quant_table;
  160207. /* Private per-component storage for DCT or IDCT subsystem. */
  160208. void * dct_table;
  160209. } jpeg_component_info;
  160210. /* The script for encoding a multiple-scan file is an array of these: */
  160211. typedef struct {
  160212. int comps_in_scan; /* number of components encoded in this scan */
  160213. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160214. int Ss, Se; /* progressive JPEG spectral selection parms */
  160215. int Ah, Al; /* progressive JPEG successive approx. parms */
  160216. } jpeg_scan_info;
  160217. /* The decompressor can save APPn and COM markers in a list of these: */
  160218. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160219. struct jpeg_marker_struct {
  160220. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160221. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160222. unsigned int original_length; /* # bytes of data in the file */
  160223. unsigned int data_length; /* # bytes of data saved at data[] */
  160224. JOCTET FAR * data; /* the data contained in the marker */
  160225. /* the marker length word is not counted in data_length or original_length */
  160226. };
  160227. /* Known color spaces. */
  160228. typedef enum {
  160229. JCS_UNKNOWN, /* error/unspecified */
  160230. JCS_GRAYSCALE, /* monochrome */
  160231. JCS_RGB, /* red/green/blue */
  160232. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160233. JCS_CMYK, /* C/M/Y/K */
  160234. JCS_YCCK /* Y/Cb/Cr/K */
  160235. } J_COLOR_SPACE;
  160236. /* DCT/IDCT algorithm options. */
  160237. typedef enum {
  160238. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160239. JDCT_IFAST, /* faster, less accurate integer method */
  160240. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160241. } J_DCT_METHOD;
  160242. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160243. #define JDCT_DEFAULT JDCT_ISLOW
  160244. #endif
  160245. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160246. #define JDCT_FASTEST JDCT_IFAST
  160247. #endif
  160248. /* Dithering options for decompression. */
  160249. typedef enum {
  160250. JDITHER_NONE, /* no dithering */
  160251. JDITHER_ORDERED, /* simple ordered dither */
  160252. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160253. } J_DITHER_MODE;
  160254. /* Common fields between JPEG compression and decompression master structs. */
  160255. #define jpeg_common_fields \
  160256. struct jpeg_error_mgr * err; /* Error handler module */\
  160257. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160258. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160259. void * client_data; /* Available for use by application */\
  160260. boolean is_decompressor; /* So common code can tell which is which */\
  160261. int global_state /* For checking call sequence validity */
  160262. /* Routines that are to be used by both halves of the library are declared
  160263. * to receive a pointer to this structure. There are no actual instances of
  160264. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160265. */
  160266. struct jpeg_common_struct {
  160267. jpeg_common_fields; /* Fields common to both master struct types */
  160268. /* Additional fields follow in an actual jpeg_compress_struct or
  160269. * jpeg_decompress_struct. All three structs must agree on these
  160270. * initial fields! (This would be a lot cleaner in C++.)
  160271. */
  160272. };
  160273. typedef struct jpeg_common_struct * j_common_ptr;
  160274. typedef struct jpeg_compress_struct * j_compress_ptr;
  160275. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160276. /* Master record for a compression instance */
  160277. struct jpeg_compress_struct {
  160278. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160279. /* Destination for compressed data */
  160280. struct jpeg_destination_mgr * dest;
  160281. /* Description of source image --- these fields must be filled in by
  160282. * outer application before starting compression. in_color_space must
  160283. * be correct before you can even call jpeg_set_defaults().
  160284. */
  160285. JDIMENSION image_width; /* input image width */
  160286. JDIMENSION image_height; /* input image height */
  160287. int input_components; /* # of color components in input image */
  160288. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160289. double input_gamma; /* image gamma of input image */
  160290. /* Compression parameters --- these fields must be set before calling
  160291. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160292. * initialize everything to reasonable defaults, then changing anything
  160293. * the application specifically wants to change. That way you won't get
  160294. * burnt when new parameters are added. Also note that there are several
  160295. * helper routines to simplify changing parameters.
  160296. */
  160297. int data_precision; /* bits of precision in image data */
  160298. int num_components; /* # of color components in JPEG image */
  160299. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160300. jpeg_component_info * comp_info;
  160301. /* comp_info[i] describes component that appears i'th in SOF */
  160302. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160303. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160304. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160305. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160306. /* ptrs to Huffman coding tables, or NULL if not defined */
  160307. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160308. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160309. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160310. int num_scans; /* # of entries in scan_info array */
  160311. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160312. /* The default value of scan_info is NULL, which causes a single-scan
  160313. * sequential JPEG file to be emitted. To create a multi-scan file,
  160314. * set num_scans and scan_info to point to an array of scan definitions.
  160315. */
  160316. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160317. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160318. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160319. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160320. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160321. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160322. /* The restart interval can be specified in absolute MCUs by setting
  160323. * restart_interval, or in MCU rows by setting restart_in_rows
  160324. * (in which case the correct restart_interval will be figured
  160325. * for each scan).
  160326. */
  160327. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160328. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160329. /* Parameters controlling emission of special markers. */
  160330. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160331. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160332. UINT8 JFIF_minor_version;
  160333. /* These three values are not used by the JPEG code, merely copied */
  160334. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160335. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160336. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160337. UINT8 density_unit; /* JFIF code for pixel size units */
  160338. UINT16 X_density; /* Horizontal pixel density */
  160339. UINT16 Y_density; /* Vertical pixel density */
  160340. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160341. /* State variable: index of next scanline to be written to
  160342. * jpeg_write_scanlines(). Application may use this to control its
  160343. * processing loop, e.g., "while (next_scanline < image_height)".
  160344. */
  160345. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160346. /* Remaining fields are known throughout compressor, but generally
  160347. * should not be touched by a surrounding application.
  160348. */
  160349. /*
  160350. * These fields are computed during compression startup
  160351. */
  160352. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160353. int max_h_samp_factor; /* largest h_samp_factor */
  160354. int max_v_samp_factor; /* largest v_samp_factor */
  160355. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160356. /* The coefficient controller receives data in units of MCU rows as defined
  160357. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160358. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160359. * "iMCU" (interleaved MCU) row.
  160360. */
  160361. /*
  160362. * These fields are valid during any one scan.
  160363. * They describe the components and MCUs actually appearing in the scan.
  160364. */
  160365. int comps_in_scan; /* # of JPEG components in this scan */
  160366. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160367. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160368. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160369. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160370. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160371. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160372. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160373. /* i'th block in an MCU */
  160374. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160375. /*
  160376. * Links to compression subobjects (methods and private variables of modules)
  160377. */
  160378. struct jpeg_comp_master * master;
  160379. struct jpeg_c_main_controller * main;
  160380. struct jpeg_c_prep_controller * prep;
  160381. struct jpeg_c_coef_controller * coef;
  160382. struct jpeg_marker_writer * marker;
  160383. struct jpeg_color_converter * cconvert;
  160384. struct jpeg_downsampler * downsample;
  160385. struct jpeg_forward_dct * fdct;
  160386. struct jpeg_entropy_encoder * entropy;
  160387. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160388. int script_space_size;
  160389. };
  160390. /* Master record for a decompression instance */
  160391. struct jpeg_decompress_struct {
  160392. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160393. /* Source of compressed data */
  160394. struct jpeg_source_mgr * src;
  160395. /* Basic description of image --- filled in by jpeg_read_header(). */
  160396. /* Application may inspect these values to decide how to process image. */
  160397. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160398. JDIMENSION image_height; /* nominal image height */
  160399. int num_components; /* # of color components in JPEG image */
  160400. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160401. /* Decompression processing parameters --- these fields must be set before
  160402. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160403. * them to default values.
  160404. */
  160405. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160406. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160407. double output_gamma; /* image gamma wanted in output */
  160408. boolean buffered_image; /* TRUE=multiple output passes */
  160409. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160410. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160411. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160412. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160413. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160414. /* the following are ignored if not quantize_colors: */
  160415. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160416. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160417. int desired_number_of_colors; /* max # colors to use in created colormap */
  160418. /* these are significant only in buffered-image mode: */
  160419. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160420. boolean enable_external_quant;/* enable future use of external colormap */
  160421. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160422. /* Description of actual output image that will be returned to application.
  160423. * These fields are computed by jpeg_start_decompress().
  160424. * You can also use jpeg_calc_output_dimensions() to determine these values
  160425. * in advance of calling jpeg_start_decompress().
  160426. */
  160427. JDIMENSION output_width; /* scaled image width */
  160428. JDIMENSION output_height; /* scaled image height */
  160429. int out_color_components; /* # of color components in out_color_space */
  160430. int output_components; /* # of color components returned */
  160431. /* output_components is 1 (a colormap index) when quantizing colors;
  160432. * otherwise it equals out_color_components.
  160433. */
  160434. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160435. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160436. * high, space and time will be wasted due to unnecessary data copying.
  160437. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160438. */
  160439. /* When quantizing colors, the output colormap is described by these fields.
  160440. * The application can supply a colormap by setting colormap non-NULL before
  160441. * calling jpeg_start_decompress; otherwise a colormap is created during
  160442. * jpeg_start_decompress or jpeg_start_output.
  160443. * The map has out_color_components rows and actual_number_of_colors columns.
  160444. */
  160445. int actual_number_of_colors; /* number of entries in use */
  160446. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160447. /* State variables: these variables indicate the progress of decompression.
  160448. * The application may examine these but must not modify them.
  160449. */
  160450. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160451. * Application may use this to control its processing loop, e.g.,
  160452. * "while (output_scanline < output_height)".
  160453. */
  160454. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160455. /* Current input scan number and number of iMCU rows completed in scan.
  160456. * These indicate the progress of the decompressor input side.
  160457. */
  160458. int input_scan_number; /* Number of SOS markers seen so far */
  160459. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160460. /* The "output scan number" is the notional scan being displayed by the
  160461. * output side. The decompressor will not allow output scan/row number
  160462. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160463. */
  160464. int output_scan_number; /* Nominal scan number being displayed */
  160465. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160466. /* Current progression status. coef_bits[c][i] indicates the precision
  160467. * with which component c's DCT coefficient i (in zigzag order) is known.
  160468. * It is -1 when no data has yet been received, otherwise it is the point
  160469. * transform (shift) value for the most recent scan of the coefficient
  160470. * (thus, 0 at completion of the progression).
  160471. * This pointer is NULL when reading a non-progressive file.
  160472. */
  160473. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160474. /* Internal JPEG parameters --- the application usually need not look at
  160475. * these fields. Note that the decompressor output side may not use
  160476. * any parameters that can change between scans.
  160477. */
  160478. /* Quantization and Huffman tables are carried forward across input
  160479. * datastreams when processing abbreviated JPEG datastreams.
  160480. */
  160481. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160482. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160483. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160484. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160485. /* ptrs to Huffman coding tables, or NULL if not defined */
  160486. /* These parameters are never carried across datastreams, since they
  160487. * are given in SOF/SOS markers or defined to be reset by SOI.
  160488. */
  160489. int data_precision; /* bits of precision in image data */
  160490. jpeg_component_info * comp_info;
  160491. /* comp_info[i] describes component that appears i'th in SOF */
  160492. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160493. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160494. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160495. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160496. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160497. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160498. /* These fields record data obtained from optional markers recognized by
  160499. * the JPEG library.
  160500. */
  160501. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160502. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160503. UINT8 JFIF_major_version; /* JFIF version number */
  160504. UINT8 JFIF_minor_version;
  160505. UINT8 density_unit; /* JFIF code for pixel size units */
  160506. UINT16 X_density; /* Horizontal pixel density */
  160507. UINT16 Y_density; /* Vertical pixel density */
  160508. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160509. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160510. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160511. /* Aside from the specific data retained from APPn markers known to the
  160512. * library, the uninterpreted contents of any or all APPn and COM markers
  160513. * can be saved in a list for examination by the application.
  160514. */
  160515. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160516. /* Remaining fields are known throughout decompressor, but generally
  160517. * should not be touched by a surrounding application.
  160518. */
  160519. /*
  160520. * These fields are computed during decompression startup
  160521. */
  160522. int max_h_samp_factor; /* largest h_samp_factor */
  160523. int max_v_samp_factor; /* largest v_samp_factor */
  160524. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160525. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160526. /* The coefficient controller's input and output progress is measured in
  160527. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160528. * in fully interleaved JPEG scans, but are used whether the scan is
  160529. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160530. * rows of each component. Therefore, the IDCT output contains
  160531. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160532. */
  160533. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160534. /*
  160535. * These fields are valid during any one scan.
  160536. * They describe the components and MCUs actually appearing in the scan.
  160537. * Note that the decompressor output side must not use these fields.
  160538. */
  160539. int comps_in_scan; /* # of JPEG components in this scan */
  160540. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160541. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160542. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160543. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160544. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160545. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160546. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160547. /* i'th block in an MCU */
  160548. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160549. /* This field is shared between entropy decoder and marker parser.
  160550. * It is either zero or the code of a JPEG marker that has been
  160551. * read from the data source, but has not yet been processed.
  160552. */
  160553. int unread_marker;
  160554. /*
  160555. * Links to decompression subobjects (methods, private variables of modules)
  160556. */
  160557. struct jpeg_decomp_master * master;
  160558. struct jpeg_d_main_controller * main;
  160559. struct jpeg_d_coef_controller * coef;
  160560. struct jpeg_d_post_controller * post;
  160561. struct jpeg_input_controller * inputctl;
  160562. struct jpeg_marker_reader * marker;
  160563. struct jpeg_entropy_decoder * entropy;
  160564. struct jpeg_inverse_dct * idct;
  160565. struct jpeg_upsampler * upsample;
  160566. struct jpeg_color_deconverter * cconvert;
  160567. struct jpeg_color_quantizer * cquantize;
  160568. };
  160569. /* "Object" declarations for JPEG modules that may be supplied or called
  160570. * directly by the surrounding application.
  160571. * As with all objects in the JPEG library, these structs only define the
  160572. * publicly visible methods and state variables of a module. Additional
  160573. * private fields may exist after the public ones.
  160574. */
  160575. /* Error handler object */
  160576. struct jpeg_error_mgr {
  160577. /* Error exit handler: does not return to caller */
  160578. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160579. /* Conditionally emit a trace or warning message */
  160580. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160581. /* Routine that actually outputs a trace or error message */
  160582. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160583. /* Format a message string for the most recent JPEG error or message */
  160584. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160585. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160586. /* Reset error state variables at start of a new image */
  160587. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160588. /* The message ID code and any parameters are saved here.
  160589. * A message can have one string parameter or up to 8 int parameters.
  160590. */
  160591. int msg_code;
  160592. #define JMSG_STR_PARM_MAX 80
  160593. union {
  160594. int i[8];
  160595. char s[JMSG_STR_PARM_MAX];
  160596. } msg_parm;
  160597. /* Standard state variables for error facility */
  160598. int trace_level; /* max msg_level that will be displayed */
  160599. /* For recoverable corrupt-data errors, we emit a warning message,
  160600. * but keep going unless emit_message chooses to abort. emit_message
  160601. * should count warnings in num_warnings. The surrounding application
  160602. * can check for bad data by seeing if num_warnings is nonzero at the
  160603. * end of processing.
  160604. */
  160605. long num_warnings; /* number of corrupt-data warnings */
  160606. /* These fields point to the table(s) of error message strings.
  160607. * An application can change the table pointer to switch to a different
  160608. * message list (typically, to change the language in which errors are
  160609. * reported). Some applications may wish to add additional error codes
  160610. * that will be handled by the JPEG library error mechanism; the second
  160611. * table pointer is used for this purpose.
  160612. *
  160613. * First table includes all errors generated by JPEG library itself.
  160614. * Error code 0 is reserved for a "no such error string" message.
  160615. */
  160616. const char * const * jpeg_message_table; /* Library errors */
  160617. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160618. /* Second table can be added by application (see cjpeg/djpeg for example).
  160619. * It contains strings numbered first_addon_message..last_addon_message.
  160620. */
  160621. const char * const * addon_message_table; /* Non-library errors */
  160622. int first_addon_message; /* code for first string in addon table */
  160623. int last_addon_message; /* code for last string in addon table */
  160624. };
  160625. /* Progress monitor object */
  160626. struct jpeg_progress_mgr {
  160627. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160628. long pass_counter; /* work units completed in this pass */
  160629. long pass_limit; /* total number of work units in this pass */
  160630. int completed_passes; /* passes completed so far */
  160631. int total_passes; /* total number of passes expected */
  160632. };
  160633. /* Data destination object for compression */
  160634. struct jpeg_destination_mgr {
  160635. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160636. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160637. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160638. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160639. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160640. };
  160641. /* Data source object for decompression */
  160642. struct jpeg_source_mgr {
  160643. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160644. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160645. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160646. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160647. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160648. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160649. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160650. };
  160651. /* Memory manager object.
  160652. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160653. * and "really big" objects (virtual arrays with backing store if needed).
  160654. * The memory manager does not allow individual objects to be freed; rather,
  160655. * each created object is assigned to a pool, and whole pools can be freed
  160656. * at once. This is faster and more convenient than remembering exactly what
  160657. * to free, especially where malloc()/free() are not too speedy.
  160658. * NB: alloc routines never return NULL. They exit to error_exit if not
  160659. * successful.
  160660. */
  160661. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160662. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160663. #define JPOOL_NUMPOOLS 2
  160664. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160665. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160666. struct jpeg_memory_mgr {
  160667. /* Method pointers */
  160668. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160669. size_t sizeofobject));
  160670. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160671. size_t sizeofobject));
  160672. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160673. JDIMENSION samplesperrow,
  160674. JDIMENSION numrows));
  160675. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160676. JDIMENSION blocksperrow,
  160677. JDIMENSION numrows));
  160678. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160679. int pool_id,
  160680. boolean pre_zero,
  160681. JDIMENSION samplesperrow,
  160682. JDIMENSION numrows,
  160683. JDIMENSION maxaccess));
  160684. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160685. int pool_id,
  160686. boolean pre_zero,
  160687. JDIMENSION blocksperrow,
  160688. JDIMENSION numrows,
  160689. JDIMENSION maxaccess));
  160690. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160691. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160692. jvirt_sarray_ptr ptr,
  160693. JDIMENSION start_row,
  160694. JDIMENSION num_rows,
  160695. boolean writable));
  160696. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160697. jvirt_barray_ptr ptr,
  160698. JDIMENSION start_row,
  160699. JDIMENSION num_rows,
  160700. boolean writable));
  160701. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160702. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160703. /* Limit on memory allocation for this JPEG object. (Note that this is
  160704. * merely advisory, not a guaranteed maximum; it only affects the space
  160705. * used for virtual-array buffers.) May be changed by outer application
  160706. * after creating the JPEG object.
  160707. */
  160708. long max_memory_to_use;
  160709. /* Maximum allocation request accepted by alloc_large. */
  160710. long max_alloc_chunk;
  160711. };
  160712. /* Routine signature for application-supplied marker processing methods.
  160713. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160714. */
  160715. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160716. /* Declarations for routines called by application.
  160717. * The JPP macro hides prototype parameters from compilers that can't cope.
  160718. * Note JPP requires double parentheses.
  160719. */
  160720. #ifdef HAVE_PROTOTYPES
  160721. #define JPP(arglist) arglist
  160722. #else
  160723. #define JPP(arglist) ()
  160724. #endif
  160725. /* Short forms of external names for systems with brain-damaged linkers.
  160726. * We shorten external names to be unique in the first six letters, which
  160727. * is good enough for all known systems.
  160728. * (If your compiler itself needs names to be unique in less than 15
  160729. * characters, you are out of luck. Get a better compiler.)
  160730. */
  160731. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160732. #define jpeg_std_error jStdError
  160733. #define jpeg_CreateCompress jCreaCompress
  160734. #define jpeg_CreateDecompress jCreaDecompress
  160735. #define jpeg_destroy_compress jDestCompress
  160736. #define jpeg_destroy_decompress jDestDecompress
  160737. #define jpeg_stdio_dest jStdDest
  160738. #define jpeg_stdio_src jStdSrc
  160739. #define jpeg_set_defaults jSetDefaults
  160740. #define jpeg_set_colorspace jSetColorspace
  160741. #define jpeg_default_colorspace jDefColorspace
  160742. #define jpeg_set_quality jSetQuality
  160743. #define jpeg_set_linear_quality jSetLQuality
  160744. #define jpeg_add_quant_table jAddQuantTable
  160745. #define jpeg_quality_scaling jQualityScaling
  160746. #define jpeg_simple_progression jSimProgress
  160747. #define jpeg_suppress_tables jSuppressTables
  160748. #define jpeg_alloc_quant_table jAlcQTable
  160749. #define jpeg_alloc_huff_table jAlcHTable
  160750. #define jpeg_start_compress jStrtCompress
  160751. #define jpeg_write_scanlines jWrtScanlines
  160752. #define jpeg_finish_compress jFinCompress
  160753. #define jpeg_write_raw_data jWrtRawData
  160754. #define jpeg_write_marker jWrtMarker
  160755. #define jpeg_write_m_header jWrtMHeader
  160756. #define jpeg_write_m_byte jWrtMByte
  160757. #define jpeg_write_tables jWrtTables
  160758. #define jpeg_read_header jReadHeader
  160759. #define jpeg_start_decompress jStrtDecompress
  160760. #define jpeg_read_scanlines jReadScanlines
  160761. #define jpeg_finish_decompress jFinDecompress
  160762. #define jpeg_read_raw_data jReadRawData
  160763. #define jpeg_has_multiple_scans jHasMultScn
  160764. #define jpeg_start_output jStrtOutput
  160765. #define jpeg_finish_output jFinOutput
  160766. #define jpeg_input_complete jInComplete
  160767. #define jpeg_new_colormap jNewCMap
  160768. #define jpeg_consume_input jConsumeInput
  160769. #define jpeg_calc_output_dimensions jCalcDimensions
  160770. #define jpeg_save_markers jSaveMarkers
  160771. #define jpeg_set_marker_processor jSetMarker
  160772. #define jpeg_read_coefficients jReadCoefs
  160773. #define jpeg_write_coefficients jWrtCoefs
  160774. #define jpeg_copy_critical_parameters jCopyCrit
  160775. #define jpeg_abort_compress jAbrtCompress
  160776. #define jpeg_abort_decompress jAbrtDecompress
  160777. #define jpeg_abort jAbort
  160778. #define jpeg_destroy jDestroy
  160779. #define jpeg_resync_to_restart jResyncRestart
  160780. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160781. /* Default error-management setup */
  160782. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160783. JPP((struct jpeg_error_mgr * err));
  160784. /* Initialization of JPEG compression objects.
  160785. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160786. * names that applications should call. These expand to calls on
  160787. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160788. * passed for version mismatch checking.
  160789. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160790. */
  160791. #define jpeg_create_compress(cinfo) \
  160792. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160793. (size_t) sizeof(struct jpeg_compress_struct))
  160794. #define jpeg_create_decompress(cinfo) \
  160795. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160796. (size_t) sizeof(struct jpeg_decompress_struct))
  160797. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160798. int version, size_t structsize));
  160799. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160800. int version, size_t structsize));
  160801. /* Destruction of JPEG compression objects */
  160802. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160803. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160804. /* Standard data source and destination managers: stdio streams. */
  160805. /* Caller is responsible for opening the file before and closing after. */
  160806. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160807. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160808. /* Default parameter setup for compression */
  160809. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160810. /* Compression parameter setup aids */
  160811. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160812. J_COLOR_SPACE colorspace));
  160813. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160814. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160815. boolean force_baseline));
  160816. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160817. int scale_factor,
  160818. boolean force_baseline));
  160819. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160820. const unsigned int *basic_table,
  160821. int scale_factor,
  160822. boolean force_baseline));
  160823. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160824. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160825. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160826. boolean suppress));
  160827. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160828. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160829. /* Main entry points for compression */
  160830. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160831. boolean write_all_tables));
  160832. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160833. JSAMPARRAY scanlines,
  160834. JDIMENSION num_lines));
  160835. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160836. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160837. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160838. JSAMPIMAGE data,
  160839. JDIMENSION num_lines));
  160840. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160841. EXTERN(void) jpeg_write_marker
  160842. JPP((j_compress_ptr cinfo, int marker,
  160843. const JOCTET * dataptr, unsigned int datalen));
  160844. /* Same, but piecemeal. */
  160845. EXTERN(void) jpeg_write_m_header
  160846. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160847. EXTERN(void) jpeg_write_m_byte
  160848. JPP((j_compress_ptr cinfo, int val));
  160849. /* Alternate compression function: just write an abbreviated table file */
  160850. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160851. /* Decompression startup: read start of JPEG datastream to see what's there */
  160852. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160853. boolean require_image));
  160854. /* Return value is one of: */
  160855. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160856. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160857. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160858. /* If you pass require_image = TRUE (normal case), you need not check for
  160859. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160860. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160861. * give a suspension return (the stdio source module doesn't).
  160862. */
  160863. /* Main entry points for decompression */
  160864. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160865. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160866. JSAMPARRAY scanlines,
  160867. JDIMENSION max_lines));
  160868. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160869. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160870. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160871. JSAMPIMAGE data,
  160872. JDIMENSION max_lines));
  160873. /* Additional entry points for buffered-image mode. */
  160874. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160875. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160876. int scan_number));
  160877. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160878. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160879. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160880. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160881. /* Return value is one of: */
  160882. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160883. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160884. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160885. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160886. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160887. /* Precalculate output dimensions for current decompression parameters. */
  160888. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160889. /* Control saving of COM and APPn markers into marker_list. */
  160890. EXTERN(void) jpeg_save_markers
  160891. JPP((j_decompress_ptr cinfo, int marker_code,
  160892. unsigned int length_limit));
  160893. /* Install a special processing method for COM or APPn markers. */
  160894. EXTERN(void) jpeg_set_marker_processor
  160895. JPP((j_decompress_ptr cinfo, int marker_code,
  160896. jpeg_marker_parser_method routine));
  160897. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160898. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160899. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160900. jvirt_barray_ptr * coef_arrays));
  160901. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160902. j_compress_ptr dstinfo));
  160903. /* If you choose to abort compression or decompression before completing
  160904. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160905. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160906. * if you're done with the JPEG object, but if you want to clean it up and
  160907. * reuse it, call this:
  160908. */
  160909. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160910. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160911. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160912. * flavor of JPEG object. These may be more convenient in some places.
  160913. */
  160914. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160915. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160916. /* Default restart-marker-resync procedure for use by data source modules */
  160917. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160918. int desired));
  160919. /* These marker codes are exported since applications and data source modules
  160920. * are likely to want to use them.
  160921. */
  160922. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160923. #define JPEG_EOI 0xD9 /* EOI marker code */
  160924. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160925. #define JPEG_COM 0xFE /* COM marker code */
  160926. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160927. * for structure definitions that are never filled in, keep it quiet by
  160928. * supplying dummy definitions for the various substructures.
  160929. */
  160930. #ifdef INCOMPLETE_TYPES_BROKEN
  160931. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160932. struct jvirt_sarray_control { long dummy; };
  160933. struct jvirt_barray_control { long dummy; };
  160934. struct jpeg_comp_master { long dummy; };
  160935. struct jpeg_c_main_controller { long dummy; };
  160936. struct jpeg_c_prep_controller { long dummy; };
  160937. struct jpeg_c_coef_controller { long dummy; };
  160938. struct jpeg_marker_writer { long dummy; };
  160939. struct jpeg_color_converter { long dummy; };
  160940. struct jpeg_downsampler { long dummy; };
  160941. struct jpeg_forward_dct { long dummy; };
  160942. struct jpeg_entropy_encoder { long dummy; };
  160943. struct jpeg_decomp_master { long dummy; };
  160944. struct jpeg_d_main_controller { long dummy; };
  160945. struct jpeg_d_coef_controller { long dummy; };
  160946. struct jpeg_d_post_controller { long dummy; };
  160947. struct jpeg_input_controller { long dummy; };
  160948. struct jpeg_marker_reader { long dummy; };
  160949. struct jpeg_entropy_decoder { long dummy; };
  160950. struct jpeg_inverse_dct { long dummy; };
  160951. struct jpeg_upsampler { long dummy; };
  160952. struct jpeg_color_deconverter { long dummy; };
  160953. struct jpeg_color_quantizer { long dummy; };
  160954. #endif /* JPEG_INTERNALS */
  160955. #endif /* INCOMPLETE_TYPES_BROKEN */
  160956. /*
  160957. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160958. * The internal structure declarations are read only when that is true.
  160959. * Applications using the library should not include jpegint.h, but may wish
  160960. * to include jerror.h.
  160961. */
  160962. #ifdef JPEG_INTERNALS
  160963. /*** Start of inlined file: jpegint.h ***/
  160964. /* Declarations for both compression & decompression */
  160965. typedef enum { /* Operating modes for buffer controllers */
  160966. JBUF_PASS_THRU, /* Plain stripwise operation */
  160967. /* Remaining modes require a full-image buffer to have been created */
  160968. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160969. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160970. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160971. } J_BUF_MODE;
  160972. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160973. #define CSTATE_START 100 /* after create_compress */
  160974. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160975. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160976. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160977. #define DSTATE_START 200 /* after create_decompress */
  160978. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160979. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160980. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160981. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160982. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160983. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160984. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160985. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160986. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160987. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160988. /* Declarations for compression modules */
  160989. /* Master control module */
  160990. struct jpeg_comp_master {
  160991. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160992. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160993. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160994. /* State variables made visible to other modules */
  160995. boolean call_pass_startup; /* True if pass_startup must be called */
  160996. boolean is_last_pass; /* True during last pass */
  160997. };
  160998. /* Main buffer control (downsampled-data buffer) */
  160999. struct jpeg_c_main_controller {
  161000. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161001. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  161002. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161003. JDIMENSION in_rows_avail));
  161004. };
  161005. /* Compression preprocessing (downsampling input buffer control) */
  161006. struct jpeg_c_prep_controller {
  161007. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161008. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  161009. JSAMPARRAY input_buf,
  161010. JDIMENSION *in_row_ctr,
  161011. JDIMENSION in_rows_avail,
  161012. JSAMPIMAGE output_buf,
  161013. JDIMENSION *out_row_group_ctr,
  161014. JDIMENSION out_row_groups_avail));
  161015. };
  161016. /* Coefficient buffer control */
  161017. struct jpeg_c_coef_controller {
  161018. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161019. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  161020. JSAMPIMAGE input_buf));
  161021. };
  161022. /* Colorspace conversion */
  161023. struct jpeg_color_converter {
  161024. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161025. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  161026. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161027. JDIMENSION output_row, int num_rows));
  161028. };
  161029. /* Downsampling */
  161030. struct jpeg_downsampler {
  161031. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161032. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  161033. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161034. JSAMPIMAGE output_buf,
  161035. JDIMENSION out_row_group_index));
  161036. boolean need_context_rows; /* TRUE if need rows above & below */
  161037. };
  161038. /* Forward DCT (also controls coefficient quantization) */
  161039. struct jpeg_forward_dct {
  161040. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161041. /* perhaps this should be an array??? */
  161042. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  161043. jpeg_component_info * compptr,
  161044. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161045. JDIMENSION start_row, JDIMENSION start_col,
  161046. JDIMENSION num_blocks));
  161047. };
  161048. /* Entropy encoding */
  161049. struct jpeg_entropy_encoder {
  161050. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  161051. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  161052. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161053. };
  161054. /* Marker writing */
  161055. struct jpeg_marker_writer {
  161056. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  161057. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  161058. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  161059. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  161060. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  161061. /* These routines are exported to allow insertion of extra markers */
  161062. /* Probably only COM and APPn markers should be written this way */
  161063. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  161064. unsigned int datalen));
  161065. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  161066. };
  161067. /* Declarations for decompression modules */
  161068. /* Master control module */
  161069. struct jpeg_decomp_master {
  161070. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  161071. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  161072. /* State variables made visible to other modules */
  161073. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  161074. };
  161075. /* Input control module */
  161076. struct jpeg_input_controller {
  161077. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  161078. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  161079. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161080. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  161081. /* State variables made visible to other modules */
  161082. boolean has_multiple_scans; /* True if file has multiple scans */
  161083. boolean eoi_reached; /* True when EOI has been consumed */
  161084. };
  161085. /* Main buffer control (downsampled-data buffer) */
  161086. struct jpeg_d_main_controller {
  161087. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161088. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  161089. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  161090. JDIMENSION out_rows_avail));
  161091. };
  161092. /* Coefficient buffer control */
  161093. struct jpeg_d_coef_controller {
  161094. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161095. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  161096. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  161097. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  161098. JSAMPIMAGE output_buf));
  161099. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  161100. jvirt_barray_ptr *coef_arrays;
  161101. };
  161102. /* Decompression postprocessing (color quantization buffer control) */
  161103. struct jpeg_d_post_controller {
  161104. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161105. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  161106. JSAMPIMAGE input_buf,
  161107. JDIMENSION *in_row_group_ctr,
  161108. JDIMENSION in_row_groups_avail,
  161109. JSAMPARRAY output_buf,
  161110. JDIMENSION *out_row_ctr,
  161111. JDIMENSION out_rows_avail));
  161112. };
  161113. /* Marker reading & parsing */
  161114. struct jpeg_marker_reader {
  161115. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161116. /* Read markers until SOS or EOI.
  161117. * Returns same codes as are defined for jpeg_consume_input:
  161118. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161119. */
  161120. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161121. /* Read a restart marker --- exported for use by entropy decoder only */
  161122. jpeg_marker_parser_method read_restart_marker;
  161123. /* State of marker reader --- nominally internal, but applications
  161124. * supplying COM or APPn handlers might like to know the state.
  161125. */
  161126. boolean saw_SOI; /* found SOI? */
  161127. boolean saw_SOF; /* found SOF? */
  161128. int next_restart_num; /* next restart number expected (0-7) */
  161129. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161130. };
  161131. /* Entropy decoding */
  161132. struct jpeg_entropy_decoder {
  161133. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161134. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161135. JBLOCKROW *MCU_data));
  161136. /* This is here to share code between baseline and progressive decoders; */
  161137. /* other modules probably should not use it */
  161138. boolean insufficient_data; /* set TRUE after emitting warning */
  161139. };
  161140. /* Inverse DCT (also performs dequantization) */
  161141. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161142. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161143. JCOEFPTR coef_block,
  161144. JSAMPARRAY output_buf, JDIMENSION output_col));
  161145. struct jpeg_inverse_dct {
  161146. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161147. /* It is useful to allow each component to have a separate IDCT method. */
  161148. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161149. };
  161150. /* Upsampling (note that upsampler must also call color converter) */
  161151. struct jpeg_upsampler {
  161152. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161153. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161154. JSAMPIMAGE input_buf,
  161155. JDIMENSION *in_row_group_ctr,
  161156. JDIMENSION in_row_groups_avail,
  161157. JSAMPARRAY output_buf,
  161158. JDIMENSION *out_row_ctr,
  161159. JDIMENSION out_rows_avail));
  161160. boolean need_context_rows; /* TRUE if need rows above & below */
  161161. };
  161162. /* Colorspace conversion */
  161163. struct jpeg_color_deconverter {
  161164. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161165. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161166. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161167. JSAMPARRAY output_buf, int num_rows));
  161168. };
  161169. /* Color quantization or color precision reduction */
  161170. struct jpeg_color_quantizer {
  161171. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161172. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161173. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161174. int num_rows));
  161175. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161176. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161177. };
  161178. /* Miscellaneous useful macros */
  161179. #undef MAX
  161180. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161181. #undef MIN
  161182. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161183. /* We assume that right shift corresponds to signed division by 2 with
  161184. * rounding towards minus infinity. This is correct for typical "arithmetic
  161185. * shift" instructions that shift in copies of the sign bit. But some
  161186. * C compilers implement >> with an unsigned shift. For these machines you
  161187. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161188. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161189. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161190. * included in the variables of any routine using RIGHT_SHIFT.
  161191. */
  161192. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161193. #define SHIFT_TEMPS INT32 shift_temp;
  161194. #define RIGHT_SHIFT(x,shft) \
  161195. ((shift_temp = (x)) < 0 ? \
  161196. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161197. (shift_temp >> (shft)))
  161198. #else
  161199. #define SHIFT_TEMPS
  161200. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161201. #endif
  161202. /* Short forms of external names for systems with brain-damaged linkers. */
  161203. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161204. #define jinit_compress_master jICompress
  161205. #define jinit_c_master_control jICMaster
  161206. #define jinit_c_main_controller jICMainC
  161207. #define jinit_c_prep_controller jICPrepC
  161208. #define jinit_c_coef_controller jICCoefC
  161209. #define jinit_color_converter jICColor
  161210. #define jinit_downsampler jIDownsampler
  161211. #define jinit_forward_dct jIFDCT
  161212. #define jinit_huff_encoder jIHEncoder
  161213. #define jinit_phuff_encoder jIPHEncoder
  161214. #define jinit_marker_writer jIMWriter
  161215. #define jinit_master_decompress jIDMaster
  161216. #define jinit_d_main_controller jIDMainC
  161217. #define jinit_d_coef_controller jIDCoefC
  161218. #define jinit_d_post_controller jIDPostC
  161219. #define jinit_input_controller jIInCtlr
  161220. #define jinit_marker_reader jIMReader
  161221. #define jinit_huff_decoder jIHDecoder
  161222. #define jinit_phuff_decoder jIPHDecoder
  161223. #define jinit_inverse_dct jIIDCT
  161224. #define jinit_upsampler jIUpsampler
  161225. #define jinit_color_deconverter jIDColor
  161226. #define jinit_1pass_quantizer jI1Quant
  161227. #define jinit_2pass_quantizer jI2Quant
  161228. #define jinit_merged_upsampler jIMUpsampler
  161229. #define jinit_memory_mgr jIMemMgr
  161230. #define jdiv_round_up jDivRound
  161231. #define jround_up jRound
  161232. #define jcopy_sample_rows jCopySamples
  161233. #define jcopy_block_row jCopyBlocks
  161234. #define jzero_far jZeroFar
  161235. #define jpeg_zigzag_order jZIGTable
  161236. #define jpeg_natural_order jZAGTable
  161237. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161238. /* Compression module initialization routines */
  161239. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161240. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161241. boolean transcode_only));
  161242. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161243. boolean need_full_buffer));
  161244. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161245. boolean need_full_buffer));
  161246. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161247. boolean need_full_buffer));
  161248. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161249. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161250. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161251. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161252. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161253. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161254. /* Decompression module initialization routines */
  161255. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161256. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161257. boolean need_full_buffer));
  161258. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161259. boolean need_full_buffer));
  161260. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161261. boolean need_full_buffer));
  161262. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161263. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161264. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161265. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161266. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161267. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161268. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161269. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161270. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161271. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161272. /* Memory manager initialization */
  161273. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161274. /* Utility routines in jutils.c */
  161275. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161276. EXTERN(long) jround_up JPP((long a, long b));
  161277. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161278. JSAMPARRAY output_array, int dest_row,
  161279. int num_rows, JDIMENSION num_cols));
  161280. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161281. JDIMENSION num_blocks));
  161282. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161283. /* Constant tables in jutils.c */
  161284. #if 0 /* This table is not actually needed in v6a */
  161285. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161286. #endif
  161287. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161288. /* Suppress undefined-structure complaints if necessary. */
  161289. #ifdef INCOMPLETE_TYPES_BROKEN
  161290. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161291. struct jvirt_sarray_control { long dummy; };
  161292. struct jvirt_barray_control { long dummy; };
  161293. #endif
  161294. #endif /* INCOMPLETE_TYPES_BROKEN */
  161295. /*** End of inlined file: jpegint.h ***/
  161296. /* fetch private declarations */
  161297. /*** Start of inlined file: jerror.h ***/
  161298. /*
  161299. * To define the enum list of message codes, include this file without
  161300. * defining macro JMESSAGE. To create a message string table, include it
  161301. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161302. */
  161303. #ifndef JMESSAGE
  161304. #ifndef JERROR_H
  161305. /* First time through, define the enum list */
  161306. #define JMAKE_ENUM_LIST
  161307. #else
  161308. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161309. #define JMESSAGE(code,string)
  161310. #endif /* JERROR_H */
  161311. #endif /* JMESSAGE */
  161312. #ifdef JMAKE_ENUM_LIST
  161313. typedef enum {
  161314. #define JMESSAGE(code,string) code ,
  161315. #endif /* JMAKE_ENUM_LIST */
  161316. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161317. /* For maintenance convenience, list is alphabetical by message code name */
  161318. JMESSAGE(JERR_ARITH_NOTIMPL,
  161319. "Sorry, there are legal restrictions on arithmetic coding")
  161320. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161321. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161322. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161323. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161324. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161325. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161326. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161327. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161328. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161329. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161330. JMESSAGE(JERR_BAD_LIB_VERSION,
  161331. "Wrong JPEG library version: library is %d, caller expects %d")
  161332. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161333. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161334. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161335. JMESSAGE(JERR_BAD_PROGRESSION,
  161336. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161337. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161338. "Invalid progressive parameters at scan script entry %d")
  161339. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161340. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161341. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161342. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161343. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161344. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161345. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161346. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161347. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161348. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161349. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161350. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161351. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161352. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161353. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161354. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161355. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161356. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161357. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161358. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161359. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161360. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161361. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161362. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161363. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161364. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161365. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161366. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161367. "Cannot transcode due to multiple use of quantization table %d")
  161368. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161369. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161370. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161371. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161372. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161373. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161374. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161375. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161376. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161377. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161378. JMESSAGE(JERR_QUANT_COMPONENTS,
  161379. "Cannot quantize more than %d color components")
  161380. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161381. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161382. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161383. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161384. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161385. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161386. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161387. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161388. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161389. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161390. JMESSAGE(JERR_TFILE_WRITE,
  161391. "Write failed on temporary file --- out of disk space?")
  161392. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161393. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161394. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161395. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161396. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161397. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161398. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161399. JMESSAGE(JMSG_VERSION, JVERSION)
  161400. JMESSAGE(JTRC_16BIT_TABLES,
  161401. "Caution: quantization tables are too coarse for baseline JPEG")
  161402. JMESSAGE(JTRC_ADOBE,
  161403. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161404. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161405. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161406. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161407. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161408. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161409. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161410. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161411. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161412. JMESSAGE(JTRC_EOI, "End Of Image")
  161413. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161414. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161415. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161416. "Warning: thumbnail image size does not match data length %u")
  161417. JMESSAGE(JTRC_JFIF_EXTENSION,
  161418. "JFIF extension marker: type 0x%02x, length %u")
  161419. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161420. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161421. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161422. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161423. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161424. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161425. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161426. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161427. JMESSAGE(JTRC_RST, "RST%d")
  161428. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161429. "Smoothing not supported with nonstandard sampling ratios")
  161430. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161431. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161432. JMESSAGE(JTRC_SOI, "Start of Image")
  161433. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161434. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161435. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161436. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161437. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161438. JMESSAGE(JTRC_THUMB_JPEG,
  161439. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161440. JMESSAGE(JTRC_THUMB_PALETTE,
  161441. "JFIF extension marker: palette thumbnail image, length %u")
  161442. JMESSAGE(JTRC_THUMB_RGB,
  161443. "JFIF extension marker: RGB thumbnail image, length %u")
  161444. JMESSAGE(JTRC_UNKNOWN_IDS,
  161445. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161446. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161447. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161448. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161449. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161450. "Inconsistent progression sequence for component %d coefficient %d")
  161451. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161452. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161453. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161454. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161455. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161456. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161457. JMESSAGE(JWRN_MUST_RESYNC,
  161458. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161459. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161460. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161461. #ifdef JMAKE_ENUM_LIST
  161462. JMSG_LASTMSGCODE
  161463. } J_MESSAGE_CODE;
  161464. #undef JMAKE_ENUM_LIST
  161465. #endif /* JMAKE_ENUM_LIST */
  161466. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161467. #undef JMESSAGE
  161468. #ifndef JERROR_H
  161469. #define JERROR_H
  161470. /* Macros to simplify using the error and trace message stuff */
  161471. /* The first parameter is either type of cinfo pointer */
  161472. /* Fatal errors (print message and exit) */
  161473. #define ERREXIT(cinfo,code) \
  161474. ((cinfo)->err->msg_code = (code), \
  161475. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161476. #define ERREXIT1(cinfo,code,p1) \
  161477. ((cinfo)->err->msg_code = (code), \
  161478. (cinfo)->err->msg_parm.i[0] = (p1), \
  161479. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161480. #define ERREXIT2(cinfo,code,p1,p2) \
  161481. ((cinfo)->err->msg_code = (code), \
  161482. (cinfo)->err->msg_parm.i[0] = (p1), \
  161483. (cinfo)->err->msg_parm.i[1] = (p2), \
  161484. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161485. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161486. ((cinfo)->err->msg_code = (code), \
  161487. (cinfo)->err->msg_parm.i[0] = (p1), \
  161488. (cinfo)->err->msg_parm.i[1] = (p2), \
  161489. (cinfo)->err->msg_parm.i[2] = (p3), \
  161490. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161491. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161492. ((cinfo)->err->msg_code = (code), \
  161493. (cinfo)->err->msg_parm.i[0] = (p1), \
  161494. (cinfo)->err->msg_parm.i[1] = (p2), \
  161495. (cinfo)->err->msg_parm.i[2] = (p3), \
  161496. (cinfo)->err->msg_parm.i[3] = (p4), \
  161497. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161498. #define ERREXITS(cinfo,code,str) \
  161499. ((cinfo)->err->msg_code = (code), \
  161500. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161501. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161502. #define MAKESTMT(stuff) do { stuff } while (0)
  161503. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161504. #define WARNMS(cinfo,code) \
  161505. ((cinfo)->err->msg_code = (code), \
  161506. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161507. #define WARNMS1(cinfo,code,p1) \
  161508. ((cinfo)->err->msg_code = (code), \
  161509. (cinfo)->err->msg_parm.i[0] = (p1), \
  161510. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161511. #define WARNMS2(cinfo,code,p1,p2) \
  161512. ((cinfo)->err->msg_code = (code), \
  161513. (cinfo)->err->msg_parm.i[0] = (p1), \
  161514. (cinfo)->err->msg_parm.i[1] = (p2), \
  161515. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161516. /* Informational/debugging messages */
  161517. #define TRACEMS(cinfo,lvl,code) \
  161518. ((cinfo)->err->msg_code = (code), \
  161519. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161520. #define TRACEMS1(cinfo,lvl,code,p1) \
  161521. ((cinfo)->err->msg_code = (code), \
  161522. (cinfo)->err->msg_parm.i[0] = (p1), \
  161523. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161524. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161525. ((cinfo)->err->msg_code = (code), \
  161526. (cinfo)->err->msg_parm.i[0] = (p1), \
  161527. (cinfo)->err->msg_parm.i[1] = (p2), \
  161528. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161529. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161530. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161531. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161532. (cinfo)->err->msg_code = (code); \
  161533. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161534. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161535. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161536. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161537. (cinfo)->err->msg_code = (code); \
  161538. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161539. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161540. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161541. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161542. _mp[4] = (p5); \
  161543. (cinfo)->err->msg_code = (code); \
  161544. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161545. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161546. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161547. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161548. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161549. (cinfo)->err->msg_code = (code); \
  161550. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161551. #define TRACEMSS(cinfo,lvl,code,str) \
  161552. ((cinfo)->err->msg_code = (code), \
  161553. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161554. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161555. #endif /* JERROR_H */
  161556. /*** End of inlined file: jerror.h ***/
  161557. /* fetch error codes too */
  161558. #endif
  161559. #endif /* JPEGLIB_H */
  161560. /*** End of inlined file: jpeglib.h ***/
  161561. /*** Start of inlined file: jcapimin.c ***/
  161562. #define JPEG_INTERNALS
  161563. /*** Start of inlined file: jinclude.h ***/
  161564. /* Include auto-config file to find out which system include files we need. */
  161565. #ifndef __jinclude_h__
  161566. #define __jinclude_h__
  161567. /*** Start of inlined file: jconfig.h ***/
  161568. /* see jconfig.doc for explanations */
  161569. // disable all the warnings under MSVC
  161570. #ifdef _MSC_VER
  161571. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161572. #endif
  161573. #ifdef __BORLANDC__
  161574. #pragma warn -8057
  161575. #pragma warn -8019
  161576. #pragma warn -8004
  161577. #pragma warn -8008
  161578. #endif
  161579. #define HAVE_PROTOTYPES
  161580. #define HAVE_UNSIGNED_CHAR
  161581. #define HAVE_UNSIGNED_SHORT
  161582. /* #define void char */
  161583. /* #define const */
  161584. #undef CHAR_IS_UNSIGNED
  161585. #define HAVE_STDDEF_H
  161586. #define HAVE_STDLIB_H
  161587. #undef NEED_BSD_STRINGS
  161588. #undef NEED_SYS_TYPES_H
  161589. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161590. #undef NEED_SHORT_EXTERNAL_NAMES
  161591. #undef INCOMPLETE_TYPES_BROKEN
  161592. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161593. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161594. typedef unsigned char boolean;
  161595. #endif
  161596. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161597. #ifdef JPEG_INTERNALS
  161598. #undef RIGHT_SHIFT_IS_UNSIGNED
  161599. #endif /* JPEG_INTERNALS */
  161600. #ifdef JPEG_CJPEG_DJPEG
  161601. #define BMP_SUPPORTED /* BMP image file format */
  161602. #define GIF_SUPPORTED /* GIF image file format */
  161603. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161604. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161605. #define TARGA_SUPPORTED /* Targa image file format */
  161606. #define TWO_FILE_COMMANDLINE /* optional */
  161607. #define USE_SETMODE /* Microsoft has setmode() */
  161608. #undef NEED_SIGNAL_CATCHER
  161609. #undef DONT_USE_B_MODE
  161610. #undef PROGRESS_REPORT /* optional */
  161611. #endif /* JPEG_CJPEG_DJPEG */
  161612. /*** End of inlined file: jconfig.h ***/
  161613. /* auto configuration options */
  161614. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161615. /*
  161616. * We need the NULL macro and size_t typedef.
  161617. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161618. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161619. * pull in <sys/types.h> as well.
  161620. * Note that the core JPEG library does not require <stdio.h>;
  161621. * only the default error handler and data source/destination modules do.
  161622. * But we must pull it in because of the references to FILE in jpeglib.h.
  161623. * You can remove those references if you want to compile without <stdio.h>.
  161624. */
  161625. #ifdef HAVE_STDDEF_H
  161626. #include <stddef.h>
  161627. #endif
  161628. #ifdef HAVE_STDLIB_H
  161629. #include <stdlib.h>
  161630. #endif
  161631. #ifdef NEED_SYS_TYPES_H
  161632. #include <sys/types.h>
  161633. #endif
  161634. #include <stdio.h>
  161635. /*
  161636. * We need memory copying and zeroing functions, plus strncpy().
  161637. * ANSI and System V implementations declare these in <string.h>.
  161638. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161639. * Some systems may declare memset and memcpy in <memory.h>.
  161640. *
  161641. * NOTE: we assume the size parameters to these functions are of type size_t.
  161642. * Change the casts in these macros if not!
  161643. */
  161644. #ifdef NEED_BSD_STRINGS
  161645. #include <strings.h>
  161646. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161647. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161648. #else /* not BSD, assume ANSI/SysV string lib */
  161649. #include <string.h>
  161650. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161651. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161652. #endif
  161653. /*
  161654. * In ANSI C, and indeed any rational implementation, size_t is also the
  161655. * type returned by sizeof(). However, it seems there are some irrational
  161656. * implementations out there, in which sizeof() returns an int even though
  161657. * size_t is defined as long or unsigned long. To ensure consistent results
  161658. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161659. */
  161660. #define SIZEOF(object) ((size_t) sizeof(object))
  161661. /*
  161662. * The modules that use fread() and fwrite() always invoke them through
  161663. * these macros. On some systems you may need to twiddle the argument casts.
  161664. * CAUTION: argument order is different from underlying functions!
  161665. */
  161666. #define JFREAD(file,buf,sizeofbuf) \
  161667. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161668. #define JFWRITE(file,buf,sizeofbuf) \
  161669. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161670. typedef enum { /* JPEG marker codes */
  161671. M_SOF0 = 0xc0,
  161672. M_SOF1 = 0xc1,
  161673. M_SOF2 = 0xc2,
  161674. M_SOF3 = 0xc3,
  161675. M_SOF5 = 0xc5,
  161676. M_SOF6 = 0xc6,
  161677. M_SOF7 = 0xc7,
  161678. M_JPG = 0xc8,
  161679. M_SOF9 = 0xc9,
  161680. M_SOF10 = 0xca,
  161681. M_SOF11 = 0xcb,
  161682. M_SOF13 = 0xcd,
  161683. M_SOF14 = 0xce,
  161684. M_SOF15 = 0xcf,
  161685. M_DHT = 0xc4,
  161686. M_DAC = 0xcc,
  161687. M_RST0 = 0xd0,
  161688. M_RST1 = 0xd1,
  161689. M_RST2 = 0xd2,
  161690. M_RST3 = 0xd3,
  161691. M_RST4 = 0xd4,
  161692. M_RST5 = 0xd5,
  161693. M_RST6 = 0xd6,
  161694. M_RST7 = 0xd7,
  161695. M_SOI = 0xd8,
  161696. M_EOI = 0xd9,
  161697. M_SOS = 0xda,
  161698. M_DQT = 0xdb,
  161699. M_DNL = 0xdc,
  161700. M_DRI = 0xdd,
  161701. M_DHP = 0xde,
  161702. M_EXP = 0xdf,
  161703. M_APP0 = 0xe0,
  161704. M_APP1 = 0xe1,
  161705. M_APP2 = 0xe2,
  161706. M_APP3 = 0xe3,
  161707. M_APP4 = 0xe4,
  161708. M_APP5 = 0xe5,
  161709. M_APP6 = 0xe6,
  161710. M_APP7 = 0xe7,
  161711. M_APP8 = 0xe8,
  161712. M_APP9 = 0xe9,
  161713. M_APP10 = 0xea,
  161714. M_APP11 = 0xeb,
  161715. M_APP12 = 0xec,
  161716. M_APP13 = 0xed,
  161717. M_APP14 = 0xee,
  161718. M_APP15 = 0xef,
  161719. M_JPG0 = 0xf0,
  161720. M_JPG13 = 0xfd,
  161721. M_COM = 0xfe,
  161722. M_TEM = 0x01,
  161723. M_ERROR = 0x100
  161724. } JPEG_MARKER;
  161725. /*
  161726. * Figure F.12: extend sign bit.
  161727. * On some machines, a shift and add will be faster than a table lookup.
  161728. */
  161729. #ifdef AVOID_TABLES
  161730. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161731. #else
  161732. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161733. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161734. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161735. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161736. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161737. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161738. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161739. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161740. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161741. #endif /* AVOID_TABLES */
  161742. #endif
  161743. /*** End of inlined file: jinclude.h ***/
  161744. /*
  161745. * Initialization of a JPEG compression object.
  161746. * The error manager must already be set up (in case memory manager fails).
  161747. */
  161748. GLOBAL(void)
  161749. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161750. {
  161751. int i;
  161752. /* Guard against version mismatches between library and caller. */
  161753. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161754. if (version != JPEG_LIB_VERSION)
  161755. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161756. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161757. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161758. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161759. /* For debugging purposes, we zero the whole master structure.
  161760. * But the application has already set the err pointer, and may have set
  161761. * client_data, so we have to save and restore those fields.
  161762. * Note: if application hasn't set client_data, tools like Purify may
  161763. * complain here.
  161764. */
  161765. {
  161766. struct jpeg_error_mgr * err = cinfo->err;
  161767. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161768. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161769. cinfo->err = err;
  161770. cinfo->client_data = client_data;
  161771. }
  161772. cinfo->is_decompressor = FALSE;
  161773. /* Initialize a memory manager instance for this object */
  161774. jinit_memory_mgr((j_common_ptr) cinfo);
  161775. /* Zero out pointers to permanent structures. */
  161776. cinfo->progress = NULL;
  161777. cinfo->dest = NULL;
  161778. cinfo->comp_info = NULL;
  161779. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161780. cinfo->quant_tbl_ptrs[i] = NULL;
  161781. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161782. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161783. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161784. }
  161785. cinfo->script_space = NULL;
  161786. cinfo->input_gamma = 1.0; /* in case application forgets */
  161787. /* OK, I'm ready */
  161788. cinfo->global_state = CSTATE_START;
  161789. }
  161790. /*
  161791. * Destruction of a JPEG compression object
  161792. */
  161793. GLOBAL(void)
  161794. jpeg_destroy_compress (j_compress_ptr cinfo)
  161795. {
  161796. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161797. }
  161798. /*
  161799. * Abort processing of a JPEG compression operation,
  161800. * but don't destroy the object itself.
  161801. */
  161802. GLOBAL(void)
  161803. jpeg_abort_compress (j_compress_ptr cinfo)
  161804. {
  161805. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161806. }
  161807. /*
  161808. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161809. * Marks all currently defined tables as already written (if suppress)
  161810. * or not written (if !suppress). This will control whether they get emitted
  161811. * by a subsequent jpeg_start_compress call.
  161812. *
  161813. * This routine is exported for use by applications that want to produce
  161814. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161815. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161816. * jcparam.o would be linked whether the application used it or not.
  161817. */
  161818. GLOBAL(void)
  161819. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161820. {
  161821. int i;
  161822. JQUANT_TBL * qtbl;
  161823. JHUFF_TBL * htbl;
  161824. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161825. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161826. qtbl->sent_table = suppress;
  161827. }
  161828. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161829. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161830. htbl->sent_table = suppress;
  161831. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161832. htbl->sent_table = suppress;
  161833. }
  161834. }
  161835. /*
  161836. * Finish JPEG compression.
  161837. *
  161838. * If a multipass operating mode was selected, this may do a great deal of
  161839. * work including most of the actual output.
  161840. */
  161841. GLOBAL(void)
  161842. jpeg_finish_compress (j_compress_ptr cinfo)
  161843. {
  161844. JDIMENSION iMCU_row;
  161845. if (cinfo->global_state == CSTATE_SCANNING ||
  161846. cinfo->global_state == CSTATE_RAW_OK) {
  161847. /* Terminate first pass */
  161848. if (cinfo->next_scanline < cinfo->image_height)
  161849. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161850. (*cinfo->master->finish_pass) (cinfo);
  161851. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161852. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161853. /* Perform any remaining passes */
  161854. while (! cinfo->master->is_last_pass) {
  161855. (*cinfo->master->prepare_for_pass) (cinfo);
  161856. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161857. if (cinfo->progress != NULL) {
  161858. cinfo->progress->pass_counter = (long) iMCU_row;
  161859. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161860. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161861. }
  161862. /* We bypass the main controller and invoke coef controller directly;
  161863. * all work is being done from the coefficient buffer.
  161864. */
  161865. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161866. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161867. }
  161868. (*cinfo->master->finish_pass) (cinfo);
  161869. }
  161870. /* Write EOI, do final cleanup */
  161871. (*cinfo->marker->write_file_trailer) (cinfo);
  161872. (*cinfo->dest->term_destination) (cinfo);
  161873. /* We can use jpeg_abort to release memory and reset global_state */
  161874. jpeg_abort((j_common_ptr) cinfo);
  161875. }
  161876. /*
  161877. * Write a special marker.
  161878. * This is only recommended for writing COM or APPn markers.
  161879. * Must be called after jpeg_start_compress() and before
  161880. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161881. */
  161882. GLOBAL(void)
  161883. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161884. const JOCTET *dataptr, unsigned int datalen)
  161885. {
  161886. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161887. if (cinfo->next_scanline != 0 ||
  161888. (cinfo->global_state != CSTATE_SCANNING &&
  161889. cinfo->global_state != CSTATE_RAW_OK &&
  161890. cinfo->global_state != CSTATE_WRCOEFS))
  161891. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161892. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161893. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161894. while (datalen--) {
  161895. (*write_marker_byte) (cinfo, *dataptr);
  161896. dataptr++;
  161897. }
  161898. }
  161899. /* Same, but piecemeal. */
  161900. GLOBAL(void)
  161901. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161902. {
  161903. if (cinfo->next_scanline != 0 ||
  161904. (cinfo->global_state != CSTATE_SCANNING &&
  161905. cinfo->global_state != CSTATE_RAW_OK &&
  161906. cinfo->global_state != CSTATE_WRCOEFS))
  161907. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161908. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161909. }
  161910. GLOBAL(void)
  161911. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161912. {
  161913. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161914. }
  161915. /*
  161916. * Alternate compression function: just write an abbreviated table file.
  161917. * Before calling this, all parameters and a data destination must be set up.
  161918. *
  161919. * To produce a pair of files containing abbreviated tables and abbreviated
  161920. * image data, one would proceed as follows:
  161921. *
  161922. * initialize JPEG object
  161923. * set JPEG parameters
  161924. * set destination to table file
  161925. * jpeg_write_tables(cinfo);
  161926. * set destination to image file
  161927. * jpeg_start_compress(cinfo, FALSE);
  161928. * write data...
  161929. * jpeg_finish_compress(cinfo);
  161930. *
  161931. * jpeg_write_tables has the side effect of marking all tables written
  161932. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161933. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161934. */
  161935. GLOBAL(void)
  161936. jpeg_write_tables (j_compress_ptr cinfo)
  161937. {
  161938. if (cinfo->global_state != CSTATE_START)
  161939. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161940. /* (Re)initialize error mgr and destination modules */
  161941. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161942. (*cinfo->dest->init_destination) (cinfo);
  161943. /* Initialize the marker writer ... bit of a crock to do it here. */
  161944. jinit_marker_writer(cinfo);
  161945. /* Write them tables! */
  161946. (*cinfo->marker->write_tables_only) (cinfo);
  161947. /* And clean up. */
  161948. (*cinfo->dest->term_destination) (cinfo);
  161949. /*
  161950. * In library releases up through v6a, we called jpeg_abort() here to free
  161951. * any working memory allocated by the destination manager and marker
  161952. * writer. Some applications had a problem with that: they allocated space
  161953. * of their own from the library memory manager, and didn't want it to go
  161954. * away during write_tables. So now we do nothing. This will cause a
  161955. * memory leak if an app calls write_tables repeatedly without doing a full
  161956. * compression cycle or otherwise resetting the JPEG object. However, that
  161957. * seems less bad than unexpectedly freeing memory in the normal case.
  161958. * An app that prefers the old behavior can call jpeg_abort for itself after
  161959. * each call to jpeg_write_tables().
  161960. */
  161961. }
  161962. /*** End of inlined file: jcapimin.c ***/
  161963. /*** Start of inlined file: jcapistd.c ***/
  161964. #define JPEG_INTERNALS
  161965. /*
  161966. * Compression initialization.
  161967. * Before calling this, all parameters and a data destination must be set up.
  161968. *
  161969. * We require a write_all_tables parameter as a failsafe check when writing
  161970. * multiple datastreams from the same compression object. Since prior runs
  161971. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161972. * would emit an abbreviated stream (no tables) by default. This may be what
  161973. * is wanted, but for safety's sake it should not be the default behavior:
  161974. * programmers should have to make a deliberate choice to emit abbreviated
  161975. * images. Therefore the documentation and examples should encourage people
  161976. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161977. * wrong thing.
  161978. */
  161979. GLOBAL(void)
  161980. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161981. {
  161982. if (cinfo->global_state != CSTATE_START)
  161983. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161984. if (write_all_tables)
  161985. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161986. /* (Re)initialize error mgr and destination modules */
  161987. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161988. (*cinfo->dest->init_destination) (cinfo);
  161989. /* Perform master selection of active modules */
  161990. jinit_compress_master(cinfo);
  161991. /* Set up for the first pass */
  161992. (*cinfo->master->prepare_for_pass) (cinfo);
  161993. /* Ready for application to drive first pass through jpeg_write_scanlines
  161994. * or jpeg_write_raw_data.
  161995. */
  161996. cinfo->next_scanline = 0;
  161997. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161998. }
  161999. /*
  162000. * Write some scanlines of data to the JPEG compressor.
  162001. *
  162002. * The return value will be the number of lines actually written.
  162003. * This should be less than the supplied num_lines only in case that
  162004. * the data destination module has requested suspension of the compressor,
  162005. * or if more than image_height scanlines are passed in.
  162006. *
  162007. * Note: we warn about excess calls to jpeg_write_scanlines() since
  162008. * this likely signals an application programmer error. However,
  162009. * excess scanlines passed in the last valid call are *silently* ignored,
  162010. * so that the application need not adjust num_lines for end-of-image
  162011. * when using a multiple-scanline buffer.
  162012. */
  162013. GLOBAL(JDIMENSION)
  162014. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  162015. JDIMENSION num_lines)
  162016. {
  162017. JDIMENSION row_ctr, rows_left;
  162018. if (cinfo->global_state != CSTATE_SCANNING)
  162019. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162020. if (cinfo->next_scanline >= cinfo->image_height)
  162021. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162022. /* Call progress monitor hook if present */
  162023. if (cinfo->progress != NULL) {
  162024. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162025. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162026. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162027. }
  162028. /* Give master control module another chance if this is first call to
  162029. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  162030. * delayed so that application can write COM, etc, markers between
  162031. * jpeg_start_compress and jpeg_write_scanlines.
  162032. */
  162033. if (cinfo->master->call_pass_startup)
  162034. (*cinfo->master->pass_startup) (cinfo);
  162035. /* Ignore any extra scanlines at bottom of image. */
  162036. rows_left = cinfo->image_height - cinfo->next_scanline;
  162037. if (num_lines > rows_left)
  162038. num_lines = rows_left;
  162039. row_ctr = 0;
  162040. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  162041. cinfo->next_scanline += row_ctr;
  162042. return row_ctr;
  162043. }
  162044. /*
  162045. * Alternate entry point to write raw data.
  162046. * Processes exactly one iMCU row per call, unless suspended.
  162047. */
  162048. GLOBAL(JDIMENSION)
  162049. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  162050. JDIMENSION num_lines)
  162051. {
  162052. JDIMENSION lines_per_iMCU_row;
  162053. if (cinfo->global_state != CSTATE_RAW_OK)
  162054. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162055. if (cinfo->next_scanline >= cinfo->image_height) {
  162056. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162057. return 0;
  162058. }
  162059. /* Call progress monitor hook if present */
  162060. if (cinfo->progress != NULL) {
  162061. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162062. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162063. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162064. }
  162065. /* Give master control module another chance if this is first call to
  162066. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  162067. * delayed so that application can write COM, etc, markers between
  162068. * jpeg_start_compress and jpeg_write_raw_data.
  162069. */
  162070. if (cinfo->master->call_pass_startup)
  162071. (*cinfo->master->pass_startup) (cinfo);
  162072. /* Verify that at least one iMCU row has been passed. */
  162073. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  162074. if (num_lines < lines_per_iMCU_row)
  162075. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162076. /* Directly compress the row. */
  162077. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  162078. /* If compressor did not consume the whole row, suspend processing. */
  162079. return 0;
  162080. }
  162081. /* OK, we processed one iMCU row. */
  162082. cinfo->next_scanline += lines_per_iMCU_row;
  162083. return lines_per_iMCU_row;
  162084. }
  162085. /*** End of inlined file: jcapistd.c ***/
  162086. /*** Start of inlined file: jccoefct.c ***/
  162087. #define JPEG_INTERNALS
  162088. /* We use a full-image coefficient buffer when doing Huffman optimization,
  162089. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  162090. * step is run during the first pass, and subsequent passes need only read
  162091. * the buffered coefficients.
  162092. */
  162093. #ifdef ENTROPY_OPT_SUPPORTED
  162094. #define FULL_COEF_BUFFER_SUPPORTED
  162095. #else
  162096. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162097. #define FULL_COEF_BUFFER_SUPPORTED
  162098. #endif
  162099. #endif
  162100. /* Private buffer controller object */
  162101. typedef struct {
  162102. struct jpeg_c_coef_controller pub; /* public fields */
  162103. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162104. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162105. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162106. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162107. /* For single-pass compression, it's sufficient to buffer just one MCU
  162108. * (although this may prove a bit slow in practice). We allocate a
  162109. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  162110. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  162111. * it's not really very big; this is to keep the module interfaces unchanged
  162112. * when a large coefficient buffer is necessary.)
  162113. * In multi-pass modes, this array points to the current MCU's blocks
  162114. * within the virtual arrays.
  162115. */
  162116. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162117. /* In multi-pass modes, we need a virtual block array for each component. */
  162118. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162119. } my_coef_controller;
  162120. typedef my_coef_controller * my_coef_ptr;
  162121. /* Forward declarations */
  162122. METHODDEF(boolean) compress_data
  162123. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162124. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162125. METHODDEF(boolean) compress_first_pass
  162126. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162127. METHODDEF(boolean) compress_output
  162128. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162129. #endif
  162130. LOCAL(void)
  162131. start_iMCU_row (j_compress_ptr cinfo)
  162132. /* Reset within-iMCU-row counters for a new row */
  162133. {
  162134. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162135. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162136. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162137. * But at the bottom of the image, process only what's left.
  162138. */
  162139. if (cinfo->comps_in_scan > 1) {
  162140. coef->MCU_rows_per_iMCU_row = 1;
  162141. } else {
  162142. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162143. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162144. else
  162145. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162146. }
  162147. coef->mcu_ctr = 0;
  162148. coef->MCU_vert_offset = 0;
  162149. }
  162150. /*
  162151. * Initialize for a processing pass.
  162152. */
  162153. METHODDEF(void)
  162154. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162155. {
  162156. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162157. coef->iMCU_row_num = 0;
  162158. start_iMCU_row(cinfo);
  162159. switch (pass_mode) {
  162160. case JBUF_PASS_THRU:
  162161. if (coef->whole_image[0] != NULL)
  162162. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162163. coef->pub.compress_data = compress_data;
  162164. break;
  162165. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162166. case JBUF_SAVE_AND_PASS:
  162167. if (coef->whole_image[0] == NULL)
  162168. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162169. coef->pub.compress_data = compress_first_pass;
  162170. break;
  162171. case JBUF_CRANK_DEST:
  162172. if (coef->whole_image[0] == NULL)
  162173. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162174. coef->pub.compress_data = compress_output;
  162175. break;
  162176. #endif
  162177. default:
  162178. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162179. break;
  162180. }
  162181. }
  162182. /*
  162183. * Process some data in the single-pass case.
  162184. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162185. * per call, ie, v_samp_factor block rows for each component in the image.
  162186. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162187. *
  162188. * NB: input_buf contains a plane for each component in image,
  162189. * which we index according to the component's SOF position.
  162190. */
  162191. METHODDEF(boolean)
  162192. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162193. {
  162194. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162195. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162196. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162197. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162198. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162199. JDIMENSION ypos, xpos;
  162200. jpeg_component_info *compptr;
  162201. /* Loop to write as much as one whole iMCU row */
  162202. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162203. yoffset++) {
  162204. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162205. MCU_col_num++) {
  162206. /* Determine where data comes from in input_buf and do the DCT thing.
  162207. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162208. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162209. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162210. * specially. The data in them does not matter for image reconstruction,
  162211. * so we fill them with values that will encode to the smallest amount of
  162212. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162213. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162214. */
  162215. blkn = 0;
  162216. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162217. compptr = cinfo->cur_comp_info[ci];
  162218. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162219. : compptr->last_col_width;
  162220. xpos = MCU_col_num * compptr->MCU_sample_width;
  162221. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162222. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162223. if (coef->iMCU_row_num < last_iMCU_row ||
  162224. yoffset+yindex < compptr->last_row_height) {
  162225. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162226. input_buf[compptr->component_index],
  162227. coef->MCU_buffer[blkn],
  162228. ypos, xpos, (JDIMENSION) blockcnt);
  162229. if (blockcnt < compptr->MCU_width) {
  162230. /* Create some dummy blocks at the right edge of the image. */
  162231. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162232. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162233. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162234. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162235. }
  162236. }
  162237. } else {
  162238. /* Create a row of dummy blocks at the bottom of the image. */
  162239. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162240. compptr->MCU_width * SIZEOF(JBLOCK));
  162241. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162242. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162243. }
  162244. }
  162245. blkn += compptr->MCU_width;
  162246. ypos += DCTSIZE;
  162247. }
  162248. }
  162249. /* Try to write the MCU. In event of a suspension failure, we will
  162250. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162251. */
  162252. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162253. /* Suspension forced; update state counters and exit */
  162254. coef->MCU_vert_offset = yoffset;
  162255. coef->mcu_ctr = MCU_col_num;
  162256. return FALSE;
  162257. }
  162258. }
  162259. /* Completed an MCU row, but perhaps not an iMCU row */
  162260. coef->mcu_ctr = 0;
  162261. }
  162262. /* Completed the iMCU row, advance counters for next one */
  162263. coef->iMCU_row_num++;
  162264. start_iMCU_row(cinfo);
  162265. return TRUE;
  162266. }
  162267. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162268. /*
  162269. * Process some data in the first pass of a multi-pass case.
  162270. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162271. * per call, ie, v_samp_factor block rows for each component in the image.
  162272. * This amount of data is read from the source buffer, DCT'd and quantized,
  162273. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162274. * as needed at the right and lower edges. (The dummy blocks are constructed
  162275. * in the virtual arrays, which have been padded appropriately.) This makes
  162276. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162277. *
  162278. * We must also emit the data to the entropy encoder. This is conveniently
  162279. * done by calling compress_output() after we've loaded the current strip
  162280. * of the virtual arrays.
  162281. *
  162282. * NB: input_buf contains a plane for each component in image. All
  162283. * components are DCT'd and loaded into the virtual arrays in this pass.
  162284. * However, it may be that only a subset of the components are emitted to
  162285. * the entropy encoder during this first pass; be careful about looking
  162286. * at the scan-dependent variables (MCU dimensions, etc).
  162287. */
  162288. METHODDEF(boolean)
  162289. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162290. {
  162291. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162292. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162293. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162294. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162295. JCOEF lastDC;
  162296. jpeg_component_info *compptr;
  162297. JBLOCKARRAY buffer;
  162298. JBLOCKROW thisblockrow, lastblockrow;
  162299. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162300. ci++, compptr++) {
  162301. /* Align the virtual buffer for this component. */
  162302. buffer = (*cinfo->mem->access_virt_barray)
  162303. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162304. coef->iMCU_row_num * compptr->v_samp_factor,
  162305. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162306. /* Count non-dummy DCT block rows in this iMCU row. */
  162307. if (coef->iMCU_row_num < last_iMCU_row)
  162308. block_rows = compptr->v_samp_factor;
  162309. else {
  162310. /* NB: can't use last_row_height here, since may not be set! */
  162311. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162312. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162313. }
  162314. blocks_across = compptr->width_in_blocks;
  162315. h_samp_factor = compptr->h_samp_factor;
  162316. /* Count number of dummy blocks to be added at the right margin. */
  162317. ndummy = (int) (blocks_across % h_samp_factor);
  162318. if (ndummy > 0)
  162319. ndummy = h_samp_factor - ndummy;
  162320. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162321. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162322. */
  162323. for (block_row = 0; block_row < block_rows; block_row++) {
  162324. thisblockrow = buffer[block_row];
  162325. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162326. input_buf[ci], thisblockrow,
  162327. (JDIMENSION) (block_row * DCTSIZE),
  162328. (JDIMENSION) 0, blocks_across);
  162329. if (ndummy > 0) {
  162330. /* Create dummy blocks at the right edge of the image. */
  162331. thisblockrow += blocks_across; /* => first dummy block */
  162332. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162333. lastDC = thisblockrow[-1][0];
  162334. for (bi = 0; bi < ndummy; bi++) {
  162335. thisblockrow[bi][0] = lastDC;
  162336. }
  162337. }
  162338. }
  162339. /* If at end of image, create dummy block rows as needed.
  162340. * The tricky part here is that within each MCU, we want the DC values
  162341. * of the dummy blocks to match the last real block's DC value.
  162342. * This squeezes a few more bytes out of the resulting file...
  162343. */
  162344. if (coef->iMCU_row_num == last_iMCU_row) {
  162345. blocks_across += ndummy; /* include lower right corner */
  162346. MCUs_across = blocks_across / h_samp_factor;
  162347. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162348. block_row++) {
  162349. thisblockrow = buffer[block_row];
  162350. lastblockrow = buffer[block_row-1];
  162351. jzero_far((void FAR *) thisblockrow,
  162352. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162353. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162354. lastDC = lastblockrow[h_samp_factor-1][0];
  162355. for (bi = 0; bi < h_samp_factor; bi++) {
  162356. thisblockrow[bi][0] = lastDC;
  162357. }
  162358. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162359. lastblockrow += h_samp_factor;
  162360. }
  162361. }
  162362. }
  162363. }
  162364. /* NB: compress_output will increment iMCU_row_num if successful.
  162365. * A suspension return will result in redoing all the work above next time.
  162366. */
  162367. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162368. return compress_output(cinfo, input_buf);
  162369. }
  162370. /*
  162371. * Process some data in subsequent passes of a multi-pass case.
  162372. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162373. * per call, ie, v_samp_factor block rows for each component in the scan.
  162374. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162375. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162376. *
  162377. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162378. */
  162379. METHODDEF(boolean)
  162380. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162381. {
  162382. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162383. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162384. int blkn, ci, xindex, yindex, yoffset;
  162385. JDIMENSION start_col;
  162386. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162387. JBLOCKROW buffer_ptr;
  162388. jpeg_component_info *compptr;
  162389. /* Align the virtual buffers for the components used in this scan.
  162390. * NB: during first pass, this is safe only because the buffers will
  162391. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162392. */
  162393. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162394. compptr = cinfo->cur_comp_info[ci];
  162395. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162396. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162397. coef->iMCU_row_num * compptr->v_samp_factor,
  162398. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162399. }
  162400. /* Loop to process one whole iMCU row */
  162401. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162402. yoffset++) {
  162403. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162404. MCU_col_num++) {
  162405. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162406. blkn = 0; /* index of current DCT block within MCU */
  162407. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162408. compptr = cinfo->cur_comp_info[ci];
  162409. start_col = MCU_col_num * compptr->MCU_width;
  162410. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162411. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162412. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162413. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162414. }
  162415. }
  162416. }
  162417. /* Try to write the MCU. */
  162418. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162419. /* Suspension forced; update state counters and exit */
  162420. coef->MCU_vert_offset = yoffset;
  162421. coef->mcu_ctr = MCU_col_num;
  162422. return FALSE;
  162423. }
  162424. }
  162425. /* Completed an MCU row, but perhaps not an iMCU row */
  162426. coef->mcu_ctr = 0;
  162427. }
  162428. /* Completed the iMCU row, advance counters for next one */
  162429. coef->iMCU_row_num++;
  162430. start_iMCU_row(cinfo);
  162431. return TRUE;
  162432. }
  162433. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162434. /*
  162435. * Initialize coefficient buffer controller.
  162436. */
  162437. GLOBAL(void)
  162438. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162439. {
  162440. my_coef_ptr coef;
  162441. coef = (my_coef_ptr)
  162442. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162443. SIZEOF(my_coef_controller));
  162444. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162445. coef->pub.start_pass = start_pass_coef;
  162446. /* Create the coefficient buffer. */
  162447. if (need_full_buffer) {
  162448. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162449. /* Allocate a full-image virtual array for each component, */
  162450. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162451. int ci;
  162452. jpeg_component_info *compptr;
  162453. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162454. ci++, compptr++) {
  162455. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162456. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162457. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162458. (long) compptr->h_samp_factor),
  162459. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162460. (long) compptr->v_samp_factor),
  162461. (JDIMENSION) compptr->v_samp_factor);
  162462. }
  162463. #else
  162464. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162465. #endif
  162466. } else {
  162467. /* We only need a single-MCU buffer. */
  162468. JBLOCKROW buffer;
  162469. int i;
  162470. buffer = (JBLOCKROW)
  162471. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162472. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162473. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162474. coef->MCU_buffer[i] = buffer + i;
  162475. }
  162476. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162477. }
  162478. }
  162479. /*** End of inlined file: jccoefct.c ***/
  162480. /*** Start of inlined file: jccolor.c ***/
  162481. #define JPEG_INTERNALS
  162482. /* Private subobject */
  162483. typedef struct {
  162484. struct jpeg_color_converter pub; /* public fields */
  162485. /* Private state for RGB->YCC conversion */
  162486. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162487. } my_color_converter;
  162488. typedef my_color_converter * my_cconvert_ptr;
  162489. /**************** RGB -> YCbCr conversion: most common case **************/
  162490. /*
  162491. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162492. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162493. * The conversion equations to be implemented are therefore
  162494. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162495. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162496. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162497. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162498. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162499. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162500. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162501. * were not represented exactly. Now we sacrifice exact representation of
  162502. * maximum red and maximum blue in order to get exact grayscales.
  162503. *
  162504. * To avoid floating-point arithmetic, we represent the fractional constants
  162505. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162506. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162507. *
  162508. * For even more speed, we avoid doing any multiplications in the inner loop
  162509. * by precalculating the constants times R,G,B for all possible values.
  162510. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162511. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162512. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162513. * colorspace anyway.
  162514. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162515. * in the tables to save adding them separately in the inner loop.
  162516. */
  162517. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162518. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162519. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162520. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162521. /* We allocate one big table and divide it up into eight parts, instead of
  162522. * doing eight alloc_small requests. This lets us use a single table base
  162523. * address, which can be held in a register in the inner loops on many
  162524. * machines (more than can hold all eight addresses, anyway).
  162525. */
  162526. #define R_Y_OFF 0 /* offset to R => Y section */
  162527. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162528. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162529. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162530. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162531. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162532. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162533. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162534. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162535. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162536. /*
  162537. * Initialize for RGB->YCC colorspace conversion.
  162538. */
  162539. METHODDEF(void)
  162540. rgb_ycc_start (j_compress_ptr cinfo)
  162541. {
  162542. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162543. INT32 * rgb_ycc_tab;
  162544. INT32 i;
  162545. /* Allocate and fill in the conversion tables. */
  162546. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162547. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162548. (TABLE_SIZE * SIZEOF(INT32)));
  162549. for (i = 0; i <= MAXJSAMPLE; i++) {
  162550. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162551. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162552. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162553. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162554. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162555. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162556. * This ensures that the maximum output will round to MAXJSAMPLE
  162557. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162558. */
  162559. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162560. /* B=>Cb and R=>Cr tables are the same
  162561. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162562. */
  162563. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162564. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162565. }
  162566. }
  162567. /*
  162568. * Convert some rows of samples to the JPEG colorspace.
  162569. *
  162570. * Note that we change from the application's interleaved-pixel format
  162571. * to our internal noninterleaved, one-plane-per-component format.
  162572. * The input buffer is therefore three times as wide as the output buffer.
  162573. *
  162574. * A starting row offset is provided only for the output buffer. The caller
  162575. * can easily adjust the passed input_buf value to accommodate any row
  162576. * offset required on that side.
  162577. */
  162578. METHODDEF(void)
  162579. rgb_ycc_convert (j_compress_ptr cinfo,
  162580. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162581. JDIMENSION output_row, int num_rows)
  162582. {
  162583. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162584. register int r, g, b;
  162585. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162586. register JSAMPROW inptr;
  162587. register JSAMPROW outptr0, outptr1, outptr2;
  162588. register JDIMENSION col;
  162589. JDIMENSION num_cols = cinfo->image_width;
  162590. while (--num_rows >= 0) {
  162591. inptr = *input_buf++;
  162592. outptr0 = output_buf[0][output_row];
  162593. outptr1 = output_buf[1][output_row];
  162594. outptr2 = output_buf[2][output_row];
  162595. output_row++;
  162596. for (col = 0; col < num_cols; col++) {
  162597. r = GETJSAMPLE(inptr[RGB_RED]);
  162598. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162599. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162600. inptr += RGB_PIXELSIZE;
  162601. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162602. * must be too; we do not need an explicit range-limiting operation.
  162603. * Hence the value being shifted is never negative, and we don't
  162604. * need the general RIGHT_SHIFT macro.
  162605. */
  162606. /* Y */
  162607. outptr0[col] = (JSAMPLE)
  162608. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162609. >> SCALEBITS);
  162610. /* Cb */
  162611. outptr1[col] = (JSAMPLE)
  162612. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162613. >> SCALEBITS);
  162614. /* Cr */
  162615. outptr2[col] = (JSAMPLE)
  162616. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162617. >> SCALEBITS);
  162618. }
  162619. }
  162620. }
  162621. /**************** Cases other than RGB -> YCbCr **************/
  162622. /*
  162623. * Convert some rows of samples to the JPEG colorspace.
  162624. * This version handles RGB->grayscale conversion, which is the same
  162625. * as the RGB->Y portion of RGB->YCbCr.
  162626. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162627. */
  162628. METHODDEF(void)
  162629. rgb_gray_convert (j_compress_ptr cinfo,
  162630. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162631. JDIMENSION output_row, int num_rows)
  162632. {
  162633. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162634. register int r, g, b;
  162635. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162636. register JSAMPROW inptr;
  162637. register JSAMPROW outptr;
  162638. register JDIMENSION col;
  162639. JDIMENSION num_cols = cinfo->image_width;
  162640. while (--num_rows >= 0) {
  162641. inptr = *input_buf++;
  162642. outptr = output_buf[0][output_row];
  162643. output_row++;
  162644. for (col = 0; col < num_cols; col++) {
  162645. r = GETJSAMPLE(inptr[RGB_RED]);
  162646. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162647. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162648. inptr += RGB_PIXELSIZE;
  162649. /* Y */
  162650. outptr[col] = (JSAMPLE)
  162651. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162652. >> SCALEBITS);
  162653. }
  162654. }
  162655. }
  162656. /*
  162657. * Convert some rows of samples to the JPEG colorspace.
  162658. * This version handles Adobe-style CMYK->YCCK conversion,
  162659. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162660. * conversion as above, while passing K (black) unchanged.
  162661. * We assume rgb_ycc_start has been called.
  162662. */
  162663. METHODDEF(void)
  162664. cmyk_ycck_convert (j_compress_ptr cinfo,
  162665. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162666. JDIMENSION output_row, int num_rows)
  162667. {
  162668. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162669. register int r, g, b;
  162670. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162671. register JSAMPROW inptr;
  162672. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162673. register JDIMENSION col;
  162674. JDIMENSION num_cols = cinfo->image_width;
  162675. while (--num_rows >= 0) {
  162676. inptr = *input_buf++;
  162677. outptr0 = output_buf[0][output_row];
  162678. outptr1 = output_buf[1][output_row];
  162679. outptr2 = output_buf[2][output_row];
  162680. outptr3 = output_buf[3][output_row];
  162681. output_row++;
  162682. for (col = 0; col < num_cols; col++) {
  162683. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162684. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162685. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162686. /* K passes through as-is */
  162687. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162688. inptr += 4;
  162689. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162690. * must be too; we do not need an explicit range-limiting operation.
  162691. * Hence the value being shifted is never negative, and we don't
  162692. * need the general RIGHT_SHIFT macro.
  162693. */
  162694. /* Y */
  162695. outptr0[col] = (JSAMPLE)
  162696. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162697. >> SCALEBITS);
  162698. /* Cb */
  162699. outptr1[col] = (JSAMPLE)
  162700. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162701. >> SCALEBITS);
  162702. /* Cr */
  162703. outptr2[col] = (JSAMPLE)
  162704. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162705. >> SCALEBITS);
  162706. }
  162707. }
  162708. }
  162709. /*
  162710. * Convert some rows of samples to the JPEG colorspace.
  162711. * This version handles grayscale output with no conversion.
  162712. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162713. */
  162714. METHODDEF(void)
  162715. grayscale_convert (j_compress_ptr cinfo,
  162716. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162717. JDIMENSION output_row, int num_rows)
  162718. {
  162719. register JSAMPROW inptr;
  162720. register JSAMPROW outptr;
  162721. register JDIMENSION col;
  162722. JDIMENSION num_cols = cinfo->image_width;
  162723. int instride = cinfo->input_components;
  162724. while (--num_rows >= 0) {
  162725. inptr = *input_buf++;
  162726. outptr = output_buf[0][output_row];
  162727. output_row++;
  162728. for (col = 0; col < num_cols; col++) {
  162729. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162730. inptr += instride;
  162731. }
  162732. }
  162733. }
  162734. /*
  162735. * Convert some rows of samples to the JPEG colorspace.
  162736. * This version handles multi-component colorspaces without conversion.
  162737. * We assume input_components == num_components.
  162738. */
  162739. METHODDEF(void)
  162740. null_convert (j_compress_ptr cinfo,
  162741. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162742. JDIMENSION output_row, int num_rows)
  162743. {
  162744. register JSAMPROW inptr;
  162745. register JSAMPROW outptr;
  162746. register JDIMENSION col;
  162747. register int ci;
  162748. int nc = cinfo->num_components;
  162749. JDIMENSION num_cols = cinfo->image_width;
  162750. while (--num_rows >= 0) {
  162751. /* It seems fastest to make a separate pass for each component. */
  162752. for (ci = 0; ci < nc; ci++) {
  162753. inptr = *input_buf;
  162754. outptr = output_buf[ci][output_row];
  162755. for (col = 0; col < num_cols; col++) {
  162756. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162757. inptr += nc;
  162758. }
  162759. }
  162760. input_buf++;
  162761. output_row++;
  162762. }
  162763. }
  162764. /*
  162765. * Empty method for start_pass.
  162766. */
  162767. METHODDEF(void)
  162768. null_method (j_compress_ptr)
  162769. {
  162770. /* no work needed */
  162771. }
  162772. /*
  162773. * Module initialization routine for input colorspace conversion.
  162774. */
  162775. GLOBAL(void)
  162776. jinit_color_converter (j_compress_ptr cinfo)
  162777. {
  162778. my_cconvert_ptr cconvert;
  162779. cconvert = (my_cconvert_ptr)
  162780. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162781. SIZEOF(my_color_converter));
  162782. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162783. /* set start_pass to null method until we find out differently */
  162784. cconvert->pub.start_pass = null_method;
  162785. /* Make sure input_components agrees with in_color_space */
  162786. switch (cinfo->in_color_space) {
  162787. case JCS_GRAYSCALE:
  162788. if (cinfo->input_components != 1)
  162789. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162790. break;
  162791. case JCS_RGB:
  162792. #if RGB_PIXELSIZE != 3
  162793. if (cinfo->input_components != RGB_PIXELSIZE)
  162794. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162795. break;
  162796. #endif /* else share code with YCbCr */
  162797. case JCS_YCbCr:
  162798. if (cinfo->input_components != 3)
  162799. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162800. break;
  162801. case JCS_CMYK:
  162802. case JCS_YCCK:
  162803. if (cinfo->input_components != 4)
  162804. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162805. break;
  162806. default: /* JCS_UNKNOWN can be anything */
  162807. if (cinfo->input_components < 1)
  162808. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162809. break;
  162810. }
  162811. /* Check num_components, set conversion method based on requested space */
  162812. switch (cinfo->jpeg_color_space) {
  162813. case JCS_GRAYSCALE:
  162814. if (cinfo->num_components != 1)
  162815. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162816. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162817. cconvert->pub.color_convert = grayscale_convert;
  162818. else if (cinfo->in_color_space == JCS_RGB) {
  162819. cconvert->pub.start_pass = rgb_ycc_start;
  162820. cconvert->pub.color_convert = rgb_gray_convert;
  162821. } else if (cinfo->in_color_space == JCS_YCbCr)
  162822. cconvert->pub.color_convert = grayscale_convert;
  162823. else
  162824. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162825. break;
  162826. case JCS_RGB:
  162827. if (cinfo->num_components != 3)
  162828. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162829. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162830. cconvert->pub.color_convert = null_convert;
  162831. else
  162832. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162833. break;
  162834. case JCS_YCbCr:
  162835. if (cinfo->num_components != 3)
  162836. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162837. if (cinfo->in_color_space == JCS_RGB) {
  162838. cconvert->pub.start_pass = rgb_ycc_start;
  162839. cconvert->pub.color_convert = rgb_ycc_convert;
  162840. } else if (cinfo->in_color_space == JCS_YCbCr)
  162841. cconvert->pub.color_convert = null_convert;
  162842. else
  162843. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162844. break;
  162845. case JCS_CMYK:
  162846. if (cinfo->num_components != 4)
  162847. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162848. if (cinfo->in_color_space == JCS_CMYK)
  162849. cconvert->pub.color_convert = null_convert;
  162850. else
  162851. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162852. break;
  162853. case JCS_YCCK:
  162854. if (cinfo->num_components != 4)
  162855. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162856. if (cinfo->in_color_space == JCS_CMYK) {
  162857. cconvert->pub.start_pass = rgb_ycc_start;
  162858. cconvert->pub.color_convert = cmyk_ycck_convert;
  162859. } else if (cinfo->in_color_space == JCS_YCCK)
  162860. cconvert->pub.color_convert = null_convert;
  162861. else
  162862. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162863. break;
  162864. default: /* allow null conversion of JCS_UNKNOWN */
  162865. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162866. cinfo->num_components != cinfo->input_components)
  162867. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162868. cconvert->pub.color_convert = null_convert;
  162869. break;
  162870. }
  162871. }
  162872. /*** End of inlined file: jccolor.c ***/
  162873. #undef FIX
  162874. /*** Start of inlined file: jcdctmgr.c ***/
  162875. #define JPEG_INTERNALS
  162876. /*** Start of inlined file: jdct.h ***/
  162877. /*
  162878. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162879. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162880. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162881. * implementations use an array of type FAST_FLOAT, instead.)
  162882. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162883. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162884. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162885. * convention improves accuracy in integer implementations and saves some
  162886. * work in floating-point ones.
  162887. * Quantization of the output coefficients is done by jcdctmgr.c.
  162888. */
  162889. #ifndef __jdct_h__
  162890. #define __jdct_h__
  162891. #if BITS_IN_JSAMPLE == 8
  162892. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162893. #else
  162894. typedef INT32 DCTELEM; /* must have 32 bits */
  162895. #endif
  162896. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162897. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162898. /*
  162899. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162900. * to an output sample array. The routine must dequantize the input data as
  162901. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162902. * pointed to by compptr->dct_table. The output data is to be placed into the
  162903. * sample array starting at a specified column. (Any row offset needed will
  162904. * be applied to the array pointer before it is passed to the IDCT code.)
  162905. * Note that the number of samples emitted by the IDCT routine is
  162906. * DCT_scaled_size * DCT_scaled_size.
  162907. */
  162908. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162909. /*
  162910. * Each IDCT routine has its own ideas about the best dct_table element type.
  162911. */
  162912. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162913. #if BITS_IN_JSAMPLE == 8
  162914. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162915. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162916. #else
  162917. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162918. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162919. #endif
  162920. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162921. /*
  162922. * Each IDCT routine is responsible for range-limiting its results and
  162923. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162924. * be quite far out of range if the input data is corrupt, so a bulletproof
  162925. * range-limiting step is required. We use a mask-and-table-lookup method
  162926. * to do the combined operations quickly. See the comments with
  162927. * prepare_range_limit_table (in jdmaster.c) for more info.
  162928. */
  162929. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162930. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162931. /* Short forms of external names for systems with brain-damaged linkers. */
  162932. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162933. #define jpeg_fdct_islow jFDislow
  162934. #define jpeg_fdct_ifast jFDifast
  162935. #define jpeg_fdct_float jFDfloat
  162936. #define jpeg_idct_islow jRDislow
  162937. #define jpeg_idct_ifast jRDifast
  162938. #define jpeg_idct_float jRDfloat
  162939. #define jpeg_idct_4x4 jRD4x4
  162940. #define jpeg_idct_2x2 jRD2x2
  162941. #define jpeg_idct_1x1 jRD1x1
  162942. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162943. /* Extern declarations for the forward and inverse DCT routines. */
  162944. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162945. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162946. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162947. EXTERN(void) jpeg_idct_islow
  162948. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162949. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162950. EXTERN(void) jpeg_idct_ifast
  162951. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162952. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162953. EXTERN(void) jpeg_idct_float
  162954. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162955. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162956. EXTERN(void) jpeg_idct_4x4
  162957. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162958. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162959. EXTERN(void) jpeg_idct_2x2
  162960. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162961. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162962. EXTERN(void) jpeg_idct_1x1
  162963. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162964. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162965. /*
  162966. * Macros for handling fixed-point arithmetic; these are used by many
  162967. * but not all of the DCT/IDCT modules.
  162968. *
  162969. * All values are expected to be of type INT32.
  162970. * Fractional constants are scaled left by CONST_BITS bits.
  162971. * CONST_BITS is defined within each module using these macros,
  162972. * and may differ from one module to the next.
  162973. */
  162974. #define ONE ((INT32) 1)
  162975. #define CONST_SCALE (ONE << CONST_BITS)
  162976. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162977. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162978. * thus causing a lot of useless floating-point operations at run time.
  162979. */
  162980. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162981. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162982. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162983. * the fudge factor is correct for either sign of X.
  162984. */
  162985. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162986. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162987. * This macro is used only when the two inputs will actually be no more than
  162988. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162989. * full 32x32 multiply. This provides a useful speedup on many machines.
  162990. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162991. * in C, but some C compilers will do the right thing if you provide the
  162992. * correct combination of casts.
  162993. */
  162994. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162995. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162996. #endif
  162997. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162998. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162999. #endif
  163000. #ifndef MULTIPLY16C16 /* default definition */
  163001. #define MULTIPLY16C16(var,const) ((var) * (const))
  163002. #endif
  163003. /* Same except both inputs are variables. */
  163004. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163005. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  163006. #endif
  163007. #ifndef MULTIPLY16V16 /* default definition */
  163008. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  163009. #endif
  163010. #endif
  163011. /*** End of inlined file: jdct.h ***/
  163012. /* Private declarations for DCT subsystem */
  163013. /* Private subobject for this module */
  163014. typedef struct {
  163015. struct jpeg_forward_dct pub; /* public fields */
  163016. /* Pointer to the DCT routine actually in use */
  163017. forward_DCT_method_ptr do_dct;
  163018. /* The actual post-DCT divisors --- not identical to the quant table
  163019. * entries, because of scaling (especially for an unnormalized DCT).
  163020. * Each table is given in normal array order.
  163021. */
  163022. DCTELEM * divisors[NUM_QUANT_TBLS];
  163023. #ifdef DCT_FLOAT_SUPPORTED
  163024. /* Same as above for the floating-point case. */
  163025. float_DCT_method_ptr do_float_dct;
  163026. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  163027. #endif
  163028. } my_fdct_controller;
  163029. typedef my_fdct_controller * my_fdct_ptr;
  163030. /*
  163031. * Initialize for a processing pass.
  163032. * Verify that all referenced Q-tables are present, and set up
  163033. * the divisor table for each one.
  163034. * In the current implementation, DCT of all components is done during
  163035. * the first pass, even if only some components will be output in the
  163036. * first scan. Hence all components should be examined here.
  163037. */
  163038. METHODDEF(void)
  163039. start_pass_fdctmgr (j_compress_ptr cinfo)
  163040. {
  163041. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163042. int ci, qtblno, i;
  163043. jpeg_component_info *compptr;
  163044. JQUANT_TBL * qtbl;
  163045. DCTELEM * dtbl;
  163046. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163047. ci++, compptr++) {
  163048. qtblno = compptr->quant_tbl_no;
  163049. /* Make sure specified quantization table is present */
  163050. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163051. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163052. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163053. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  163054. /* Compute divisors for this quant table */
  163055. /* We may do this more than once for same table, but it's not a big deal */
  163056. switch (cinfo->dct_method) {
  163057. #ifdef DCT_ISLOW_SUPPORTED
  163058. case JDCT_ISLOW:
  163059. /* For LL&M IDCT method, divisors are equal to raw quantization
  163060. * coefficients multiplied by 8 (to counteract scaling).
  163061. */
  163062. if (fdct->divisors[qtblno] == NULL) {
  163063. fdct->divisors[qtblno] = (DCTELEM *)
  163064. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163065. DCTSIZE2 * SIZEOF(DCTELEM));
  163066. }
  163067. dtbl = fdct->divisors[qtblno];
  163068. for (i = 0; i < DCTSIZE2; i++) {
  163069. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  163070. }
  163071. break;
  163072. #endif
  163073. #ifdef DCT_IFAST_SUPPORTED
  163074. case JDCT_IFAST:
  163075. {
  163076. /* For AA&N IDCT method, divisors are equal to quantization
  163077. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163078. * scalefactor[0] = 1
  163079. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163080. * We apply a further scale factor of 8.
  163081. */
  163082. #define CONST_BITS 14
  163083. static const INT16 aanscales[DCTSIZE2] = {
  163084. /* precomputed values scaled up by 14 bits */
  163085. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163086. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163087. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163088. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163089. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163090. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163091. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163092. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163093. };
  163094. SHIFT_TEMPS
  163095. if (fdct->divisors[qtblno] == NULL) {
  163096. fdct->divisors[qtblno] = (DCTELEM *)
  163097. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163098. DCTSIZE2 * SIZEOF(DCTELEM));
  163099. }
  163100. dtbl = fdct->divisors[qtblno];
  163101. for (i = 0; i < DCTSIZE2; i++) {
  163102. dtbl[i] = (DCTELEM)
  163103. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163104. (INT32) aanscales[i]),
  163105. CONST_BITS-3);
  163106. }
  163107. }
  163108. break;
  163109. #endif
  163110. #ifdef DCT_FLOAT_SUPPORTED
  163111. case JDCT_FLOAT:
  163112. {
  163113. /* For float AA&N IDCT method, divisors are equal to quantization
  163114. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163115. * scalefactor[0] = 1
  163116. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163117. * We apply a further scale factor of 8.
  163118. * What's actually stored is 1/divisor so that the inner loop can
  163119. * use a multiplication rather than a division.
  163120. */
  163121. FAST_FLOAT * fdtbl;
  163122. int row, col;
  163123. static const double aanscalefactor[DCTSIZE] = {
  163124. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163125. 1.0, 0.785694958, 0.541196100, 0.275899379
  163126. };
  163127. if (fdct->float_divisors[qtblno] == NULL) {
  163128. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163129. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163130. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163131. }
  163132. fdtbl = fdct->float_divisors[qtblno];
  163133. i = 0;
  163134. for (row = 0; row < DCTSIZE; row++) {
  163135. for (col = 0; col < DCTSIZE; col++) {
  163136. fdtbl[i] = (FAST_FLOAT)
  163137. (1.0 / (((double) qtbl->quantval[i] *
  163138. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163139. i++;
  163140. }
  163141. }
  163142. }
  163143. break;
  163144. #endif
  163145. default:
  163146. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163147. break;
  163148. }
  163149. }
  163150. }
  163151. /*
  163152. * Perform forward DCT on one or more blocks of a component.
  163153. *
  163154. * The input samples are taken from the sample_data[] array starting at
  163155. * position start_row/start_col, and moving to the right for any additional
  163156. * blocks. The quantized coefficients are returned in coef_blocks[].
  163157. */
  163158. METHODDEF(void)
  163159. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163160. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163161. JDIMENSION start_row, JDIMENSION start_col,
  163162. JDIMENSION num_blocks)
  163163. /* This version is used for integer DCT implementations. */
  163164. {
  163165. /* This routine is heavily used, so it's worth coding it tightly. */
  163166. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163167. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163168. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163169. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163170. JDIMENSION bi;
  163171. sample_data += start_row; /* fold in the vertical offset once */
  163172. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163173. /* Load data into workspace, applying unsigned->signed conversion */
  163174. { register DCTELEM *workspaceptr;
  163175. register JSAMPROW elemptr;
  163176. register int elemr;
  163177. workspaceptr = workspace;
  163178. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163179. elemptr = sample_data[elemr] + start_col;
  163180. #if DCTSIZE == 8 /* unroll the inner loop */
  163181. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163182. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163183. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163184. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163185. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163186. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163187. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163188. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163189. #else
  163190. { register int elemc;
  163191. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163192. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163193. }
  163194. }
  163195. #endif
  163196. }
  163197. }
  163198. /* Perform the DCT */
  163199. (*do_dct) (workspace);
  163200. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163201. { register DCTELEM temp, qval;
  163202. register int i;
  163203. register JCOEFPTR output_ptr = coef_blocks[bi];
  163204. for (i = 0; i < DCTSIZE2; i++) {
  163205. qval = divisors[i];
  163206. temp = workspace[i];
  163207. /* Divide the coefficient value by qval, ensuring proper rounding.
  163208. * Since C does not specify the direction of rounding for negative
  163209. * quotients, we have to force the dividend positive for portability.
  163210. *
  163211. * In most files, at least half of the output values will be zero
  163212. * (at default quantization settings, more like three-quarters...)
  163213. * so we should ensure that this case is fast. On many machines,
  163214. * a comparison is enough cheaper than a divide to make a special test
  163215. * a win. Since both inputs will be nonnegative, we need only test
  163216. * for a < b to discover whether a/b is 0.
  163217. * If your machine's division is fast enough, define FAST_DIVIDE.
  163218. */
  163219. #ifdef FAST_DIVIDE
  163220. #define DIVIDE_BY(a,b) a /= b
  163221. #else
  163222. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163223. #endif
  163224. if (temp < 0) {
  163225. temp = -temp;
  163226. temp += qval>>1; /* for rounding */
  163227. DIVIDE_BY(temp, qval);
  163228. temp = -temp;
  163229. } else {
  163230. temp += qval>>1; /* for rounding */
  163231. DIVIDE_BY(temp, qval);
  163232. }
  163233. output_ptr[i] = (JCOEF) temp;
  163234. }
  163235. }
  163236. }
  163237. }
  163238. #ifdef DCT_FLOAT_SUPPORTED
  163239. METHODDEF(void)
  163240. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163241. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163242. JDIMENSION start_row, JDIMENSION start_col,
  163243. JDIMENSION num_blocks)
  163244. /* This version is used for floating-point DCT implementations. */
  163245. {
  163246. /* This routine is heavily used, so it's worth coding it tightly. */
  163247. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163248. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163249. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163250. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163251. JDIMENSION bi;
  163252. sample_data += start_row; /* fold in the vertical offset once */
  163253. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163254. /* Load data into workspace, applying unsigned->signed conversion */
  163255. { register FAST_FLOAT *workspaceptr;
  163256. register JSAMPROW elemptr;
  163257. register int elemr;
  163258. workspaceptr = workspace;
  163259. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163260. elemptr = sample_data[elemr] + start_col;
  163261. #if DCTSIZE == 8 /* unroll the inner loop */
  163262. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163263. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163264. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163265. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163266. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163267. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163268. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163269. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163270. #else
  163271. { register int elemc;
  163272. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163273. *workspaceptr++ = (FAST_FLOAT)
  163274. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163275. }
  163276. }
  163277. #endif
  163278. }
  163279. }
  163280. /* Perform the DCT */
  163281. (*do_dct) (workspace);
  163282. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163283. { register FAST_FLOAT temp;
  163284. register int i;
  163285. register JCOEFPTR output_ptr = coef_blocks[bi];
  163286. for (i = 0; i < DCTSIZE2; i++) {
  163287. /* Apply the quantization and scaling factor */
  163288. temp = workspace[i] * divisors[i];
  163289. /* Round to nearest integer.
  163290. * Since C does not specify the direction of rounding for negative
  163291. * quotients, we have to force the dividend positive for portability.
  163292. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163293. * code should work for either 16-bit or 32-bit ints.
  163294. */
  163295. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163296. }
  163297. }
  163298. }
  163299. }
  163300. #endif /* DCT_FLOAT_SUPPORTED */
  163301. /*
  163302. * Initialize FDCT manager.
  163303. */
  163304. GLOBAL(void)
  163305. jinit_forward_dct (j_compress_ptr cinfo)
  163306. {
  163307. my_fdct_ptr fdct;
  163308. int i;
  163309. fdct = (my_fdct_ptr)
  163310. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163311. SIZEOF(my_fdct_controller));
  163312. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163313. fdct->pub.start_pass = start_pass_fdctmgr;
  163314. switch (cinfo->dct_method) {
  163315. #ifdef DCT_ISLOW_SUPPORTED
  163316. case JDCT_ISLOW:
  163317. fdct->pub.forward_DCT = forward_DCT;
  163318. fdct->do_dct = jpeg_fdct_islow;
  163319. break;
  163320. #endif
  163321. #ifdef DCT_IFAST_SUPPORTED
  163322. case JDCT_IFAST:
  163323. fdct->pub.forward_DCT = forward_DCT;
  163324. fdct->do_dct = jpeg_fdct_ifast;
  163325. break;
  163326. #endif
  163327. #ifdef DCT_FLOAT_SUPPORTED
  163328. case JDCT_FLOAT:
  163329. fdct->pub.forward_DCT = forward_DCT_float;
  163330. fdct->do_float_dct = jpeg_fdct_float;
  163331. break;
  163332. #endif
  163333. default:
  163334. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163335. break;
  163336. }
  163337. /* Mark divisor tables unallocated */
  163338. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163339. fdct->divisors[i] = NULL;
  163340. #ifdef DCT_FLOAT_SUPPORTED
  163341. fdct->float_divisors[i] = NULL;
  163342. #endif
  163343. }
  163344. }
  163345. /*** End of inlined file: jcdctmgr.c ***/
  163346. #undef CONST_BITS
  163347. /*** Start of inlined file: jchuff.c ***/
  163348. #define JPEG_INTERNALS
  163349. /*** Start of inlined file: jchuff.h ***/
  163350. /* The legal range of a DCT coefficient is
  163351. * -1024 .. +1023 for 8-bit data;
  163352. * -16384 .. +16383 for 12-bit data.
  163353. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163354. */
  163355. #ifndef _jchuff_h_
  163356. #define _jchuff_h_
  163357. #if BITS_IN_JSAMPLE == 8
  163358. #define MAX_COEF_BITS 10
  163359. #else
  163360. #define MAX_COEF_BITS 14
  163361. #endif
  163362. /* Derived data constructed for each Huffman table */
  163363. typedef struct {
  163364. unsigned int ehufco[256]; /* code for each symbol */
  163365. char ehufsi[256]; /* length of code for each symbol */
  163366. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163367. } c_derived_tbl;
  163368. /* Short forms of external names for systems with brain-damaged linkers. */
  163369. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163370. #define jpeg_make_c_derived_tbl jMkCDerived
  163371. #define jpeg_gen_optimal_table jGenOptTbl
  163372. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163373. /* Expand a Huffman table definition into the derived format */
  163374. EXTERN(void) jpeg_make_c_derived_tbl
  163375. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163376. c_derived_tbl ** pdtbl));
  163377. /* Generate an optimal table definition given the specified counts */
  163378. EXTERN(void) jpeg_gen_optimal_table
  163379. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163380. #endif
  163381. /*** End of inlined file: jchuff.h ***/
  163382. /* Declarations shared with jcphuff.c */
  163383. /* Expanded entropy encoder object for Huffman encoding.
  163384. *
  163385. * The savable_state subrecord contains fields that change within an MCU,
  163386. * but must not be updated permanently until we complete the MCU.
  163387. */
  163388. typedef struct {
  163389. INT32 put_buffer; /* current bit-accumulation buffer */
  163390. int put_bits; /* # of bits now in it */
  163391. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163392. } savable_state;
  163393. /* This macro is to work around compilers with missing or broken
  163394. * structure assignment. You'll need to fix this code if you have
  163395. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163396. */
  163397. #ifndef NO_STRUCT_ASSIGN
  163398. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163399. #else
  163400. #if MAX_COMPS_IN_SCAN == 4
  163401. #define ASSIGN_STATE(dest,src) \
  163402. ((dest).put_buffer = (src).put_buffer, \
  163403. (dest).put_bits = (src).put_bits, \
  163404. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163405. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163406. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163407. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163408. #endif
  163409. #endif
  163410. typedef struct {
  163411. struct jpeg_entropy_encoder pub; /* public fields */
  163412. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163413. /* These fields are NOT loaded into local working state. */
  163414. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163415. int next_restart_num; /* next restart number to write (0-7) */
  163416. /* Pointers to derived tables (these workspaces have image lifespan) */
  163417. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163418. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163419. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163420. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163421. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163422. #endif
  163423. } huff_entropy_encoder;
  163424. typedef huff_entropy_encoder * huff_entropy_ptr;
  163425. /* Working state while writing an MCU.
  163426. * This struct contains all the fields that are needed by subroutines.
  163427. */
  163428. typedef struct {
  163429. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163430. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163431. savable_state cur; /* Current bit buffer & DC state */
  163432. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163433. } working_state;
  163434. /* Forward declarations */
  163435. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163436. JBLOCKROW *MCU_data));
  163437. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163438. #ifdef ENTROPY_OPT_SUPPORTED
  163439. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163440. JBLOCKROW *MCU_data));
  163441. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163442. #endif
  163443. /*
  163444. * Initialize for a Huffman-compressed scan.
  163445. * If gather_statistics is TRUE, we do not output anything during the scan,
  163446. * just count the Huffman symbols used and generate Huffman code tables.
  163447. */
  163448. METHODDEF(void)
  163449. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163450. {
  163451. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163452. int ci, dctbl, actbl;
  163453. jpeg_component_info * compptr;
  163454. if (gather_statistics) {
  163455. #ifdef ENTROPY_OPT_SUPPORTED
  163456. entropy->pub.encode_mcu = encode_mcu_gather;
  163457. entropy->pub.finish_pass = finish_pass_gather;
  163458. #else
  163459. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163460. #endif
  163461. } else {
  163462. entropy->pub.encode_mcu = encode_mcu_huff;
  163463. entropy->pub.finish_pass = finish_pass_huff;
  163464. }
  163465. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163466. compptr = cinfo->cur_comp_info[ci];
  163467. dctbl = compptr->dc_tbl_no;
  163468. actbl = compptr->ac_tbl_no;
  163469. if (gather_statistics) {
  163470. #ifdef ENTROPY_OPT_SUPPORTED
  163471. /* Check for invalid table indexes */
  163472. /* (make_c_derived_tbl does this in the other path) */
  163473. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163474. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163475. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163476. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163477. /* Allocate and zero the statistics tables */
  163478. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163479. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163480. entropy->dc_count_ptrs[dctbl] = (long *)
  163481. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163482. 257 * SIZEOF(long));
  163483. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163484. if (entropy->ac_count_ptrs[actbl] == NULL)
  163485. entropy->ac_count_ptrs[actbl] = (long *)
  163486. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163487. 257 * SIZEOF(long));
  163488. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163489. #endif
  163490. } else {
  163491. /* Compute derived values for Huffman tables */
  163492. /* We may do this more than once for a table, but it's not expensive */
  163493. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163494. & entropy->dc_derived_tbls[dctbl]);
  163495. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163496. & entropy->ac_derived_tbls[actbl]);
  163497. }
  163498. /* Initialize DC predictions to 0 */
  163499. entropy->saved.last_dc_val[ci] = 0;
  163500. }
  163501. /* Initialize bit buffer to empty */
  163502. entropy->saved.put_buffer = 0;
  163503. entropy->saved.put_bits = 0;
  163504. /* Initialize restart stuff */
  163505. entropy->restarts_to_go = cinfo->restart_interval;
  163506. entropy->next_restart_num = 0;
  163507. }
  163508. /*
  163509. * Compute the derived values for a Huffman table.
  163510. * This routine also performs some validation checks on the table.
  163511. *
  163512. * Note this is also used by jcphuff.c.
  163513. */
  163514. GLOBAL(void)
  163515. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163516. c_derived_tbl ** pdtbl)
  163517. {
  163518. JHUFF_TBL *htbl;
  163519. c_derived_tbl *dtbl;
  163520. int p, i, l, lastp, si, maxsymbol;
  163521. char huffsize[257];
  163522. unsigned int huffcode[257];
  163523. unsigned int code;
  163524. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163525. * paralleling the order of the symbols themselves in htbl->huffval[].
  163526. */
  163527. /* Find the input Huffman table */
  163528. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163529. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163530. htbl =
  163531. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163532. if (htbl == NULL)
  163533. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163534. /* Allocate a workspace if we haven't already done so. */
  163535. if (*pdtbl == NULL)
  163536. *pdtbl = (c_derived_tbl *)
  163537. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163538. SIZEOF(c_derived_tbl));
  163539. dtbl = *pdtbl;
  163540. /* Figure C.1: make table of Huffman code length for each symbol */
  163541. p = 0;
  163542. for (l = 1; l <= 16; l++) {
  163543. i = (int) htbl->bits[l];
  163544. if (i < 0 || p + i > 256) /* protect against table overrun */
  163545. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163546. while (i--)
  163547. huffsize[p++] = (char) l;
  163548. }
  163549. huffsize[p] = 0;
  163550. lastp = p;
  163551. /* Figure C.2: generate the codes themselves */
  163552. /* We also validate that the counts represent a legal Huffman code tree. */
  163553. code = 0;
  163554. si = huffsize[0];
  163555. p = 0;
  163556. while (huffsize[p]) {
  163557. while (((int) huffsize[p]) == si) {
  163558. huffcode[p++] = code;
  163559. code++;
  163560. }
  163561. /* code is now 1 more than the last code used for codelength si; but
  163562. * it must still fit in si bits, since no code is allowed to be all ones.
  163563. */
  163564. if (((INT32) code) >= (((INT32) 1) << si))
  163565. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163566. code <<= 1;
  163567. si++;
  163568. }
  163569. /* Figure C.3: generate encoding tables */
  163570. /* These are code and size indexed by symbol value */
  163571. /* Set all codeless symbols to have code length 0;
  163572. * this lets us detect duplicate VAL entries here, and later
  163573. * allows emit_bits to detect any attempt to emit such symbols.
  163574. */
  163575. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163576. /* This is also a convenient place to check for out-of-range
  163577. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163578. * but only 0..15 for DC. (We could constrain them further
  163579. * based on data depth and mode, but this seems enough.)
  163580. */
  163581. maxsymbol = isDC ? 15 : 255;
  163582. for (p = 0; p < lastp; p++) {
  163583. i = htbl->huffval[p];
  163584. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163585. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163586. dtbl->ehufco[i] = huffcode[p];
  163587. dtbl->ehufsi[i] = huffsize[p];
  163588. }
  163589. }
  163590. /* Outputting bytes to the file */
  163591. /* Emit a byte, taking 'action' if must suspend. */
  163592. #define emit_byte(state,val,action) \
  163593. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163594. if (--(state)->free_in_buffer == 0) \
  163595. if (! dump_buffer(state)) \
  163596. { action; } }
  163597. LOCAL(boolean)
  163598. dump_buffer (working_state * state)
  163599. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163600. {
  163601. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163602. if (! (*dest->empty_output_buffer) (state->cinfo))
  163603. return FALSE;
  163604. /* After a successful buffer dump, must reset buffer pointers */
  163605. state->next_output_byte = dest->next_output_byte;
  163606. state->free_in_buffer = dest->free_in_buffer;
  163607. return TRUE;
  163608. }
  163609. /* Outputting bits to the file */
  163610. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163611. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163612. * in one call, and we never retain more than 7 bits in put_buffer
  163613. * between calls, so 24 bits are sufficient.
  163614. */
  163615. INLINE
  163616. LOCAL(boolean)
  163617. emit_bits (working_state * state, unsigned int code, int size)
  163618. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163619. {
  163620. /* This routine is heavily used, so it's worth coding tightly. */
  163621. register INT32 put_buffer = (INT32) code;
  163622. register int put_bits = state->cur.put_bits;
  163623. /* if size is 0, caller used an invalid Huffman table entry */
  163624. if (size == 0)
  163625. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163626. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163627. put_bits += size; /* new number of bits in buffer */
  163628. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163629. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163630. while (put_bits >= 8) {
  163631. int c = (int) ((put_buffer >> 16) & 0xFF);
  163632. emit_byte(state, c, return FALSE);
  163633. if (c == 0xFF) { /* need to stuff a zero byte? */
  163634. emit_byte(state, 0, return FALSE);
  163635. }
  163636. put_buffer <<= 8;
  163637. put_bits -= 8;
  163638. }
  163639. state->cur.put_buffer = put_buffer; /* update state variables */
  163640. state->cur.put_bits = put_bits;
  163641. return TRUE;
  163642. }
  163643. LOCAL(boolean)
  163644. flush_bits (working_state * state)
  163645. {
  163646. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163647. return FALSE;
  163648. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163649. state->cur.put_bits = 0;
  163650. return TRUE;
  163651. }
  163652. /* Encode a single block's worth of coefficients */
  163653. LOCAL(boolean)
  163654. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163655. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163656. {
  163657. register int temp, temp2;
  163658. register int nbits;
  163659. register int k, r, i;
  163660. /* Encode the DC coefficient difference per section F.1.2.1 */
  163661. temp = temp2 = block[0] - last_dc_val;
  163662. if (temp < 0) {
  163663. temp = -temp; /* temp is abs value of input */
  163664. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163665. /* This code assumes we are on a two's complement machine */
  163666. temp2--;
  163667. }
  163668. /* Find the number of bits needed for the magnitude of the coefficient */
  163669. nbits = 0;
  163670. while (temp) {
  163671. nbits++;
  163672. temp >>= 1;
  163673. }
  163674. /* Check for out-of-range coefficient values.
  163675. * Since we're encoding a difference, the range limit is twice as much.
  163676. */
  163677. if (nbits > MAX_COEF_BITS+1)
  163678. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163679. /* Emit the Huffman-coded symbol for the number of bits */
  163680. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163681. return FALSE;
  163682. /* Emit that number of bits of the value, if positive, */
  163683. /* or the complement of its magnitude, if negative. */
  163684. if (nbits) /* emit_bits rejects calls with size 0 */
  163685. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163686. return FALSE;
  163687. /* Encode the AC coefficients per section F.1.2.2 */
  163688. r = 0; /* r = run length of zeros */
  163689. for (k = 1; k < DCTSIZE2; k++) {
  163690. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163691. r++;
  163692. } else {
  163693. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163694. while (r > 15) {
  163695. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163696. return FALSE;
  163697. r -= 16;
  163698. }
  163699. temp2 = temp;
  163700. if (temp < 0) {
  163701. temp = -temp; /* temp is abs value of input */
  163702. /* This code assumes we are on a two's complement machine */
  163703. temp2--;
  163704. }
  163705. /* Find the number of bits needed for the magnitude of the coefficient */
  163706. nbits = 1; /* there must be at least one 1 bit */
  163707. while ((temp >>= 1))
  163708. nbits++;
  163709. /* Check for out-of-range coefficient values */
  163710. if (nbits > MAX_COEF_BITS)
  163711. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163712. /* Emit Huffman symbol for run length / number of bits */
  163713. i = (r << 4) + nbits;
  163714. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163715. return FALSE;
  163716. /* Emit that number of bits of the value, if positive, */
  163717. /* or the complement of its magnitude, if negative. */
  163718. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163719. return FALSE;
  163720. r = 0;
  163721. }
  163722. }
  163723. /* If the last coef(s) were zero, emit an end-of-block code */
  163724. if (r > 0)
  163725. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163726. return FALSE;
  163727. return TRUE;
  163728. }
  163729. /*
  163730. * Emit a restart marker & resynchronize predictions.
  163731. */
  163732. LOCAL(boolean)
  163733. emit_restart (working_state * state, int restart_num)
  163734. {
  163735. int ci;
  163736. if (! flush_bits(state))
  163737. return FALSE;
  163738. emit_byte(state, 0xFF, return FALSE);
  163739. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163740. /* Re-initialize DC predictions to 0 */
  163741. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163742. state->cur.last_dc_val[ci] = 0;
  163743. /* The restart counter is not updated until we successfully write the MCU. */
  163744. return TRUE;
  163745. }
  163746. /*
  163747. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163748. */
  163749. METHODDEF(boolean)
  163750. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163751. {
  163752. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163753. working_state state;
  163754. int blkn, ci;
  163755. jpeg_component_info * compptr;
  163756. /* Load up working state */
  163757. state.next_output_byte = cinfo->dest->next_output_byte;
  163758. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163759. ASSIGN_STATE(state.cur, entropy->saved);
  163760. state.cinfo = cinfo;
  163761. /* Emit restart marker if needed */
  163762. if (cinfo->restart_interval) {
  163763. if (entropy->restarts_to_go == 0)
  163764. if (! emit_restart(&state, entropy->next_restart_num))
  163765. return FALSE;
  163766. }
  163767. /* Encode the MCU data blocks */
  163768. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163769. ci = cinfo->MCU_membership[blkn];
  163770. compptr = cinfo->cur_comp_info[ci];
  163771. if (! encode_one_block(&state,
  163772. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163773. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163774. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163775. return FALSE;
  163776. /* Update last_dc_val */
  163777. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163778. }
  163779. /* Completed MCU, so update state */
  163780. cinfo->dest->next_output_byte = state.next_output_byte;
  163781. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163782. ASSIGN_STATE(entropy->saved, state.cur);
  163783. /* Update restart-interval state too */
  163784. if (cinfo->restart_interval) {
  163785. if (entropy->restarts_to_go == 0) {
  163786. entropy->restarts_to_go = cinfo->restart_interval;
  163787. entropy->next_restart_num++;
  163788. entropy->next_restart_num &= 7;
  163789. }
  163790. entropy->restarts_to_go--;
  163791. }
  163792. return TRUE;
  163793. }
  163794. /*
  163795. * Finish up at the end of a Huffman-compressed scan.
  163796. */
  163797. METHODDEF(void)
  163798. finish_pass_huff (j_compress_ptr cinfo)
  163799. {
  163800. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163801. working_state state;
  163802. /* Load up working state ... flush_bits needs it */
  163803. state.next_output_byte = cinfo->dest->next_output_byte;
  163804. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163805. ASSIGN_STATE(state.cur, entropy->saved);
  163806. state.cinfo = cinfo;
  163807. /* Flush out the last data */
  163808. if (! flush_bits(&state))
  163809. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163810. /* Update state */
  163811. cinfo->dest->next_output_byte = state.next_output_byte;
  163812. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163813. ASSIGN_STATE(entropy->saved, state.cur);
  163814. }
  163815. /*
  163816. * Huffman coding optimization.
  163817. *
  163818. * We first scan the supplied data and count the number of uses of each symbol
  163819. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163820. * Then we build a Huffman coding tree for the observed counts.
  163821. * Symbols which are not needed at all for the particular image are not
  163822. * assigned any code, which saves space in the DHT marker as well as in
  163823. * the compressed data.
  163824. */
  163825. #ifdef ENTROPY_OPT_SUPPORTED
  163826. /* Process a single block's worth of coefficients */
  163827. LOCAL(void)
  163828. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163829. long dc_counts[], long ac_counts[])
  163830. {
  163831. register int temp;
  163832. register int nbits;
  163833. register int k, r;
  163834. /* Encode the DC coefficient difference per section F.1.2.1 */
  163835. temp = block[0] - last_dc_val;
  163836. if (temp < 0)
  163837. temp = -temp;
  163838. /* Find the number of bits needed for the magnitude of the coefficient */
  163839. nbits = 0;
  163840. while (temp) {
  163841. nbits++;
  163842. temp >>= 1;
  163843. }
  163844. /* Check for out-of-range coefficient values.
  163845. * Since we're encoding a difference, the range limit is twice as much.
  163846. */
  163847. if (nbits > MAX_COEF_BITS+1)
  163848. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163849. /* Count the Huffman symbol for the number of bits */
  163850. dc_counts[nbits]++;
  163851. /* Encode the AC coefficients per section F.1.2.2 */
  163852. r = 0; /* r = run length of zeros */
  163853. for (k = 1; k < DCTSIZE2; k++) {
  163854. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163855. r++;
  163856. } else {
  163857. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163858. while (r > 15) {
  163859. ac_counts[0xF0]++;
  163860. r -= 16;
  163861. }
  163862. /* Find the number of bits needed for the magnitude of the coefficient */
  163863. if (temp < 0)
  163864. temp = -temp;
  163865. /* Find the number of bits needed for the magnitude of the coefficient */
  163866. nbits = 1; /* there must be at least one 1 bit */
  163867. while ((temp >>= 1))
  163868. nbits++;
  163869. /* Check for out-of-range coefficient values */
  163870. if (nbits > MAX_COEF_BITS)
  163871. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163872. /* Count Huffman symbol for run length / number of bits */
  163873. ac_counts[(r << 4) + nbits]++;
  163874. r = 0;
  163875. }
  163876. }
  163877. /* If the last coef(s) were zero, emit an end-of-block code */
  163878. if (r > 0)
  163879. ac_counts[0]++;
  163880. }
  163881. /*
  163882. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163883. * No data is actually output, so no suspension return is possible.
  163884. */
  163885. METHODDEF(boolean)
  163886. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163887. {
  163888. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163889. int blkn, ci;
  163890. jpeg_component_info * compptr;
  163891. /* Take care of restart intervals if needed */
  163892. if (cinfo->restart_interval) {
  163893. if (entropy->restarts_to_go == 0) {
  163894. /* Re-initialize DC predictions to 0 */
  163895. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163896. entropy->saved.last_dc_val[ci] = 0;
  163897. /* Update restart state */
  163898. entropy->restarts_to_go = cinfo->restart_interval;
  163899. }
  163900. entropy->restarts_to_go--;
  163901. }
  163902. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163903. ci = cinfo->MCU_membership[blkn];
  163904. compptr = cinfo->cur_comp_info[ci];
  163905. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163906. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163907. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163908. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163909. }
  163910. return TRUE;
  163911. }
  163912. /*
  163913. * Generate the best Huffman code table for the given counts, fill htbl.
  163914. * Note this is also used by jcphuff.c.
  163915. *
  163916. * The JPEG standard requires that no symbol be assigned a codeword of all
  163917. * one bits (so that padding bits added at the end of a compressed segment
  163918. * can't look like a valid code). Because of the canonical ordering of
  163919. * codewords, this just means that there must be an unused slot in the
  163920. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163921. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163922. * with count 1. In theory that's not optimal; giving it count zero but
  163923. * including it in the symbol set anyway should give a better Huffman code.
  163924. * But the theoretically better code actually seems to come out worse in
  163925. * practice, because it produces more all-ones bytes (which incur stuffed
  163926. * zero bytes in the final file). In any case the difference is tiny.
  163927. *
  163928. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163929. * If some symbols have a very small but nonzero probability, the Huffman tree
  163930. * must be adjusted to meet the code length restriction. We currently use
  163931. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163932. * optimal; it may not choose the best possible limited-length code. But
  163933. * typically only very-low-frequency symbols will be given less-than-optimal
  163934. * lengths, so the code is almost optimal. Experimental comparisons against
  163935. * an optimal limited-length-code algorithm indicate that the difference is
  163936. * microscopic --- usually less than a hundredth of a percent of total size.
  163937. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163938. */
  163939. GLOBAL(void)
  163940. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163941. {
  163942. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163943. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163944. int codesize[257]; /* codesize[k] = code length of symbol k */
  163945. int others[257]; /* next symbol in current branch of tree */
  163946. int c1, c2;
  163947. int p, i, j;
  163948. long v;
  163949. /* This algorithm is explained in section K.2 of the JPEG standard */
  163950. MEMZERO(bits, SIZEOF(bits));
  163951. MEMZERO(codesize, SIZEOF(codesize));
  163952. for (i = 0; i < 257; i++)
  163953. others[i] = -1; /* init links to empty */
  163954. freq[256] = 1; /* make sure 256 has a nonzero count */
  163955. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163956. * that no real symbol is given code-value of all ones, because 256
  163957. * will be placed last in the largest codeword category.
  163958. */
  163959. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163960. for (;;) {
  163961. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163962. /* In case of ties, take the larger symbol number */
  163963. c1 = -1;
  163964. v = 1000000000L;
  163965. for (i = 0; i <= 256; i++) {
  163966. if (freq[i] && freq[i] <= v) {
  163967. v = freq[i];
  163968. c1 = i;
  163969. }
  163970. }
  163971. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163972. /* In case of ties, take the larger symbol number */
  163973. c2 = -1;
  163974. v = 1000000000L;
  163975. for (i = 0; i <= 256; i++) {
  163976. if (freq[i] && freq[i] <= v && i != c1) {
  163977. v = freq[i];
  163978. c2 = i;
  163979. }
  163980. }
  163981. /* Done if we've merged everything into one frequency */
  163982. if (c2 < 0)
  163983. break;
  163984. /* Else merge the two counts/trees */
  163985. freq[c1] += freq[c2];
  163986. freq[c2] = 0;
  163987. /* Increment the codesize of everything in c1's tree branch */
  163988. codesize[c1]++;
  163989. while (others[c1] >= 0) {
  163990. c1 = others[c1];
  163991. codesize[c1]++;
  163992. }
  163993. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163994. /* Increment the codesize of everything in c2's tree branch */
  163995. codesize[c2]++;
  163996. while (others[c2] >= 0) {
  163997. c2 = others[c2];
  163998. codesize[c2]++;
  163999. }
  164000. }
  164001. /* Now count the number of symbols of each code length */
  164002. for (i = 0; i <= 256; i++) {
  164003. if (codesize[i]) {
  164004. /* The JPEG standard seems to think that this can't happen, */
  164005. /* but I'm paranoid... */
  164006. if (codesize[i] > MAX_CLEN)
  164007. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  164008. bits[codesize[i]]++;
  164009. }
  164010. }
  164011. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  164012. * Huffman procedure assigned any such lengths, we must adjust the coding.
  164013. * Here is what the JPEG spec says about how this next bit works:
  164014. * Since symbols are paired for the longest Huffman code, the symbols are
  164015. * removed from this length category two at a time. The prefix for the pair
  164016. * (which is one bit shorter) is allocated to one of the pair; then,
  164017. * skipping the BITS entry for that prefix length, a code word from the next
  164018. * shortest nonzero BITS entry is converted into a prefix for two code words
  164019. * one bit longer.
  164020. */
  164021. for (i = MAX_CLEN; i > 16; i--) {
  164022. while (bits[i] > 0) {
  164023. j = i - 2; /* find length of new prefix to be used */
  164024. while (bits[j] == 0)
  164025. j--;
  164026. bits[i] -= 2; /* remove two symbols */
  164027. bits[i-1]++; /* one goes in this length */
  164028. bits[j+1] += 2; /* two new symbols in this length */
  164029. bits[j]--; /* symbol of this length is now a prefix */
  164030. }
  164031. }
  164032. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  164033. while (bits[i] == 0) /* find largest codelength still in use */
  164034. i--;
  164035. bits[i]--;
  164036. /* Return final symbol counts (only for lengths 0..16) */
  164037. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  164038. /* Return a list of the symbols sorted by code length */
  164039. /* It's not real clear to me why we don't need to consider the codelength
  164040. * changes made above, but the JPEG spec seems to think this works.
  164041. */
  164042. p = 0;
  164043. for (i = 1; i <= MAX_CLEN; i++) {
  164044. for (j = 0; j <= 255; j++) {
  164045. if (codesize[j] == i) {
  164046. htbl->huffval[p] = (UINT8) j;
  164047. p++;
  164048. }
  164049. }
  164050. }
  164051. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  164052. htbl->sent_table = FALSE;
  164053. }
  164054. /*
  164055. * Finish up a statistics-gathering pass and create the new Huffman tables.
  164056. */
  164057. METHODDEF(void)
  164058. finish_pass_gather (j_compress_ptr cinfo)
  164059. {
  164060. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164061. int ci, dctbl, actbl;
  164062. jpeg_component_info * compptr;
  164063. JHUFF_TBL **htblptr;
  164064. boolean did_dc[NUM_HUFF_TBLS];
  164065. boolean did_ac[NUM_HUFF_TBLS];
  164066. /* It's important not to apply jpeg_gen_optimal_table more than once
  164067. * per table, because it clobbers the input frequency counts!
  164068. */
  164069. MEMZERO(did_dc, SIZEOF(did_dc));
  164070. MEMZERO(did_ac, SIZEOF(did_ac));
  164071. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164072. compptr = cinfo->cur_comp_info[ci];
  164073. dctbl = compptr->dc_tbl_no;
  164074. actbl = compptr->ac_tbl_no;
  164075. if (! did_dc[dctbl]) {
  164076. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  164077. if (*htblptr == NULL)
  164078. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164079. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  164080. did_dc[dctbl] = TRUE;
  164081. }
  164082. if (! did_ac[actbl]) {
  164083. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  164084. if (*htblptr == NULL)
  164085. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164086. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  164087. did_ac[actbl] = TRUE;
  164088. }
  164089. }
  164090. }
  164091. #endif /* ENTROPY_OPT_SUPPORTED */
  164092. /*
  164093. * Module initialization routine for Huffman entropy encoding.
  164094. */
  164095. GLOBAL(void)
  164096. jinit_huff_encoder (j_compress_ptr cinfo)
  164097. {
  164098. huff_entropy_ptr entropy;
  164099. int i;
  164100. entropy = (huff_entropy_ptr)
  164101. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164102. SIZEOF(huff_entropy_encoder));
  164103. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  164104. entropy->pub.start_pass = start_pass_huff;
  164105. /* Mark tables unallocated */
  164106. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164107. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164108. #ifdef ENTROPY_OPT_SUPPORTED
  164109. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  164110. #endif
  164111. }
  164112. }
  164113. /*** End of inlined file: jchuff.c ***/
  164114. #undef emit_byte
  164115. /*** Start of inlined file: jcinit.c ***/
  164116. #define JPEG_INTERNALS
  164117. /*
  164118. * Master selection of compression modules.
  164119. * This is done once at the start of processing an image. We determine
  164120. * which modules will be used and give them appropriate initialization calls.
  164121. */
  164122. GLOBAL(void)
  164123. jinit_compress_master (j_compress_ptr cinfo)
  164124. {
  164125. /* Initialize master control (includes parameter checking/processing) */
  164126. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164127. /* Preprocessing */
  164128. if (! cinfo->raw_data_in) {
  164129. jinit_color_converter(cinfo);
  164130. jinit_downsampler(cinfo);
  164131. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164132. }
  164133. /* Forward DCT */
  164134. jinit_forward_dct(cinfo);
  164135. /* Entropy encoding: either Huffman or arithmetic coding. */
  164136. if (cinfo->arith_code) {
  164137. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164138. } else {
  164139. if (cinfo->progressive_mode) {
  164140. #ifdef C_PROGRESSIVE_SUPPORTED
  164141. jinit_phuff_encoder(cinfo);
  164142. #else
  164143. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164144. #endif
  164145. } else
  164146. jinit_huff_encoder(cinfo);
  164147. }
  164148. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164149. jinit_c_coef_controller(cinfo,
  164150. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164151. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164152. jinit_marker_writer(cinfo);
  164153. /* We can now tell the memory manager to allocate virtual arrays. */
  164154. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164155. /* Write the datastream header (SOI) immediately.
  164156. * Frame and scan headers are postponed till later.
  164157. * This lets application insert special markers after the SOI.
  164158. */
  164159. (*cinfo->marker->write_file_header) (cinfo);
  164160. }
  164161. /*** End of inlined file: jcinit.c ***/
  164162. /*** Start of inlined file: jcmainct.c ***/
  164163. #define JPEG_INTERNALS
  164164. /* Note: currently, there is no operating mode in which a full-image buffer
  164165. * is needed at this step. If there were, that mode could not be used with
  164166. * "raw data" input, since this module is bypassed in that case. However,
  164167. * we've left the code here for possible use in special applications.
  164168. */
  164169. #undef FULL_MAIN_BUFFER_SUPPORTED
  164170. /* Private buffer controller object */
  164171. typedef struct {
  164172. struct jpeg_c_main_controller pub; /* public fields */
  164173. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164174. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164175. boolean suspended; /* remember if we suspended output */
  164176. J_BUF_MODE pass_mode; /* current operating mode */
  164177. /* If using just a strip buffer, this points to the entire set of buffers
  164178. * (we allocate one for each component). In the full-image case, this
  164179. * points to the currently accessible strips of the virtual arrays.
  164180. */
  164181. JSAMPARRAY buffer[MAX_COMPONENTS];
  164182. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164183. /* If using full-image storage, this array holds pointers to virtual-array
  164184. * control blocks for each component. Unused if not full-image storage.
  164185. */
  164186. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164187. #endif
  164188. } my_main_controller;
  164189. typedef my_main_controller * my_main_ptr;
  164190. /* Forward declarations */
  164191. METHODDEF(void) process_data_simple_main
  164192. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164193. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164194. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164195. METHODDEF(void) process_data_buffer_main
  164196. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164197. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164198. #endif
  164199. /*
  164200. * Initialize for a processing pass.
  164201. */
  164202. METHODDEF(void)
  164203. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164204. {
  164205. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164206. /* Do nothing in raw-data mode. */
  164207. if (cinfo->raw_data_in)
  164208. return;
  164209. main_->cur_iMCU_row = 0; /* initialize counters */
  164210. main_->rowgroup_ctr = 0;
  164211. main_->suspended = FALSE;
  164212. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164213. switch (pass_mode) {
  164214. case JBUF_PASS_THRU:
  164215. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164216. if (main_->whole_image[0] != NULL)
  164217. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164218. #endif
  164219. main_->pub.process_data = process_data_simple_main;
  164220. break;
  164221. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164222. case JBUF_SAVE_SOURCE:
  164223. case JBUF_CRANK_DEST:
  164224. case JBUF_SAVE_AND_PASS:
  164225. if (main_->whole_image[0] == NULL)
  164226. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164227. main_->pub.process_data = process_data_buffer_main;
  164228. break;
  164229. #endif
  164230. default:
  164231. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164232. break;
  164233. }
  164234. }
  164235. /*
  164236. * Process some data.
  164237. * This routine handles the simple pass-through mode,
  164238. * where we have only a strip buffer.
  164239. */
  164240. METHODDEF(void)
  164241. process_data_simple_main (j_compress_ptr cinfo,
  164242. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164243. JDIMENSION in_rows_avail)
  164244. {
  164245. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164246. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164247. /* Read input data if we haven't filled the main buffer yet */
  164248. if (main_->rowgroup_ctr < DCTSIZE)
  164249. (*cinfo->prep->pre_process_data) (cinfo,
  164250. input_buf, in_row_ctr, in_rows_avail,
  164251. main_->buffer, &main_->rowgroup_ctr,
  164252. (JDIMENSION) DCTSIZE);
  164253. /* If we don't have a full iMCU row buffered, return to application for
  164254. * more data. Note that preprocessor will always pad to fill the iMCU row
  164255. * at the bottom of the image.
  164256. */
  164257. if (main_->rowgroup_ctr != DCTSIZE)
  164258. return;
  164259. /* Send the completed row to the compressor */
  164260. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164261. /* If compressor did not consume the whole row, then we must need to
  164262. * suspend processing and return to the application. In this situation
  164263. * we pretend we didn't yet consume the last input row; otherwise, if
  164264. * it happened to be the last row of the image, the application would
  164265. * think we were done.
  164266. */
  164267. if (! main_->suspended) {
  164268. (*in_row_ctr)--;
  164269. main_->suspended = TRUE;
  164270. }
  164271. return;
  164272. }
  164273. /* We did finish the row. Undo our little suspension hack if a previous
  164274. * call suspended; then mark the main buffer empty.
  164275. */
  164276. if (main_->suspended) {
  164277. (*in_row_ctr)++;
  164278. main_->suspended = FALSE;
  164279. }
  164280. main_->rowgroup_ctr = 0;
  164281. main_->cur_iMCU_row++;
  164282. }
  164283. }
  164284. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164285. /*
  164286. * Process some data.
  164287. * This routine handles all of the modes that use a full-size buffer.
  164288. */
  164289. METHODDEF(void)
  164290. process_data_buffer_main (j_compress_ptr cinfo,
  164291. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164292. JDIMENSION in_rows_avail)
  164293. {
  164294. my_main_ptr main = (my_main_ptr) cinfo->main;
  164295. int ci;
  164296. jpeg_component_info *compptr;
  164297. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164298. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164299. /* Realign the virtual buffers if at the start of an iMCU row. */
  164300. if (main->rowgroup_ctr == 0) {
  164301. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164302. ci++, compptr++) {
  164303. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164304. ((j_common_ptr) cinfo, main->whole_image[ci],
  164305. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164306. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164307. }
  164308. /* In a read pass, pretend we just read some source data. */
  164309. if (! writing) {
  164310. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164311. main->rowgroup_ctr = DCTSIZE;
  164312. }
  164313. }
  164314. /* If a write pass, read input data until the current iMCU row is full. */
  164315. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164316. if (writing) {
  164317. (*cinfo->prep->pre_process_data) (cinfo,
  164318. input_buf, in_row_ctr, in_rows_avail,
  164319. main->buffer, &main->rowgroup_ctr,
  164320. (JDIMENSION) DCTSIZE);
  164321. /* Return to application if we need more data to fill the iMCU row. */
  164322. if (main->rowgroup_ctr < DCTSIZE)
  164323. return;
  164324. }
  164325. /* Emit data, unless this is a sink-only pass. */
  164326. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164327. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164328. /* If compressor did not consume the whole row, then we must need to
  164329. * suspend processing and return to the application. In this situation
  164330. * we pretend we didn't yet consume the last input row; otherwise, if
  164331. * it happened to be the last row of the image, the application would
  164332. * think we were done.
  164333. */
  164334. if (! main->suspended) {
  164335. (*in_row_ctr)--;
  164336. main->suspended = TRUE;
  164337. }
  164338. return;
  164339. }
  164340. /* We did finish the row. Undo our little suspension hack if a previous
  164341. * call suspended; then mark the main buffer empty.
  164342. */
  164343. if (main->suspended) {
  164344. (*in_row_ctr)++;
  164345. main->suspended = FALSE;
  164346. }
  164347. }
  164348. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164349. main->rowgroup_ctr = 0;
  164350. main->cur_iMCU_row++;
  164351. }
  164352. }
  164353. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164354. /*
  164355. * Initialize main buffer controller.
  164356. */
  164357. GLOBAL(void)
  164358. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164359. {
  164360. my_main_ptr main_;
  164361. int ci;
  164362. jpeg_component_info *compptr;
  164363. main_ = (my_main_ptr)
  164364. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164365. SIZEOF(my_main_controller));
  164366. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164367. main_->pub.start_pass = start_pass_main;
  164368. /* We don't need to create a buffer in raw-data mode. */
  164369. if (cinfo->raw_data_in)
  164370. return;
  164371. /* Create the buffer. It holds downsampled data, so each component
  164372. * may be of a different size.
  164373. */
  164374. if (need_full_buffer) {
  164375. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164376. /* Allocate a full-image virtual array for each component */
  164377. /* Note we pad the bottom to a multiple of the iMCU height */
  164378. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164379. ci++, compptr++) {
  164380. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164381. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164382. compptr->width_in_blocks * DCTSIZE,
  164383. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164384. (long) compptr->v_samp_factor) * DCTSIZE,
  164385. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164386. }
  164387. #else
  164388. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164389. #endif
  164390. } else {
  164391. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164392. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164393. #endif
  164394. /* Allocate a strip buffer for each component */
  164395. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164396. ci++, compptr++) {
  164397. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164398. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164399. compptr->width_in_blocks * DCTSIZE,
  164400. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164401. }
  164402. }
  164403. }
  164404. /*** End of inlined file: jcmainct.c ***/
  164405. /*** Start of inlined file: jcmarker.c ***/
  164406. #define JPEG_INTERNALS
  164407. /* Private state */
  164408. typedef struct {
  164409. struct jpeg_marker_writer pub; /* public fields */
  164410. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164411. } my_marker_writer;
  164412. typedef my_marker_writer * my_marker_ptr;
  164413. /*
  164414. * Basic output routines.
  164415. *
  164416. * Note that we do not support suspension while writing a marker.
  164417. * Therefore, an application using suspension must ensure that there is
  164418. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164419. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164420. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164421. * modes are not supported at all with suspension, so those two are the only
  164422. * points where markers will be written.
  164423. */
  164424. LOCAL(void)
  164425. emit_byte (j_compress_ptr cinfo, int val)
  164426. /* Emit a byte */
  164427. {
  164428. struct jpeg_destination_mgr * dest = cinfo->dest;
  164429. *(dest->next_output_byte)++ = (JOCTET) val;
  164430. if (--dest->free_in_buffer == 0) {
  164431. if (! (*dest->empty_output_buffer) (cinfo))
  164432. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164433. }
  164434. }
  164435. LOCAL(void)
  164436. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164437. /* Emit a marker code */
  164438. {
  164439. emit_byte(cinfo, 0xFF);
  164440. emit_byte(cinfo, (int) mark);
  164441. }
  164442. LOCAL(void)
  164443. emit_2bytes (j_compress_ptr cinfo, int value)
  164444. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164445. {
  164446. emit_byte(cinfo, (value >> 8) & 0xFF);
  164447. emit_byte(cinfo, value & 0xFF);
  164448. }
  164449. /*
  164450. * Routines to write specific marker types.
  164451. */
  164452. LOCAL(int)
  164453. emit_dqt (j_compress_ptr cinfo, int index)
  164454. /* Emit a DQT marker */
  164455. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164456. {
  164457. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164458. int prec;
  164459. int i;
  164460. if (qtbl == NULL)
  164461. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164462. prec = 0;
  164463. for (i = 0; i < DCTSIZE2; i++) {
  164464. if (qtbl->quantval[i] > 255)
  164465. prec = 1;
  164466. }
  164467. if (! qtbl->sent_table) {
  164468. emit_marker(cinfo, M_DQT);
  164469. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164470. emit_byte(cinfo, index + (prec<<4));
  164471. for (i = 0; i < DCTSIZE2; i++) {
  164472. /* The table entries must be emitted in zigzag order. */
  164473. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164474. if (prec)
  164475. emit_byte(cinfo, (int) (qval >> 8));
  164476. emit_byte(cinfo, (int) (qval & 0xFF));
  164477. }
  164478. qtbl->sent_table = TRUE;
  164479. }
  164480. return prec;
  164481. }
  164482. LOCAL(void)
  164483. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164484. /* Emit a DHT marker */
  164485. {
  164486. JHUFF_TBL * htbl;
  164487. int length, i;
  164488. if (is_ac) {
  164489. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164490. index += 0x10; /* output index has AC bit set */
  164491. } else {
  164492. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164493. }
  164494. if (htbl == NULL)
  164495. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164496. if (! htbl->sent_table) {
  164497. emit_marker(cinfo, M_DHT);
  164498. length = 0;
  164499. for (i = 1; i <= 16; i++)
  164500. length += htbl->bits[i];
  164501. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164502. emit_byte(cinfo, index);
  164503. for (i = 1; i <= 16; i++)
  164504. emit_byte(cinfo, htbl->bits[i]);
  164505. for (i = 0; i < length; i++)
  164506. emit_byte(cinfo, htbl->huffval[i]);
  164507. htbl->sent_table = TRUE;
  164508. }
  164509. }
  164510. LOCAL(void)
  164511. emit_dac (j_compress_ptr)
  164512. /* Emit a DAC marker */
  164513. /* Since the useful info is so small, we want to emit all the tables in */
  164514. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164515. {
  164516. #ifdef C_ARITH_CODING_SUPPORTED
  164517. char dc_in_use[NUM_ARITH_TBLS];
  164518. char ac_in_use[NUM_ARITH_TBLS];
  164519. int length, i;
  164520. jpeg_component_info *compptr;
  164521. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164522. dc_in_use[i] = ac_in_use[i] = 0;
  164523. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164524. compptr = cinfo->cur_comp_info[i];
  164525. dc_in_use[compptr->dc_tbl_no] = 1;
  164526. ac_in_use[compptr->ac_tbl_no] = 1;
  164527. }
  164528. length = 0;
  164529. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164530. length += dc_in_use[i] + ac_in_use[i];
  164531. emit_marker(cinfo, M_DAC);
  164532. emit_2bytes(cinfo, length*2 + 2);
  164533. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164534. if (dc_in_use[i]) {
  164535. emit_byte(cinfo, i);
  164536. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164537. }
  164538. if (ac_in_use[i]) {
  164539. emit_byte(cinfo, i + 0x10);
  164540. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164541. }
  164542. }
  164543. #endif /* C_ARITH_CODING_SUPPORTED */
  164544. }
  164545. LOCAL(void)
  164546. emit_dri (j_compress_ptr cinfo)
  164547. /* Emit a DRI marker */
  164548. {
  164549. emit_marker(cinfo, M_DRI);
  164550. emit_2bytes(cinfo, 4); /* fixed length */
  164551. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164552. }
  164553. LOCAL(void)
  164554. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164555. /* Emit a SOF marker */
  164556. {
  164557. int ci;
  164558. jpeg_component_info *compptr;
  164559. emit_marker(cinfo, code);
  164560. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164561. /* Make sure image isn't bigger than SOF field can handle */
  164562. if ((long) cinfo->image_height > 65535L ||
  164563. (long) cinfo->image_width > 65535L)
  164564. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164565. emit_byte(cinfo, cinfo->data_precision);
  164566. emit_2bytes(cinfo, (int) cinfo->image_height);
  164567. emit_2bytes(cinfo, (int) cinfo->image_width);
  164568. emit_byte(cinfo, cinfo->num_components);
  164569. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164570. ci++, compptr++) {
  164571. emit_byte(cinfo, compptr->component_id);
  164572. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164573. emit_byte(cinfo, compptr->quant_tbl_no);
  164574. }
  164575. }
  164576. LOCAL(void)
  164577. emit_sos (j_compress_ptr cinfo)
  164578. /* Emit a SOS marker */
  164579. {
  164580. int i, td, ta;
  164581. jpeg_component_info *compptr;
  164582. emit_marker(cinfo, M_SOS);
  164583. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164584. emit_byte(cinfo, cinfo->comps_in_scan);
  164585. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164586. compptr = cinfo->cur_comp_info[i];
  164587. emit_byte(cinfo, compptr->component_id);
  164588. td = compptr->dc_tbl_no;
  164589. ta = compptr->ac_tbl_no;
  164590. if (cinfo->progressive_mode) {
  164591. /* Progressive mode: only DC or only AC tables are used in one scan;
  164592. * furthermore, Huffman coding of DC refinement uses no table at all.
  164593. * We emit 0 for unused field(s); this is recommended by the P&M text
  164594. * but does not seem to be specified in the standard.
  164595. */
  164596. if (cinfo->Ss == 0) {
  164597. ta = 0; /* DC scan */
  164598. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164599. td = 0; /* no DC table either */
  164600. } else {
  164601. td = 0; /* AC scan */
  164602. }
  164603. }
  164604. emit_byte(cinfo, (td << 4) + ta);
  164605. }
  164606. emit_byte(cinfo, cinfo->Ss);
  164607. emit_byte(cinfo, cinfo->Se);
  164608. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164609. }
  164610. LOCAL(void)
  164611. emit_jfif_app0 (j_compress_ptr cinfo)
  164612. /* Emit a JFIF-compliant APP0 marker */
  164613. {
  164614. /*
  164615. * Length of APP0 block (2 bytes)
  164616. * Block ID (4 bytes - ASCII "JFIF")
  164617. * Zero byte (1 byte to terminate the ID string)
  164618. * Version Major, Minor (2 bytes - major first)
  164619. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164620. * Xdpu (2 bytes - dots per unit horizontal)
  164621. * Ydpu (2 bytes - dots per unit vertical)
  164622. * Thumbnail X size (1 byte)
  164623. * Thumbnail Y size (1 byte)
  164624. */
  164625. emit_marker(cinfo, M_APP0);
  164626. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164627. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164628. emit_byte(cinfo, 0x46);
  164629. emit_byte(cinfo, 0x49);
  164630. emit_byte(cinfo, 0x46);
  164631. emit_byte(cinfo, 0);
  164632. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164633. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164634. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164635. emit_2bytes(cinfo, (int) cinfo->X_density);
  164636. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164637. emit_byte(cinfo, 0); /* No thumbnail image */
  164638. emit_byte(cinfo, 0);
  164639. }
  164640. LOCAL(void)
  164641. emit_adobe_app14 (j_compress_ptr cinfo)
  164642. /* Emit an Adobe APP14 marker */
  164643. {
  164644. /*
  164645. * Length of APP14 block (2 bytes)
  164646. * Block ID (5 bytes - ASCII "Adobe")
  164647. * Version Number (2 bytes - currently 100)
  164648. * Flags0 (2 bytes - currently 0)
  164649. * Flags1 (2 bytes - currently 0)
  164650. * Color transform (1 byte)
  164651. *
  164652. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164653. * now in circulation seem to use Version = 100, so that's what we write.
  164654. *
  164655. * We write the color transform byte as 1 if the JPEG color space is
  164656. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164657. * whether the encoder performed a transformation, which is pretty useless.
  164658. */
  164659. emit_marker(cinfo, M_APP14);
  164660. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164661. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164662. emit_byte(cinfo, 0x64);
  164663. emit_byte(cinfo, 0x6F);
  164664. emit_byte(cinfo, 0x62);
  164665. emit_byte(cinfo, 0x65);
  164666. emit_2bytes(cinfo, 100); /* Version */
  164667. emit_2bytes(cinfo, 0); /* Flags0 */
  164668. emit_2bytes(cinfo, 0); /* Flags1 */
  164669. switch (cinfo->jpeg_color_space) {
  164670. case JCS_YCbCr:
  164671. emit_byte(cinfo, 1); /* Color transform = 1 */
  164672. break;
  164673. case JCS_YCCK:
  164674. emit_byte(cinfo, 2); /* Color transform = 2 */
  164675. break;
  164676. default:
  164677. emit_byte(cinfo, 0); /* Color transform = 0 */
  164678. break;
  164679. }
  164680. }
  164681. /*
  164682. * These routines allow writing an arbitrary marker with parameters.
  164683. * The only intended use is to emit COM or APPn markers after calling
  164684. * write_file_header and before calling write_frame_header.
  164685. * Other uses are not guaranteed to produce desirable results.
  164686. * Counting the parameter bytes properly is the caller's responsibility.
  164687. */
  164688. METHODDEF(void)
  164689. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164690. /* Emit an arbitrary marker header */
  164691. {
  164692. if (datalen > (unsigned int) 65533) /* safety check */
  164693. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164694. emit_marker(cinfo, (JPEG_MARKER) marker);
  164695. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164696. }
  164697. METHODDEF(void)
  164698. write_marker_byte (j_compress_ptr cinfo, int val)
  164699. /* Emit one byte of marker parameters following write_marker_header */
  164700. {
  164701. emit_byte(cinfo, val);
  164702. }
  164703. /*
  164704. * Write datastream header.
  164705. * This consists of an SOI and optional APPn markers.
  164706. * We recommend use of the JFIF marker, but not the Adobe marker,
  164707. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164708. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164709. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164710. * Note that an application can write additional header markers after
  164711. * jpeg_start_compress returns.
  164712. */
  164713. METHODDEF(void)
  164714. write_file_header (j_compress_ptr cinfo)
  164715. {
  164716. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164717. emit_marker(cinfo, M_SOI); /* first the SOI */
  164718. /* SOI is defined to reset restart interval to 0 */
  164719. marker->last_restart_interval = 0;
  164720. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164721. emit_jfif_app0(cinfo);
  164722. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164723. emit_adobe_app14(cinfo);
  164724. }
  164725. /*
  164726. * Write frame header.
  164727. * This consists of DQT and SOFn markers.
  164728. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164729. * This avoids compatibility problems with incorrect implementations that
  164730. * try to error-check the quant table numbers as soon as they see the SOF.
  164731. */
  164732. METHODDEF(void)
  164733. write_frame_header (j_compress_ptr cinfo)
  164734. {
  164735. int ci, prec;
  164736. boolean is_baseline;
  164737. jpeg_component_info *compptr;
  164738. /* Emit DQT for each quantization table.
  164739. * Note that emit_dqt() suppresses any duplicate tables.
  164740. */
  164741. prec = 0;
  164742. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164743. ci++, compptr++) {
  164744. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164745. }
  164746. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164747. /* Check for a non-baseline specification.
  164748. * Note we assume that Huffman table numbers won't be changed later.
  164749. */
  164750. if (cinfo->arith_code || cinfo->progressive_mode ||
  164751. cinfo->data_precision != 8) {
  164752. is_baseline = FALSE;
  164753. } else {
  164754. is_baseline = TRUE;
  164755. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164756. ci++, compptr++) {
  164757. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164758. is_baseline = FALSE;
  164759. }
  164760. if (prec && is_baseline) {
  164761. is_baseline = FALSE;
  164762. /* If it's baseline except for quantizer size, warn the user */
  164763. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164764. }
  164765. }
  164766. /* Emit the proper SOF marker */
  164767. if (cinfo->arith_code) {
  164768. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164769. } else {
  164770. if (cinfo->progressive_mode)
  164771. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164772. else if (is_baseline)
  164773. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164774. else
  164775. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164776. }
  164777. }
  164778. /*
  164779. * Write scan header.
  164780. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164781. * Compressed data will be written following the SOS.
  164782. */
  164783. METHODDEF(void)
  164784. write_scan_header (j_compress_ptr cinfo)
  164785. {
  164786. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164787. int i;
  164788. jpeg_component_info *compptr;
  164789. if (cinfo->arith_code) {
  164790. /* Emit arith conditioning info. We may have some duplication
  164791. * if the file has multiple scans, but it's so small it's hardly
  164792. * worth worrying about.
  164793. */
  164794. emit_dac(cinfo);
  164795. } else {
  164796. /* Emit Huffman tables.
  164797. * Note that emit_dht() suppresses any duplicate tables.
  164798. */
  164799. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164800. compptr = cinfo->cur_comp_info[i];
  164801. if (cinfo->progressive_mode) {
  164802. /* Progressive mode: only DC or only AC tables are used in one scan */
  164803. if (cinfo->Ss == 0) {
  164804. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164805. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164806. } else {
  164807. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164808. }
  164809. } else {
  164810. /* Sequential mode: need both DC and AC tables */
  164811. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164812. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164813. }
  164814. }
  164815. }
  164816. /* Emit DRI if required --- note that DRI value could change for each scan.
  164817. * We avoid wasting space with unnecessary DRIs, however.
  164818. */
  164819. if (cinfo->restart_interval != marker->last_restart_interval) {
  164820. emit_dri(cinfo);
  164821. marker->last_restart_interval = cinfo->restart_interval;
  164822. }
  164823. emit_sos(cinfo);
  164824. }
  164825. /*
  164826. * Write datastream trailer.
  164827. */
  164828. METHODDEF(void)
  164829. write_file_trailer (j_compress_ptr cinfo)
  164830. {
  164831. emit_marker(cinfo, M_EOI);
  164832. }
  164833. /*
  164834. * Write an abbreviated table-specification datastream.
  164835. * This consists of SOI, DQT and DHT tables, and EOI.
  164836. * Any table that is defined and not marked sent_table = TRUE will be
  164837. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164838. */
  164839. METHODDEF(void)
  164840. write_tables_only (j_compress_ptr cinfo)
  164841. {
  164842. int i;
  164843. emit_marker(cinfo, M_SOI);
  164844. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164845. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164846. (void) emit_dqt(cinfo, i);
  164847. }
  164848. if (! cinfo->arith_code) {
  164849. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164850. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164851. emit_dht(cinfo, i, FALSE);
  164852. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164853. emit_dht(cinfo, i, TRUE);
  164854. }
  164855. }
  164856. emit_marker(cinfo, M_EOI);
  164857. }
  164858. /*
  164859. * Initialize the marker writer module.
  164860. */
  164861. GLOBAL(void)
  164862. jinit_marker_writer (j_compress_ptr cinfo)
  164863. {
  164864. my_marker_ptr marker;
  164865. /* Create the subobject */
  164866. marker = (my_marker_ptr)
  164867. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164868. SIZEOF(my_marker_writer));
  164869. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164870. /* Initialize method pointers */
  164871. marker->pub.write_file_header = write_file_header;
  164872. marker->pub.write_frame_header = write_frame_header;
  164873. marker->pub.write_scan_header = write_scan_header;
  164874. marker->pub.write_file_trailer = write_file_trailer;
  164875. marker->pub.write_tables_only = write_tables_only;
  164876. marker->pub.write_marker_header = write_marker_header;
  164877. marker->pub.write_marker_byte = write_marker_byte;
  164878. /* Initialize private state */
  164879. marker->last_restart_interval = 0;
  164880. }
  164881. /*** End of inlined file: jcmarker.c ***/
  164882. /*** Start of inlined file: jcmaster.c ***/
  164883. #define JPEG_INTERNALS
  164884. /* Private state */
  164885. typedef enum {
  164886. main_pass, /* input data, also do first output step */
  164887. huff_opt_pass, /* Huffman code optimization pass */
  164888. output_pass /* data output pass */
  164889. } c_pass_type;
  164890. typedef struct {
  164891. struct jpeg_comp_master pub; /* public fields */
  164892. c_pass_type pass_type; /* the type of the current pass */
  164893. int pass_number; /* # of passes completed */
  164894. int total_passes; /* total # of passes needed */
  164895. int scan_number; /* current index in scan_info[] */
  164896. } my_comp_master;
  164897. typedef my_comp_master * my_master_ptr;
  164898. /*
  164899. * Support routines that do various essential calculations.
  164900. */
  164901. LOCAL(void)
  164902. initial_setup (j_compress_ptr cinfo)
  164903. /* Do computations that are needed before master selection phase */
  164904. {
  164905. int ci;
  164906. jpeg_component_info *compptr;
  164907. long samplesperrow;
  164908. JDIMENSION jd_samplesperrow;
  164909. /* Sanity check on image dimensions */
  164910. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164911. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164912. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164913. /* Make sure image isn't bigger than I can handle */
  164914. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164915. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164916. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164917. /* Width of an input scanline must be representable as JDIMENSION. */
  164918. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164919. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164920. if ((long) jd_samplesperrow != samplesperrow)
  164921. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164922. /* For now, precision must match compiled-in value... */
  164923. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164924. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164925. /* Check that number of components won't exceed internal array sizes */
  164926. if (cinfo->num_components > MAX_COMPONENTS)
  164927. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164928. MAX_COMPONENTS);
  164929. /* Compute maximum sampling factors; check factor validity */
  164930. cinfo->max_h_samp_factor = 1;
  164931. cinfo->max_v_samp_factor = 1;
  164932. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164933. ci++, compptr++) {
  164934. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164935. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164936. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164937. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164938. compptr->h_samp_factor);
  164939. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164940. compptr->v_samp_factor);
  164941. }
  164942. /* Compute dimensions of components */
  164943. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164944. ci++, compptr++) {
  164945. /* Fill in the correct component_index value; don't rely on application */
  164946. compptr->component_index = ci;
  164947. /* For compression, we never do DCT scaling. */
  164948. compptr->DCT_scaled_size = DCTSIZE;
  164949. /* Size in DCT blocks */
  164950. compptr->width_in_blocks = (JDIMENSION)
  164951. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164952. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164953. compptr->height_in_blocks = (JDIMENSION)
  164954. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164955. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164956. /* Size in samples */
  164957. compptr->downsampled_width = (JDIMENSION)
  164958. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164959. (long) cinfo->max_h_samp_factor);
  164960. compptr->downsampled_height = (JDIMENSION)
  164961. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164962. (long) cinfo->max_v_samp_factor);
  164963. /* Mark component needed (this flag isn't actually used for compression) */
  164964. compptr->component_needed = TRUE;
  164965. }
  164966. /* Compute number of fully interleaved MCU rows (number of times that
  164967. * main controller will call coefficient controller).
  164968. */
  164969. cinfo->total_iMCU_rows = (JDIMENSION)
  164970. jdiv_round_up((long) cinfo->image_height,
  164971. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164972. }
  164973. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164974. LOCAL(void)
  164975. validate_script (j_compress_ptr cinfo)
  164976. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164977. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164978. */
  164979. {
  164980. const jpeg_scan_info * scanptr;
  164981. int scanno, ncomps, ci, coefi, thisi;
  164982. int Ss, Se, Ah, Al;
  164983. boolean component_sent[MAX_COMPONENTS];
  164984. #ifdef C_PROGRESSIVE_SUPPORTED
  164985. int * last_bitpos_ptr;
  164986. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164987. /* -1 until that coefficient has been seen; then last Al for it */
  164988. #endif
  164989. if (cinfo->num_scans <= 0)
  164990. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164991. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164992. * for progressive JPEG, no scan can have this.
  164993. */
  164994. scanptr = cinfo->scan_info;
  164995. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164996. #ifdef C_PROGRESSIVE_SUPPORTED
  164997. cinfo->progressive_mode = TRUE;
  164998. last_bitpos_ptr = & last_bitpos[0][0];
  164999. for (ci = 0; ci < cinfo->num_components; ci++)
  165000. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  165001. *last_bitpos_ptr++ = -1;
  165002. #else
  165003. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165004. #endif
  165005. } else {
  165006. cinfo->progressive_mode = FALSE;
  165007. for (ci = 0; ci < cinfo->num_components; ci++)
  165008. component_sent[ci] = FALSE;
  165009. }
  165010. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  165011. /* Validate component indexes */
  165012. ncomps = scanptr->comps_in_scan;
  165013. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  165014. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  165015. for (ci = 0; ci < ncomps; ci++) {
  165016. thisi = scanptr->component_index[ci];
  165017. if (thisi < 0 || thisi >= cinfo->num_components)
  165018. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165019. /* Components must appear in SOF order within each scan */
  165020. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  165021. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165022. }
  165023. /* Validate progression parameters */
  165024. Ss = scanptr->Ss;
  165025. Se = scanptr->Se;
  165026. Ah = scanptr->Ah;
  165027. Al = scanptr->Al;
  165028. if (cinfo->progressive_mode) {
  165029. #ifdef C_PROGRESSIVE_SUPPORTED
  165030. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  165031. * seems wrong: the upper bound ought to depend on data precision.
  165032. * Perhaps they really meant 0..N+1 for N-bit precision.
  165033. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  165034. * out-of-range reconstructed DC values during the first DC scan,
  165035. * which might cause problems for some decoders.
  165036. */
  165037. #if BITS_IN_JSAMPLE == 8
  165038. #define MAX_AH_AL 10
  165039. #else
  165040. #define MAX_AH_AL 13
  165041. #endif
  165042. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  165043. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  165044. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165045. if (Ss == 0) {
  165046. if (Se != 0) /* DC and AC together not OK */
  165047. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165048. } else {
  165049. if (ncomps != 1) /* AC scans must be for only one component */
  165050. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165051. }
  165052. for (ci = 0; ci < ncomps; ci++) {
  165053. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  165054. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  165055. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165056. for (coefi = Ss; coefi <= Se; coefi++) {
  165057. if (last_bitpos_ptr[coefi] < 0) {
  165058. /* first scan of this coefficient */
  165059. if (Ah != 0)
  165060. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165061. } else {
  165062. /* not first scan */
  165063. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  165064. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165065. }
  165066. last_bitpos_ptr[coefi] = Al;
  165067. }
  165068. }
  165069. #endif
  165070. } else {
  165071. /* For sequential JPEG, all progression parameters must be these: */
  165072. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  165073. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165074. /* Make sure components are not sent twice */
  165075. for (ci = 0; ci < ncomps; ci++) {
  165076. thisi = scanptr->component_index[ci];
  165077. if (component_sent[thisi])
  165078. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165079. component_sent[thisi] = TRUE;
  165080. }
  165081. }
  165082. }
  165083. /* Now verify that everything got sent. */
  165084. if (cinfo->progressive_mode) {
  165085. #ifdef C_PROGRESSIVE_SUPPORTED
  165086. /* For progressive mode, we only check that at least some DC data
  165087. * got sent for each component; the spec does not require that all bits
  165088. * of all coefficients be transmitted. Would it be wiser to enforce
  165089. * transmission of all coefficient bits??
  165090. */
  165091. for (ci = 0; ci < cinfo->num_components; ci++) {
  165092. if (last_bitpos[ci][0] < 0)
  165093. ERREXIT(cinfo, JERR_MISSING_DATA);
  165094. }
  165095. #endif
  165096. } else {
  165097. for (ci = 0; ci < cinfo->num_components; ci++) {
  165098. if (! component_sent[ci])
  165099. ERREXIT(cinfo, JERR_MISSING_DATA);
  165100. }
  165101. }
  165102. }
  165103. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  165104. LOCAL(void)
  165105. select_scan_parameters (j_compress_ptr cinfo)
  165106. /* Set up the scan parameters for the current scan */
  165107. {
  165108. int ci;
  165109. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165110. if (cinfo->scan_info != NULL) {
  165111. /* Prepare for current scan --- the script is already validated */
  165112. my_master_ptr master = (my_master_ptr) cinfo->master;
  165113. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  165114. cinfo->comps_in_scan = scanptr->comps_in_scan;
  165115. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165116. cinfo->cur_comp_info[ci] =
  165117. &cinfo->comp_info[scanptr->component_index[ci]];
  165118. }
  165119. cinfo->Ss = scanptr->Ss;
  165120. cinfo->Se = scanptr->Se;
  165121. cinfo->Ah = scanptr->Ah;
  165122. cinfo->Al = scanptr->Al;
  165123. }
  165124. else
  165125. #endif
  165126. {
  165127. /* Prepare for single sequential-JPEG scan containing all components */
  165128. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165129. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165130. MAX_COMPS_IN_SCAN);
  165131. cinfo->comps_in_scan = cinfo->num_components;
  165132. for (ci = 0; ci < cinfo->num_components; ci++) {
  165133. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165134. }
  165135. cinfo->Ss = 0;
  165136. cinfo->Se = DCTSIZE2-1;
  165137. cinfo->Ah = 0;
  165138. cinfo->Al = 0;
  165139. }
  165140. }
  165141. LOCAL(void)
  165142. per_scan_setup (j_compress_ptr cinfo)
  165143. /* Do computations that are needed before processing a JPEG scan */
  165144. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165145. {
  165146. int ci, mcublks, tmp;
  165147. jpeg_component_info *compptr;
  165148. if (cinfo->comps_in_scan == 1) {
  165149. /* Noninterleaved (single-component) scan */
  165150. compptr = cinfo->cur_comp_info[0];
  165151. /* Overall image size in MCUs */
  165152. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165153. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165154. /* For noninterleaved scan, always one block per MCU */
  165155. compptr->MCU_width = 1;
  165156. compptr->MCU_height = 1;
  165157. compptr->MCU_blocks = 1;
  165158. compptr->MCU_sample_width = DCTSIZE;
  165159. compptr->last_col_width = 1;
  165160. /* For noninterleaved scans, it is convenient to define last_row_height
  165161. * as the number of block rows present in the last iMCU row.
  165162. */
  165163. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165164. if (tmp == 0) tmp = compptr->v_samp_factor;
  165165. compptr->last_row_height = tmp;
  165166. /* Prepare array describing MCU composition */
  165167. cinfo->blocks_in_MCU = 1;
  165168. cinfo->MCU_membership[0] = 0;
  165169. } else {
  165170. /* Interleaved (multi-component) scan */
  165171. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165172. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165173. MAX_COMPS_IN_SCAN);
  165174. /* Overall image size in MCUs */
  165175. cinfo->MCUs_per_row = (JDIMENSION)
  165176. jdiv_round_up((long) cinfo->image_width,
  165177. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165178. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165179. jdiv_round_up((long) cinfo->image_height,
  165180. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165181. cinfo->blocks_in_MCU = 0;
  165182. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165183. compptr = cinfo->cur_comp_info[ci];
  165184. /* Sampling factors give # of blocks of component in each MCU */
  165185. compptr->MCU_width = compptr->h_samp_factor;
  165186. compptr->MCU_height = compptr->v_samp_factor;
  165187. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165188. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165189. /* Figure number of non-dummy blocks in last MCU column & row */
  165190. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165191. if (tmp == 0) tmp = compptr->MCU_width;
  165192. compptr->last_col_width = tmp;
  165193. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165194. if (tmp == 0) tmp = compptr->MCU_height;
  165195. compptr->last_row_height = tmp;
  165196. /* Prepare array describing MCU composition */
  165197. mcublks = compptr->MCU_blocks;
  165198. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165199. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165200. while (mcublks-- > 0) {
  165201. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165202. }
  165203. }
  165204. }
  165205. /* Convert restart specified in rows to actual MCU count. */
  165206. /* Note that count must fit in 16 bits, so we provide limiting. */
  165207. if (cinfo->restart_in_rows > 0) {
  165208. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165209. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165210. }
  165211. }
  165212. /*
  165213. * Per-pass setup.
  165214. * This is called at the beginning of each pass. We determine which modules
  165215. * will be active during this pass and give them appropriate start_pass calls.
  165216. * We also set is_last_pass to indicate whether any more passes will be
  165217. * required.
  165218. */
  165219. METHODDEF(void)
  165220. prepare_for_pass (j_compress_ptr cinfo)
  165221. {
  165222. my_master_ptr master = (my_master_ptr) cinfo->master;
  165223. switch (master->pass_type) {
  165224. case main_pass:
  165225. /* Initial pass: will collect input data, and do either Huffman
  165226. * optimization or data output for the first scan.
  165227. */
  165228. select_scan_parameters(cinfo);
  165229. per_scan_setup(cinfo);
  165230. if (! cinfo->raw_data_in) {
  165231. (*cinfo->cconvert->start_pass) (cinfo);
  165232. (*cinfo->downsample->start_pass) (cinfo);
  165233. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165234. }
  165235. (*cinfo->fdct->start_pass) (cinfo);
  165236. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165237. (*cinfo->coef->start_pass) (cinfo,
  165238. (master->total_passes > 1 ?
  165239. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165240. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165241. if (cinfo->optimize_coding) {
  165242. /* No immediate data output; postpone writing frame/scan headers */
  165243. master->pub.call_pass_startup = FALSE;
  165244. } else {
  165245. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165246. master->pub.call_pass_startup = TRUE;
  165247. }
  165248. break;
  165249. #ifdef ENTROPY_OPT_SUPPORTED
  165250. case huff_opt_pass:
  165251. /* Do Huffman optimization for a scan after the first one. */
  165252. select_scan_parameters(cinfo);
  165253. per_scan_setup(cinfo);
  165254. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165255. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165256. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165257. master->pub.call_pass_startup = FALSE;
  165258. break;
  165259. }
  165260. /* Special case: Huffman DC refinement scans need no Huffman table
  165261. * and therefore we can skip the optimization pass for them.
  165262. */
  165263. master->pass_type = output_pass;
  165264. master->pass_number++;
  165265. /*FALLTHROUGH*/
  165266. #endif
  165267. case output_pass:
  165268. /* Do a data-output pass. */
  165269. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165270. if (! cinfo->optimize_coding) {
  165271. select_scan_parameters(cinfo);
  165272. per_scan_setup(cinfo);
  165273. }
  165274. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165275. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165276. /* We emit frame/scan headers now */
  165277. if (master->scan_number == 0)
  165278. (*cinfo->marker->write_frame_header) (cinfo);
  165279. (*cinfo->marker->write_scan_header) (cinfo);
  165280. master->pub.call_pass_startup = FALSE;
  165281. break;
  165282. default:
  165283. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165284. }
  165285. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165286. /* Set up progress monitor's pass info if present */
  165287. if (cinfo->progress != NULL) {
  165288. cinfo->progress->completed_passes = master->pass_number;
  165289. cinfo->progress->total_passes = master->total_passes;
  165290. }
  165291. }
  165292. /*
  165293. * Special start-of-pass hook.
  165294. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165295. * In single-pass processing, we need this hook because we don't want to
  165296. * write frame/scan headers during jpeg_start_compress; we want to let the
  165297. * application write COM markers etc. between jpeg_start_compress and the
  165298. * jpeg_write_scanlines loop.
  165299. * In multi-pass processing, this routine is not used.
  165300. */
  165301. METHODDEF(void)
  165302. pass_startup (j_compress_ptr cinfo)
  165303. {
  165304. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165305. (*cinfo->marker->write_frame_header) (cinfo);
  165306. (*cinfo->marker->write_scan_header) (cinfo);
  165307. }
  165308. /*
  165309. * Finish up at end of pass.
  165310. */
  165311. METHODDEF(void)
  165312. finish_pass_master (j_compress_ptr cinfo)
  165313. {
  165314. my_master_ptr master = (my_master_ptr) cinfo->master;
  165315. /* The entropy coder always needs an end-of-pass call,
  165316. * either to analyze statistics or to flush its output buffer.
  165317. */
  165318. (*cinfo->entropy->finish_pass) (cinfo);
  165319. /* Update state for next pass */
  165320. switch (master->pass_type) {
  165321. case main_pass:
  165322. /* next pass is either output of scan 0 (after optimization)
  165323. * or output of scan 1 (if no optimization).
  165324. */
  165325. master->pass_type = output_pass;
  165326. if (! cinfo->optimize_coding)
  165327. master->scan_number++;
  165328. break;
  165329. case huff_opt_pass:
  165330. /* next pass is always output of current scan */
  165331. master->pass_type = output_pass;
  165332. break;
  165333. case output_pass:
  165334. /* next pass is either optimization or output of next scan */
  165335. if (cinfo->optimize_coding)
  165336. master->pass_type = huff_opt_pass;
  165337. master->scan_number++;
  165338. break;
  165339. }
  165340. master->pass_number++;
  165341. }
  165342. /*
  165343. * Initialize master compression control.
  165344. */
  165345. GLOBAL(void)
  165346. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165347. {
  165348. my_master_ptr master;
  165349. master = (my_master_ptr)
  165350. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165351. SIZEOF(my_comp_master));
  165352. cinfo->master = (struct jpeg_comp_master *) master;
  165353. master->pub.prepare_for_pass = prepare_for_pass;
  165354. master->pub.pass_startup = pass_startup;
  165355. master->pub.finish_pass = finish_pass_master;
  165356. master->pub.is_last_pass = FALSE;
  165357. /* Validate parameters, determine derived values */
  165358. initial_setup(cinfo);
  165359. if (cinfo->scan_info != NULL) {
  165360. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165361. validate_script(cinfo);
  165362. #else
  165363. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165364. #endif
  165365. } else {
  165366. cinfo->progressive_mode = FALSE;
  165367. cinfo->num_scans = 1;
  165368. }
  165369. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165370. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165371. /* Initialize my private state */
  165372. if (transcode_only) {
  165373. /* no main pass in transcoding */
  165374. if (cinfo->optimize_coding)
  165375. master->pass_type = huff_opt_pass;
  165376. else
  165377. master->pass_type = output_pass;
  165378. } else {
  165379. /* for normal compression, first pass is always this type: */
  165380. master->pass_type = main_pass;
  165381. }
  165382. master->scan_number = 0;
  165383. master->pass_number = 0;
  165384. if (cinfo->optimize_coding)
  165385. master->total_passes = cinfo->num_scans * 2;
  165386. else
  165387. master->total_passes = cinfo->num_scans;
  165388. }
  165389. /*** End of inlined file: jcmaster.c ***/
  165390. /*** Start of inlined file: jcomapi.c ***/
  165391. #define JPEG_INTERNALS
  165392. /*
  165393. * Abort processing of a JPEG compression or decompression operation,
  165394. * but don't destroy the object itself.
  165395. *
  165396. * For this, we merely clean up all the nonpermanent memory pools.
  165397. * Note that temp files (virtual arrays) are not allowed to belong to
  165398. * the permanent pool, so we will be able to close all temp files here.
  165399. * Closing a data source or destination, if necessary, is the application's
  165400. * responsibility.
  165401. */
  165402. GLOBAL(void)
  165403. jpeg_abort (j_common_ptr cinfo)
  165404. {
  165405. int pool;
  165406. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165407. if (cinfo->mem == NULL)
  165408. return;
  165409. /* Releasing pools in reverse order might help avoid fragmentation
  165410. * with some (brain-damaged) malloc libraries.
  165411. */
  165412. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165413. (*cinfo->mem->free_pool) (cinfo, pool);
  165414. }
  165415. /* Reset overall state for possible reuse of object */
  165416. if (cinfo->is_decompressor) {
  165417. cinfo->global_state = DSTATE_START;
  165418. /* Try to keep application from accessing now-deleted marker list.
  165419. * A bit kludgy to do it here, but this is the most central place.
  165420. */
  165421. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165422. } else {
  165423. cinfo->global_state = CSTATE_START;
  165424. }
  165425. }
  165426. /*
  165427. * Destruction of a JPEG object.
  165428. *
  165429. * Everything gets deallocated except the master jpeg_compress_struct itself
  165430. * and the error manager struct. Both of these are supplied by the application
  165431. * and must be freed, if necessary, by the application. (Often they are on
  165432. * the stack and so don't need to be freed anyway.)
  165433. * Closing a data source or destination, if necessary, is the application's
  165434. * responsibility.
  165435. */
  165436. GLOBAL(void)
  165437. jpeg_destroy (j_common_ptr cinfo)
  165438. {
  165439. /* We need only tell the memory manager to release everything. */
  165440. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165441. if (cinfo->mem != NULL)
  165442. (*cinfo->mem->self_destruct) (cinfo);
  165443. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165444. cinfo->global_state = 0; /* mark it destroyed */
  165445. }
  165446. /*
  165447. * Convenience routines for allocating quantization and Huffman tables.
  165448. * (Would jutils.c be a more reasonable place to put these?)
  165449. */
  165450. GLOBAL(JQUANT_TBL *)
  165451. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165452. {
  165453. JQUANT_TBL *tbl;
  165454. tbl = (JQUANT_TBL *)
  165455. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165456. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165457. return tbl;
  165458. }
  165459. GLOBAL(JHUFF_TBL *)
  165460. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165461. {
  165462. JHUFF_TBL *tbl;
  165463. tbl = (JHUFF_TBL *)
  165464. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165465. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165466. return tbl;
  165467. }
  165468. /*** End of inlined file: jcomapi.c ***/
  165469. /*** Start of inlined file: jcparam.c ***/
  165470. #define JPEG_INTERNALS
  165471. /*
  165472. * Quantization table setup routines
  165473. */
  165474. GLOBAL(void)
  165475. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165476. const unsigned int *basic_table,
  165477. int scale_factor, boolean force_baseline)
  165478. /* Define a quantization table equal to the basic_table times
  165479. * a scale factor (given as a percentage).
  165480. * If force_baseline is TRUE, the computed quantization table entries
  165481. * are limited to 1..255 for JPEG baseline compatibility.
  165482. */
  165483. {
  165484. JQUANT_TBL ** qtblptr;
  165485. int i;
  165486. long temp;
  165487. /* Safety check to ensure start_compress not called yet. */
  165488. if (cinfo->global_state != CSTATE_START)
  165489. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165490. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165491. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165492. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165493. if (*qtblptr == NULL)
  165494. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165495. for (i = 0; i < DCTSIZE2; i++) {
  165496. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165497. /* limit the values to the valid range */
  165498. if (temp <= 0L) temp = 1L;
  165499. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165500. if (force_baseline && temp > 255L)
  165501. temp = 255L; /* limit to baseline range if requested */
  165502. (*qtblptr)->quantval[i] = (UINT16) temp;
  165503. }
  165504. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165505. (*qtblptr)->sent_table = FALSE;
  165506. }
  165507. GLOBAL(void)
  165508. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165509. boolean force_baseline)
  165510. /* Set or change the 'quality' (quantization) setting, using default tables
  165511. * and a straight percentage-scaling quality scale. In most cases it's better
  165512. * to use jpeg_set_quality (below); this entry point is provided for
  165513. * applications that insist on a linear percentage scaling.
  165514. */
  165515. {
  165516. /* These are the sample quantization tables given in JPEG spec section K.1.
  165517. * The spec says that the values given produce "good" quality, and
  165518. * when divided by 2, "very good" quality.
  165519. */
  165520. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165521. 16, 11, 10, 16, 24, 40, 51, 61,
  165522. 12, 12, 14, 19, 26, 58, 60, 55,
  165523. 14, 13, 16, 24, 40, 57, 69, 56,
  165524. 14, 17, 22, 29, 51, 87, 80, 62,
  165525. 18, 22, 37, 56, 68, 109, 103, 77,
  165526. 24, 35, 55, 64, 81, 104, 113, 92,
  165527. 49, 64, 78, 87, 103, 121, 120, 101,
  165528. 72, 92, 95, 98, 112, 100, 103, 99
  165529. };
  165530. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165531. 17, 18, 24, 47, 99, 99, 99, 99,
  165532. 18, 21, 26, 66, 99, 99, 99, 99,
  165533. 24, 26, 56, 99, 99, 99, 99, 99,
  165534. 47, 66, 99, 99, 99, 99, 99, 99,
  165535. 99, 99, 99, 99, 99, 99, 99, 99,
  165536. 99, 99, 99, 99, 99, 99, 99, 99,
  165537. 99, 99, 99, 99, 99, 99, 99, 99,
  165538. 99, 99, 99, 99, 99, 99, 99, 99
  165539. };
  165540. /* Set up two quantization tables using the specified scaling */
  165541. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165542. scale_factor, force_baseline);
  165543. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165544. scale_factor, force_baseline);
  165545. }
  165546. GLOBAL(int)
  165547. jpeg_quality_scaling (int quality)
  165548. /* Convert a user-specified quality rating to a percentage scaling factor
  165549. * for an underlying quantization table, using our recommended scaling curve.
  165550. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165551. */
  165552. {
  165553. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165554. if (quality <= 0) quality = 1;
  165555. if (quality > 100) quality = 100;
  165556. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165557. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165558. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165559. * to make all the table entries 1 (hence, minimum quantization loss).
  165560. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165561. */
  165562. if (quality < 50)
  165563. quality = 5000 / quality;
  165564. else
  165565. quality = 200 - quality*2;
  165566. return quality;
  165567. }
  165568. GLOBAL(void)
  165569. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165570. /* Set or change the 'quality' (quantization) setting, using default tables.
  165571. * This is the standard quality-adjusting entry point for typical user
  165572. * interfaces; only those who want detailed control over quantization tables
  165573. * would use the preceding three routines directly.
  165574. */
  165575. {
  165576. /* Convert user 0-100 rating to percentage scaling */
  165577. quality = jpeg_quality_scaling(quality);
  165578. /* Set up standard quality tables */
  165579. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165580. }
  165581. /*
  165582. * Huffman table setup routines
  165583. */
  165584. LOCAL(void)
  165585. add_huff_table (j_compress_ptr cinfo,
  165586. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165587. /* Define a Huffman table */
  165588. {
  165589. int nsymbols, len;
  165590. if (*htblptr == NULL)
  165591. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165592. /* Copy the number-of-symbols-of-each-code-length counts */
  165593. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165594. /* Validate the counts. We do this here mainly so we can copy the right
  165595. * number of symbols from the val[] array, without risking marching off
  165596. * the end of memory. jchuff.c will do a more thorough test later.
  165597. */
  165598. nsymbols = 0;
  165599. for (len = 1; len <= 16; len++)
  165600. nsymbols += bits[len];
  165601. if (nsymbols < 1 || nsymbols > 256)
  165602. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165603. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165604. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165605. (*htblptr)->sent_table = FALSE;
  165606. }
  165607. LOCAL(void)
  165608. std_huff_tables (j_compress_ptr cinfo)
  165609. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165610. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165611. {
  165612. static const UINT8 bits_dc_luminance[17] =
  165613. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165614. static const UINT8 val_dc_luminance[] =
  165615. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165616. static const UINT8 bits_dc_chrominance[17] =
  165617. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165618. static const UINT8 val_dc_chrominance[] =
  165619. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165620. static const UINT8 bits_ac_luminance[17] =
  165621. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165622. static const UINT8 val_ac_luminance[] =
  165623. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165624. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165625. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165626. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165627. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165628. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165629. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165630. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165631. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165632. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165633. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165634. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165635. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165636. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165637. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165638. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165639. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165640. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165641. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165642. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165643. 0xf9, 0xfa };
  165644. static const UINT8 bits_ac_chrominance[17] =
  165645. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165646. static const UINT8 val_ac_chrominance[] =
  165647. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165648. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165649. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165650. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165651. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165652. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165653. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165654. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165655. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165656. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165657. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165658. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165659. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165660. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165661. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165662. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165663. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165664. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165665. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165666. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165667. 0xf9, 0xfa };
  165668. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165669. bits_dc_luminance, val_dc_luminance);
  165670. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165671. bits_ac_luminance, val_ac_luminance);
  165672. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165673. bits_dc_chrominance, val_dc_chrominance);
  165674. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165675. bits_ac_chrominance, val_ac_chrominance);
  165676. }
  165677. /*
  165678. * Default parameter setup for compression.
  165679. *
  165680. * Applications that don't choose to use this routine must do their
  165681. * own setup of all these parameters. Alternately, you can call this
  165682. * to establish defaults and then alter parameters selectively. This
  165683. * is the recommended approach since, if we add any new parameters,
  165684. * your code will still work (they'll be set to reasonable defaults).
  165685. */
  165686. GLOBAL(void)
  165687. jpeg_set_defaults (j_compress_ptr cinfo)
  165688. {
  165689. int i;
  165690. /* Safety check to ensure start_compress not called yet. */
  165691. if (cinfo->global_state != CSTATE_START)
  165692. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165693. /* Allocate comp_info array large enough for maximum component count.
  165694. * Array is made permanent in case application wants to compress
  165695. * multiple images at same param settings.
  165696. */
  165697. if (cinfo->comp_info == NULL)
  165698. cinfo->comp_info = (jpeg_component_info *)
  165699. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165700. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165701. /* Initialize everything not dependent on the color space */
  165702. cinfo->data_precision = BITS_IN_JSAMPLE;
  165703. /* Set up two quantization tables using default quality of 75 */
  165704. jpeg_set_quality(cinfo, 75, TRUE);
  165705. /* Set up two Huffman tables */
  165706. std_huff_tables(cinfo);
  165707. /* Initialize default arithmetic coding conditioning */
  165708. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165709. cinfo->arith_dc_L[i] = 0;
  165710. cinfo->arith_dc_U[i] = 1;
  165711. cinfo->arith_ac_K[i] = 5;
  165712. }
  165713. /* Default is no multiple-scan output */
  165714. cinfo->scan_info = NULL;
  165715. cinfo->num_scans = 0;
  165716. /* Expect normal source image, not raw downsampled data */
  165717. cinfo->raw_data_in = FALSE;
  165718. /* Use Huffman coding, not arithmetic coding, by default */
  165719. cinfo->arith_code = FALSE;
  165720. /* By default, don't do extra passes to optimize entropy coding */
  165721. cinfo->optimize_coding = FALSE;
  165722. /* The standard Huffman tables are only valid for 8-bit data precision.
  165723. * If the precision is higher, force optimization on so that usable
  165724. * tables will be computed. This test can be removed if default tables
  165725. * are supplied that are valid for the desired precision.
  165726. */
  165727. if (cinfo->data_precision > 8)
  165728. cinfo->optimize_coding = TRUE;
  165729. /* By default, use the simpler non-cosited sampling alignment */
  165730. cinfo->CCIR601_sampling = FALSE;
  165731. /* No input smoothing */
  165732. cinfo->smoothing_factor = 0;
  165733. /* DCT algorithm preference */
  165734. cinfo->dct_method = JDCT_DEFAULT;
  165735. /* No restart markers */
  165736. cinfo->restart_interval = 0;
  165737. cinfo->restart_in_rows = 0;
  165738. /* Fill in default JFIF marker parameters. Note that whether the marker
  165739. * will actually be written is determined by jpeg_set_colorspace.
  165740. *
  165741. * By default, the library emits JFIF version code 1.01.
  165742. * An application that wants to emit JFIF 1.02 extension markers should set
  165743. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165744. * to 1.02, but there may still be some decoders in use that will complain
  165745. * about that; saying 1.01 should minimize compatibility problems.
  165746. */
  165747. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165748. cinfo->JFIF_minor_version = 1;
  165749. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165750. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165751. cinfo->Y_density = 1;
  165752. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165753. jpeg_default_colorspace(cinfo);
  165754. }
  165755. /*
  165756. * Select an appropriate JPEG colorspace for in_color_space.
  165757. */
  165758. GLOBAL(void)
  165759. jpeg_default_colorspace (j_compress_ptr cinfo)
  165760. {
  165761. switch (cinfo->in_color_space) {
  165762. case JCS_GRAYSCALE:
  165763. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165764. break;
  165765. case JCS_RGB:
  165766. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165767. break;
  165768. case JCS_YCbCr:
  165769. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165770. break;
  165771. case JCS_CMYK:
  165772. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165773. break;
  165774. case JCS_YCCK:
  165775. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165776. break;
  165777. case JCS_UNKNOWN:
  165778. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165779. break;
  165780. default:
  165781. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165782. }
  165783. }
  165784. /*
  165785. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165786. */
  165787. GLOBAL(void)
  165788. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165789. {
  165790. jpeg_component_info * compptr;
  165791. int ci;
  165792. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165793. (compptr = &cinfo->comp_info[index], \
  165794. compptr->component_id = (id), \
  165795. compptr->h_samp_factor = (hsamp), \
  165796. compptr->v_samp_factor = (vsamp), \
  165797. compptr->quant_tbl_no = (quant), \
  165798. compptr->dc_tbl_no = (dctbl), \
  165799. compptr->ac_tbl_no = (actbl) )
  165800. /* Safety check to ensure start_compress not called yet. */
  165801. if (cinfo->global_state != CSTATE_START)
  165802. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165803. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165804. * tables 1 for chrominance components.
  165805. */
  165806. cinfo->jpeg_color_space = colorspace;
  165807. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165808. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165809. switch (colorspace) {
  165810. case JCS_GRAYSCALE:
  165811. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165812. cinfo->num_components = 1;
  165813. /* JFIF specifies component ID 1 */
  165814. SET_COMP(0, 1, 1,1, 0, 0,0);
  165815. break;
  165816. case JCS_RGB:
  165817. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165818. cinfo->num_components = 3;
  165819. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165820. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165821. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165822. break;
  165823. case JCS_YCbCr:
  165824. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165825. cinfo->num_components = 3;
  165826. /* JFIF specifies component IDs 1,2,3 */
  165827. /* We default to 2x2 subsamples of chrominance */
  165828. SET_COMP(0, 1, 2,2, 0, 0,0);
  165829. SET_COMP(1, 2, 1,1, 1, 1,1);
  165830. SET_COMP(2, 3, 1,1, 1, 1,1);
  165831. break;
  165832. case JCS_CMYK:
  165833. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165834. cinfo->num_components = 4;
  165835. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165836. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165837. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165838. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165839. break;
  165840. case JCS_YCCK:
  165841. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165842. cinfo->num_components = 4;
  165843. SET_COMP(0, 1, 2,2, 0, 0,0);
  165844. SET_COMP(1, 2, 1,1, 1, 1,1);
  165845. SET_COMP(2, 3, 1,1, 1, 1,1);
  165846. SET_COMP(3, 4, 2,2, 0, 0,0);
  165847. break;
  165848. case JCS_UNKNOWN:
  165849. cinfo->num_components = cinfo->input_components;
  165850. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165851. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165852. MAX_COMPONENTS);
  165853. for (ci = 0; ci < cinfo->num_components; ci++) {
  165854. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165855. }
  165856. break;
  165857. default:
  165858. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165859. }
  165860. }
  165861. #ifdef C_PROGRESSIVE_SUPPORTED
  165862. LOCAL(jpeg_scan_info *)
  165863. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165864. int Ss, int Se, int Ah, int Al)
  165865. /* Support routine: generate one scan for specified component */
  165866. {
  165867. scanptr->comps_in_scan = 1;
  165868. scanptr->component_index[0] = ci;
  165869. scanptr->Ss = Ss;
  165870. scanptr->Se = Se;
  165871. scanptr->Ah = Ah;
  165872. scanptr->Al = Al;
  165873. scanptr++;
  165874. return scanptr;
  165875. }
  165876. LOCAL(jpeg_scan_info *)
  165877. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165878. int Ss, int Se, int Ah, int Al)
  165879. /* Support routine: generate one scan for each component */
  165880. {
  165881. int ci;
  165882. for (ci = 0; ci < ncomps; ci++) {
  165883. scanptr->comps_in_scan = 1;
  165884. scanptr->component_index[0] = ci;
  165885. scanptr->Ss = Ss;
  165886. scanptr->Se = Se;
  165887. scanptr->Ah = Ah;
  165888. scanptr->Al = Al;
  165889. scanptr++;
  165890. }
  165891. return scanptr;
  165892. }
  165893. LOCAL(jpeg_scan_info *)
  165894. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165895. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165896. {
  165897. int ci;
  165898. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165899. /* Single interleaved DC scan */
  165900. scanptr->comps_in_scan = ncomps;
  165901. for (ci = 0; ci < ncomps; ci++)
  165902. scanptr->component_index[ci] = ci;
  165903. scanptr->Ss = scanptr->Se = 0;
  165904. scanptr->Ah = Ah;
  165905. scanptr->Al = Al;
  165906. scanptr++;
  165907. } else {
  165908. /* Noninterleaved DC scan for each component */
  165909. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165910. }
  165911. return scanptr;
  165912. }
  165913. /*
  165914. * Create a recommended progressive-JPEG script.
  165915. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165916. */
  165917. GLOBAL(void)
  165918. jpeg_simple_progression (j_compress_ptr cinfo)
  165919. {
  165920. int ncomps = cinfo->num_components;
  165921. int nscans;
  165922. jpeg_scan_info * scanptr;
  165923. /* Safety check to ensure start_compress not called yet. */
  165924. if (cinfo->global_state != CSTATE_START)
  165925. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165926. /* Figure space needed for script. Calculation must match code below! */
  165927. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165928. /* Custom script for YCbCr color images. */
  165929. nscans = 10;
  165930. } else {
  165931. /* All-purpose script for other color spaces. */
  165932. if (ncomps > MAX_COMPS_IN_SCAN)
  165933. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165934. else
  165935. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165936. }
  165937. /* Allocate space for script.
  165938. * We need to put it in the permanent pool in case the application performs
  165939. * multiple compressions without changing the settings. To avoid a memory
  165940. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165941. * object, we try to re-use previously allocated space, and we allocate
  165942. * enough space to handle YCbCr even if initially asked for grayscale.
  165943. */
  165944. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165945. cinfo->script_space_size = MAX(nscans, 10);
  165946. cinfo->script_space = (jpeg_scan_info *)
  165947. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165948. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165949. }
  165950. scanptr = cinfo->script_space;
  165951. cinfo->scan_info = scanptr;
  165952. cinfo->num_scans = nscans;
  165953. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165954. /* Custom script for YCbCr color images. */
  165955. /* Initial DC scan */
  165956. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165957. /* Initial AC scan: get some luma data out in a hurry */
  165958. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165959. /* Chroma data is too small to be worth expending many scans on */
  165960. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165961. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165962. /* Complete spectral selection for luma AC */
  165963. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165964. /* Refine next bit of luma AC */
  165965. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165966. /* Finish DC successive approximation */
  165967. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165968. /* Finish AC successive approximation */
  165969. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165970. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165971. /* Luma bottom bit comes last since it's usually largest scan */
  165972. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165973. } else {
  165974. /* All-purpose script for other color spaces. */
  165975. /* Successive approximation first pass */
  165976. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165977. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165978. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165979. /* Successive approximation second pass */
  165980. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165981. /* Successive approximation final pass */
  165982. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165983. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165984. }
  165985. }
  165986. #endif /* C_PROGRESSIVE_SUPPORTED */
  165987. /*** End of inlined file: jcparam.c ***/
  165988. /*** Start of inlined file: jcphuff.c ***/
  165989. #define JPEG_INTERNALS
  165990. #ifdef C_PROGRESSIVE_SUPPORTED
  165991. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165992. typedef struct {
  165993. struct jpeg_entropy_encoder pub; /* public fields */
  165994. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165995. boolean gather_statistics;
  165996. /* Bit-level coding status.
  165997. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165998. */
  165999. JOCTET * next_output_byte; /* => next byte to write in buffer */
  166000. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  166001. INT32 put_buffer; /* current bit-accumulation buffer */
  166002. int put_bits; /* # of bits now in it */
  166003. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  166004. /* Coding status for DC components */
  166005. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166006. /* Coding status for AC components */
  166007. int ac_tbl_no; /* the table number of the single component */
  166008. unsigned int EOBRUN; /* run length of EOBs */
  166009. unsigned int BE; /* # of buffered correction bits before MCU */
  166010. char * bit_buffer; /* buffer for correction bits (1 per char) */
  166011. /* packing correction bits tightly would save some space but cost time... */
  166012. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166013. int next_restart_num; /* next restart number to write (0-7) */
  166014. /* Pointers to derived tables (these workspaces have image lifespan).
  166015. * Since any one scan codes only DC or only AC, we only need one set
  166016. * of tables, not one for DC and one for AC.
  166017. */
  166018. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166019. /* Statistics tables for optimization; again, one set is enough */
  166020. long * count_ptrs[NUM_HUFF_TBLS];
  166021. } phuff_entropy_encoder;
  166022. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  166023. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  166024. * buffer can hold. Larger sizes may slightly improve compression, but
  166025. * 1000 is already well into the realm of overkill.
  166026. * The minimum safe size is 64 bits.
  166027. */
  166028. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  166029. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  166030. * We assume that int right shift is unsigned if INT32 right shift is,
  166031. * which should be safe.
  166032. */
  166033. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  166034. #define ISHIFT_TEMPS int ishift_temp;
  166035. #define IRIGHT_SHIFT(x,shft) \
  166036. ((ishift_temp = (x)) < 0 ? \
  166037. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  166038. (ishift_temp >> (shft)))
  166039. #else
  166040. #define ISHIFT_TEMPS
  166041. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  166042. #endif
  166043. /* Forward declarations */
  166044. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  166045. JBLOCKROW *MCU_data));
  166046. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  166047. JBLOCKROW *MCU_data));
  166048. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  166049. JBLOCKROW *MCU_data));
  166050. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  166051. JBLOCKROW *MCU_data));
  166052. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  166053. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  166054. /*
  166055. * Initialize for a Huffman-compressed scan using progressive JPEG.
  166056. */
  166057. METHODDEF(void)
  166058. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  166059. {
  166060. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166061. boolean is_DC_band;
  166062. int ci, tbl;
  166063. jpeg_component_info * compptr;
  166064. entropy->cinfo = cinfo;
  166065. entropy->gather_statistics = gather_statistics;
  166066. is_DC_band = (cinfo->Ss == 0);
  166067. /* We assume jcmaster.c already validated the scan parameters. */
  166068. /* Select execution routines */
  166069. if (cinfo->Ah == 0) {
  166070. if (is_DC_band)
  166071. entropy->pub.encode_mcu = encode_mcu_DC_first;
  166072. else
  166073. entropy->pub.encode_mcu = encode_mcu_AC_first;
  166074. } else {
  166075. if (is_DC_band)
  166076. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  166077. else {
  166078. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  166079. /* AC refinement needs a correction bit buffer */
  166080. if (entropy->bit_buffer == NULL)
  166081. entropy->bit_buffer = (char *)
  166082. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166083. MAX_CORR_BITS * SIZEOF(char));
  166084. }
  166085. }
  166086. if (gather_statistics)
  166087. entropy->pub.finish_pass = finish_pass_gather_phuff;
  166088. else
  166089. entropy->pub.finish_pass = finish_pass_phuff;
  166090. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  166091. * for AC coefficients.
  166092. */
  166093. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166094. compptr = cinfo->cur_comp_info[ci];
  166095. /* Initialize DC predictions to 0 */
  166096. entropy->last_dc_val[ci] = 0;
  166097. /* Get table index */
  166098. if (is_DC_band) {
  166099. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166100. continue;
  166101. tbl = compptr->dc_tbl_no;
  166102. } else {
  166103. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  166104. }
  166105. if (gather_statistics) {
  166106. /* Check for invalid table index */
  166107. /* (make_c_derived_tbl does this in the other path) */
  166108. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  166109. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  166110. /* Allocate and zero the statistics tables */
  166111. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  166112. if (entropy->count_ptrs[tbl] == NULL)
  166113. entropy->count_ptrs[tbl] = (long *)
  166114. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166115. 257 * SIZEOF(long));
  166116. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166117. } else {
  166118. /* Compute derived values for Huffman table */
  166119. /* We may do this more than once for a table, but it's not expensive */
  166120. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166121. & entropy->derived_tbls[tbl]);
  166122. }
  166123. }
  166124. /* Initialize AC stuff */
  166125. entropy->EOBRUN = 0;
  166126. entropy->BE = 0;
  166127. /* Initialize bit buffer to empty */
  166128. entropy->put_buffer = 0;
  166129. entropy->put_bits = 0;
  166130. /* Initialize restart stuff */
  166131. entropy->restarts_to_go = cinfo->restart_interval;
  166132. entropy->next_restart_num = 0;
  166133. }
  166134. /* Outputting bytes to the file.
  166135. * NB: these must be called only when actually outputting,
  166136. * that is, entropy->gather_statistics == FALSE.
  166137. */
  166138. /* Emit a byte */
  166139. #define emit_byte(entropy,val) \
  166140. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166141. if (--(entropy)->free_in_buffer == 0) \
  166142. dump_buffer_p(entropy); }
  166143. LOCAL(void)
  166144. dump_buffer_p (phuff_entropy_ptr entropy)
  166145. /* Empty the output buffer; we do not support suspension in this module. */
  166146. {
  166147. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166148. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166149. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166150. /* After a successful buffer dump, must reset buffer pointers */
  166151. entropy->next_output_byte = dest->next_output_byte;
  166152. entropy->free_in_buffer = dest->free_in_buffer;
  166153. }
  166154. /* Outputting bits to the file */
  166155. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166156. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166157. * in one call, and we never retain more than 7 bits in put_buffer
  166158. * between calls, so 24 bits are sufficient.
  166159. */
  166160. INLINE
  166161. LOCAL(void)
  166162. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166163. /* Emit some bits, unless we are in gather mode */
  166164. {
  166165. /* This routine is heavily used, so it's worth coding tightly. */
  166166. register INT32 put_buffer = (INT32) code;
  166167. register int put_bits = entropy->put_bits;
  166168. /* if size is 0, caller used an invalid Huffman table entry */
  166169. if (size == 0)
  166170. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166171. if (entropy->gather_statistics)
  166172. return; /* do nothing if we're only getting stats */
  166173. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166174. put_bits += size; /* new number of bits in buffer */
  166175. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166176. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166177. while (put_bits >= 8) {
  166178. int c = (int) ((put_buffer >> 16) & 0xFF);
  166179. emit_byte(entropy, c);
  166180. if (c == 0xFF) { /* need to stuff a zero byte? */
  166181. emit_byte(entropy, 0);
  166182. }
  166183. put_buffer <<= 8;
  166184. put_bits -= 8;
  166185. }
  166186. entropy->put_buffer = put_buffer; /* update variables */
  166187. entropy->put_bits = put_bits;
  166188. }
  166189. LOCAL(void)
  166190. flush_bits_p (phuff_entropy_ptr entropy)
  166191. {
  166192. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166193. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166194. entropy->put_bits = 0;
  166195. }
  166196. /*
  166197. * Emit (or just count) a Huffman symbol.
  166198. */
  166199. INLINE
  166200. LOCAL(void)
  166201. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166202. {
  166203. if (entropy->gather_statistics)
  166204. entropy->count_ptrs[tbl_no][symbol]++;
  166205. else {
  166206. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166207. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166208. }
  166209. }
  166210. /*
  166211. * Emit bits from a correction bit buffer.
  166212. */
  166213. LOCAL(void)
  166214. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166215. unsigned int nbits)
  166216. {
  166217. if (entropy->gather_statistics)
  166218. return; /* no real work */
  166219. while (nbits > 0) {
  166220. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166221. bufstart++;
  166222. nbits--;
  166223. }
  166224. }
  166225. /*
  166226. * Emit any pending EOBRUN symbol.
  166227. */
  166228. LOCAL(void)
  166229. emit_eobrun (phuff_entropy_ptr entropy)
  166230. {
  166231. register int temp, nbits;
  166232. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166233. temp = entropy->EOBRUN;
  166234. nbits = 0;
  166235. while ((temp >>= 1))
  166236. nbits++;
  166237. /* safety check: shouldn't happen given limited correction-bit buffer */
  166238. if (nbits > 14)
  166239. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166240. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166241. if (nbits)
  166242. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166243. entropy->EOBRUN = 0;
  166244. /* Emit any buffered correction bits */
  166245. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166246. entropy->BE = 0;
  166247. }
  166248. }
  166249. /*
  166250. * Emit a restart marker & resynchronize predictions.
  166251. */
  166252. LOCAL(void)
  166253. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166254. {
  166255. int ci;
  166256. emit_eobrun(entropy);
  166257. if (! entropy->gather_statistics) {
  166258. flush_bits_p(entropy);
  166259. emit_byte(entropy, 0xFF);
  166260. emit_byte(entropy, JPEG_RST0 + restart_num);
  166261. }
  166262. if (entropy->cinfo->Ss == 0) {
  166263. /* Re-initialize DC predictions to 0 */
  166264. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166265. entropy->last_dc_val[ci] = 0;
  166266. } else {
  166267. /* Re-initialize all AC-related fields to 0 */
  166268. entropy->EOBRUN = 0;
  166269. entropy->BE = 0;
  166270. }
  166271. }
  166272. /*
  166273. * MCU encoding for DC initial scan (either spectral selection,
  166274. * or first pass of successive approximation).
  166275. */
  166276. METHODDEF(boolean)
  166277. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166278. {
  166279. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166280. register int temp, temp2;
  166281. register int nbits;
  166282. int blkn, ci;
  166283. int Al = cinfo->Al;
  166284. JBLOCKROW block;
  166285. jpeg_component_info * compptr;
  166286. ISHIFT_TEMPS
  166287. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166288. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166289. /* Emit restart marker if needed */
  166290. if (cinfo->restart_interval)
  166291. if (entropy->restarts_to_go == 0)
  166292. emit_restart_p(entropy, entropy->next_restart_num);
  166293. /* Encode the MCU data blocks */
  166294. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166295. block = MCU_data[blkn];
  166296. ci = cinfo->MCU_membership[blkn];
  166297. compptr = cinfo->cur_comp_info[ci];
  166298. /* Compute the DC value after the required point transform by Al.
  166299. * This is simply an arithmetic right shift.
  166300. */
  166301. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166302. /* DC differences are figured on the point-transformed values. */
  166303. temp = temp2 - entropy->last_dc_val[ci];
  166304. entropy->last_dc_val[ci] = temp2;
  166305. /* Encode the DC coefficient difference per section G.1.2.1 */
  166306. temp2 = temp;
  166307. if (temp < 0) {
  166308. temp = -temp; /* temp is abs value of input */
  166309. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166310. /* This code assumes we are on a two's complement machine */
  166311. temp2--;
  166312. }
  166313. /* Find the number of bits needed for the magnitude of the coefficient */
  166314. nbits = 0;
  166315. while (temp) {
  166316. nbits++;
  166317. temp >>= 1;
  166318. }
  166319. /* Check for out-of-range coefficient values.
  166320. * Since we're encoding a difference, the range limit is twice as much.
  166321. */
  166322. if (nbits > MAX_COEF_BITS+1)
  166323. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166324. /* Count/emit the Huffman-coded symbol for the number of bits */
  166325. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166326. /* Emit that number of bits of the value, if positive, */
  166327. /* or the complement of its magnitude, if negative. */
  166328. if (nbits) /* emit_bits rejects calls with size 0 */
  166329. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166330. }
  166331. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166332. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166333. /* Update restart-interval state too */
  166334. if (cinfo->restart_interval) {
  166335. if (entropy->restarts_to_go == 0) {
  166336. entropy->restarts_to_go = cinfo->restart_interval;
  166337. entropy->next_restart_num++;
  166338. entropy->next_restart_num &= 7;
  166339. }
  166340. entropy->restarts_to_go--;
  166341. }
  166342. return TRUE;
  166343. }
  166344. /*
  166345. * MCU encoding for AC initial scan (either spectral selection,
  166346. * or first pass of successive approximation).
  166347. */
  166348. METHODDEF(boolean)
  166349. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166350. {
  166351. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166352. register int temp, temp2;
  166353. register int nbits;
  166354. register int r, k;
  166355. int Se = cinfo->Se;
  166356. int Al = cinfo->Al;
  166357. JBLOCKROW block;
  166358. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166359. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166360. /* Emit restart marker if needed */
  166361. if (cinfo->restart_interval)
  166362. if (entropy->restarts_to_go == 0)
  166363. emit_restart_p(entropy, entropy->next_restart_num);
  166364. /* Encode the MCU data block */
  166365. block = MCU_data[0];
  166366. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166367. r = 0; /* r = run length of zeros */
  166368. for (k = cinfo->Ss; k <= Se; k++) {
  166369. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166370. r++;
  166371. continue;
  166372. }
  166373. /* We must apply the point transform by Al. For AC coefficients this
  166374. * is an integer division with rounding towards 0. To do this portably
  166375. * in C, we shift after obtaining the absolute value; so the code is
  166376. * interwoven with finding the abs value (temp) and output bits (temp2).
  166377. */
  166378. if (temp < 0) {
  166379. temp = -temp; /* temp is abs value of input */
  166380. temp >>= Al; /* apply the point transform */
  166381. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166382. temp2 = ~temp;
  166383. } else {
  166384. temp >>= Al; /* apply the point transform */
  166385. temp2 = temp;
  166386. }
  166387. /* Watch out for case that nonzero coef is zero after point transform */
  166388. if (temp == 0) {
  166389. r++;
  166390. continue;
  166391. }
  166392. /* Emit any pending EOBRUN */
  166393. if (entropy->EOBRUN > 0)
  166394. emit_eobrun(entropy);
  166395. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166396. while (r > 15) {
  166397. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166398. r -= 16;
  166399. }
  166400. /* Find the number of bits needed for the magnitude of the coefficient */
  166401. nbits = 1; /* there must be at least one 1 bit */
  166402. while ((temp >>= 1))
  166403. nbits++;
  166404. /* Check for out-of-range coefficient values */
  166405. if (nbits > MAX_COEF_BITS)
  166406. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166407. /* Count/emit Huffman symbol for run length / number of bits */
  166408. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166409. /* Emit that number of bits of the value, if positive, */
  166410. /* or the complement of its magnitude, if negative. */
  166411. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166412. r = 0; /* reset zero run length */
  166413. }
  166414. if (r > 0) { /* If there are trailing zeroes, */
  166415. entropy->EOBRUN++; /* count an EOB */
  166416. if (entropy->EOBRUN == 0x7FFF)
  166417. emit_eobrun(entropy); /* force it out to avoid overflow */
  166418. }
  166419. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166420. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166421. /* Update restart-interval state too */
  166422. if (cinfo->restart_interval) {
  166423. if (entropy->restarts_to_go == 0) {
  166424. entropy->restarts_to_go = cinfo->restart_interval;
  166425. entropy->next_restart_num++;
  166426. entropy->next_restart_num &= 7;
  166427. }
  166428. entropy->restarts_to_go--;
  166429. }
  166430. return TRUE;
  166431. }
  166432. /*
  166433. * MCU encoding for DC successive approximation refinement scan.
  166434. * Note: we assume such scans can be multi-component, although the spec
  166435. * is not very clear on the point.
  166436. */
  166437. METHODDEF(boolean)
  166438. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166439. {
  166440. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166441. register int temp;
  166442. int blkn;
  166443. int Al = cinfo->Al;
  166444. JBLOCKROW block;
  166445. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166446. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166447. /* Emit restart marker if needed */
  166448. if (cinfo->restart_interval)
  166449. if (entropy->restarts_to_go == 0)
  166450. emit_restart_p(entropy, entropy->next_restart_num);
  166451. /* Encode the MCU data blocks */
  166452. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166453. block = MCU_data[blkn];
  166454. /* We simply emit the Al'th bit of the DC coefficient value. */
  166455. temp = (*block)[0];
  166456. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166457. }
  166458. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166459. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166460. /* Update restart-interval state too */
  166461. if (cinfo->restart_interval) {
  166462. if (entropy->restarts_to_go == 0) {
  166463. entropy->restarts_to_go = cinfo->restart_interval;
  166464. entropy->next_restart_num++;
  166465. entropy->next_restart_num &= 7;
  166466. }
  166467. entropy->restarts_to_go--;
  166468. }
  166469. return TRUE;
  166470. }
  166471. /*
  166472. * MCU encoding for AC successive approximation refinement scan.
  166473. */
  166474. METHODDEF(boolean)
  166475. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166476. {
  166477. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166478. register int temp;
  166479. register int r, k;
  166480. int EOB;
  166481. char *BR_buffer;
  166482. unsigned int BR;
  166483. int Se = cinfo->Se;
  166484. int Al = cinfo->Al;
  166485. JBLOCKROW block;
  166486. int absvalues[DCTSIZE2];
  166487. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166488. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166489. /* Emit restart marker if needed */
  166490. if (cinfo->restart_interval)
  166491. if (entropy->restarts_to_go == 0)
  166492. emit_restart_p(entropy, entropy->next_restart_num);
  166493. /* Encode the MCU data block */
  166494. block = MCU_data[0];
  166495. /* It is convenient to make a pre-pass to determine the transformed
  166496. * coefficients' absolute values and the EOB position.
  166497. */
  166498. EOB = 0;
  166499. for (k = cinfo->Ss; k <= Se; k++) {
  166500. temp = (*block)[jpeg_natural_order[k]];
  166501. /* We must apply the point transform by Al. For AC coefficients this
  166502. * is an integer division with rounding towards 0. To do this portably
  166503. * in C, we shift after obtaining the absolute value.
  166504. */
  166505. if (temp < 0)
  166506. temp = -temp; /* temp is abs value of input */
  166507. temp >>= Al; /* apply the point transform */
  166508. absvalues[k] = temp; /* save abs value for main pass */
  166509. if (temp == 1)
  166510. EOB = k; /* EOB = index of last newly-nonzero coef */
  166511. }
  166512. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166513. r = 0; /* r = run length of zeros */
  166514. BR = 0; /* BR = count of buffered bits added now */
  166515. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166516. for (k = cinfo->Ss; k <= Se; k++) {
  166517. if ((temp = absvalues[k]) == 0) {
  166518. r++;
  166519. continue;
  166520. }
  166521. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166522. while (r > 15 && k <= EOB) {
  166523. /* emit any pending EOBRUN and the BE correction bits */
  166524. emit_eobrun(entropy);
  166525. /* Emit ZRL */
  166526. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166527. r -= 16;
  166528. /* Emit buffered correction bits that must be associated with ZRL */
  166529. emit_buffered_bits(entropy, BR_buffer, BR);
  166530. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166531. BR = 0;
  166532. }
  166533. /* If the coef was previously nonzero, it only needs a correction bit.
  166534. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166535. * that we also need to test r > 15. But if r > 15, we can only get here
  166536. * if k > EOB, which implies that this coefficient is not 1.
  166537. */
  166538. if (temp > 1) {
  166539. /* The correction bit is the next bit of the absolute value. */
  166540. BR_buffer[BR++] = (char) (temp & 1);
  166541. continue;
  166542. }
  166543. /* Emit any pending EOBRUN and the BE correction bits */
  166544. emit_eobrun(entropy);
  166545. /* Count/emit Huffman symbol for run length / number of bits */
  166546. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166547. /* Emit output bit for newly-nonzero coef */
  166548. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166549. emit_bits_p(entropy, (unsigned int) temp, 1);
  166550. /* Emit buffered correction bits that must be associated with this code */
  166551. emit_buffered_bits(entropy, BR_buffer, BR);
  166552. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166553. BR = 0;
  166554. r = 0; /* reset zero run length */
  166555. }
  166556. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166557. entropy->EOBRUN++; /* count an EOB */
  166558. entropy->BE += BR; /* concat my correction bits to older ones */
  166559. /* We force out the EOB if we risk either:
  166560. * 1. overflow of the EOB counter;
  166561. * 2. overflow of the correction bit buffer during the next MCU.
  166562. */
  166563. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166564. emit_eobrun(entropy);
  166565. }
  166566. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166567. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166568. /* Update restart-interval state too */
  166569. if (cinfo->restart_interval) {
  166570. if (entropy->restarts_to_go == 0) {
  166571. entropy->restarts_to_go = cinfo->restart_interval;
  166572. entropy->next_restart_num++;
  166573. entropy->next_restart_num &= 7;
  166574. }
  166575. entropy->restarts_to_go--;
  166576. }
  166577. return TRUE;
  166578. }
  166579. /*
  166580. * Finish up at the end of a Huffman-compressed progressive scan.
  166581. */
  166582. METHODDEF(void)
  166583. finish_pass_phuff (j_compress_ptr cinfo)
  166584. {
  166585. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166586. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166587. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166588. /* Flush out any buffered data */
  166589. emit_eobrun(entropy);
  166590. flush_bits_p(entropy);
  166591. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166592. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166593. }
  166594. /*
  166595. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166596. */
  166597. METHODDEF(void)
  166598. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166599. {
  166600. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166601. boolean is_DC_band;
  166602. int ci, tbl;
  166603. jpeg_component_info * compptr;
  166604. JHUFF_TBL **htblptr;
  166605. boolean did[NUM_HUFF_TBLS];
  166606. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166607. emit_eobrun(entropy);
  166608. is_DC_band = (cinfo->Ss == 0);
  166609. /* It's important not to apply jpeg_gen_optimal_table more than once
  166610. * per table, because it clobbers the input frequency counts!
  166611. */
  166612. MEMZERO(did, SIZEOF(did));
  166613. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166614. compptr = cinfo->cur_comp_info[ci];
  166615. if (is_DC_band) {
  166616. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166617. continue;
  166618. tbl = compptr->dc_tbl_no;
  166619. } else {
  166620. tbl = compptr->ac_tbl_no;
  166621. }
  166622. if (! did[tbl]) {
  166623. if (is_DC_band)
  166624. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166625. else
  166626. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166627. if (*htblptr == NULL)
  166628. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166629. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166630. did[tbl] = TRUE;
  166631. }
  166632. }
  166633. }
  166634. /*
  166635. * Module initialization routine for progressive Huffman entropy encoding.
  166636. */
  166637. GLOBAL(void)
  166638. jinit_phuff_encoder (j_compress_ptr cinfo)
  166639. {
  166640. phuff_entropy_ptr entropy;
  166641. int i;
  166642. entropy = (phuff_entropy_ptr)
  166643. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166644. SIZEOF(phuff_entropy_encoder));
  166645. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166646. entropy->pub.start_pass = start_pass_phuff;
  166647. /* Mark tables unallocated */
  166648. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166649. entropy->derived_tbls[i] = NULL;
  166650. entropy->count_ptrs[i] = NULL;
  166651. }
  166652. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166653. }
  166654. #endif /* C_PROGRESSIVE_SUPPORTED */
  166655. /*** End of inlined file: jcphuff.c ***/
  166656. /*** Start of inlined file: jcprepct.c ***/
  166657. #define JPEG_INTERNALS
  166658. /* At present, jcsample.c can request context rows only for smoothing.
  166659. * In the future, we might also need context rows for CCIR601 sampling
  166660. * or other more-complex downsampling procedures. The code to support
  166661. * context rows should be compiled only if needed.
  166662. */
  166663. #ifdef INPUT_SMOOTHING_SUPPORTED
  166664. #define CONTEXT_ROWS_SUPPORTED
  166665. #endif
  166666. /*
  166667. * For the simple (no-context-row) case, we just need to buffer one
  166668. * row group's worth of pixels for the downsampling step. At the bottom of
  166669. * the image, we pad to a full row group by replicating the last pixel row.
  166670. * The downsampler's last output row is then replicated if needed to pad
  166671. * out to a full iMCU row.
  166672. *
  166673. * When providing context rows, we must buffer three row groups' worth of
  166674. * pixels. Three row groups are physically allocated, but the row pointer
  166675. * arrays are made five row groups high, with the extra pointers above and
  166676. * below "wrapping around" to point to the last and first real row groups.
  166677. * This allows the downsampler to access the proper context rows.
  166678. * At the top and bottom of the image, we create dummy context rows by
  166679. * copying the first or last real pixel row. This copying could be avoided
  166680. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166681. * trouble on the compression side.
  166682. */
  166683. /* Private buffer controller object */
  166684. typedef struct {
  166685. struct jpeg_c_prep_controller pub; /* public fields */
  166686. /* Downsampling input buffer. This buffer holds color-converted data
  166687. * until we have enough to do a downsample step.
  166688. */
  166689. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166690. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166691. int next_buf_row; /* index of next row to store in color_buf */
  166692. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166693. int this_row_group; /* starting row index of group to process */
  166694. int next_buf_stop; /* downsample when we reach this index */
  166695. #endif
  166696. } my_prep_controller;
  166697. typedef my_prep_controller * my_prep_ptr;
  166698. /*
  166699. * Initialize for a processing pass.
  166700. */
  166701. METHODDEF(void)
  166702. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166703. {
  166704. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166705. if (pass_mode != JBUF_PASS_THRU)
  166706. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166707. /* Initialize total-height counter for detecting bottom of image */
  166708. prep->rows_to_go = cinfo->image_height;
  166709. /* Mark the conversion buffer empty */
  166710. prep->next_buf_row = 0;
  166711. #ifdef CONTEXT_ROWS_SUPPORTED
  166712. /* Preset additional state variables for context mode.
  166713. * These aren't used in non-context mode, so we needn't test which mode.
  166714. */
  166715. prep->this_row_group = 0;
  166716. /* Set next_buf_stop to stop after two row groups have been read in. */
  166717. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166718. #endif
  166719. }
  166720. /*
  166721. * Expand an image vertically from height input_rows to height output_rows,
  166722. * by duplicating the bottom row.
  166723. */
  166724. LOCAL(void)
  166725. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166726. int input_rows, int output_rows)
  166727. {
  166728. register int row;
  166729. for (row = input_rows; row < output_rows; row++) {
  166730. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166731. 1, num_cols);
  166732. }
  166733. }
  166734. /*
  166735. * Process some data in the simple no-context case.
  166736. *
  166737. * Preprocessor output data is counted in "row groups". A row group
  166738. * is defined to be v_samp_factor sample rows of each component.
  166739. * Downsampling will produce this much data from each max_v_samp_factor
  166740. * input rows.
  166741. */
  166742. METHODDEF(void)
  166743. pre_process_data (j_compress_ptr cinfo,
  166744. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166745. JDIMENSION in_rows_avail,
  166746. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166747. JDIMENSION out_row_groups_avail)
  166748. {
  166749. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166750. int numrows, ci;
  166751. JDIMENSION inrows;
  166752. jpeg_component_info * compptr;
  166753. while (*in_row_ctr < in_rows_avail &&
  166754. *out_row_group_ctr < out_row_groups_avail) {
  166755. /* Do color conversion to fill the conversion buffer. */
  166756. inrows = in_rows_avail - *in_row_ctr;
  166757. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166758. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166759. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166760. prep->color_buf,
  166761. (JDIMENSION) prep->next_buf_row,
  166762. numrows);
  166763. *in_row_ctr += numrows;
  166764. prep->next_buf_row += numrows;
  166765. prep->rows_to_go -= numrows;
  166766. /* If at bottom of image, pad to fill the conversion buffer. */
  166767. if (prep->rows_to_go == 0 &&
  166768. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166769. for (ci = 0; ci < cinfo->num_components; ci++) {
  166770. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166771. prep->next_buf_row, cinfo->max_v_samp_factor);
  166772. }
  166773. prep->next_buf_row = cinfo->max_v_samp_factor;
  166774. }
  166775. /* If we've filled the conversion buffer, empty it. */
  166776. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166777. (*cinfo->downsample->downsample) (cinfo,
  166778. prep->color_buf, (JDIMENSION) 0,
  166779. output_buf, *out_row_group_ctr);
  166780. prep->next_buf_row = 0;
  166781. (*out_row_group_ctr)++;
  166782. }
  166783. /* If at bottom of image, pad the output to a full iMCU height.
  166784. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166785. */
  166786. if (prep->rows_to_go == 0 &&
  166787. *out_row_group_ctr < out_row_groups_avail) {
  166788. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166789. ci++, compptr++) {
  166790. expand_bottom_edge(output_buf[ci],
  166791. compptr->width_in_blocks * DCTSIZE,
  166792. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166793. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166794. }
  166795. *out_row_group_ctr = out_row_groups_avail;
  166796. break; /* can exit outer loop without test */
  166797. }
  166798. }
  166799. }
  166800. #ifdef CONTEXT_ROWS_SUPPORTED
  166801. /*
  166802. * Process some data in the context case.
  166803. */
  166804. METHODDEF(void)
  166805. pre_process_context (j_compress_ptr cinfo,
  166806. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166807. JDIMENSION in_rows_avail,
  166808. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166809. JDIMENSION out_row_groups_avail)
  166810. {
  166811. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166812. int numrows, ci;
  166813. int buf_height = cinfo->max_v_samp_factor * 3;
  166814. JDIMENSION inrows;
  166815. while (*out_row_group_ctr < out_row_groups_avail) {
  166816. if (*in_row_ctr < in_rows_avail) {
  166817. /* Do color conversion to fill the conversion buffer. */
  166818. inrows = in_rows_avail - *in_row_ctr;
  166819. numrows = prep->next_buf_stop - prep->next_buf_row;
  166820. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166821. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166822. prep->color_buf,
  166823. (JDIMENSION) prep->next_buf_row,
  166824. numrows);
  166825. /* Pad at top of image, if first time through */
  166826. if (prep->rows_to_go == cinfo->image_height) {
  166827. for (ci = 0; ci < cinfo->num_components; ci++) {
  166828. int row;
  166829. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166830. jcopy_sample_rows(prep->color_buf[ci], 0,
  166831. prep->color_buf[ci], -row,
  166832. 1, cinfo->image_width);
  166833. }
  166834. }
  166835. }
  166836. *in_row_ctr += numrows;
  166837. prep->next_buf_row += numrows;
  166838. prep->rows_to_go -= numrows;
  166839. } else {
  166840. /* Return for more data, unless we are at the bottom of the image. */
  166841. if (prep->rows_to_go != 0)
  166842. break;
  166843. /* When at bottom of image, pad to fill the conversion buffer. */
  166844. if (prep->next_buf_row < prep->next_buf_stop) {
  166845. for (ci = 0; ci < cinfo->num_components; ci++) {
  166846. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166847. prep->next_buf_row, prep->next_buf_stop);
  166848. }
  166849. prep->next_buf_row = prep->next_buf_stop;
  166850. }
  166851. }
  166852. /* If we've gotten enough data, downsample a row group. */
  166853. if (prep->next_buf_row == prep->next_buf_stop) {
  166854. (*cinfo->downsample->downsample) (cinfo,
  166855. prep->color_buf,
  166856. (JDIMENSION) prep->this_row_group,
  166857. output_buf, *out_row_group_ctr);
  166858. (*out_row_group_ctr)++;
  166859. /* Advance pointers with wraparound as necessary. */
  166860. prep->this_row_group += cinfo->max_v_samp_factor;
  166861. if (prep->this_row_group >= buf_height)
  166862. prep->this_row_group = 0;
  166863. if (prep->next_buf_row >= buf_height)
  166864. prep->next_buf_row = 0;
  166865. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166866. }
  166867. }
  166868. }
  166869. /*
  166870. * Create the wrapped-around downsampling input buffer needed for context mode.
  166871. */
  166872. LOCAL(void)
  166873. create_context_buffer (j_compress_ptr cinfo)
  166874. {
  166875. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166876. int rgroup_height = cinfo->max_v_samp_factor;
  166877. int ci, i;
  166878. jpeg_component_info * compptr;
  166879. JSAMPARRAY true_buffer, fake_buffer;
  166880. /* Grab enough space for fake row pointers for all the components;
  166881. * we need five row groups' worth of pointers for each component.
  166882. */
  166883. fake_buffer = (JSAMPARRAY)
  166884. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166885. (cinfo->num_components * 5 * rgroup_height) *
  166886. SIZEOF(JSAMPROW));
  166887. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166888. ci++, compptr++) {
  166889. /* Allocate the actual buffer space (3 row groups) for this component.
  166890. * We make the buffer wide enough to allow the downsampler to edge-expand
  166891. * horizontally within the buffer, if it so chooses.
  166892. */
  166893. true_buffer = (*cinfo->mem->alloc_sarray)
  166894. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166895. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166896. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166897. (JDIMENSION) (3 * rgroup_height));
  166898. /* Copy true buffer row pointers into the middle of the fake row array */
  166899. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166900. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166901. /* Fill in the above and below wraparound pointers */
  166902. for (i = 0; i < rgroup_height; i++) {
  166903. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166904. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166905. }
  166906. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166907. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166908. }
  166909. }
  166910. #endif /* CONTEXT_ROWS_SUPPORTED */
  166911. /*
  166912. * Initialize preprocessing controller.
  166913. */
  166914. GLOBAL(void)
  166915. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166916. {
  166917. my_prep_ptr prep;
  166918. int ci;
  166919. jpeg_component_info * compptr;
  166920. if (need_full_buffer) /* safety check */
  166921. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166922. prep = (my_prep_ptr)
  166923. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166924. SIZEOF(my_prep_controller));
  166925. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166926. prep->pub.start_pass = start_pass_prep;
  166927. /* Allocate the color conversion buffer.
  166928. * We make the buffer wide enough to allow the downsampler to edge-expand
  166929. * horizontally within the buffer, if it so chooses.
  166930. */
  166931. if (cinfo->downsample->need_context_rows) {
  166932. /* Set up to provide context rows */
  166933. #ifdef CONTEXT_ROWS_SUPPORTED
  166934. prep->pub.pre_process_data = pre_process_context;
  166935. create_context_buffer(cinfo);
  166936. #else
  166937. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166938. #endif
  166939. } else {
  166940. /* No context, just make it tall enough for one row group */
  166941. prep->pub.pre_process_data = pre_process_data;
  166942. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166943. ci++, compptr++) {
  166944. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166945. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166946. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166947. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166948. (JDIMENSION) cinfo->max_v_samp_factor);
  166949. }
  166950. }
  166951. }
  166952. /*** End of inlined file: jcprepct.c ***/
  166953. /*** Start of inlined file: jcsample.c ***/
  166954. #define JPEG_INTERNALS
  166955. /* Pointer to routine to downsample a single component */
  166956. typedef JMETHOD(void, downsample1_ptr,
  166957. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166958. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166959. /* Private subobject */
  166960. typedef struct {
  166961. struct jpeg_downsampler pub; /* public fields */
  166962. /* Downsampling method pointers, one per component */
  166963. downsample1_ptr methods[MAX_COMPONENTS];
  166964. } my_downsampler;
  166965. typedef my_downsampler * my_downsample_ptr;
  166966. /*
  166967. * Initialize for a downsampling pass.
  166968. */
  166969. METHODDEF(void)
  166970. start_pass_downsample (j_compress_ptr)
  166971. {
  166972. /* no work for now */
  166973. }
  166974. /*
  166975. * Expand a component horizontally from width input_cols to width output_cols,
  166976. * by duplicating the rightmost samples.
  166977. */
  166978. LOCAL(void)
  166979. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166980. JDIMENSION input_cols, JDIMENSION output_cols)
  166981. {
  166982. register JSAMPROW ptr;
  166983. register JSAMPLE pixval;
  166984. register int count;
  166985. int row;
  166986. int numcols = (int) (output_cols - input_cols);
  166987. if (numcols > 0) {
  166988. for (row = 0; row < num_rows; row++) {
  166989. ptr = image_data[row] + input_cols;
  166990. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166991. for (count = numcols; count > 0; count--)
  166992. *ptr++ = pixval;
  166993. }
  166994. }
  166995. }
  166996. /*
  166997. * Do downsampling for a whole row group (all components).
  166998. *
  166999. * In this version we simply downsample each component independently.
  167000. */
  167001. METHODDEF(void)
  167002. sep_downsample (j_compress_ptr cinfo,
  167003. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  167004. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  167005. {
  167006. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  167007. int ci;
  167008. jpeg_component_info * compptr;
  167009. JSAMPARRAY in_ptr, out_ptr;
  167010. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167011. ci++, compptr++) {
  167012. in_ptr = input_buf[ci] + in_row_index;
  167013. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  167014. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  167015. }
  167016. }
  167017. /*
  167018. * Downsample pixel values of a single component.
  167019. * One row group is processed per call.
  167020. * This version handles arbitrary integral sampling ratios, without smoothing.
  167021. * Note that this version is not actually used for customary sampling ratios.
  167022. */
  167023. METHODDEF(void)
  167024. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167025. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167026. {
  167027. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  167028. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  167029. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167030. JSAMPROW inptr, outptr;
  167031. INT32 outvalue;
  167032. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  167033. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  167034. numpix = h_expand * v_expand;
  167035. numpix2 = numpix/2;
  167036. /* Expand input data enough to let all the output samples be generated
  167037. * by the standard loop. Special-casing padded output would be more
  167038. * efficient.
  167039. */
  167040. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167041. cinfo->image_width, output_cols * h_expand);
  167042. inrow = 0;
  167043. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167044. outptr = output_data[outrow];
  167045. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  167046. outcol++, outcol_h += h_expand) {
  167047. outvalue = 0;
  167048. for (v = 0; v < v_expand; v++) {
  167049. inptr = input_data[inrow+v] + outcol_h;
  167050. for (h = 0; h < h_expand; h++) {
  167051. outvalue += (INT32) GETJSAMPLE(*inptr++);
  167052. }
  167053. }
  167054. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  167055. }
  167056. inrow += v_expand;
  167057. }
  167058. }
  167059. /*
  167060. * Downsample pixel values of a single component.
  167061. * This version handles the special case of a full-size component,
  167062. * without smoothing.
  167063. */
  167064. METHODDEF(void)
  167065. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167066. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167067. {
  167068. /* Copy the data */
  167069. jcopy_sample_rows(input_data, 0, output_data, 0,
  167070. cinfo->max_v_samp_factor, cinfo->image_width);
  167071. /* Edge-expand */
  167072. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  167073. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  167074. }
  167075. /*
  167076. * Downsample pixel values of a single component.
  167077. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  167078. * without smoothing.
  167079. *
  167080. * A note about the "bias" calculations: when rounding fractional values to
  167081. * integer, we do not want to always round 0.5 up to the next integer.
  167082. * If we did that, we'd introduce a noticeable bias towards larger values.
  167083. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167084. * alternate pixel locations (a simple ordered dither pattern).
  167085. */
  167086. METHODDEF(void)
  167087. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167088. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167089. {
  167090. int outrow;
  167091. JDIMENSION outcol;
  167092. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167093. register JSAMPROW inptr, outptr;
  167094. register int bias;
  167095. /* Expand input data enough to let all the output samples be generated
  167096. * by the standard loop. Special-casing padded output would be more
  167097. * efficient.
  167098. */
  167099. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167100. cinfo->image_width, output_cols * 2);
  167101. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167102. outptr = output_data[outrow];
  167103. inptr = input_data[outrow];
  167104. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  167105. for (outcol = 0; outcol < output_cols; outcol++) {
  167106. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  167107. + bias) >> 1);
  167108. bias ^= 1; /* 0=>1, 1=>0 */
  167109. inptr += 2;
  167110. }
  167111. }
  167112. }
  167113. /*
  167114. * Downsample pixel values of a single component.
  167115. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167116. * without smoothing.
  167117. */
  167118. METHODDEF(void)
  167119. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167120. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167121. {
  167122. int inrow, outrow;
  167123. JDIMENSION outcol;
  167124. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167125. register JSAMPROW inptr0, inptr1, outptr;
  167126. register int bias;
  167127. /* Expand input data enough to let all the output samples be generated
  167128. * by the standard loop. Special-casing padded output would be more
  167129. * efficient.
  167130. */
  167131. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167132. cinfo->image_width, output_cols * 2);
  167133. inrow = 0;
  167134. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167135. outptr = output_data[outrow];
  167136. inptr0 = input_data[inrow];
  167137. inptr1 = input_data[inrow+1];
  167138. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167139. for (outcol = 0; outcol < output_cols; outcol++) {
  167140. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167141. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167142. + bias) >> 2);
  167143. bias ^= 3; /* 1=>2, 2=>1 */
  167144. inptr0 += 2; inptr1 += 2;
  167145. }
  167146. inrow += 2;
  167147. }
  167148. }
  167149. #ifdef INPUT_SMOOTHING_SUPPORTED
  167150. /*
  167151. * Downsample pixel values of a single component.
  167152. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167153. * with smoothing. One row of context is required.
  167154. */
  167155. METHODDEF(void)
  167156. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167157. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167158. {
  167159. int inrow, outrow;
  167160. JDIMENSION colctr;
  167161. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167162. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167163. INT32 membersum, neighsum, memberscale, neighscale;
  167164. /* Expand input data enough to let all the output samples be generated
  167165. * by the standard loop. Special-casing padded output would be more
  167166. * efficient.
  167167. */
  167168. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167169. cinfo->image_width, output_cols * 2);
  167170. /* We don't bother to form the individual "smoothed" input pixel values;
  167171. * we can directly compute the output which is the average of the four
  167172. * smoothed values. Each of the four member pixels contributes a fraction
  167173. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167174. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167175. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167176. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167177. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167178. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167179. * factors are scaled by 2^16 = 65536.
  167180. * Also recall that SF = smoothing_factor / 1024.
  167181. */
  167182. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167183. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167184. inrow = 0;
  167185. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167186. outptr = output_data[outrow];
  167187. inptr0 = input_data[inrow];
  167188. inptr1 = input_data[inrow+1];
  167189. above_ptr = input_data[inrow-1];
  167190. below_ptr = input_data[inrow+2];
  167191. /* Special case for first column: pretend column -1 is same as column 0 */
  167192. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167193. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167194. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167195. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167196. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167197. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167198. neighsum += neighsum;
  167199. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167200. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167201. membersum = membersum * memberscale + neighsum * neighscale;
  167202. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167203. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167204. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167205. /* sum of pixels directly mapped to this output element */
  167206. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167207. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167208. /* sum of edge-neighbor pixels */
  167209. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167210. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167211. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167212. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167213. /* The edge-neighbors count twice as much as corner-neighbors */
  167214. neighsum += neighsum;
  167215. /* Add in the corner-neighbors */
  167216. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167217. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167218. /* form final output scaled up by 2^16 */
  167219. membersum = membersum * memberscale + neighsum * neighscale;
  167220. /* round, descale and output it */
  167221. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167222. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167223. }
  167224. /* Special case for last column */
  167225. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167226. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167227. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167228. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167229. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167230. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167231. neighsum += neighsum;
  167232. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167233. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167234. membersum = membersum * memberscale + neighsum * neighscale;
  167235. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167236. inrow += 2;
  167237. }
  167238. }
  167239. /*
  167240. * Downsample pixel values of a single component.
  167241. * This version handles the special case of a full-size component,
  167242. * with smoothing. One row of context is required.
  167243. */
  167244. METHODDEF(void)
  167245. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167246. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167247. {
  167248. int outrow;
  167249. JDIMENSION colctr;
  167250. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167251. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167252. INT32 membersum, neighsum, memberscale, neighscale;
  167253. int colsum, lastcolsum, nextcolsum;
  167254. /* Expand input data enough to let all the output samples be generated
  167255. * by the standard loop. Special-casing padded output would be more
  167256. * efficient.
  167257. */
  167258. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167259. cinfo->image_width, output_cols);
  167260. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167261. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167262. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167263. * Also recall that SF = smoothing_factor / 1024.
  167264. */
  167265. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167266. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167267. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167268. outptr = output_data[outrow];
  167269. inptr = input_data[outrow];
  167270. above_ptr = input_data[outrow-1];
  167271. below_ptr = input_data[outrow+1];
  167272. /* Special case for first column */
  167273. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167274. GETJSAMPLE(*inptr);
  167275. membersum = GETJSAMPLE(*inptr++);
  167276. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167277. GETJSAMPLE(*inptr);
  167278. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167279. membersum = membersum * memberscale + neighsum * neighscale;
  167280. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167281. lastcolsum = colsum; colsum = nextcolsum;
  167282. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167283. membersum = GETJSAMPLE(*inptr++);
  167284. above_ptr++; below_ptr++;
  167285. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167286. GETJSAMPLE(*inptr);
  167287. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167288. membersum = membersum * memberscale + neighsum * neighscale;
  167289. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167290. lastcolsum = colsum; colsum = nextcolsum;
  167291. }
  167292. /* Special case for last column */
  167293. membersum = GETJSAMPLE(*inptr);
  167294. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167295. membersum = membersum * memberscale + neighsum * neighscale;
  167296. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167297. }
  167298. }
  167299. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167300. /*
  167301. * Module initialization routine for downsampling.
  167302. * Note that we must select a routine for each component.
  167303. */
  167304. GLOBAL(void)
  167305. jinit_downsampler (j_compress_ptr cinfo)
  167306. {
  167307. my_downsample_ptr downsample;
  167308. int ci;
  167309. jpeg_component_info * compptr;
  167310. boolean smoothok = TRUE;
  167311. downsample = (my_downsample_ptr)
  167312. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167313. SIZEOF(my_downsampler));
  167314. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167315. downsample->pub.start_pass = start_pass_downsample;
  167316. downsample->pub.downsample = sep_downsample;
  167317. downsample->pub.need_context_rows = FALSE;
  167318. if (cinfo->CCIR601_sampling)
  167319. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167320. /* Verify we can handle the sampling factors, and set up method pointers */
  167321. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167322. ci++, compptr++) {
  167323. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167324. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167325. #ifdef INPUT_SMOOTHING_SUPPORTED
  167326. if (cinfo->smoothing_factor) {
  167327. downsample->methods[ci] = fullsize_smooth_downsample;
  167328. downsample->pub.need_context_rows = TRUE;
  167329. } else
  167330. #endif
  167331. downsample->methods[ci] = fullsize_downsample;
  167332. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167333. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167334. smoothok = FALSE;
  167335. downsample->methods[ci] = h2v1_downsample;
  167336. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167337. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167338. #ifdef INPUT_SMOOTHING_SUPPORTED
  167339. if (cinfo->smoothing_factor) {
  167340. downsample->methods[ci] = h2v2_smooth_downsample;
  167341. downsample->pub.need_context_rows = TRUE;
  167342. } else
  167343. #endif
  167344. downsample->methods[ci] = h2v2_downsample;
  167345. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167346. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167347. smoothok = FALSE;
  167348. downsample->methods[ci] = int_downsample;
  167349. } else
  167350. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167351. }
  167352. #ifdef INPUT_SMOOTHING_SUPPORTED
  167353. if (cinfo->smoothing_factor && !smoothok)
  167354. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167355. #endif
  167356. }
  167357. /*** End of inlined file: jcsample.c ***/
  167358. /*** Start of inlined file: jctrans.c ***/
  167359. #define JPEG_INTERNALS
  167360. /* Forward declarations */
  167361. LOCAL(void) transencode_master_selection
  167362. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167363. LOCAL(void) transencode_coef_controller
  167364. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167365. /*
  167366. * Compression initialization for writing raw-coefficient data.
  167367. * Before calling this, all parameters and a data destination must be set up.
  167368. * Call jpeg_finish_compress() to actually write the data.
  167369. *
  167370. * The number of passed virtual arrays must match cinfo->num_components.
  167371. * Note that the virtual arrays need not be filled or even realized at
  167372. * the time write_coefficients is called; indeed, if the virtual arrays
  167373. * were requested from this compression object's memory manager, they
  167374. * typically will be realized during this routine and filled afterwards.
  167375. */
  167376. GLOBAL(void)
  167377. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167378. {
  167379. if (cinfo->global_state != CSTATE_START)
  167380. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167381. /* Mark all tables to be written */
  167382. jpeg_suppress_tables(cinfo, FALSE);
  167383. /* (Re)initialize error mgr and destination modules */
  167384. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167385. (*cinfo->dest->init_destination) (cinfo);
  167386. /* Perform master selection of active modules */
  167387. transencode_master_selection(cinfo, coef_arrays);
  167388. /* Wait for jpeg_finish_compress() call */
  167389. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167390. cinfo->global_state = CSTATE_WRCOEFS;
  167391. }
  167392. /*
  167393. * Initialize the compression object with default parameters,
  167394. * then copy from the source object all parameters needed for lossless
  167395. * transcoding. Parameters that can be varied without loss (such as
  167396. * scan script and Huffman optimization) are left in their default states.
  167397. */
  167398. GLOBAL(void)
  167399. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167400. j_compress_ptr dstinfo)
  167401. {
  167402. JQUANT_TBL ** qtblptr;
  167403. jpeg_component_info *incomp, *outcomp;
  167404. JQUANT_TBL *c_quant, *slot_quant;
  167405. int tblno, ci, coefi;
  167406. /* Safety check to ensure start_compress not called yet. */
  167407. if (dstinfo->global_state != CSTATE_START)
  167408. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167409. /* Copy fundamental image dimensions */
  167410. dstinfo->image_width = srcinfo->image_width;
  167411. dstinfo->image_height = srcinfo->image_height;
  167412. dstinfo->input_components = srcinfo->num_components;
  167413. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167414. /* Initialize all parameters to default values */
  167415. jpeg_set_defaults(dstinfo);
  167416. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167417. * Fix it to get the right header markers for the image colorspace.
  167418. */
  167419. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167420. dstinfo->data_precision = srcinfo->data_precision;
  167421. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167422. /* Copy the source's quantization tables. */
  167423. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167424. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167425. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167426. if (*qtblptr == NULL)
  167427. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167428. MEMCOPY((*qtblptr)->quantval,
  167429. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167430. SIZEOF((*qtblptr)->quantval));
  167431. (*qtblptr)->sent_table = FALSE;
  167432. }
  167433. }
  167434. /* Copy the source's per-component info.
  167435. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167436. */
  167437. dstinfo->num_components = srcinfo->num_components;
  167438. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167439. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167440. MAX_COMPONENTS);
  167441. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167442. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167443. outcomp->component_id = incomp->component_id;
  167444. outcomp->h_samp_factor = incomp->h_samp_factor;
  167445. outcomp->v_samp_factor = incomp->v_samp_factor;
  167446. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167447. /* Make sure saved quantization table for component matches the qtable
  167448. * slot. If not, the input file re-used this qtable slot.
  167449. * IJG encoder currently cannot duplicate this.
  167450. */
  167451. tblno = outcomp->quant_tbl_no;
  167452. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167453. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167454. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167455. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167456. c_quant = incomp->quant_table;
  167457. if (c_quant != NULL) {
  167458. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167459. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167460. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167461. }
  167462. }
  167463. /* Note: we do not copy the source's Huffman table assignments;
  167464. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167465. */
  167466. }
  167467. /* Also copy JFIF version and resolution information, if available.
  167468. * Strictly speaking this isn't "critical" info, but it's nearly
  167469. * always appropriate to copy it if available. In particular,
  167470. * if the application chooses to copy JFIF 1.02 extension markers from
  167471. * the source file, we need to copy the version to make sure we don't
  167472. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167473. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167474. */
  167475. if (srcinfo->saw_JFIF_marker) {
  167476. if (srcinfo->JFIF_major_version == 1) {
  167477. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167478. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167479. }
  167480. dstinfo->density_unit = srcinfo->density_unit;
  167481. dstinfo->X_density = srcinfo->X_density;
  167482. dstinfo->Y_density = srcinfo->Y_density;
  167483. }
  167484. }
  167485. /*
  167486. * Master selection of compression modules for transcoding.
  167487. * This substitutes for jcinit.c's initialization of the full compressor.
  167488. */
  167489. LOCAL(void)
  167490. transencode_master_selection (j_compress_ptr cinfo,
  167491. jvirt_barray_ptr * coef_arrays)
  167492. {
  167493. /* Although we don't actually use input_components for transcoding,
  167494. * jcmaster.c's initial_setup will complain if input_components is 0.
  167495. */
  167496. cinfo->input_components = 1;
  167497. /* Initialize master control (includes parameter checking/processing) */
  167498. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167499. /* Entropy encoding: either Huffman or arithmetic coding. */
  167500. if (cinfo->arith_code) {
  167501. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167502. } else {
  167503. if (cinfo->progressive_mode) {
  167504. #ifdef C_PROGRESSIVE_SUPPORTED
  167505. jinit_phuff_encoder(cinfo);
  167506. #else
  167507. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167508. #endif
  167509. } else
  167510. jinit_huff_encoder(cinfo);
  167511. }
  167512. /* We need a special coefficient buffer controller. */
  167513. transencode_coef_controller(cinfo, coef_arrays);
  167514. jinit_marker_writer(cinfo);
  167515. /* We can now tell the memory manager to allocate virtual arrays. */
  167516. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167517. /* Write the datastream header (SOI, JFIF) immediately.
  167518. * Frame and scan headers are postponed till later.
  167519. * This lets application insert special markers after the SOI.
  167520. */
  167521. (*cinfo->marker->write_file_header) (cinfo);
  167522. }
  167523. /*
  167524. * The rest of this file is a special implementation of the coefficient
  167525. * buffer controller. This is similar to jccoefct.c, but it handles only
  167526. * output from presupplied virtual arrays. Furthermore, we generate any
  167527. * dummy padding blocks on-the-fly rather than expecting them to be present
  167528. * in the arrays.
  167529. */
  167530. /* Private buffer controller object */
  167531. typedef struct {
  167532. struct jpeg_c_coef_controller pub; /* public fields */
  167533. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167534. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167535. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167536. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167537. /* Virtual block array for each component. */
  167538. jvirt_barray_ptr * whole_image;
  167539. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167540. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167541. } my_coef_controller2;
  167542. typedef my_coef_controller2 * my_coef_ptr2;
  167543. LOCAL(void)
  167544. start_iMCU_row2 (j_compress_ptr cinfo)
  167545. /* Reset within-iMCU-row counters for a new row */
  167546. {
  167547. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167548. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167549. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167550. * But at the bottom of the image, process only what's left.
  167551. */
  167552. if (cinfo->comps_in_scan > 1) {
  167553. coef->MCU_rows_per_iMCU_row = 1;
  167554. } else {
  167555. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167556. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167557. else
  167558. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167559. }
  167560. coef->mcu_ctr = 0;
  167561. coef->MCU_vert_offset = 0;
  167562. }
  167563. /*
  167564. * Initialize for a processing pass.
  167565. */
  167566. METHODDEF(void)
  167567. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167568. {
  167569. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167570. if (pass_mode != JBUF_CRANK_DEST)
  167571. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167572. coef->iMCU_row_num = 0;
  167573. start_iMCU_row2(cinfo);
  167574. }
  167575. /*
  167576. * Process some data.
  167577. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167578. * per call, ie, v_samp_factor block rows for each component in the scan.
  167579. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167580. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167581. *
  167582. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167583. */
  167584. METHODDEF(boolean)
  167585. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167586. {
  167587. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167588. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167589. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167590. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167591. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167592. JDIMENSION start_col;
  167593. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167594. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167595. JBLOCKROW buffer_ptr;
  167596. jpeg_component_info *compptr;
  167597. /* Align the virtual buffers for the components used in this scan. */
  167598. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167599. compptr = cinfo->cur_comp_info[ci];
  167600. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167601. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167602. coef->iMCU_row_num * compptr->v_samp_factor,
  167603. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167604. }
  167605. /* Loop to process one whole iMCU row */
  167606. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167607. yoffset++) {
  167608. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167609. MCU_col_num++) {
  167610. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167611. blkn = 0; /* index of current DCT block within MCU */
  167612. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167613. compptr = cinfo->cur_comp_info[ci];
  167614. start_col = MCU_col_num * compptr->MCU_width;
  167615. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167616. : compptr->last_col_width;
  167617. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167618. if (coef->iMCU_row_num < last_iMCU_row ||
  167619. yindex+yoffset < compptr->last_row_height) {
  167620. /* Fill in pointers to real blocks in this row */
  167621. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167622. for (xindex = 0; xindex < blockcnt; xindex++)
  167623. MCU_buffer[blkn++] = buffer_ptr++;
  167624. } else {
  167625. /* At bottom of image, need a whole row of dummy blocks */
  167626. xindex = 0;
  167627. }
  167628. /* Fill in any dummy blocks needed in this row.
  167629. * Dummy blocks are filled in the same way as in jccoefct.c:
  167630. * all zeroes in the AC entries, DC entries equal to previous
  167631. * block's DC value. The init routine has already zeroed the
  167632. * AC entries, so we need only set the DC entries correctly.
  167633. */
  167634. for (; xindex < compptr->MCU_width; xindex++) {
  167635. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167636. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167637. blkn++;
  167638. }
  167639. }
  167640. }
  167641. /* Try to write the MCU. */
  167642. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167643. /* Suspension forced; update state counters and exit */
  167644. coef->MCU_vert_offset = yoffset;
  167645. coef->mcu_ctr = MCU_col_num;
  167646. return FALSE;
  167647. }
  167648. }
  167649. /* Completed an MCU row, but perhaps not an iMCU row */
  167650. coef->mcu_ctr = 0;
  167651. }
  167652. /* Completed the iMCU row, advance counters for next one */
  167653. coef->iMCU_row_num++;
  167654. start_iMCU_row2(cinfo);
  167655. return TRUE;
  167656. }
  167657. /*
  167658. * Initialize coefficient buffer controller.
  167659. *
  167660. * Each passed coefficient array must be the right size for that
  167661. * coefficient: width_in_blocks wide and height_in_blocks high,
  167662. * with unitheight at least v_samp_factor.
  167663. */
  167664. LOCAL(void)
  167665. transencode_coef_controller (j_compress_ptr cinfo,
  167666. jvirt_barray_ptr * coef_arrays)
  167667. {
  167668. my_coef_ptr2 coef;
  167669. JBLOCKROW buffer;
  167670. int i;
  167671. coef = (my_coef_ptr2)
  167672. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167673. SIZEOF(my_coef_controller2));
  167674. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167675. coef->pub.start_pass = start_pass_coef2;
  167676. coef->pub.compress_data = compress_output2;
  167677. /* Save pointer to virtual arrays */
  167678. coef->whole_image = coef_arrays;
  167679. /* Allocate and pre-zero space for dummy DCT blocks. */
  167680. buffer = (JBLOCKROW)
  167681. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167682. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167683. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167684. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167685. coef->dummy_buffer[i] = buffer + i;
  167686. }
  167687. }
  167688. /*** End of inlined file: jctrans.c ***/
  167689. /*** Start of inlined file: jdapistd.c ***/
  167690. #define JPEG_INTERNALS
  167691. /* Forward declarations */
  167692. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167693. /*
  167694. * Decompression initialization.
  167695. * jpeg_read_header must be completed before calling this.
  167696. *
  167697. * If a multipass operating mode was selected, this will do all but the
  167698. * last pass, and thus may take a great deal of time.
  167699. *
  167700. * Returns FALSE if suspended. The return value need be inspected only if
  167701. * a suspending data source is used.
  167702. */
  167703. GLOBAL(boolean)
  167704. jpeg_start_decompress (j_decompress_ptr cinfo)
  167705. {
  167706. if (cinfo->global_state == DSTATE_READY) {
  167707. /* First call: initialize master control, select active modules */
  167708. jinit_master_decompress(cinfo);
  167709. if (cinfo->buffered_image) {
  167710. /* No more work here; expecting jpeg_start_output next */
  167711. cinfo->global_state = DSTATE_BUFIMAGE;
  167712. return TRUE;
  167713. }
  167714. cinfo->global_state = DSTATE_PRELOAD;
  167715. }
  167716. if (cinfo->global_state == DSTATE_PRELOAD) {
  167717. /* If file has multiple scans, absorb them all into the coef buffer */
  167718. if (cinfo->inputctl->has_multiple_scans) {
  167719. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167720. for (;;) {
  167721. int retcode;
  167722. /* Call progress monitor hook if present */
  167723. if (cinfo->progress != NULL)
  167724. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167725. /* Absorb some more input */
  167726. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167727. if (retcode == JPEG_SUSPENDED)
  167728. return FALSE;
  167729. if (retcode == JPEG_REACHED_EOI)
  167730. break;
  167731. /* Advance progress counter if appropriate */
  167732. if (cinfo->progress != NULL &&
  167733. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167734. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167735. /* jdmaster underestimated number of scans; ratchet up one scan */
  167736. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167737. }
  167738. }
  167739. }
  167740. #else
  167741. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167742. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167743. }
  167744. cinfo->output_scan_number = cinfo->input_scan_number;
  167745. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167746. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167747. /* Perform any dummy output passes, and set up for the final pass */
  167748. return output_pass_setup(cinfo);
  167749. }
  167750. /*
  167751. * Set up for an output pass, and perform any dummy pass(es) needed.
  167752. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167753. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167754. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167755. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167756. */
  167757. LOCAL(boolean)
  167758. output_pass_setup (j_decompress_ptr cinfo)
  167759. {
  167760. if (cinfo->global_state != DSTATE_PRESCAN) {
  167761. /* First call: do pass setup */
  167762. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167763. cinfo->output_scanline = 0;
  167764. cinfo->global_state = DSTATE_PRESCAN;
  167765. }
  167766. /* Loop over any required dummy passes */
  167767. while (cinfo->master->is_dummy_pass) {
  167768. #ifdef QUANT_2PASS_SUPPORTED
  167769. /* Crank through the dummy pass */
  167770. while (cinfo->output_scanline < cinfo->output_height) {
  167771. JDIMENSION last_scanline;
  167772. /* Call progress monitor hook if present */
  167773. if (cinfo->progress != NULL) {
  167774. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167775. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167776. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167777. }
  167778. /* Process some data */
  167779. last_scanline = cinfo->output_scanline;
  167780. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167781. &cinfo->output_scanline, (JDIMENSION) 0);
  167782. if (cinfo->output_scanline == last_scanline)
  167783. return FALSE; /* No progress made, must suspend */
  167784. }
  167785. /* Finish up dummy pass, and set up for another one */
  167786. (*cinfo->master->finish_output_pass) (cinfo);
  167787. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167788. cinfo->output_scanline = 0;
  167789. #else
  167790. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167791. #endif /* QUANT_2PASS_SUPPORTED */
  167792. }
  167793. /* Ready for application to drive output pass through
  167794. * jpeg_read_scanlines or jpeg_read_raw_data.
  167795. */
  167796. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167797. return TRUE;
  167798. }
  167799. /*
  167800. * Read some scanlines of data from the JPEG decompressor.
  167801. *
  167802. * The return value will be the number of lines actually read.
  167803. * This may be less than the number requested in several cases,
  167804. * including bottom of image, data source suspension, and operating
  167805. * modes that emit multiple scanlines at a time.
  167806. *
  167807. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167808. * this likely signals an application programmer error. However,
  167809. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167810. */
  167811. GLOBAL(JDIMENSION)
  167812. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167813. JDIMENSION max_lines)
  167814. {
  167815. JDIMENSION row_ctr;
  167816. if (cinfo->global_state != DSTATE_SCANNING)
  167817. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167818. if (cinfo->output_scanline >= cinfo->output_height) {
  167819. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167820. return 0;
  167821. }
  167822. /* Call progress monitor hook if present */
  167823. if (cinfo->progress != NULL) {
  167824. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167825. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167826. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167827. }
  167828. /* Process some data */
  167829. row_ctr = 0;
  167830. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167831. cinfo->output_scanline += row_ctr;
  167832. return row_ctr;
  167833. }
  167834. /*
  167835. * Alternate entry point to read raw data.
  167836. * Processes exactly one iMCU row per call, unless suspended.
  167837. */
  167838. GLOBAL(JDIMENSION)
  167839. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167840. JDIMENSION max_lines)
  167841. {
  167842. JDIMENSION lines_per_iMCU_row;
  167843. if (cinfo->global_state != DSTATE_RAW_OK)
  167844. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167845. if (cinfo->output_scanline >= cinfo->output_height) {
  167846. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167847. return 0;
  167848. }
  167849. /* Call progress monitor hook if present */
  167850. if (cinfo->progress != NULL) {
  167851. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167852. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167853. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167854. }
  167855. /* Verify that at least one iMCU row can be returned. */
  167856. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167857. if (max_lines < lines_per_iMCU_row)
  167858. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167859. /* Decompress directly into user's buffer. */
  167860. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167861. return 0; /* suspension forced, can do nothing more */
  167862. /* OK, we processed one iMCU row. */
  167863. cinfo->output_scanline += lines_per_iMCU_row;
  167864. return lines_per_iMCU_row;
  167865. }
  167866. /* Additional entry points for buffered-image mode. */
  167867. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167868. /*
  167869. * Initialize for an output pass in buffered-image mode.
  167870. */
  167871. GLOBAL(boolean)
  167872. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167873. {
  167874. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167875. cinfo->global_state != DSTATE_PRESCAN)
  167876. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167877. /* Limit scan number to valid range */
  167878. if (scan_number <= 0)
  167879. scan_number = 1;
  167880. if (cinfo->inputctl->eoi_reached &&
  167881. scan_number > cinfo->input_scan_number)
  167882. scan_number = cinfo->input_scan_number;
  167883. cinfo->output_scan_number = scan_number;
  167884. /* Perform any dummy output passes, and set up for the real pass */
  167885. return output_pass_setup(cinfo);
  167886. }
  167887. /*
  167888. * Finish up after an output pass in buffered-image mode.
  167889. *
  167890. * Returns FALSE if suspended. The return value need be inspected only if
  167891. * a suspending data source is used.
  167892. */
  167893. GLOBAL(boolean)
  167894. jpeg_finish_output (j_decompress_ptr cinfo)
  167895. {
  167896. if ((cinfo->global_state == DSTATE_SCANNING ||
  167897. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167898. /* Terminate this pass. */
  167899. /* We do not require the whole pass to have been completed. */
  167900. (*cinfo->master->finish_output_pass) (cinfo);
  167901. cinfo->global_state = DSTATE_BUFPOST;
  167902. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167903. /* BUFPOST = repeat call after a suspension, anything else is error */
  167904. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167905. }
  167906. /* Read markers looking for SOS or EOI */
  167907. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167908. ! cinfo->inputctl->eoi_reached) {
  167909. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167910. return FALSE; /* Suspend, come back later */
  167911. }
  167912. cinfo->global_state = DSTATE_BUFIMAGE;
  167913. return TRUE;
  167914. }
  167915. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167916. /*** End of inlined file: jdapistd.c ***/
  167917. /*** Start of inlined file: jdapimin.c ***/
  167918. #define JPEG_INTERNALS
  167919. /*
  167920. * Initialization of a JPEG decompression object.
  167921. * The error manager must already be set up (in case memory manager fails).
  167922. */
  167923. GLOBAL(void)
  167924. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167925. {
  167926. int i;
  167927. /* Guard against version mismatches between library and caller. */
  167928. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167929. if (version != JPEG_LIB_VERSION)
  167930. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167931. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167932. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167933. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167934. /* For debugging purposes, we zero the whole master structure.
  167935. * But the application has already set the err pointer, and may have set
  167936. * client_data, so we have to save and restore those fields.
  167937. * Note: if application hasn't set client_data, tools like Purify may
  167938. * complain here.
  167939. */
  167940. {
  167941. struct jpeg_error_mgr * err = cinfo->err;
  167942. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167943. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167944. cinfo->err = err;
  167945. cinfo->client_data = client_data;
  167946. }
  167947. cinfo->is_decompressor = TRUE;
  167948. /* Initialize a memory manager instance for this object */
  167949. jinit_memory_mgr((j_common_ptr) cinfo);
  167950. /* Zero out pointers to permanent structures. */
  167951. cinfo->progress = NULL;
  167952. cinfo->src = NULL;
  167953. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167954. cinfo->quant_tbl_ptrs[i] = NULL;
  167955. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167956. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167957. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167958. }
  167959. /* Initialize marker processor so application can override methods
  167960. * for COM, APPn markers before calling jpeg_read_header.
  167961. */
  167962. cinfo->marker_list = NULL;
  167963. jinit_marker_reader(cinfo);
  167964. /* And initialize the overall input controller. */
  167965. jinit_input_controller(cinfo);
  167966. /* OK, I'm ready */
  167967. cinfo->global_state = DSTATE_START;
  167968. }
  167969. /*
  167970. * Destruction of a JPEG decompression object
  167971. */
  167972. GLOBAL(void)
  167973. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167974. {
  167975. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167976. }
  167977. /*
  167978. * Abort processing of a JPEG decompression operation,
  167979. * but don't destroy the object itself.
  167980. */
  167981. GLOBAL(void)
  167982. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167983. {
  167984. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167985. }
  167986. /*
  167987. * Set default decompression parameters.
  167988. */
  167989. LOCAL(void)
  167990. default_decompress_parms (j_decompress_ptr cinfo)
  167991. {
  167992. /* Guess the input colorspace, and set output colorspace accordingly. */
  167993. /* (Wish JPEG committee had provided a real way to specify this...) */
  167994. /* Note application may override our guesses. */
  167995. switch (cinfo->num_components) {
  167996. case 1:
  167997. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167998. cinfo->out_color_space = JCS_GRAYSCALE;
  167999. break;
  168000. case 3:
  168001. if (cinfo->saw_JFIF_marker) {
  168002. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  168003. } else if (cinfo->saw_Adobe_marker) {
  168004. switch (cinfo->Adobe_transform) {
  168005. case 0:
  168006. cinfo->jpeg_color_space = JCS_RGB;
  168007. break;
  168008. case 1:
  168009. cinfo->jpeg_color_space = JCS_YCbCr;
  168010. break;
  168011. default:
  168012. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168013. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168014. break;
  168015. }
  168016. } else {
  168017. /* Saw no special markers, try to guess from the component IDs */
  168018. int cid0 = cinfo->comp_info[0].component_id;
  168019. int cid1 = cinfo->comp_info[1].component_id;
  168020. int cid2 = cinfo->comp_info[2].component_id;
  168021. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  168022. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  168023. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  168024. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  168025. else {
  168026. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  168027. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168028. }
  168029. }
  168030. /* Always guess RGB is proper output colorspace. */
  168031. cinfo->out_color_space = JCS_RGB;
  168032. break;
  168033. case 4:
  168034. if (cinfo->saw_Adobe_marker) {
  168035. switch (cinfo->Adobe_transform) {
  168036. case 0:
  168037. cinfo->jpeg_color_space = JCS_CMYK;
  168038. break;
  168039. case 2:
  168040. cinfo->jpeg_color_space = JCS_YCCK;
  168041. break;
  168042. default:
  168043. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168044. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  168045. break;
  168046. }
  168047. } else {
  168048. /* No special markers, assume straight CMYK. */
  168049. cinfo->jpeg_color_space = JCS_CMYK;
  168050. }
  168051. cinfo->out_color_space = JCS_CMYK;
  168052. break;
  168053. default:
  168054. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168055. cinfo->out_color_space = JCS_UNKNOWN;
  168056. break;
  168057. }
  168058. /* Set defaults for other decompression parameters. */
  168059. cinfo->scale_num = 1; /* 1:1 scaling */
  168060. cinfo->scale_denom = 1;
  168061. cinfo->output_gamma = 1.0;
  168062. cinfo->buffered_image = FALSE;
  168063. cinfo->raw_data_out = FALSE;
  168064. cinfo->dct_method = JDCT_DEFAULT;
  168065. cinfo->do_fancy_upsampling = TRUE;
  168066. cinfo->do_block_smoothing = TRUE;
  168067. cinfo->quantize_colors = FALSE;
  168068. /* We set these in case application only sets quantize_colors. */
  168069. cinfo->dither_mode = JDITHER_FS;
  168070. #ifdef QUANT_2PASS_SUPPORTED
  168071. cinfo->two_pass_quantize = TRUE;
  168072. #else
  168073. cinfo->two_pass_quantize = FALSE;
  168074. #endif
  168075. cinfo->desired_number_of_colors = 256;
  168076. cinfo->colormap = NULL;
  168077. /* Initialize for no mode change in buffered-image mode. */
  168078. cinfo->enable_1pass_quant = FALSE;
  168079. cinfo->enable_external_quant = FALSE;
  168080. cinfo->enable_2pass_quant = FALSE;
  168081. }
  168082. /*
  168083. * Decompression startup: read start of JPEG datastream to see what's there.
  168084. * Need only initialize JPEG object and supply a data source before calling.
  168085. *
  168086. * This routine will read as far as the first SOS marker (ie, actual start of
  168087. * compressed data), and will save all tables and parameters in the JPEG
  168088. * object. It will also initialize the decompression parameters to default
  168089. * values, and finally return JPEG_HEADER_OK. On return, the application may
  168090. * adjust the decompression parameters and then call jpeg_start_decompress.
  168091. * (Or, if the application only wanted to determine the image parameters,
  168092. * the data need not be decompressed. In that case, call jpeg_abort or
  168093. * jpeg_destroy to release any temporary space.)
  168094. * If an abbreviated (tables only) datastream is presented, the routine will
  168095. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  168096. * re-use the JPEG object to read the abbreviated image datastream(s).
  168097. * It is unnecessary (but OK) to call jpeg_abort in this case.
  168098. * The JPEG_SUSPENDED return code only occurs if the data source module
  168099. * requests suspension of the decompressor. In this case the application
  168100. * should load more source data and then re-call jpeg_read_header to resume
  168101. * processing.
  168102. * If a non-suspending data source is used and require_image is TRUE, then the
  168103. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  168104. *
  168105. * This routine is now just a front end to jpeg_consume_input, with some
  168106. * extra error checking.
  168107. */
  168108. GLOBAL(int)
  168109. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  168110. {
  168111. int retcode;
  168112. if (cinfo->global_state != DSTATE_START &&
  168113. cinfo->global_state != DSTATE_INHEADER)
  168114. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168115. retcode = jpeg_consume_input(cinfo);
  168116. switch (retcode) {
  168117. case JPEG_REACHED_SOS:
  168118. retcode = JPEG_HEADER_OK;
  168119. break;
  168120. case JPEG_REACHED_EOI:
  168121. if (require_image) /* Complain if application wanted an image */
  168122. ERREXIT(cinfo, JERR_NO_IMAGE);
  168123. /* Reset to start state; it would be safer to require the application to
  168124. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168125. * A side effect is to free any temporary memory (there shouldn't be any).
  168126. */
  168127. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168128. retcode = JPEG_HEADER_TABLES_ONLY;
  168129. break;
  168130. case JPEG_SUSPENDED:
  168131. /* no work */
  168132. break;
  168133. }
  168134. return retcode;
  168135. }
  168136. /*
  168137. * Consume data in advance of what the decompressor requires.
  168138. * This can be called at any time once the decompressor object has
  168139. * been created and a data source has been set up.
  168140. *
  168141. * This routine is essentially a state machine that handles a couple
  168142. * of critical state-transition actions, namely initial setup and
  168143. * transition from header scanning to ready-for-start_decompress.
  168144. * All the actual input is done via the input controller's consume_input
  168145. * method.
  168146. */
  168147. GLOBAL(int)
  168148. jpeg_consume_input (j_decompress_ptr cinfo)
  168149. {
  168150. int retcode = JPEG_SUSPENDED;
  168151. /* NB: every possible DSTATE value should be listed in this switch */
  168152. switch (cinfo->global_state) {
  168153. case DSTATE_START:
  168154. /* Start-of-datastream actions: reset appropriate modules */
  168155. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168156. /* Initialize application's data source module */
  168157. (*cinfo->src->init_source) (cinfo);
  168158. cinfo->global_state = DSTATE_INHEADER;
  168159. /*FALLTHROUGH*/
  168160. case DSTATE_INHEADER:
  168161. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168162. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168163. /* Set up default parameters based on header data */
  168164. default_decompress_parms(cinfo);
  168165. /* Set global state: ready for start_decompress */
  168166. cinfo->global_state = DSTATE_READY;
  168167. }
  168168. break;
  168169. case DSTATE_READY:
  168170. /* Can't advance past first SOS until start_decompress is called */
  168171. retcode = JPEG_REACHED_SOS;
  168172. break;
  168173. case DSTATE_PRELOAD:
  168174. case DSTATE_PRESCAN:
  168175. case DSTATE_SCANNING:
  168176. case DSTATE_RAW_OK:
  168177. case DSTATE_BUFIMAGE:
  168178. case DSTATE_BUFPOST:
  168179. case DSTATE_STOPPING:
  168180. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168181. break;
  168182. default:
  168183. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168184. }
  168185. return retcode;
  168186. }
  168187. /*
  168188. * Have we finished reading the input file?
  168189. */
  168190. GLOBAL(boolean)
  168191. jpeg_input_complete (j_decompress_ptr cinfo)
  168192. {
  168193. /* Check for valid jpeg object */
  168194. if (cinfo->global_state < DSTATE_START ||
  168195. cinfo->global_state > DSTATE_STOPPING)
  168196. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168197. return cinfo->inputctl->eoi_reached;
  168198. }
  168199. /*
  168200. * Is there more than one scan?
  168201. */
  168202. GLOBAL(boolean)
  168203. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168204. {
  168205. /* Only valid after jpeg_read_header completes */
  168206. if (cinfo->global_state < DSTATE_READY ||
  168207. cinfo->global_state > DSTATE_STOPPING)
  168208. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168209. return cinfo->inputctl->has_multiple_scans;
  168210. }
  168211. /*
  168212. * Finish JPEG decompression.
  168213. *
  168214. * This will normally just verify the file trailer and release temp storage.
  168215. *
  168216. * Returns FALSE if suspended. The return value need be inspected only if
  168217. * a suspending data source is used.
  168218. */
  168219. GLOBAL(boolean)
  168220. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168221. {
  168222. if ((cinfo->global_state == DSTATE_SCANNING ||
  168223. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168224. /* Terminate final pass of non-buffered mode */
  168225. if (cinfo->output_scanline < cinfo->output_height)
  168226. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168227. (*cinfo->master->finish_output_pass) (cinfo);
  168228. cinfo->global_state = DSTATE_STOPPING;
  168229. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168230. /* Finishing after a buffered-image operation */
  168231. cinfo->global_state = DSTATE_STOPPING;
  168232. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168233. /* STOPPING = repeat call after a suspension, anything else is error */
  168234. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168235. }
  168236. /* Read until EOI */
  168237. while (! cinfo->inputctl->eoi_reached) {
  168238. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168239. return FALSE; /* Suspend, come back later */
  168240. }
  168241. /* Do final cleanup */
  168242. (*cinfo->src->term_source) (cinfo);
  168243. /* We can use jpeg_abort to release memory and reset global_state */
  168244. jpeg_abort((j_common_ptr) cinfo);
  168245. return TRUE;
  168246. }
  168247. /*** End of inlined file: jdapimin.c ***/
  168248. /*** Start of inlined file: jdatasrc.c ***/
  168249. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168250. /*** Start of inlined file: jerror.h ***/
  168251. /*
  168252. * To define the enum list of message codes, include this file without
  168253. * defining macro JMESSAGE. To create a message string table, include it
  168254. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168255. */
  168256. #ifndef JMESSAGE
  168257. #ifndef JERROR_H
  168258. /* First time through, define the enum list */
  168259. #define JMAKE_ENUM_LIST
  168260. #else
  168261. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168262. #define JMESSAGE(code,string)
  168263. #endif /* JERROR_H */
  168264. #endif /* JMESSAGE */
  168265. #ifdef JMAKE_ENUM_LIST
  168266. typedef enum {
  168267. #define JMESSAGE(code,string) code ,
  168268. #endif /* JMAKE_ENUM_LIST */
  168269. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168270. /* For maintenance convenience, list is alphabetical by message code name */
  168271. JMESSAGE(JERR_ARITH_NOTIMPL,
  168272. "Sorry, there are legal restrictions on arithmetic coding")
  168273. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168274. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168275. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168276. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168277. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168278. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168279. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168280. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168281. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168282. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168283. JMESSAGE(JERR_BAD_LIB_VERSION,
  168284. "Wrong JPEG library version: library is %d, caller expects %d")
  168285. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168286. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168287. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168288. JMESSAGE(JERR_BAD_PROGRESSION,
  168289. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168290. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168291. "Invalid progressive parameters at scan script entry %d")
  168292. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168293. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168294. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168295. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168296. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168297. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168298. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168299. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168300. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168301. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168302. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168303. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168304. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168305. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168306. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168307. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168308. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168309. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168310. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168311. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168312. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168313. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168314. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168315. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168316. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168317. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168318. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168319. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168320. "Cannot transcode due to multiple use of quantization table %d")
  168321. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168322. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168323. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168324. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168325. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168326. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168327. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168328. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168329. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168330. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168331. JMESSAGE(JERR_QUANT_COMPONENTS,
  168332. "Cannot quantize more than %d color components")
  168333. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168334. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168335. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168336. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168337. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168338. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168339. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168340. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168341. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168342. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168343. JMESSAGE(JERR_TFILE_WRITE,
  168344. "Write failed on temporary file --- out of disk space?")
  168345. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168346. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168347. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168348. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168349. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168350. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168351. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168352. JMESSAGE(JMSG_VERSION, JVERSION)
  168353. JMESSAGE(JTRC_16BIT_TABLES,
  168354. "Caution: quantization tables are too coarse for baseline JPEG")
  168355. JMESSAGE(JTRC_ADOBE,
  168356. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168357. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168358. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168359. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168360. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168361. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168362. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168363. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168364. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168365. JMESSAGE(JTRC_EOI, "End Of Image")
  168366. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168367. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168368. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168369. "Warning: thumbnail image size does not match data length %u")
  168370. JMESSAGE(JTRC_JFIF_EXTENSION,
  168371. "JFIF extension marker: type 0x%02x, length %u")
  168372. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168373. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168374. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168375. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168376. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168377. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168378. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168379. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168380. JMESSAGE(JTRC_RST, "RST%d")
  168381. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168382. "Smoothing not supported with nonstandard sampling ratios")
  168383. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168384. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168385. JMESSAGE(JTRC_SOI, "Start of Image")
  168386. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168387. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168388. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168389. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168390. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168391. JMESSAGE(JTRC_THUMB_JPEG,
  168392. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168393. JMESSAGE(JTRC_THUMB_PALETTE,
  168394. "JFIF extension marker: palette thumbnail image, length %u")
  168395. JMESSAGE(JTRC_THUMB_RGB,
  168396. "JFIF extension marker: RGB thumbnail image, length %u")
  168397. JMESSAGE(JTRC_UNKNOWN_IDS,
  168398. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168399. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168400. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168401. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168402. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168403. "Inconsistent progression sequence for component %d coefficient %d")
  168404. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168405. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168406. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168407. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168408. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168409. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168410. JMESSAGE(JWRN_MUST_RESYNC,
  168411. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168412. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168413. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168414. #ifdef JMAKE_ENUM_LIST
  168415. JMSG_LASTMSGCODE
  168416. } J_MESSAGE_CODE;
  168417. #undef JMAKE_ENUM_LIST
  168418. #endif /* JMAKE_ENUM_LIST */
  168419. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168420. #undef JMESSAGE
  168421. #ifndef JERROR_H
  168422. #define JERROR_H
  168423. /* Macros to simplify using the error and trace message stuff */
  168424. /* The first parameter is either type of cinfo pointer */
  168425. /* Fatal errors (print message and exit) */
  168426. #define ERREXIT(cinfo,code) \
  168427. ((cinfo)->err->msg_code = (code), \
  168428. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168429. #define ERREXIT1(cinfo,code,p1) \
  168430. ((cinfo)->err->msg_code = (code), \
  168431. (cinfo)->err->msg_parm.i[0] = (p1), \
  168432. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168433. #define ERREXIT2(cinfo,code,p1,p2) \
  168434. ((cinfo)->err->msg_code = (code), \
  168435. (cinfo)->err->msg_parm.i[0] = (p1), \
  168436. (cinfo)->err->msg_parm.i[1] = (p2), \
  168437. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168438. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168439. ((cinfo)->err->msg_code = (code), \
  168440. (cinfo)->err->msg_parm.i[0] = (p1), \
  168441. (cinfo)->err->msg_parm.i[1] = (p2), \
  168442. (cinfo)->err->msg_parm.i[2] = (p3), \
  168443. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168444. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168445. ((cinfo)->err->msg_code = (code), \
  168446. (cinfo)->err->msg_parm.i[0] = (p1), \
  168447. (cinfo)->err->msg_parm.i[1] = (p2), \
  168448. (cinfo)->err->msg_parm.i[2] = (p3), \
  168449. (cinfo)->err->msg_parm.i[3] = (p4), \
  168450. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168451. #define ERREXITS(cinfo,code,str) \
  168452. ((cinfo)->err->msg_code = (code), \
  168453. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168454. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168455. #define MAKESTMT(stuff) do { stuff } while (0)
  168456. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168457. #define WARNMS(cinfo,code) \
  168458. ((cinfo)->err->msg_code = (code), \
  168459. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168460. #define WARNMS1(cinfo,code,p1) \
  168461. ((cinfo)->err->msg_code = (code), \
  168462. (cinfo)->err->msg_parm.i[0] = (p1), \
  168463. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168464. #define WARNMS2(cinfo,code,p1,p2) \
  168465. ((cinfo)->err->msg_code = (code), \
  168466. (cinfo)->err->msg_parm.i[0] = (p1), \
  168467. (cinfo)->err->msg_parm.i[1] = (p2), \
  168468. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168469. /* Informational/debugging messages */
  168470. #define TRACEMS(cinfo,lvl,code) \
  168471. ((cinfo)->err->msg_code = (code), \
  168472. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168473. #define TRACEMS1(cinfo,lvl,code,p1) \
  168474. ((cinfo)->err->msg_code = (code), \
  168475. (cinfo)->err->msg_parm.i[0] = (p1), \
  168476. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168477. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168478. ((cinfo)->err->msg_code = (code), \
  168479. (cinfo)->err->msg_parm.i[0] = (p1), \
  168480. (cinfo)->err->msg_parm.i[1] = (p2), \
  168481. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168482. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168483. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168484. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168485. (cinfo)->err->msg_code = (code); \
  168486. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168487. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168488. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168489. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168490. (cinfo)->err->msg_code = (code); \
  168491. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168492. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168493. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168494. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168495. _mp[4] = (p5); \
  168496. (cinfo)->err->msg_code = (code); \
  168497. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168498. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168499. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168500. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168501. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168502. (cinfo)->err->msg_code = (code); \
  168503. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168504. #define TRACEMSS(cinfo,lvl,code,str) \
  168505. ((cinfo)->err->msg_code = (code), \
  168506. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168507. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168508. #endif /* JERROR_H */
  168509. /*** End of inlined file: jerror.h ***/
  168510. /* Expanded data source object for stdio input */
  168511. typedef struct {
  168512. struct jpeg_source_mgr pub; /* public fields */
  168513. FILE * infile; /* source stream */
  168514. JOCTET * buffer; /* start of buffer */
  168515. boolean start_of_file; /* have we gotten any data yet? */
  168516. } my_source_mgr;
  168517. typedef my_source_mgr * my_src_ptr;
  168518. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168519. /*
  168520. * Initialize source --- called by jpeg_read_header
  168521. * before any data is actually read.
  168522. */
  168523. METHODDEF(void)
  168524. init_source (j_decompress_ptr cinfo)
  168525. {
  168526. my_src_ptr src = (my_src_ptr) cinfo->src;
  168527. /* We reset the empty-input-file flag for each image,
  168528. * but we don't clear the input buffer.
  168529. * This is correct behavior for reading a series of images from one source.
  168530. */
  168531. src->start_of_file = TRUE;
  168532. }
  168533. /*
  168534. * Fill the input buffer --- called whenever buffer is emptied.
  168535. *
  168536. * In typical applications, this should read fresh data into the buffer
  168537. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168538. * reset the pointer & count to the start of the buffer, and return TRUE
  168539. * indicating that the buffer has been reloaded. It is not necessary to
  168540. * fill the buffer entirely, only to obtain at least one more byte.
  168541. *
  168542. * There is no such thing as an EOF return. If the end of the file has been
  168543. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168544. * the buffer. In most cases, generating a warning message and inserting a
  168545. * fake EOI marker is the best course of action --- this will allow the
  168546. * decompressor to output however much of the image is there. However,
  168547. * the resulting error message is misleading if the real problem is an empty
  168548. * input file, so we handle that case specially.
  168549. *
  168550. * In applications that need to be able to suspend compression due to input
  168551. * not being available yet, a FALSE return indicates that no more data can be
  168552. * obtained right now, but more may be forthcoming later. In this situation,
  168553. * the decompressor will return to its caller (with an indication of the
  168554. * number of scanlines it has read, if any). The application should resume
  168555. * decompression after it has loaded more data into the input buffer. Note
  168556. * that there are substantial restrictions on the use of suspension --- see
  168557. * the documentation.
  168558. *
  168559. * When suspending, the decompressor will back up to a convenient restart point
  168560. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168561. * indicate where the restart point will be if the current call returns FALSE.
  168562. * Data beyond this point must be rescanned after resumption, so move it to
  168563. * the front of the buffer rather than discarding it.
  168564. */
  168565. METHODDEF(boolean)
  168566. fill_input_buffer (j_decompress_ptr cinfo)
  168567. {
  168568. my_src_ptr src = (my_src_ptr) cinfo->src;
  168569. size_t nbytes;
  168570. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168571. if (nbytes <= 0) {
  168572. if (src->start_of_file) /* Treat empty input file as fatal error */
  168573. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168574. WARNMS(cinfo, JWRN_JPEG_EOF);
  168575. /* Insert a fake EOI marker */
  168576. src->buffer[0] = (JOCTET) 0xFF;
  168577. src->buffer[1] = (JOCTET) JPEG_EOI;
  168578. nbytes = 2;
  168579. }
  168580. src->pub.next_input_byte = src->buffer;
  168581. src->pub.bytes_in_buffer = nbytes;
  168582. src->start_of_file = FALSE;
  168583. return TRUE;
  168584. }
  168585. /*
  168586. * Skip data --- used to skip over a potentially large amount of
  168587. * uninteresting data (such as an APPn marker).
  168588. *
  168589. * Writers of suspendable-input applications must note that skip_input_data
  168590. * is not granted the right to give a suspension return. If the skip extends
  168591. * beyond the data currently in the buffer, the buffer can be marked empty so
  168592. * that the next read will cause a fill_input_buffer call that can suspend.
  168593. * Arranging for additional bytes to be discarded before reloading the input
  168594. * buffer is the application writer's problem.
  168595. */
  168596. METHODDEF(void)
  168597. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168598. {
  168599. my_src_ptr src = (my_src_ptr) cinfo->src;
  168600. /* Just a dumb implementation for now. Could use fseek() except
  168601. * it doesn't work on pipes. Not clear that being smart is worth
  168602. * any trouble anyway --- large skips are infrequent.
  168603. */
  168604. if (num_bytes > 0) {
  168605. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168606. num_bytes -= (long) src->pub.bytes_in_buffer;
  168607. (void) fill_input_buffer(cinfo);
  168608. /* note we assume that fill_input_buffer will never return FALSE,
  168609. * so suspension need not be handled.
  168610. */
  168611. }
  168612. src->pub.next_input_byte += (size_t) num_bytes;
  168613. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168614. }
  168615. }
  168616. /*
  168617. * An additional method that can be provided by data source modules is the
  168618. * resync_to_restart method for error recovery in the presence of RST markers.
  168619. * For the moment, this source module just uses the default resync method
  168620. * provided by the JPEG library. That method assumes that no backtracking
  168621. * is possible.
  168622. */
  168623. /*
  168624. * Terminate source --- called by jpeg_finish_decompress
  168625. * after all data has been read. Often a no-op.
  168626. *
  168627. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168628. * application must deal with any cleanup that should happen even
  168629. * for error exit.
  168630. */
  168631. METHODDEF(void)
  168632. term_source (j_decompress_ptr)
  168633. {
  168634. /* no work necessary here */
  168635. }
  168636. /*
  168637. * Prepare for input from a stdio stream.
  168638. * The caller must have already opened the stream, and is responsible
  168639. * for closing it after finishing decompression.
  168640. */
  168641. GLOBAL(void)
  168642. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168643. {
  168644. my_src_ptr src;
  168645. /* The source object and input buffer are made permanent so that a series
  168646. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168647. * only before the first one. (If we discarded the buffer at the end of
  168648. * one image, we'd likely lose the start of the next one.)
  168649. * This makes it unsafe to use this manager and a different source
  168650. * manager serially with the same JPEG object. Caveat programmer.
  168651. */
  168652. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168653. cinfo->src = (struct jpeg_source_mgr *)
  168654. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168655. SIZEOF(my_source_mgr));
  168656. src = (my_src_ptr) cinfo->src;
  168657. src->buffer = (JOCTET *)
  168658. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168659. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168660. }
  168661. src = (my_src_ptr) cinfo->src;
  168662. src->pub.init_source = init_source;
  168663. src->pub.fill_input_buffer = fill_input_buffer;
  168664. src->pub.skip_input_data = skip_input_data;
  168665. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168666. src->pub.term_source = term_source;
  168667. src->infile = infile;
  168668. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168669. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168670. }
  168671. /*** End of inlined file: jdatasrc.c ***/
  168672. /*** Start of inlined file: jdcoefct.c ***/
  168673. #define JPEG_INTERNALS
  168674. /* Block smoothing is only applicable for progressive JPEG, so: */
  168675. #ifndef D_PROGRESSIVE_SUPPORTED
  168676. #undef BLOCK_SMOOTHING_SUPPORTED
  168677. #endif
  168678. /* Private buffer controller object */
  168679. typedef struct {
  168680. struct jpeg_d_coef_controller pub; /* public fields */
  168681. /* These variables keep track of the current location of the input side. */
  168682. /* cinfo->input_iMCU_row is also used for this. */
  168683. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168684. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168685. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168686. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168687. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168688. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168689. * and let the entropy decoder write into that workspace each time.
  168690. * (On 80x86, the workspace is FAR even though it's not really very big;
  168691. * this is to keep the module interfaces unchanged when a large coefficient
  168692. * buffer is necessary.)
  168693. * In multi-pass modes, this array points to the current MCU's blocks
  168694. * within the virtual arrays; it is used only by the input side.
  168695. */
  168696. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168697. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168698. /* In multi-pass modes, we need a virtual block array for each component. */
  168699. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168700. #endif
  168701. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168702. /* When doing block smoothing, we latch coefficient Al values here */
  168703. int * coef_bits_latch;
  168704. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168705. #endif
  168706. } my_coef_controller3;
  168707. typedef my_coef_controller3 * my_coef_ptr3;
  168708. /* Forward declarations */
  168709. METHODDEF(int) decompress_onepass
  168710. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168711. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168712. METHODDEF(int) decompress_data
  168713. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168714. #endif
  168715. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168716. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168717. METHODDEF(int) decompress_smooth_data
  168718. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168719. #endif
  168720. LOCAL(void)
  168721. start_iMCU_row3 (j_decompress_ptr cinfo)
  168722. /* Reset within-iMCU-row counters for a new row (input side) */
  168723. {
  168724. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168725. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168726. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168727. * But at the bottom of the image, process only what's left.
  168728. */
  168729. if (cinfo->comps_in_scan > 1) {
  168730. coef->MCU_rows_per_iMCU_row = 1;
  168731. } else {
  168732. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168733. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168734. else
  168735. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168736. }
  168737. coef->MCU_ctr = 0;
  168738. coef->MCU_vert_offset = 0;
  168739. }
  168740. /*
  168741. * Initialize for an input processing pass.
  168742. */
  168743. METHODDEF(void)
  168744. start_input_pass (j_decompress_ptr cinfo)
  168745. {
  168746. cinfo->input_iMCU_row = 0;
  168747. start_iMCU_row3(cinfo);
  168748. }
  168749. /*
  168750. * Initialize for an output processing pass.
  168751. */
  168752. METHODDEF(void)
  168753. start_output_pass (j_decompress_ptr cinfo)
  168754. {
  168755. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168756. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168757. /* If multipass, check to see whether to use block smoothing on this pass */
  168758. if (coef->pub.coef_arrays != NULL) {
  168759. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168760. coef->pub.decompress_data = decompress_smooth_data;
  168761. else
  168762. coef->pub.decompress_data = decompress_data;
  168763. }
  168764. #endif
  168765. cinfo->output_iMCU_row = 0;
  168766. }
  168767. /*
  168768. * Decompress and return some data in the single-pass case.
  168769. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168770. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168771. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168772. *
  168773. * NB: output_buf contains a plane for each component in image,
  168774. * which we index according to the component's SOF position.
  168775. */
  168776. METHODDEF(int)
  168777. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168778. {
  168779. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168780. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168781. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168782. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168783. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168784. JSAMPARRAY output_ptr;
  168785. JDIMENSION start_col, output_col;
  168786. jpeg_component_info *compptr;
  168787. inverse_DCT_method_ptr inverse_DCT;
  168788. /* Loop to process as much as one whole iMCU row */
  168789. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168790. yoffset++) {
  168791. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168792. MCU_col_num++) {
  168793. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168794. jzero_far((void FAR *) coef->MCU_buffer[0],
  168795. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168796. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168797. /* Suspension forced; update state counters and exit */
  168798. coef->MCU_vert_offset = yoffset;
  168799. coef->MCU_ctr = MCU_col_num;
  168800. return JPEG_SUSPENDED;
  168801. }
  168802. /* Determine where data should go in output_buf and do the IDCT thing.
  168803. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168804. * incremented past them!). Note the inner loop relies on having
  168805. * allocated the MCU_buffer[] blocks sequentially.
  168806. */
  168807. blkn = 0; /* index of current DCT block within MCU */
  168808. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168809. compptr = cinfo->cur_comp_info[ci];
  168810. /* Don't bother to IDCT an uninteresting component. */
  168811. if (! compptr->component_needed) {
  168812. blkn += compptr->MCU_blocks;
  168813. continue;
  168814. }
  168815. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168816. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168817. : compptr->last_col_width;
  168818. output_ptr = output_buf[compptr->component_index] +
  168819. yoffset * compptr->DCT_scaled_size;
  168820. start_col = MCU_col_num * compptr->MCU_sample_width;
  168821. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168822. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168823. yoffset+yindex < compptr->last_row_height) {
  168824. output_col = start_col;
  168825. for (xindex = 0; xindex < useful_width; xindex++) {
  168826. (*inverse_DCT) (cinfo, compptr,
  168827. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168828. output_ptr, output_col);
  168829. output_col += compptr->DCT_scaled_size;
  168830. }
  168831. }
  168832. blkn += compptr->MCU_width;
  168833. output_ptr += compptr->DCT_scaled_size;
  168834. }
  168835. }
  168836. }
  168837. /* Completed an MCU row, but perhaps not an iMCU row */
  168838. coef->MCU_ctr = 0;
  168839. }
  168840. /* Completed the iMCU row, advance counters for next one */
  168841. cinfo->output_iMCU_row++;
  168842. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168843. start_iMCU_row3(cinfo);
  168844. return JPEG_ROW_COMPLETED;
  168845. }
  168846. /* Completed the scan */
  168847. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168848. return JPEG_SCAN_COMPLETED;
  168849. }
  168850. /*
  168851. * Dummy consume-input routine for single-pass operation.
  168852. */
  168853. METHODDEF(int)
  168854. dummy_consume_data (j_decompress_ptr)
  168855. {
  168856. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168857. }
  168858. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168859. /*
  168860. * Consume input data and store it in the full-image coefficient buffer.
  168861. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168862. * ie, v_samp_factor block rows for each component in the scan.
  168863. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168864. */
  168865. METHODDEF(int)
  168866. consume_data (j_decompress_ptr cinfo)
  168867. {
  168868. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168869. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168870. int blkn, ci, xindex, yindex, yoffset;
  168871. JDIMENSION start_col;
  168872. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168873. JBLOCKROW buffer_ptr;
  168874. jpeg_component_info *compptr;
  168875. /* Align the virtual buffers for the components used in this scan. */
  168876. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168877. compptr = cinfo->cur_comp_info[ci];
  168878. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168879. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168880. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168881. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168882. /* Note: entropy decoder expects buffer to be zeroed,
  168883. * but this is handled automatically by the memory manager
  168884. * because we requested a pre-zeroed array.
  168885. */
  168886. }
  168887. /* Loop to process one whole iMCU row */
  168888. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168889. yoffset++) {
  168890. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168891. MCU_col_num++) {
  168892. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168893. blkn = 0; /* index of current DCT block within MCU */
  168894. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168895. compptr = cinfo->cur_comp_info[ci];
  168896. start_col = MCU_col_num * compptr->MCU_width;
  168897. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168898. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168899. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168900. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168901. }
  168902. }
  168903. }
  168904. /* Try to fetch the MCU. */
  168905. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168906. /* Suspension forced; update state counters and exit */
  168907. coef->MCU_vert_offset = yoffset;
  168908. coef->MCU_ctr = MCU_col_num;
  168909. return JPEG_SUSPENDED;
  168910. }
  168911. }
  168912. /* Completed an MCU row, but perhaps not an iMCU row */
  168913. coef->MCU_ctr = 0;
  168914. }
  168915. /* Completed the iMCU row, advance counters for next one */
  168916. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168917. start_iMCU_row3(cinfo);
  168918. return JPEG_ROW_COMPLETED;
  168919. }
  168920. /* Completed the scan */
  168921. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168922. return JPEG_SCAN_COMPLETED;
  168923. }
  168924. /*
  168925. * Decompress and return some data in the multi-pass case.
  168926. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168927. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168928. *
  168929. * NB: output_buf contains a plane for each component in image.
  168930. */
  168931. METHODDEF(int)
  168932. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168933. {
  168934. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168935. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168936. JDIMENSION block_num;
  168937. int ci, block_row, block_rows;
  168938. JBLOCKARRAY buffer;
  168939. JBLOCKROW buffer_ptr;
  168940. JSAMPARRAY output_ptr;
  168941. JDIMENSION output_col;
  168942. jpeg_component_info *compptr;
  168943. inverse_DCT_method_ptr inverse_DCT;
  168944. /* Force some input to be done if we are getting ahead of the input. */
  168945. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168946. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168947. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168948. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168949. return JPEG_SUSPENDED;
  168950. }
  168951. /* OK, output from the virtual arrays. */
  168952. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168953. ci++, compptr++) {
  168954. /* Don't bother to IDCT an uninteresting component. */
  168955. if (! compptr->component_needed)
  168956. continue;
  168957. /* Align the virtual buffer for this component. */
  168958. buffer = (*cinfo->mem->access_virt_barray)
  168959. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168960. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168961. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168962. /* Count non-dummy DCT block rows in this iMCU row. */
  168963. if (cinfo->output_iMCU_row < last_iMCU_row)
  168964. block_rows = compptr->v_samp_factor;
  168965. else {
  168966. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168967. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168968. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168969. }
  168970. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168971. output_ptr = output_buf[ci];
  168972. /* Loop over all DCT blocks to be processed. */
  168973. for (block_row = 0; block_row < block_rows; block_row++) {
  168974. buffer_ptr = buffer[block_row];
  168975. output_col = 0;
  168976. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168977. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168978. output_ptr, output_col);
  168979. buffer_ptr++;
  168980. output_col += compptr->DCT_scaled_size;
  168981. }
  168982. output_ptr += compptr->DCT_scaled_size;
  168983. }
  168984. }
  168985. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168986. return JPEG_ROW_COMPLETED;
  168987. return JPEG_SCAN_COMPLETED;
  168988. }
  168989. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168990. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168991. /*
  168992. * This code applies interblock smoothing as described by section K.8
  168993. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168994. * the DC values of a DCT block and its 8 neighboring blocks.
  168995. * We apply smoothing only for progressive JPEG decoding, and only if
  168996. * the coefficients it can estimate are not yet known to full precision.
  168997. */
  168998. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168999. #define Q01_POS 1
  169000. #define Q10_POS 8
  169001. #define Q20_POS 16
  169002. #define Q11_POS 9
  169003. #define Q02_POS 2
  169004. /*
  169005. * Determine whether block smoothing is applicable and safe.
  169006. * We also latch the current states of the coef_bits[] entries for the
  169007. * AC coefficients; otherwise, if the input side of the decompressor
  169008. * advances into a new scan, we might think the coefficients are known
  169009. * more accurately than they really are.
  169010. */
  169011. LOCAL(boolean)
  169012. smoothing_ok (j_decompress_ptr cinfo)
  169013. {
  169014. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169015. boolean smoothing_useful = FALSE;
  169016. int ci, coefi;
  169017. jpeg_component_info *compptr;
  169018. JQUANT_TBL * qtable;
  169019. int * coef_bits;
  169020. int * coef_bits_latch;
  169021. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  169022. return FALSE;
  169023. /* Allocate latch area if not already done */
  169024. if (coef->coef_bits_latch == NULL)
  169025. coef->coef_bits_latch = (int *)
  169026. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169027. cinfo->num_components *
  169028. (SAVED_COEFS * SIZEOF(int)));
  169029. coef_bits_latch = coef->coef_bits_latch;
  169030. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169031. ci++, compptr++) {
  169032. /* All components' quantization values must already be latched. */
  169033. if ((qtable = compptr->quant_table) == NULL)
  169034. return FALSE;
  169035. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  169036. if (qtable->quantval[0] == 0 ||
  169037. qtable->quantval[Q01_POS] == 0 ||
  169038. qtable->quantval[Q10_POS] == 0 ||
  169039. qtable->quantval[Q20_POS] == 0 ||
  169040. qtable->quantval[Q11_POS] == 0 ||
  169041. qtable->quantval[Q02_POS] == 0)
  169042. return FALSE;
  169043. /* DC values must be at least partly known for all components. */
  169044. coef_bits = cinfo->coef_bits[ci];
  169045. if (coef_bits[0] < 0)
  169046. return FALSE;
  169047. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  169048. for (coefi = 1; coefi <= 5; coefi++) {
  169049. coef_bits_latch[coefi] = coef_bits[coefi];
  169050. if (coef_bits[coefi] != 0)
  169051. smoothing_useful = TRUE;
  169052. }
  169053. coef_bits_latch += SAVED_COEFS;
  169054. }
  169055. return smoothing_useful;
  169056. }
  169057. /*
  169058. * Variant of decompress_data for use when doing block smoothing.
  169059. */
  169060. METHODDEF(int)
  169061. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169062. {
  169063. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169064. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169065. JDIMENSION block_num, last_block_column;
  169066. int ci, block_row, block_rows, access_rows;
  169067. JBLOCKARRAY buffer;
  169068. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  169069. JSAMPARRAY output_ptr;
  169070. JDIMENSION output_col;
  169071. jpeg_component_info *compptr;
  169072. inverse_DCT_method_ptr inverse_DCT;
  169073. boolean first_row, last_row;
  169074. JBLOCK workspace;
  169075. int *coef_bits;
  169076. JQUANT_TBL *quanttbl;
  169077. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  169078. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  169079. int Al, pred;
  169080. /* Force some input to be done if we are getting ahead of the input. */
  169081. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  169082. ! cinfo->inputctl->eoi_reached) {
  169083. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  169084. /* If input is working on current scan, we ordinarily want it to
  169085. * have completed the current row. But if input scan is DC,
  169086. * we want it to keep one row ahead so that next block row's DC
  169087. * values are up to date.
  169088. */
  169089. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  169090. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  169091. break;
  169092. }
  169093. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169094. return JPEG_SUSPENDED;
  169095. }
  169096. /* OK, output from the virtual arrays. */
  169097. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169098. ci++, compptr++) {
  169099. /* Don't bother to IDCT an uninteresting component. */
  169100. if (! compptr->component_needed)
  169101. continue;
  169102. /* Count non-dummy DCT block rows in this iMCU row. */
  169103. if (cinfo->output_iMCU_row < last_iMCU_row) {
  169104. block_rows = compptr->v_samp_factor;
  169105. access_rows = block_rows * 2; /* this and next iMCU row */
  169106. last_row = FALSE;
  169107. } else {
  169108. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169109. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169110. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169111. access_rows = block_rows; /* this iMCU row only */
  169112. last_row = TRUE;
  169113. }
  169114. /* Align the virtual buffer for this component. */
  169115. if (cinfo->output_iMCU_row > 0) {
  169116. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169117. buffer = (*cinfo->mem->access_virt_barray)
  169118. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169119. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169120. (JDIMENSION) access_rows, FALSE);
  169121. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169122. first_row = FALSE;
  169123. } else {
  169124. buffer = (*cinfo->mem->access_virt_barray)
  169125. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169126. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169127. first_row = TRUE;
  169128. }
  169129. /* Fetch component-dependent info */
  169130. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169131. quanttbl = compptr->quant_table;
  169132. Q00 = quanttbl->quantval[0];
  169133. Q01 = quanttbl->quantval[Q01_POS];
  169134. Q10 = quanttbl->quantval[Q10_POS];
  169135. Q20 = quanttbl->quantval[Q20_POS];
  169136. Q11 = quanttbl->quantval[Q11_POS];
  169137. Q02 = quanttbl->quantval[Q02_POS];
  169138. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169139. output_ptr = output_buf[ci];
  169140. /* Loop over all DCT blocks to be processed. */
  169141. for (block_row = 0; block_row < block_rows; block_row++) {
  169142. buffer_ptr = buffer[block_row];
  169143. if (first_row && block_row == 0)
  169144. prev_block_row = buffer_ptr;
  169145. else
  169146. prev_block_row = buffer[block_row-1];
  169147. if (last_row && block_row == block_rows-1)
  169148. next_block_row = buffer_ptr;
  169149. else
  169150. next_block_row = buffer[block_row+1];
  169151. /* We fetch the surrounding DC values using a sliding-register approach.
  169152. * Initialize all nine here so as to do the right thing on narrow pics.
  169153. */
  169154. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169155. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169156. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169157. output_col = 0;
  169158. last_block_column = compptr->width_in_blocks - 1;
  169159. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169160. /* Fetch current DCT block into workspace so we can modify it. */
  169161. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169162. /* Update DC values */
  169163. if (block_num < last_block_column) {
  169164. DC3 = (int) prev_block_row[1][0];
  169165. DC6 = (int) buffer_ptr[1][0];
  169166. DC9 = (int) next_block_row[1][0];
  169167. }
  169168. /* Compute coefficient estimates per K.8.
  169169. * An estimate is applied only if coefficient is still zero,
  169170. * and is not known to be fully accurate.
  169171. */
  169172. /* AC01 */
  169173. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169174. num = 36 * Q00 * (DC4 - DC6);
  169175. if (num >= 0) {
  169176. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169177. if (Al > 0 && pred >= (1<<Al))
  169178. pred = (1<<Al)-1;
  169179. } else {
  169180. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169181. if (Al > 0 && pred >= (1<<Al))
  169182. pred = (1<<Al)-1;
  169183. pred = -pred;
  169184. }
  169185. workspace[1] = (JCOEF) pred;
  169186. }
  169187. /* AC10 */
  169188. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169189. num = 36 * Q00 * (DC2 - DC8);
  169190. if (num >= 0) {
  169191. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169192. if (Al > 0 && pred >= (1<<Al))
  169193. pred = (1<<Al)-1;
  169194. } else {
  169195. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169196. if (Al > 0 && pred >= (1<<Al))
  169197. pred = (1<<Al)-1;
  169198. pred = -pred;
  169199. }
  169200. workspace[8] = (JCOEF) pred;
  169201. }
  169202. /* AC20 */
  169203. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169204. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169205. if (num >= 0) {
  169206. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169207. if (Al > 0 && pred >= (1<<Al))
  169208. pred = (1<<Al)-1;
  169209. } else {
  169210. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169211. if (Al > 0 && pred >= (1<<Al))
  169212. pred = (1<<Al)-1;
  169213. pred = -pred;
  169214. }
  169215. workspace[16] = (JCOEF) pred;
  169216. }
  169217. /* AC11 */
  169218. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169219. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169220. if (num >= 0) {
  169221. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169222. if (Al > 0 && pred >= (1<<Al))
  169223. pred = (1<<Al)-1;
  169224. } else {
  169225. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169226. if (Al > 0 && pred >= (1<<Al))
  169227. pred = (1<<Al)-1;
  169228. pred = -pred;
  169229. }
  169230. workspace[9] = (JCOEF) pred;
  169231. }
  169232. /* AC02 */
  169233. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169234. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169235. if (num >= 0) {
  169236. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169237. if (Al > 0 && pred >= (1<<Al))
  169238. pred = (1<<Al)-1;
  169239. } else {
  169240. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169241. if (Al > 0 && pred >= (1<<Al))
  169242. pred = (1<<Al)-1;
  169243. pred = -pred;
  169244. }
  169245. workspace[2] = (JCOEF) pred;
  169246. }
  169247. /* OK, do the IDCT */
  169248. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169249. output_ptr, output_col);
  169250. /* Advance for next column */
  169251. DC1 = DC2; DC2 = DC3;
  169252. DC4 = DC5; DC5 = DC6;
  169253. DC7 = DC8; DC8 = DC9;
  169254. buffer_ptr++, prev_block_row++, next_block_row++;
  169255. output_col += compptr->DCT_scaled_size;
  169256. }
  169257. output_ptr += compptr->DCT_scaled_size;
  169258. }
  169259. }
  169260. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169261. return JPEG_ROW_COMPLETED;
  169262. return JPEG_SCAN_COMPLETED;
  169263. }
  169264. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169265. /*
  169266. * Initialize coefficient buffer controller.
  169267. */
  169268. GLOBAL(void)
  169269. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169270. {
  169271. my_coef_ptr3 coef;
  169272. coef = (my_coef_ptr3)
  169273. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169274. SIZEOF(my_coef_controller3));
  169275. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169276. coef->pub.start_input_pass = start_input_pass;
  169277. coef->pub.start_output_pass = start_output_pass;
  169278. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169279. coef->coef_bits_latch = NULL;
  169280. #endif
  169281. /* Create the coefficient buffer. */
  169282. if (need_full_buffer) {
  169283. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169284. /* Allocate a full-image virtual array for each component, */
  169285. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169286. /* Note we ask for a pre-zeroed array. */
  169287. int ci, access_rows;
  169288. jpeg_component_info *compptr;
  169289. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169290. ci++, compptr++) {
  169291. access_rows = compptr->v_samp_factor;
  169292. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169293. /* If block smoothing could be used, need a bigger window */
  169294. if (cinfo->progressive_mode)
  169295. access_rows *= 3;
  169296. #endif
  169297. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169298. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169299. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169300. (long) compptr->h_samp_factor),
  169301. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169302. (long) compptr->v_samp_factor),
  169303. (JDIMENSION) access_rows);
  169304. }
  169305. coef->pub.consume_data = consume_data;
  169306. coef->pub.decompress_data = decompress_data;
  169307. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169308. #else
  169309. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169310. #endif
  169311. } else {
  169312. /* We only need a single-MCU buffer. */
  169313. JBLOCKROW buffer;
  169314. int i;
  169315. buffer = (JBLOCKROW)
  169316. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169317. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169318. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169319. coef->MCU_buffer[i] = buffer + i;
  169320. }
  169321. coef->pub.consume_data = dummy_consume_data;
  169322. coef->pub.decompress_data = decompress_onepass;
  169323. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169324. }
  169325. }
  169326. /*** End of inlined file: jdcoefct.c ***/
  169327. #undef FIX
  169328. /*** Start of inlined file: jdcolor.c ***/
  169329. #define JPEG_INTERNALS
  169330. /* Private subobject */
  169331. typedef struct {
  169332. struct jpeg_color_deconverter pub; /* public fields */
  169333. /* Private state for YCC->RGB conversion */
  169334. int * Cr_r_tab; /* => table for Cr to R conversion */
  169335. int * Cb_b_tab; /* => table for Cb to B conversion */
  169336. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169337. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169338. } my_color_deconverter2;
  169339. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169340. /**************** YCbCr -> RGB conversion: most common case **************/
  169341. /*
  169342. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169343. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169344. * The conversion equations to be implemented are therefore
  169345. * R = Y + 1.40200 * Cr
  169346. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169347. * B = Y + 1.77200 * Cb
  169348. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169349. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169350. *
  169351. * To avoid floating-point arithmetic, we represent the fractional constants
  169352. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169353. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169354. * Notice that Y, being an integral input, does not contribute any fraction
  169355. * so it need not participate in the rounding.
  169356. *
  169357. * For even more speed, we avoid doing any multiplications in the inner loop
  169358. * by precalculating the constants times Cb and Cr for all possible values.
  169359. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169360. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169361. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169362. * colorspace anyway.
  169363. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169364. * values for the G calculation are left scaled up, since we must add them
  169365. * together before rounding.
  169366. */
  169367. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169368. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169369. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169370. /*
  169371. * Initialize tables for YCC->RGB colorspace conversion.
  169372. */
  169373. LOCAL(void)
  169374. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169375. {
  169376. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169377. int i;
  169378. INT32 x;
  169379. SHIFT_TEMPS
  169380. cconvert->Cr_r_tab = (int *)
  169381. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169382. (MAXJSAMPLE+1) * SIZEOF(int));
  169383. cconvert->Cb_b_tab = (int *)
  169384. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169385. (MAXJSAMPLE+1) * SIZEOF(int));
  169386. cconvert->Cr_g_tab = (INT32 *)
  169387. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169388. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169389. cconvert->Cb_g_tab = (INT32 *)
  169390. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169391. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169392. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169393. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169394. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169395. /* Cr=>R value is nearest int to 1.40200 * x */
  169396. cconvert->Cr_r_tab[i] = (int)
  169397. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169398. /* Cb=>B value is nearest int to 1.77200 * x */
  169399. cconvert->Cb_b_tab[i] = (int)
  169400. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169401. /* Cr=>G value is scaled-up -0.71414 * x */
  169402. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169403. /* Cb=>G value is scaled-up -0.34414 * x */
  169404. /* We also add in ONE_HALF so that need not do it in inner loop */
  169405. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169406. }
  169407. }
  169408. /*
  169409. * Convert some rows of samples to the output colorspace.
  169410. *
  169411. * Note that we change from noninterleaved, one-plane-per-component format
  169412. * to interleaved-pixel format. The output buffer is therefore three times
  169413. * as wide as the input buffer.
  169414. * A starting row offset is provided only for the input buffer. The caller
  169415. * can easily adjust the passed output_buf value to accommodate any row
  169416. * offset required on that side.
  169417. */
  169418. METHODDEF(void)
  169419. ycc_rgb_convert (j_decompress_ptr cinfo,
  169420. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169421. JSAMPARRAY output_buf, int num_rows)
  169422. {
  169423. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169424. register int y, cb, cr;
  169425. register JSAMPROW outptr;
  169426. register JSAMPROW inptr0, inptr1, inptr2;
  169427. register JDIMENSION col;
  169428. JDIMENSION num_cols = cinfo->output_width;
  169429. /* copy these pointers into registers if possible */
  169430. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169431. register int * Crrtab = cconvert->Cr_r_tab;
  169432. register int * Cbbtab = cconvert->Cb_b_tab;
  169433. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169434. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169435. SHIFT_TEMPS
  169436. while (--num_rows >= 0) {
  169437. inptr0 = input_buf[0][input_row];
  169438. inptr1 = input_buf[1][input_row];
  169439. inptr2 = input_buf[2][input_row];
  169440. input_row++;
  169441. outptr = *output_buf++;
  169442. for (col = 0; col < num_cols; col++) {
  169443. y = GETJSAMPLE(inptr0[col]);
  169444. cb = GETJSAMPLE(inptr1[col]);
  169445. cr = GETJSAMPLE(inptr2[col]);
  169446. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169447. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169448. outptr[RGB_GREEN] = range_limit[y +
  169449. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169450. SCALEBITS))];
  169451. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169452. outptr += RGB_PIXELSIZE;
  169453. }
  169454. }
  169455. }
  169456. /**************** Cases other than YCbCr -> RGB **************/
  169457. /*
  169458. * Color conversion for no colorspace change: just copy the data,
  169459. * converting from separate-planes to interleaved representation.
  169460. */
  169461. METHODDEF(void)
  169462. null_convert2 (j_decompress_ptr cinfo,
  169463. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169464. JSAMPARRAY output_buf, int num_rows)
  169465. {
  169466. register JSAMPROW inptr, outptr;
  169467. register JDIMENSION count;
  169468. register int num_components = cinfo->num_components;
  169469. JDIMENSION num_cols = cinfo->output_width;
  169470. int ci;
  169471. while (--num_rows >= 0) {
  169472. for (ci = 0; ci < num_components; ci++) {
  169473. inptr = input_buf[ci][input_row];
  169474. outptr = output_buf[0] + ci;
  169475. for (count = num_cols; count > 0; count--) {
  169476. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169477. outptr += num_components;
  169478. }
  169479. }
  169480. input_row++;
  169481. output_buf++;
  169482. }
  169483. }
  169484. /*
  169485. * Color conversion for grayscale: just copy the data.
  169486. * This also works for YCbCr -> grayscale conversion, in which
  169487. * we just copy the Y (luminance) component and ignore chrominance.
  169488. */
  169489. METHODDEF(void)
  169490. grayscale_convert2 (j_decompress_ptr cinfo,
  169491. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169492. JSAMPARRAY output_buf, int num_rows)
  169493. {
  169494. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169495. num_rows, cinfo->output_width);
  169496. }
  169497. /*
  169498. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169499. * This is provided to support applications that don't want to cope
  169500. * with grayscale as a separate case.
  169501. */
  169502. METHODDEF(void)
  169503. gray_rgb_convert (j_decompress_ptr cinfo,
  169504. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169505. JSAMPARRAY output_buf, int num_rows)
  169506. {
  169507. register JSAMPROW inptr, outptr;
  169508. register JDIMENSION col;
  169509. JDIMENSION num_cols = cinfo->output_width;
  169510. while (--num_rows >= 0) {
  169511. inptr = input_buf[0][input_row++];
  169512. outptr = *output_buf++;
  169513. for (col = 0; col < num_cols; col++) {
  169514. /* We can dispense with GETJSAMPLE() here */
  169515. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169516. outptr += RGB_PIXELSIZE;
  169517. }
  169518. }
  169519. }
  169520. /*
  169521. * Adobe-style YCCK->CMYK conversion.
  169522. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169523. * conversion as above, while passing K (black) unchanged.
  169524. * We assume build_ycc_rgb_table has been called.
  169525. */
  169526. METHODDEF(void)
  169527. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169528. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169529. JSAMPARRAY output_buf, int num_rows)
  169530. {
  169531. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169532. register int y, cb, cr;
  169533. register JSAMPROW outptr;
  169534. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169535. register JDIMENSION col;
  169536. JDIMENSION num_cols = cinfo->output_width;
  169537. /* copy these pointers into registers if possible */
  169538. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169539. register int * Crrtab = cconvert->Cr_r_tab;
  169540. register int * Cbbtab = cconvert->Cb_b_tab;
  169541. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169542. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169543. SHIFT_TEMPS
  169544. while (--num_rows >= 0) {
  169545. inptr0 = input_buf[0][input_row];
  169546. inptr1 = input_buf[1][input_row];
  169547. inptr2 = input_buf[2][input_row];
  169548. inptr3 = input_buf[3][input_row];
  169549. input_row++;
  169550. outptr = *output_buf++;
  169551. for (col = 0; col < num_cols; col++) {
  169552. y = GETJSAMPLE(inptr0[col]);
  169553. cb = GETJSAMPLE(inptr1[col]);
  169554. cr = GETJSAMPLE(inptr2[col]);
  169555. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169556. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169557. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169558. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169559. SCALEBITS)))];
  169560. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169561. /* K passes through unchanged */
  169562. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169563. outptr += 4;
  169564. }
  169565. }
  169566. }
  169567. /*
  169568. * Empty method for start_pass.
  169569. */
  169570. METHODDEF(void)
  169571. start_pass_dcolor (j_decompress_ptr)
  169572. {
  169573. /* no work needed */
  169574. }
  169575. /*
  169576. * Module initialization routine for output colorspace conversion.
  169577. */
  169578. GLOBAL(void)
  169579. jinit_color_deconverter (j_decompress_ptr cinfo)
  169580. {
  169581. my_cconvert_ptr2 cconvert;
  169582. int ci;
  169583. cconvert = (my_cconvert_ptr2)
  169584. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169585. SIZEOF(my_color_deconverter2));
  169586. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169587. cconvert->pub.start_pass = start_pass_dcolor;
  169588. /* Make sure num_components agrees with jpeg_color_space */
  169589. switch (cinfo->jpeg_color_space) {
  169590. case JCS_GRAYSCALE:
  169591. if (cinfo->num_components != 1)
  169592. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169593. break;
  169594. case JCS_RGB:
  169595. case JCS_YCbCr:
  169596. if (cinfo->num_components != 3)
  169597. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169598. break;
  169599. case JCS_CMYK:
  169600. case JCS_YCCK:
  169601. if (cinfo->num_components != 4)
  169602. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169603. break;
  169604. default: /* JCS_UNKNOWN can be anything */
  169605. if (cinfo->num_components < 1)
  169606. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169607. break;
  169608. }
  169609. /* Set out_color_components and conversion method based on requested space.
  169610. * Also clear the component_needed flags for any unused components,
  169611. * so that earlier pipeline stages can avoid useless computation.
  169612. */
  169613. switch (cinfo->out_color_space) {
  169614. case JCS_GRAYSCALE:
  169615. cinfo->out_color_components = 1;
  169616. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169617. cinfo->jpeg_color_space == JCS_YCbCr) {
  169618. cconvert->pub.color_convert = grayscale_convert2;
  169619. /* For color->grayscale conversion, only the Y (0) component is needed */
  169620. for (ci = 1; ci < cinfo->num_components; ci++)
  169621. cinfo->comp_info[ci].component_needed = FALSE;
  169622. } else
  169623. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169624. break;
  169625. case JCS_RGB:
  169626. cinfo->out_color_components = RGB_PIXELSIZE;
  169627. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169628. cconvert->pub.color_convert = ycc_rgb_convert;
  169629. build_ycc_rgb_table(cinfo);
  169630. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169631. cconvert->pub.color_convert = gray_rgb_convert;
  169632. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169633. cconvert->pub.color_convert = null_convert2;
  169634. } else
  169635. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169636. break;
  169637. case JCS_CMYK:
  169638. cinfo->out_color_components = 4;
  169639. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169640. cconvert->pub.color_convert = ycck_cmyk_convert;
  169641. build_ycc_rgb_table(cinfo);
  169642. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169643. cconvert->pub.color_convert = null_convert2;
  169644. } else
  169645. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169646. break;
  169647. default:
  169648. /* Permit null conversion to same output space */
  169649. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169650. cinfo->out_color_components = cinfo->num_components;
  169651. cconvert->pub.color_convert = null_convert2;
  169652. } else /* unsupported non-null conversion */
  169653. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169654. break;
  169655. }
  169656. if (cinfo->quantize_colors)
  169657. cinfo->output_components = 1; /* single colormapped output component */
  169658. else
  169659. cinfo->output_components = cinfo->out_color_components;
  169660. }
  169661. /*** End of inlined file: jdcolor.c ***/
  169662. #undef FIX
  169663. /*** Start of inlined file: jddctmgr.c ***/
  169664. #define JPEG_INTERNALS
  169665. /*
  169666. * The decompressor input side (jdinput.c) saves away the appropriate
  169667. * quantization table for each component at the start of the first scan
  169668. * involving that component. (This is necessary in order to correctly
  169669. * decode files that reuse Q-table slots.)
  169670. * When we are ready to make an output pass, the saved Q-table is converted
  169671. * to a multiplier table that will actually be used by the IDCT routine.
  169672. * The multiplier table contents are IDCT-method-dependent. To support
  169673. * application changes in IDCT method between scans, we can remake the
  169674. * multiplier tables if necessary.
  169675. * In buffered-image mode, the first output pass may occur before any data
  169676. * has been seen for some components, and thus before their Q-tables have
  169677. * been saved away. To handle this case, multiplier tables are preset
  169678. * to zeroes; the result of the IDCT will be a neutral gray level.
  169679. */
  169680. /* Private subobject for this module */
  169681. typedef struct {
  169682. struct jpeg_inverse_dct pub; /* public fields */
  169683. /* This array contains the IDCT method code that each multiplier table
  169684. * is currently set up for, or -1 if it's not yet set up.
  169685. * The actual multiplier tables are pointed to by dct_table in the
  169686. * per-component comp_info structures.
  169687. */
  169688. int cur_method[MAX_COMPONENTS];
  169689. } my_idct_controller;
  169690. typedef my_idct_controller * my_idct_ptr;
  169691. /* Allocated multiplier tables: big enough for any supported variant */
  169692. typedef union {
  169693. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169694. #ifdef DCT_IFAST_SUPPORTED
  169695. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169696. #endif
  169697. #ifdef DCT_FLOAT_SUPPORTED
  169698. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169699. #endif
  169700. } multiplier_table;
  169701. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169702. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169703. */
  169704. #ifdef DCT_ISLOW_SUPPORTED
  169705. #define PROVIDE_ISLOW_TABLES
  169706. #else
  169707. #ifdef IDCT_SCALING_SUPPORTED
  169708. #define PROVIDE_ISLOW_TABLES
  169709. #endif
  169710. #endif
  169711. /*
  169712. * Prepare for an output pass.
  169713. * Here we select the proper IDCT routine for each component and build
  169714. * a matching multiplier table.
  169715. */
  169716. METHODDEF(void)
  169717. start_pass (j_decompress_ptr cinfo)
  169718. {
  169719. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169720. int ci, i;
  169721. jpeg_component_info *compptr;
  169722. int method = 0;
  169723. inverse_DCT_method_ptr method_ptr = NULL;
  169724. JQUANT_TBL * qtbl;
  169725. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169726. ci++, compptr++) {
  169727. /* Select the proper IDCT routine for this component's scaling */
  169728. switch (compptr->DCT_scaled_size) {
  169729. #ifdef IDCT_SCALING_SUPPORTED
  169730. case 1:
  169731. method_ptr = jpeg_idct_1x1;
  169732. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169733. break;
  169734. case 2:
  169735. method_ptr = jpeg_idct_2x2;
  169736. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169737. break;
  169738. case 4:
  169739. method_ptr = jpeg_idct_4x4;
  169740. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169741. break;
  169742. #endif
  169743. case DCTSIZE:
  169744. switch (cinfo->dct_method) {
  169745. #ifdef DCT_ISLOW_SUPPORTED
  169746. case JDCT_ISLOW:
  169747. method_ptr = jpeg_idct_islow;
  169748. method = JDCT_ISLOW;
  169749. break;
  169750. #endif
  169751. #ifdef DCT_IFAST_SUPPORTED
  169752. case JDCT_IFAST:
  169753. method_ptr = jpeg_idct_ifast;
  169754. method = JDCT_IFAST;
  169755. break;
  169756. #endif
  169757. #ifdef DCT_FLOAT_SUPPORTED
  169758. case JDCT_FLOAT:
  169759. method_ptr = jpeg_idct_float;
  169760. method = JDCT_FLOAT;
  169761. break;
  169762. #endif
  169763. default:
  169764. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169765. break;
  169766. }
  169767. break;
  169768. default:
  169769. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169770. break;
  169771. }
  169772. idct->pub.inverse_DCT[ci] = method_ptr;
  169773. /* Create multiplier table from quant table.
  169774. * However, we can skip this if the component is uninteresting
  169775. * or if we already built the table. Also, if no quant table
  169776. * has yet been saved for the component, we leave the
  169777. * multiplier table all-zero; we'll be reading zeroes from the
  169778. * coefficient controller's buffer anyway.
  169779. */
  169780. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169781. continue;
  169782. qtbl = compptr->quant_table;
  169783. if (qtbl == NULL) /* happens if no data yet for component */
  169784. continue;
  169785. idct->cur_method[ci] = method;
  169786. switch (method) {
  169787. #ifdef PROVIDE_ISLOW_TABLES
  169788. case JDCT_ISLOW:
  169789. {
  169790. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169791. * coefficients, but are stored as ints to ensure access efficiency.
  169792. */
  169793. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169794. for (i = 0; i < DCTSIZE2; i++) {
  169795. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169796. }
  169797. }
  169798. break;
  169799. #endif
  169800. #ifdef DCT_IFAST_SUPPORTED
  169801. case JDCT_IFAST:
  169802. {
  169803. /* For AA&N IDCT method, multipliers are equal to quantization
  169804. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169805. * scalefactor[0] = 1
  169806. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169807. * For integer operation, the multiplier table is to be scaled by
  169808. * IFAST_SCALE_BITS.
  169809. */
  169810. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169811. #define CONST_BITS 14
  169812. static const INT16 aanscales[DCTSIZE2] = {
  169813. /* precomputed values scaled up by 14 bits */
  169814. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169815. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169816. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169817. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169818. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169819. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169820. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169821. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169822. };
  169823. SHIFT_TEMPS
  169824. for (i = 0; i < DCTSIZE2; i++) {
  169825. ifmtbl[i] = (IFAST_MULT_TYPE)
  169826. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169827. (INT32) aanscales[i]),
  169828. CONST_BITS-IFAST_SCALE_BITS);
  169829. }
  169830. }
  169831. break;
  169832. #endif
  169833. #ifdef DCT_FLOAT_SUPPORTED
  169834. case JDCT_FLOAT:
  169835. {
  169836. /* For float AA&N IDCT method, multipliers are equal to quantization
  169837. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169838. * scalefactor[0] = 1
  169839. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169840. */
  169841. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169842. int row, col;
  169843. static const double aanscalefactor[DCTSIZE] = {
  169844. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169845. 1.0, 0.785694958, 0.541196100, 0.275899379
  169846. };
  169847. i = 0;
  169848. for (row = 0; row < DCTSIZE; row++) {
  169849. for (col = 0; col < DCTSIZE; col++) {
  169850. fmtbl[i] = (FLOAT_MULT_TYPE)
  169851. ((double) qtbl->quantval[i] *
  169852. aanscalefactor[row] * aanscalefactor[col]);
  169853. i++;
  169854. }
  169855. }
  169856. }
  169857. break;
  169858. #endif
  169859. default:
  169860. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169861. break;
  169862. }
  169863. }
  169864. }
  169865. /*
  169866. * Initialize IDCT manager.
  169867. */
  169868. GLOBAL(void)
  169869. jinit_inverse_dct (j_decompress_ptr cinfo)
  169870. {
  169871. my_idct_ptr idct;
  169872. int ci;
  169873. jpeg_component_info *compptr;
  169874. idct = (my_idct_ptr)
  169875. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169876. SIZEOF(my_idct_controller));
  169877. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169878. idct->pub.start_pass = start_pass;
  169879. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169880. ci++, compptr++) {
  169881. /* Allocate and pre-zero a multiplier table for each component */
  169882. compptr->dct_table =
  169883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169884. SIZEOF(multiplier_table));
  169885. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169886. /* Mark multiplier table not yet set up for any method */
  169887. idct->cur_method[ci] = -1;
  169888. }
  169889. }
  169890. /*** End of inlined file: jddctmgr.c ***/
  169891. #undef CONST_BITS
  169892. #undef ASSIGN_STATE
  169893. /*** Start of inlined file: jdhuff.c ***/
  169894. #define JPEG_INTERNALS
  169895. /*** Start of inlined file: jdhuff.h ***/
  169896. /* Short forms of external names for systems with brain-damaged linkers. */
  169897. #ifndef __jdhuff_h__
  169898. #define __jdhuff_h__
  169899. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169900. #define jpeg_make_d_derived_tbl jMkDDerived
  169901. #define jpeg_fill_bit_buffer jFilBitBuf
  169902. #define jpeg_huff_decode jHufDecode
  169903. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169904. /* Derived data constructed for each Huffman table */
  169905. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169906. typedef struct {
  169907. /* Basic tables: (element [0] of each array is unused) */
  169908. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169909. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169910. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169911. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169912. * the smallest code of length k; so given a code of length k, the
  169913. * corresponding symbol is huffval[code + valoffset[k]]
  169914. */
  169915. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169916. JHUFF_TBL *pub;
  169917. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169918. * the input data stream. If the next Huffman code is no more
  169919. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169920. * the corresponding symbol directly from these tables.
  169921. */
  169922. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169923. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169924. } d_derived_tbl;
  169925. /* Expand a Huffman table definition into the derived format */
  169926. EXTERN(void) jpeg_make_d_derived_tbl
  169927. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169928. d_derived_tbl ** pdtbl));
  169929. /*
  169930. * Fetching the next N bits from the input stream is a time-critical operation
  169931. * for the Huffman decoders. We implement it with a combination of inline
  169932. * macros and out-of-line subroutines. Note that N (the number of bits
  169933. * demanded at one time) never exceeds 15 for JPEG use.
  169934. *
  169935. * We read source bytes into get_buffer and dole out bits as needed.
  169936. * If get_buffer already contains enough bits, they are fetched in-line
  169937. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169938. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169939. * as full as possible (not just to the number of bits needed; this
  169940. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169941. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169942. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169943. * at least the requested number of bits --- dummy zeroes are inserted if
  169944. * necessary.
  169945. */
  169946. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169947. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169948. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169949. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169950. * appropriately should be a win. Unfortunately we can't define the size
  169951. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169952. * because not all machines measure sizeof in 8-bit bytes.
  169953. */
  169954. typedef struct { /* Bitreading state saved across MCUs */
  169955. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169956. int bits_left; /* # of unused bits in it */
  169957. } bitread_perm_state;
  169958. typedef struct { /* Bitreading working state within an MCU */
  169959. /* Current data source location */
  169960. /* We need a copy, rather than munging the original, in case of suspension */
  169961. const JOCTET * next_input_byte; /* => next byte to read from source */
  169962. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169963. /* Bit input buffer --- note these values are kept in register variables,
  169964. * not in this struct, inside the inner loops.
  169965. */
  169966. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169967. int bits_left; /* # of unused bits in it */
  169968. /* Pointer needed by jpeg_fill_bit_buffer. */
  169969. j_decompress_ptr cinfo; /* back link to decompress master record */
  169970. } bitread_working_state;
  169971. /* Macros to declare and load/save bitread local variables. */
  169972. #define BITREAD_STATE_VARS \
  169973. register bit_buf_type get_buffer; \
  169974. register int bits_left; \
  169975. bitread_working_state br_state
  169976. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169977. br_state.cinfo = cinfop; \
  169978. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169979. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169980. get_buffer = permstate.get_buffer; \
  169981. bits_left = permstate.bits_left;
  169982. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169983. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169984. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169985. permstate.get_buffer = get_buffer; \
  169986. permstate.bits_left = bits_left
  169987. /*
  169988. * These macros provide the in-line portion of bit fetching.
  169989. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169990. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169991. * The variables get_buffer and bits_left are assumed to be locals,
  169992. * but the state struct might not be (jpeg_huff_decode needs this).
  169993. * CHECK_BIT_BUFFER(state,n,action);
  169994. * Ensure there are N bits in get_buffer; if suspend, take action.
  169995. * val = GET_BITS(n);
  169996. * Fetch next N bits.
  169997. * val = PEEK_BITS(n);
  169998. * Fetch next N bits without removing them from the buffer.
  169999. * DROP_BITS(n);
  170000. * Discard next N bits.
  170001. * The value N should be a simple variable, not an expression, because it
  170002. * is evaluated multiple times.
  170003. */
  170004. #define CHECK_BIT_BUFFER(state,nbits,action) \
  170005. { if (bits_left < (nbits)) { \
  170006. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  170007. { action; } \
  170008. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  170009. #define GET_BITS(nbits) \
  170010. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  170011. #define PEEK_BITS(nbits) \
  170012. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  170013. #define DROP_BITS(nbits) \
  170014. (bits_left -= (nbits))
  170015. /* Load up the bit buffer to a depth of at least nbits */
  170016. EXTERN(boolean) jpeg_fill_bit_buffer
  170017. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170018. register int bits_left, int nbits));
  170019. /*
  170020. * Code for extracting next Huffman-coded symbol from input bit stream.
  170021. * Again, this is time-critical and we make the main paths be macros.
  170022. *
  170023. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  170024. * without looping. Usually, more than 95% of the Huffman codes will be 8
  170025. * or fewer bits long. The few overlength codes are handled with a loop,
  170026. * which need not be inline code.
  170027. *
  170028. * Notes about the HUFF_DECODE macro:
  170029. * 1. Near the end of the data segment, we may fail to get enough bits
  170030. * for a lookahead. In that case, we do it the hard way.
  170031. * 2. If the lookahead table contains no entry, the next code must be
  170032. * more than HUFF_LOOKAHEAD bits long.
  170033. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  170034. */
  170035. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  170036. { register int nb, look; \
  170037. if (bits_left < HUFF_LOOKAHEAD) { \
  170038. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  170039. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170040. if (bits_left < HUFF_LOOKAHEAD) { \
  170041. nb = 1; goto slowlabel; \
  170042. } \
  170043. } \
  170044. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  170045. if ((nb = htbl->look_nbits[look]) != 0) { \
  170046. DROP_BITS(nb); \
  170047. result = htbl->look_sym[look]; \
  170048. } else { \
  170049. nb = HUFF_LOOKAHEAD+1; \
  170050. slowlabel: \
  170051. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  170052. { failaction; } \
  170053. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170054. } \
  170055. }
  170056. /* Out-of-line case for Huffman code fetching */
  170057. EXTERN(int) jpeg_huff_decode
  170058. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170059. register int bits_left, d_derived_tbl * htbl, int min_bits));
  170060. #endif
  170061. /*** End of inlined file: jdhuff.h ***/
  170062. /* Declarations shared with jdphuff.c */
  170063. /*
  170064. * Expanded entropy decoder object for Huffman decoding.
  170065. *
  170066. * The savable_state subrecord contains fields that change within an MCU,
  170067. * but must not be updated permanently until we complete the MCU.
  170068. */
  170069. typedef struct {
  170070. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170071. } savable_state2;
  170072. /* This macro is to work around compilers with missing or broken
  170073. * structure assignment. You'll need to fix this code if you have
  170074. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170075. */
  170076. #ifndef NO_STRUCT_ASSIGN
  170077. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170078. #else
  170079. #if MAX_COMPS_IN_SCAN == 4
  170080. #define ASSIGN_STATE(dest,src) \
  170081. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  170082. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170083. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170084. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170085. #endif
  170086. #endif
  170087. typedef struct {
  170088. struct jpeg_entropy_decoder pub; /* public fields */
  170089. /* These fields are loaded into local variables at start of each MCU.
  170090. * In case of suspension, we exit WITHOUT updating them.
  170091. */
  170092. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170093. savable_state2 saved; /* Other state at start of MCU */
  170094. /* These fields are NOT loaded into local working state. */
  170095. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170096. /* Pointers to derived tables (these workspaces have image lifespan) */
  170097. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  170098. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  170099. /* Precalculated info set up by start_pass for use in decode_mcu: */
  170100. /* Pointers to derived tables to be used for each block within an MCU */
  170101. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170102. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170103. /* Whether we care about the DC and AC coefficient values for each block */
  170104. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  170105. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  170106. } huff_entropy_decoder2;
  170107. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  170108. /*
  170109. * Initialize for a Huffman-compressed scan.
  170110. */
  170111. METHODDEF(void)
  170112. start_pass_huff_decoder (j_decompress_ptr cinfo)
  170113. {
  170114. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170115. int ci, blkn, dctbl, actbl;
  170116. jpeg_component_info * compptr;
  170117. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170118. * This ought to be an error condition, but we make it a warning because
  170119. * there are some baseline files out there with all zeroes in these bytes.
  170120. */
  170121. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170122. cinfo->Ah != 0 || cinfo->Al != 0)
  170123. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170124. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170125. compptr = cinfo->cur_comp_info[ci];
  170126. dctbl = compptr->dc_tbl_no;
  170127. actbl = compptr->ac_tbl_no;
  170128. /* Compute derived values for Huffman tables */
  170129. /* We may do this more than once for a table, but it's not expensive */
  170130. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170131. & entropy->dc_derived_tbls[dctbl]);
  170132. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170133. & entropy->ac_derived_tbls[actbl]);
  170134. /* Initialize DC predictions to 0 */
  170135. entropy->saved.last_dc_val[ci] = 0;
  170136. }
  170137. /* Precalculate decoding info for each block in an MCU of this scan */
  170138. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170139. ci = cinfo->MCU_membership[blkn];
  170140. compptr = cinfo->cur_comp_info[ci];
  170141. /* Precalculate which table to use for each block */
  170142. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170143. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170144. /* Decide whether we really care about the coefficient values */
  170145. if (compptr->component_needed) {
  170146. entropy->dc_needed[blkn] = TRUE;
  170147. /* we don't need the ACs if producing a 1/8th-size image */
  170148. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170149. } else {
  170150. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170151. }
  170152. }
  170153. /* Initialize bitread state variables */
  170154. entropy->bitstate.bits_left = 0;
  170155. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170156. entropy->pub.insufficient_data = FALSE;
  170157. /* Initialize restart counter */
  170158. entropy->restarts_to_go = cinfo->restart_interval;
  170159. }
  170160. /*
  170161. * Compute the derived values for a Huffman table.
  170162. * This routine also performs some validation checks on the table.
  170163. *
  170164. * Note this is also used by jdphuff.c.
  170165. */
  170166. GLOBAL(void)
  170167. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170168. d_derived_tbl ** pdtbl)
  170169. {
  170170. JHUFF_TBL *htbl;
  170171. d_derived_tbl *dtbl;
  170172. int p, i, l, si, numsymbols;
  170173. int lookbits, ctr;
  170174. char huffsize[257];
  170175. unsigned int huffcode[257];
  170176. unsigned int code;
  170177. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170178. * paralleling the order of the symbols themselves in htbl->huffval[].
  170179. */
  170180. /* Find the input Huffman table */
  170181. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170182. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170183. htbl =
  170184. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170185. if (htbl == NULL)
  170186. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170187. /* Allocate a workspace if we haven't already done so. */
  170188. if (*pdtbl == NULL)
  170189. *pdtbl = (d_derived_tbl *)
  170190. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170191. SIZEOF(d_derived_tbl));
  170192. dtbl = *pdtbl;
  170193. dtbl->pub = htbl; /* fill in back link */
  170194. /* Figure C.1: make table of Huffman code length for each symbol */
  170195. p = 0;
  170196. for (l = 1; l <= 16; l++) {
  170197. i = (int) htbl->bits[l];
  170198. if (i < 0 || p + i > 256) /* protect against table overrun */
  170199. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170200. while (i--)
  170201. huffsize[p++] = (char) l;
  170202. }
  170203. huffsize[p] = 0;
  170204. numsymbols = p;
  170205. /* Figure C.2: generate the codes themselves */
  170206. /* We also validate that the counts represent a legal Huffman code tree. */
  170207. code = 0;
  170208. si = huffsize[0];
  170209. p = 0;
  170210. while (huffsize[p]) {
  170211. while (((int) huffsize[p]) == si) {
  170212. huffcode[p++] = code;
  170213. code++;
  170214. }
  170215. /* code is now 1 more than the last code used for codelength si; but
  170216. * it must still fit in si bits, since no code is allowed to be all ones.
  170217. */
  170218. if (((INT32) code) >= (((INT32) 1) << si))
  170219. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170220. code <<= 1;
  170221. si++;
  170222. }
  170223. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170224. p = 0;
  170225. for (l = 1; l <= 16; l++) {
  170226. if (htbl->bits[l]) {
  170227. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170228. * minus the minimum code of length l
  170229. */
  170230. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170231. p += htbl->bits[l];
  170232. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170233. } else {
  170234. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170235. }
  170236. }
  170237. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170238. /* Compute lookahead tables to speed up decoding.
  170239. * First we set all the table entries to 0, indicating "too long";
  170240. * then we iterate through the Huffman codes that are short enough and
  170241. * fill in all the entries that correspond to bit sequences starting
  170242. * with that code.
  170243. */
  170244. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170245. p = 0;
  170246. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170247. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170248. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170249. /* Generate left-justified code followed by all possible bit sequences */
  170250. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170251. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170252. dtbl->look_nbits[lookbits] = l;
  170253. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170254. lookbits++;
  170255. }
  170256. }
  170257. }
  170258. /* Validate symbols as being reasonable.
  170259. * For AC tables, we make no check, but accept all byte values 0..255.
  170260. * For DC tables, we require the symbols to be in range 0..15.
  170261. * (Tighter bounds could be applied depending on the data depth and mode,
  170262. * but this is sufficient to ensure safe decoding.)
  170263. */
  170264. if (isDC) {
  170265. for (i = 0; i < numsymbols; i++) {
  170266. int sym = htbl->huffval[i];
  170267. if (sym < 0 || sym > 15)
  170268. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170269. }
  170270. }
  170271. }
  170272. /*
  170273. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170274. * See jdhuff.h for info about usage.
  170275. * Note: current values of get_buffer and bits_left are passed as parameters,
  170276. * but are returned in the corresponding fields of the state struct.
  170277. *
  170278. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170279. * of get_buffer to be used. (On machines with wider words, an even larger
  170280. * buffer could be used.) However, on some machines 32-bit shifts are
  170281. * quite slow and take time proportional to the number of places shifted.
  170282. * (This is true with most PC compilers, for instance.) In this case it may
  170283. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170284. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170285. */
  170286. #ifdef SLOW_SHIFT_32
  170287. #define MIN_GET_BITS 15 /* minimum allowable value */
  170288. #else
  170289. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170290. #endif
  170291. GLOBAL(boolean)
  170292. jpeg_fill_bit_buffer (bitread_working_state * state,
  170293. register bit_buf_type get_buffer, register int bits_left,
  170294. int nbits)
  170295. /* Load up the bit buffer to a depth of at least nbits */
  170296. {
  170297. /* Copy heavily used state fields into locals (hopefully registers) */
  170298. register const JOCTET * next_input_byte = state->next_input_byte;
  170299. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170300. j_decompress_ptr cinfo = state->cinfo;
  170301. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170302. /* (It is assumed that no request will be for more than that many bits.) */
  170303. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170304. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170305. while (bits_left < MIN_GET_BITS) {
  170306. register int c;
  170307. /* Attempt to read a byte */
  170308. if (bytes_in_buffer == 0) {
  170309. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170310. return FALSE;
  170311. next_input_byte = cinfo->src->next_input_byte;
  170312. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170313. }
  170314. bytes_in_buffer--;
  170315. c = GETJOCTET(*next_input_byte++);
  170316. /* If it's 0xFF, check and discard stuffed zero byte */
  170317. if (c == 0xFF) {
  170318. /* Loop here to discard any padding FF's on terminating marker,
  170319. * so that we can save a valid unread_marker value. NOTE: we will
  170320. * accept multiple FF's followed by a 0 as meaning a single FF data
  170321. * byte. This data pattern is not valid according to the standard.
  170322. */
  170323. do {
  170324. if (bytes_in_buffer == 0) {
  170325. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170326. return FALSE;
  170327. next_input_byte = cinfo->src->next_input_byte;
  170328. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170329. }
  170330. bytes_in_buffer--;
  170331. c = GETJOCTET(*next_input_byte++);
  170332. } while (c == 0xFF);
  170333. if (c == 0) {
  170334. /* Found FF/00, which represents an FF data byte */
  170335. c = 0xFF;
  170336. } else {
  170337. /* Oops, it's actually a marker indicating end of compressed data.
  170338. * Save the marker code for later use.
  170339. * Fine point: it might appear that we should save the marker into
  170340. * bitread working state, not straight into permanent state. But
  170341. * once we have hit a marker, we cannot need to suspend within the
  170342. * current MCU, because we will read no more bytes from the data
  170343. * source. So it is OK to update permanent state right away.
  170344. */
  170345. cinfo->unread_marker = c;
  170346. /* See if we need to insert some fake zero bits. */
  170347. goto no_more_bytes;
  170348. }
  170349. }
  170350. /* OK, load c into get_buffer */
  170351. get_buffer = (get_buffer << 8) | c;
  170352. bits_left += 8;
  170353. } /* end while */
  170354. } else {
  170355. no_more_bytes:
  170356. /* We get here if we've read the marker that terminates the compressed
  170357. * data segment. There should be enough bits in the buffer register
  170358. * to satisfy the request; if so, no problem.
  170359. */
  170360. if (nbits > bits_left) {
  170361. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170362. * the data stream, so that we can produce some kind of image.
  170363. * We use a nonvolatile flag to ensure that only one warning message
  170364. * appears per data segment.
  170365. */
  170366. if (! cinfo->entropy->insufficient_data) {
  170367. WARNMS(cinfo, JWRN_HIT_MARKER);
  170368. cinfo->entropy->insufficient_data = TRUE;
  170369. }
  170370. /* Fill the buffer with zero bits */
  170371. get_buffer <<= MIN_GET_BITS - bits_left;
  170372. bits_left = MIN_GET_BITS;
  170373. }
  170374. }
  170375. /* Unload the local registers */
  170376. state->next_input_byte = next_input_byte;
  170377. state->bytes_in_buffer = bytes_in_buffer;
  170378. state->get_buffer = get_buffer;
  170379. state->bits_left = bits_left;
  170380. return TRUE;
  170381. }
  170382. /*
  170383. * Out-of-line code for Huffman code decoding.
  170384. * See jdhuff.h for info about usage.
  170385. */
  170386. GLOBAL(int)
  170387. jpeg_huff_decode (bitread_working_state * state,
  170388. register bit_buf_type get_buffer, register int bits_left,
  170389. d_derived_tbl * htbl, int min_bits)
  170390. {
  170391. register int l = min_bits;
  170392. register INT32 code;
  170393. /* HUFF_DECODE has determined that the code is at least min_bits */
  170394. /* bits long, so fetch that many bits in one swoop. */
  170395. CHECK_BIT_BUFFER(*state, l, return -1);
  170396. code = GET_BITS(l);
  170397. /* Collect the rest of the Huffman code one bit at a time. */
  170398. /* This is per Figure F.16 in the JPEG spec. */
  170399. while (code > htbl->maxcode[l]) {
  170400. code <<= 1;
  170401. CHECK_BIT_BUFFER(*state, 1, return -1);
  170402. code |= GET_BITS(1);
  170403. l++;
  170404. }
  170405. /* Unload the local registers */
  170406. state->get_buffer = get_buffer;
  170407. state->bits_left = bits_left;
  170408. /* With garbage input we may reach the sentinel value l = 17. */
  170409. if (l > 16) {
  170410. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170411. return 0; /* fake a zero as the safest result */
  170412. }
  170413. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170414. }
  170415. /*
  170416. * Check for a restart marker & resynchronize decoder.
  170417. * Returns FALSE if must suspend.
  170418. */
  170419. LOCAL(boolean)
  170420. process_restart (j_decompress_ptr cinfo)
  170421. {
  170422. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170423. int ci;
  170424. /* Throw away any unused bits remaining in bit buffer; */
  170425. /* include any full bytes in next_marker's count of discarded bytes */
  170426. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170427. entropy->bitstate.bits_left = 0;
  170428. /* Advance past the RSTn marker */
  170429. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170430. return FALSE;
  170431. /* Re-initialize DC predictions to 0 */
  170432. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170433. entropy->saved.last_dc_val[ci] = 0;
  170434. /* Reset restart counter */
  170435. entropy->restarts_to_go = cinfo->restart_interval;
  170436. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170437. * against a marker. In that case we will end up treating the next data
  170438. * segment as empty, and we can avoid producing bogus output pixels by
  170439. * leaving the flag set.
  170440. */
  170441. if (cinfo->unread_marker == 0)
  170442. entropy->pub.insufficient_data = FALSE;
  170443. return TRUE;
  170444. }
  170445. /*
  170446. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170447. * The coefficients are reordered from zigzag order into natural array order,
  170448. * but are not dequantized.
  170449. *
  170450. * The i'th block of the MCU is stored into the block pointed to by
  170451. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170452. * (Wholesale zeroing is usually a little faster than retail...)
  170453. *
  170454. * Returns FALSE if data source requested suspension. In that case no
  170455. * changes have been made to permanent state. (Exception: some output
  170456. * coefficients may already have been assigned. This is harmless for
  170457. * this module, since we'll just re-assign them on the next call.)
  170458. */
  170459. METHODDEF(boolean)
  170460. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170461. {
  170462. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170463. int blkn;
  170464. BITREAD_STATE_VARS;
  170465. savable_state2 state;
  170466. /* Process restart marker if needed; may have to suspend */
  170467. if (cinfo->restart_interval) {
  170468. if (entropy->restarts_to_go == 0)
  170469. if (! process_restart(cinfo))
  170470. return FALSE;
  170471. }
  170472. /* If we've run out of data, just leave the MCU set to zeroes.
  170473. * This way, we return uniform gray for the remainder of the segment.
  170474. */
  170475. if (! entropy->pub.insufficient_data) {
  170476. /* Load up working state */
  170477. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170478. ASSIGN_STATE(state, entropy->saved);
  170479. /* Outer loop handles each block in the MCU */
  170480. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170481. JBLOCKROW block = MCU_data[blkn];
  170482. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170483. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170484. register int s, k, r;
  170485. /* Decode a single block's worth of coefficients */
  170486. /* Section F.2.2.1: decode the DC coefficient difference */
  170487. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170488. if (s) {
  170489. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170490. r = GET_BITS(s);
  170491. s = HUFF_EXTEND(r, s);
  170492. }
  170493. if (entropy->dc_needed[blkn]) {
  170494. /* Convert DC difference to actual value, update last_dc_val */
  170495. int ci = cinfo->MCU_membership[blkn];
  170496. s += state.last_dc_val[ci];
  170497. state.last_dc_val[ci] = s;
  170498. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170499. (*block)[0] = (JCOEF) s;
  170500. }
  170501. if (entropy->ac_needed[blkn]) {
  170502. /* Section F.2.2.2: decode the AC coefficients */
  170503. /* Since zeroes are skipped, output area must be cleared beforehand */
  170504. for (k = 1; k < DCTSIZE2; k++) {
  170505. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170506. r = s >> 4;
  170507. s &= 15;
  170508. if (s) {
  170509. k += r;
  170510. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170511. r = GET_BITS(s);
  170512. s = HUFF_EXTEND(r, s);
  170513. /* Output coefficient in natural (dezigzagged) order.
  170514. * Note: the extra entries in jpeg_natural_order[] will save us
  170515. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170516. */
  170517. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170518. } else {
  170519. if (r != 15)
  170520. break;
  170521. k += 15;
  170522. }
  170523. }
  170524. } else {
  170525. /* Section F.2.2.2: decode the AC coefficients */
  170526. /* In this path we just discard the values */
  170527. for (k = 1; k < DCTSIZE2; k++) {
  170528. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170529. r = s >> 4;
  170530. s &= 15;
  170531. if (s) {
  170532. k += r;
  170533. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170534. DROP_BITS(s);
  170535. } else {
  170536. if (r != 15)
  170537. break;
  170538. k += 15;
  170539. }
  170540. }
  170541. }
  170542. }
  170543. /* Completed MCU, so update state */
  170544. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170545. ASSIGN_STATE(entropy->saved, state);
  170546. }
  170547. /* Account for restart interval (no-op if not using restarts) */
  170548. entropy->restarts_to_go--;
  170549. return TRUE;
  170550. }
  170551. /*
  170552. * Module initialization routine for Huffman entropy decoding.
  170553. */
  170554. GLOBAL(void)
  170555. jinit_huff_decoder (j_decompress_ptr cinfo)
  170556. {
  170557. huff_entropy_ptr2 entropy;
  170558. int i;
  170559. entropy = (huff_entropy_ptr2)
  170560. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170561. SIZEOF(huff_entropy_decoder2));
  170562. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170563. entropy->pub.start_pass = start_pass_huff_decoder;
  170564. entropy->pub.decode_mcu = decode_mcu;
  170565. /* Mark tables unallocated */
  170566. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170567. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170568. }
  170569. }
  170570. /*** End of inlined file: jdhuff.c ***/
  170571. /*** Start of inlined file: jdinput.c ***/
  170572. #define JPEG_INTERNALS
  170573. /* Private state */
  170574. typedef struct {
  170575. struct jpeg_input_controller pub; /* public fields */
  170576. boolean inheaders; /* TRUE until first SOS is reached */
  170577. } my_input_controller;
  170578. typedef my_input_controller * my_inputctl_ptr;
  170579. /* Forward declarations */
  170580. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170581. /*
  170582. * Routines to calculate various quantities related to the size of the image.
  170583. */
  170584. LOCAL(void)
  170585. initial_setup2 (j_decompress_ptr cinfo)
  170586. /* Called once, when first SOS marker is reached */
  170587. {
  170588. int ci;
  170589. jpeg_component_info *compptr;
  170590. /* Make sure image isn't bigger than I can handle */
  170591. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170592. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170593. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170594. /* For now, precision must match compiled-in value... */
  170595. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170596. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170597. /* Check that number of components won't exceed internal array sizes */
  170598. if (cinfo->num_components > MAX_COMPONENTS)
  170599. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170600. MAX_COMPONENTS);
  170601. /* Compute maximum sampling factors; check factor validity */
  170602. cinfo->max_h_samp_factor = 1;
  170603. cinfo->max_v_samp_factor = 1;
  170604. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170605. ci++, compptr++) {
  170606. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170607. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170608. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170609. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170610. compptr->h_samp_factor);
  170611. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170612. compptr->v_samp_factor);
  170613. }
  170614. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170615. * In the full decompressor, this will be overridden by jdmaster.c;
  170616. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170617. */
  170618. cinfo->min_DCT_scaled_size = DCTSIZE;
  170619. /* Compute dimensions of components */
  170620. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170621. ci++, compptr++) {
  170622. compptr->DCT_scaled_size = DCTSIZE;
  170623. /* Size in DCT blocks */
  170624. compptr->width_in_blocks = (JDIMENSION)
  170625. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170626. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170627. compptr->height_in_blocks = (JDIMENSION)
  170628. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170629. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170630. /* downsampled_width and downsampled_height will also be overridden by
  170631. * jdmaster.c if we are doing full decompression. The transcoder library
  170632. * doesn't use these values, but the calling application might.
  170633. */
  170634. /* Size in samples */
  170635. compptr->downsampled_width = (JDIMENSION)
  170636. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170637. (long) cinfo->max_h_samp_factor);
  170638. compptr->downsampled_height = (JDIMENSION)
  170639. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170640. (long) cinfo->max_v_samp_factor);
  170641. /* Mark component needed, until color conversion says otherwise */
  170642. compptr->component_needed = TRUE;
  170643. /* Mark no quantization table yet saved for component */
  170644. compptr->quant_table = NULL;
  170645. }
  170646. /* Compute number of fully interleaved MCU rows. */
  170647. cinfo->total_iMCU_rows = (JDIMENSION)
  170648. jdiv_round_up((long) cinfo->image_height,
  170649. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170650. /* Decide whether file contains multiple scans */
  170651. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170652. cinfo->inputctl->has_multiple_scans = TRUE;
  170653. else
  170654. cinfo->inputctl->has_multiple_scans = FALSE;
  170655. }
  170656. LOCAL(void)
  170657. per_scan_setup2 (j_decompress_ptr cinfo)
  170658. /* Do computations that are needed before processing a JPEG scan */
  170659. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170660. {
  170661. int ci, mcublks, tmp;
  170662. jpeg_component_info *compptr;
  170663. if (cinfo->comps_in_scan == 1) {
  170664. /* Noninterleaved (single-component) scan */
  170665. compptr = cinfo->cur_comp_info[0];
  170666. /* Overall image size in MCUs */
  170667. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170668. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170669. /* For noninterleaved scan, always one block per MCU */
  170670. compptr->MCU_width = 1;
  170671. compptr->MCU_height = 1;
  170672. compptr->MCU_blocks = 1;
  170673. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170674. compptr->last_col_width = 1;
  170675. /* For noninterleaved scans, it is convenient to define last_row_height
  170676. * as the number of block rows present in the last iMCU row.
  170677. */
  170678. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170679. if (tmp == 0) tmp = compptr->v_samp_factor;
  170680. compptr->last_row_height = tmp;
  170681. /* Prepare array describing MCU composition */
  170682. cinfo->blocks_in_MCU = 1;
  170683. cinfo->MCU_membership[0] = 0;
  170684. } else {
  170685. /* Interleaved (multi-component) scan */
  170686. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170687. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170688. MAX_COMPS_IN_SCAN);
  170689. /* Overall image size in MCUs */
  170690. cinfo->MCUs_per_row = (JDIMENSION)
  170691. jdiv_round_up((long) cinfo->image_width,
  170692. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170693. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170694. jdiv_round_up((long) cinfo->image_height,
  170695. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170696. cinfo->blocks_in_MCU = 0;
  170697. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170698. compptr = cinfo->cur_comp_info[ci];
  170699. /* Sampling factors give # of blocks of component in each MCU */
  170700. compptr->MCU_width = compptr->h_samp_factor;
  170701. compptr->MCU_height = compptr->v_samp_factor;
  170702. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170703. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170704. /* Figure number of non-dummy blocks in last MCU column & row */
  170705. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170706. if (tmp == 0) tmp = compptr->MCU_width;
  170707. compptr->last_col_width = tmp;
  170708. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170709. if (tmp == 0) tmp = compptr->MCU_height;
  170710. compptr->last_row_height = tmp;
  170711. /* Prepare array describing MCU composition */
  170712. mcublks = compptr->MCU_blocks;
  170713. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170714. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170715. while (mcublks-- > 0) {
  170716. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170717. }
  170718. }
  170719. }
  170720. }
  170721. /*
  170722. * Save away a copy of the Q-table referenced by each component present
  170723. * in the current scan, unless already saved during a prior scan.
  170724. *
  170725. * In a multiple-scan JPEG file, the encoder could assign different components
  170726. * the same Q-table slot number, but change table definitions between scans
  170727. * so that each component uses a different Q-table. (The IJG encoder is not
  170728. * currently capable of doing this, but other encoders might.) Since we want
  170729. * to be able to dequantize all the components at the end of the file, this
  170730. * means that we have to save away the table actually used for each component.
  170731. * We do this by copying the table at the start of the first scan containing
  170732. * the component.
  170733. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170734. * slot between scans of a component using that slot. If the encoder does so
  170735. * anyway, this decoder will simply use the Q-table values that were current
  170736. * at the start of the first scan for the component.
  170737. *
  170738. * The decompressor output side looks only at the saved quant tables,
  170739. * not at the current Q-table slots.
  170740. */
  170741. LOCAL(void)
  170742. latch_quant_tables (j_decompress_ptr cinfo)
  170743. {
  170744. int ci, qtblno;
  170745. jpeg_component_info *compptr;
  170746. JQUANT_TBL * qtbl;
  170747. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170748. compptr = cinfo->cur_comp_info[ci];
  170749. /* No work if we already saved Q-table for this component */
  170750. if (compptr->quant_table != NULL)
  170751. continue;
  170752. /* Make sure specified quantization table is present */
  170753. qtblno = compptr->quant_tbl_no;
  170754. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170755. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170756. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170757. /* OK, save away the quantization table */
  170758. qtbl = (JQUANT_TBL *)
  170759. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170760. SIZEOF(JQUANT_TBL));
  170761. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170762. compptr->quant_table = qtbl;
  170763. }
  170764. }
  170765. /*
  170766. * Initialize the input modules to read a scan of compressed data.
  170767. * The first call to this is done by jdmaster.c after initializing
  170768. * the entire decompressor (during jpeg_start_decompress).
  170769. * Subsequent calls come from consume_markers, below.
  170770. */
  170771. METHODDEF(void)
  170772. start_input_pass2 (j_decompress_ptr cinfo)
  170773. {
  170774. per_scan_setup2(cinfo);
  170775. latch_quant_tables(cinfo);
  170776. (*cinfo->entropy->start_pass) (cinfo);
  170777. (*cinfo->coef->start_input_pass) (cinfo);
  170778. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170779. }
  170780. /*
  170781. * Finish up after inputting a compressed-data scan.
  170782. * This is called by the coefficient controller after it's read all
  170783. * the expected data of the scan.
  170784. */
  170785. METHODDEF(void)
  170786. finish_input_pass (j_decompress_ptr cinfo)
  170787. {
  170788. cinfo->inputctl->consume_input = consume_markers;
  170789. }
  170790. /*
  170791. * Read JPEG markers before, between, or after compressed-data scans.
  170792. * Change state as necessary when a new scan is reached.
  170793. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170794. *
  170795. * The consume_input method pointer points either here or to the
  170796. * coefficient controller's consume_data routine, depending on whether
  170797. * we are reading a compressed data segment or inter-segment markers.
  170798. */
  170799. METHODDEF(int)
  170800. consume_markers (j_decompress_ptr cinfo)
  170801. {
  170802. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170803. int val;
  170804. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170805. return JPEG_REACHED_EOI;
  170806. val = (*cinfo->marker->read_markers) (cinfo);
  170807. switch (val) {
  170808. case JPEG_REACHED_SOS: /* Found SOS */
  170809. if (inputctl->inheaders) { /* 1st SOS */
  170810. initial_setup2(cinfo);
  170811. inputctl->inheaders = FALSE;
  170812. /* Note: start_input_pass must be called by jdmaster.c
  170813. * before any more input can be consumed. jdapimin.c is
  170814. * responsible for enforcing this sequencing.
  170815. */
  170816. } else { /* 2nd or later SOS marker */
  170817. if (! inputctl->pub.has_multiple_scans)
  170818. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170819. start_input_pass2(cinfo);
  170820. }
  170821. break;
  170822. case JPEG_REACHED_EOI: /* Found EOI */
  170823. inputctl->pub.eoi_reached = TRUE;
  170824. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170825. if (cinfo->marker->saw_SOF)
  170826. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170827. } else {
  170828. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170829. * if user set output_scan_number larger than number of scans.
  170830. */
  170831. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170832. cinfo->output_scan_number = cinfo->input_scan_number;
  170833. }
  170834. break;
  170835. case JPEG_SUSPENDED:
  170836. break;
  170837. }
  170838. return val;
  170839. }
  170840. /*
  170841. * Reset state to begin a fresh datastream.
  170842. */
  170843. METHODDEF(void)
  170844. reset_input_controller (j_decompress_ptr cinfo)
  170845. {
  170846. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170847. inputctl->pub.consume_input = consume_markers;
  170848. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170849. inputctl->pub.eoi_reached = FALSE;
  170850. inputctl->inheaders = TRUE;
  170851. /* Reset other modules */
  170852. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170853. (*cinfo->marker->reset_marker_reader) (cinfo);
  170854. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170855. cinfo->coef_bits = NULL;
  170856. }
  170857. /*
  170858. * Initialize the input controller module.
  170859. * This is called only once, when the decompression object is created.
  170860. */
  170861. GLOBAL(void)
  170862. jinit_input_controller (j_decompress_ptr cinfo)
  170863. {
  170864. my_inputctl_ptr inputctl;
  170865. /* Create subobject in permanent pool */
  170866. inputctl = (my_inputctl_ptr)
  170867. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170868. SIZEOF(my_input_controller));
  170869. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170870. /* Initialize method pointers */
  170871. inputctl->pub.consume_input = consume_markers;
  170872. inputctl->pub.reset_input_controller = reset_input_controller;
  170873. inputctl->pub.start_input_pass = start_input_pass2;
  170874. inputctl->pub.finish_input_pass = finish_input_pass;
  170875. /* Initialize state: can't use reset_input_controller since we don't
  170876. * want to try to reset other modules yet.
  170877. */
  170878. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170879. inputctl->pub.eoi_reached = FALSE;
  170880. inputctl->inheaders = TRUE;
  170881. }
  170882. /*** End of inlined file: jdinput.c ***/
  170883. /*** Start of inlined file: jdmainct.c ***/
  170884. #define JPEG_INTERNALS
  170885. /*
  170886. * In the current system design, the main buffer need never be a full-image
  170887. * buffer; any full-height buffers will be found inside the coefficient or
  170888. * postprocessing controllers. Nonetheless, the main controller is not
  170889. * trivial. Its responsibility is to provide context rows for upsampling/
  170890. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170891. *
  170892. * Postprocessor input data is counted in "row groups". A row group
  170893. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170894. * sample rows of each component. (We require DCT_scaled_size values to be
  170895. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170896. * values will likely be powers of two, so we actually have the stronger
  170897. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170898. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170899. * row group (times any additional scale factor that the upsampler is
  170900. * applying).
  170901. *
  170902. * The coefficient controller will deliver data to us one iMCU row at a time;
  170903. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170904. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170905. * to one row of MCUs when the image is fully interleaved.) Note that the
  170906. * number of sample rows varies across components, but the number of row
  170907. * groups does not. Some garbage sample rows may be included in the last iMCU
  170908. * row at the bottom of the image.
  170909. *
  170910. * Depending on the vertical scaling algorithm used, the upsampler may need
  170911. * access to the sample row(s) above and below its current input row group.
  170912. * The upsampler is required to set need_context_rows TRUE at global selection
  170913. * time if so. When need_context_rows is FALSE, this controller can simply
  170914. * obtain one iMCU row at a time from the coefficient controller and dole it
  170915. * out as row groups to the postprocessor.
  170916. *
  170917. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170918. * passed to postprocessing contains at least one row group's worth of samples
  170919. * above and below the row group(s) being processed. Note that the context
  170920. * rows "above" the first passed row group appear at negative row offsets in
  170921. * the passed buffer. At the top and bottom of the image, the required
  170922. * context rows are manufactured by duplicating the first or last real sample
  170923. * row; this avoids having special cases in the upsampling inner loops.
  170924. *
  170925. * The amount of context is fixed at one row group just because that's a
  170926. * convenient number for this controller to work with. The existing
  170927. * upsamplers really only need one sample row of context. An upsampler
  170928. * supporting arbitrary output rescaling might wish for more than one row
  170929. * group of context when shrinking the image; tough, we don't handle that.
  170930. * (This is justified by the assumption that downsizing will be handled mostly
  170931. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170932. * the upsample step needn't be much less than one.)
  170933. *
  170934. * To provide the desired context, we have to retain the last two row groups
  170935. * of one iMCU row while reading in the next iMCU row. (The last row group
  170936. * can't be processed until we have another row group for its below-context,
  170937. * and so we have to save the next-to-last group too for its above-context.)
  170938. * We could do this most simply by copying data around in our buffer, but
  170939. * that'd be very slow. We can avoid copying any data by creating a rather
  170940. * strange pointer structure. Here's how it works. We allocate a workspace
  170941. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170942. * of row groups per iMCU row). We create two sets of redundant pointers to
  170943. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170944. * pointer lists look like this:
  170945. * M+1 M-1
  170946. * master pointer --> 0 master pointer --> 0
  170947. * 1 1
  170948. * ... ...
  170949. * M-3 M-3
  170950. * M-2 M
  170951. * M-1 M+1
  170952. * M M-2
  170953. * M+1 M-1
  170954. * 0 0
  170955. * We read alternate iMCU rows using each master pointer; thus the last two
  170956. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170957. * The pointer lists are set up so that the required context rows appear to
  170958. * be adjacent to the proper places when we pass the pointer lists to the
  170959. * upsampler.
  170960. *
  170961. * The above pictures describe the normal state of the pointer lists.
  170962. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170963. * the first or last sample row as necessary (this is cheaper than copying
  170964. * sample rows around).
  170965. *
  170966. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170967. * situation each iMCU row provides only one row group so the buffering logic
  170968. * must be different (eg, we must read two iMCU rows before we can emit the
  170969. * first row group). For now, we simply do not support providing context
  170970. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170971. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170972. * want it quick and dirty, so a context-free upsampler is sufficient.
  170973. */
  170974. /* Private buffer controller object */
  170975. typedef struct {
  170976. struct jpeg_d_main_controller pub; /* public fields */
  170977. /* Pointer to allocated workspace (M or M+2 row groups). */
  170978. JSAMPARRAY buffer[MAX_COMPONENTS];
  170979. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170980. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170981. /* Remaining fields are only used in the context case. */
  170982. /* These are the master pointers to the funny-order pointer lists. */
  170983. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170984. int whichptr; /* indicates which pointer set is now in use */
  170985. int context_state; /* process_data state machine status */
  170986. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170987. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170988. } my_main_controller4;
  170989. typedef my_main_controller4 * my_main_ptr4;
  170990. /* context_state values: */
  170991. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170992. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170993. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170994. /* Forward declarations */
  170995. METHODDEF(void) process_data_simple_main2
  170996. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170997. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170998. METHODDEF(void) process_data_context_main
  170999. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171000. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171001. #ifdef QUANT_2PASS_SUPPORTED
  171002. METHODDEF(void) process_data_crank_post
  171003. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171004. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171005. #endif
  171006. LOCAL(void)
  171007. alloc_funny_pointers (j_decompress_ptr cinfo)
  171008. /* Allocate space for the funny pointer lists.
  171009. * This is done only once, not once per pass.
  171010. */
  171011. {
  171012. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171013. int ci, rgroup;
  171014. int M = cinfo->min_DCT_scaled_size;
  171015. jpeg_component_info *compptr;
  171016. JSAMPARRAY xbuf;
  171017. /* Get top-level space for component array pointers.
  171018. * We alloc both arrays with one call to save a few cycles.
  171019. */
  171020. main_->xbuffer[0] = (JSAMPIMAGE)
  171021. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171022. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  171023. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  171024. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171025. ci++, compptr++) {
  171026. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171027. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171028. /* Get space for pointer lists --- M+4 row groups in each list.
  171029. * We alloc both pointer lists with one call to save a few cycles.
  171030. */
  171031. xbuf = (JSAMPARRAY)
  171032. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171033. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  171034. xbuf += rgroup; /* want one row group at negative offsets */
  171035. main_->xbuffer[0][ci] = xbuf;
  171036. xbuf += rgroup * (M + 4);
  171037. main_->xbuffer[1][ci] = xbuf;
  171038. }
  171039. }
  171040. LOCAL(void)
  171041. make_funny_pointers (j_decompress_ptr cinfo)
  171042. /* Create the funny pointer lists discussed in the comments above.
  171043. * The actual workspace is already allocated (in main->buffer),
  171044. * and the space for the pointer lists is allocated too.
  171045. * This routine just fills in the curiously ordered lists.
  171046. * This will be repeated at the beginning of each pass.
  171047. */
  171048. {
  171049. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171050. int ci, i, rgroup;
  171051. int M = cinfo->min_DCT_scaled_size;
  171052. jpeg_component_info *compptr;
  171053. JSAMPARRAY buf, xbuf0, xbuf1;
  171054. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171055. ci++, compptr++) {
  171056. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171057. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171058. xbuf0 = main_->xbuffer[0][ci];
  171059. xbuf1 = main_->xbuffer[1][ci];
  171060. /* First copy the workspace pointers as-is */
  171061. buf = main_->buffer[ci];
  171062. for (i = 0; i < rgroup * (M + 2); i++) {
  171063. xbuf0[i] = xbuf1[i] = buf[i];
  171064. }
  171065. /* In the second list, put the last four row groups in swapped order */
  171066. for (i = 0; i < rgroup * 2; i++) {
  171067. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  171068. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  171069. }
  171070. /* The wraparound pointers at top and bottom will be filled later
  171071. * (see set_wraparound_pointers, below). Initially we want the "above"
  171072. * pointers to duplicate the first actual data line. This only needs
  171073. * to happen in xbuffer[0].
  171074. */
  171075. for (i = 0; i < rgroup; i++) {
  171076. xbuf0[i - rgroup] = xbuf0[0];
  171077. }
  171078. }
  171079. }
  171080. LOCAL(void)
  171081. set_wraparound_pointers (j_decompress_ptr cinfo)
  171082. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  171083. * This changes the pointer list state from top-of-image to the normal state.
  171084. */
  171085. {
  171086. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171087. int ci, i, rgroup;
  171088. int M = cinfo->min_DCT_scaled_size;
  171089. jpeg_component_info *compptr;
  171090. JSAMPARRAY xbuf0, xbuf1;
  171091. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171092. ci++, compptr++) {
  171093. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171094. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171095. xbuf0 = main_->xbuffer[0][ci];
  171096. xbuf1 = main_->xbuffer[1][ci];
  171097. for (i = 0; i < rgroup; i++) {
  171098. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  171099. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  171100. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  171101. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  171102. }
  171103. }
  171104. }
  171105. LOCAL(void)
  171106. set_bottom_pointers (j_decompress_ptr cinfo)
  171107. /* Change the pointer lists to duplicate the last sample row at the bottom
  171108. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  171109. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  171110. */
  171111. {
  171112. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171113. int ci, i, rgroup, iMCUheight, rows_left;
  171114. jpeg_component_info *compptr;
  171115. JSAMPARRAY xbuf;
  171116. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171117. ci++, compptr++) {
  171118. /* Count sample rows in one iMCU row and in one row group */
  171119. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171120. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171121. /* Count nondummy sample rows remaining for this component */
  171122. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171123. if (rows_left == 0) rows_left = iMCUheight;
  171124. /* Count nondummy row groups. Should get same answer for each component,
  171125. * so we need only do it once.
  171126. */
  171127. if (ci == 0) {
  171128. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171129. }
  171130. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171131. * last partial rowgroup and ensures at least one full rowgroup of context.
  171132. */
  171133. xbuf = main_->xbuffer[main_->whichptr][ci];
  171134. for (i = 0; i < rgroup * 2; i++) {
  171135. xbuf[rows_left + i] = xbuf[rows_left-1];
  171136. }
  171137. }
  171138. }
  171139. /*
  171140. * Initialize for a processing pass.
  171141. */
  171142. METHODDEF(void)
  171143. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171144. {
  171145. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171146. switch (pass_mode) {
  171147. case JBUF_PASS_THRU:
  171148. if (cinfo->upsample->need_context_rows) {
  171149. main_->pub.process_data = process_data_context_main;
  171150. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171151. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171152. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171153. main_->iMCU_row_ctr = 0;
  171154. } else {
  171155. /* Simple case with no context needed */
  171156. main_->pub.process_data = process_data_simple_main2;
  171157. }
  171158. main_->buffer_full = FALSE; /* Mark buffer empty */
  171159. main_->rowgroup_ctr = 0;
  171160. break;
  171161. #ifdef QUANT_2PASS_SUPPORTED
  171162. case JBUF_CRANK_DEST:
  171163. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171164. main_->pub.process_data = process_data_crank_post;
  171165. break;
  171166. #endif
  171167. default:
  171168. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171169. break;
  171170. }
  171171. }
  171172. /*
  171173. * Process some data.
  171174. * This handles the simple case where no context is required.
  171175. */
  171176. METHODDEF(void)
  171177. process_data_simple_main2 (j_decompress_ptr cinfo,
  171178. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171179. JDIMENSION out_rows_avail)
  171180. {
  171181. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171182. JDIMENSION rowgroups_avail;
  171183. /* Read input data if we haven't filled the main buffer yet */
  171184. if (! main_->buffer_full) {
  171185. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171186. return; /* suspension forced, can do nothing more */
  171187. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171188. }
  171189. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171190. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171191. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171192. * to the postprocessor. The postprocessor has to check for bottom
  171193. * of image anyway (at row resolution), so no point in us doing it too.
  171194. */
  171195. /* Feed the postprocessor */
  171196. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171197. &main_->rowgroup_ctr, rowgroups_avail,
  171198. output_buf, out_row_ctr, out_rows_avail);
  171199. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171200. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171201. main_->buffer_full = FALSE;
  171202. main_->rowgroup_ctr = 0;
  171203. }
  171204. }
  171205. /*
  171206. * Process some data.
  171207. * This handles the case where context rows must be provided.
  171208. */
  171209. METHODDEF(void)
  171210. process_data_context_main (j_decompress_ptr cinfo,
  171211. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171212. JDIMENSION out_rows_avail)
  171213. {
  171214. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171215. /* Read input data if we haven't filled the main buffer yet */
  171216. if (! main_->buffer_full) {
  171217. if (! (*cinfo->coef->decompress_data) (cinfo,
  171218. main_->xbuffer[main_->whichptr]))
  171219. return; /* suspension forced, can do nothing more */
  171220. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171221. main_->iMCU_row_ctr++; /* count rows received */
  171222. }
  171223. /* Postprocessor typically will not swallow all the input data it is handed
  171224. * in one call (due to filling the output buffer first). Must be prepared
  171225. * to exit and restart. This switch lets us keep track of how far we got.
  171226. * Note that each case falls through to the next on successful completion.
  171227. */
  171228. switch (main_->context_state) {
  171229. case CTX_POSTPONED_ROW:
  171230. /* Call postprocessor using previously set pointers for postponed row */
  171231. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171232. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171233. output_buf, out_row_ctr, out_rows_avail);
  171234. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171235. return; /* Need to suspend */
  171236. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171237. if (*out_row_ctr >= out_rows_avail)
  171238. return; /* Postprocessor exactly filled output buf */
  171239. /*FALLTHROUGH*/
  171240. case CTX_PREPARE_FOR_IMCU:
  171241. /* Prepare to process first M-1 row groups of this iMCU row */
  171242. main_->rowgroup_ctr = 0;
  171243. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171244. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171245. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171246. */
  171247. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171248. set_bottom_pointers(cinfo);
  171249. main_->context_state = CTX_PROCESS_IMCU;
  171250. /*FALLTHROUGH*/
  171251. case CTX_PROCESS_IMCU:
  171252. /* Call postprocessor using previously set pointers */
  171253. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171254. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171255. output_buf, out_row_ctr, out_rows_avail);
  171256. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171257. return; /* Need to suspend */
  171258. /* After the first iMCU, change wraparound pointers to normal state */
  171259. if (main_->iMCU_row_ctr == 1)
  171260. set_wraparound_pointers(cinfo);
  171261. /* Prepare to load new iMCU row using other xbuffer list */
  171262. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171263. main_->buffer_full = FALSE;
  171264. /* Still need to process last row group of this iMCU row, */
  171265. /* which is saved at index M+1 of the other xbuffer */
  171266. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171267. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171268. main_->context_state = CTX_POSTPONED_ROW;
  171269. }
  171270. }
  171271. /*
  171272. * Process some data.
  171273. * Final pass of two-pass quantization: just call the postprocessor.
  171274. * Source data will be the postprocessor controller's internal buffer.
  171275. */
  171276. #ifdef QUANT_2PASS_SUPPORTED
  171277. METHODDEF(void)
  171278. process_data_crank_post (j_decompress_ptr cinfo,
  171279. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171280. JDIMENSION out_rows_avail)
  171281. {
  171282. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171283. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171284. output_buf, out_row_ctr, out_rows_avail);
  171285. }
  171286. #endif /* QUANT_2PASS_SUPPORTED */
  171287. /*
  171288. * Initialize main buffer controller.
  171289. */
  171290. GLOBAL(void)
  171291. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171292. {
  171293. my_main_ptr4 main_;
  171294. int ci, rgroup, ngroups;
  171295. jpeg_component_info *compptr;
  171296. main_ = (my_main_ptr4)
  171297. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171298. SIZEOF(my_main_controller4));
  171299. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171300. main_->pub.start_pass = start_pass_main2;
  171301. if (need_full_buffer) /* shouldn't happen */
  171302. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171303. /* Allocate the workspace.
  171304. * ngroups is the number of row groups we need.
  171305. */
  171306. if (cinfo->upsample->need_context_rows) {
  171307. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171308. ERREXIT(cinfo, JERR_NOTIMPL);
  171309. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171310. ngroups = cinfo->min_DCT_scaled_size + 2;
  171311. } else {
  171312. ngroups = cinfo->min_DCT_scaled_size;
  171313. }
  171314. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171315. ci++, compptr++) {
  171316. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171317. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171318. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171319. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171320. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171321. (JDIMENSION) (rgroup * ngroups));
  171322. }
  171323. }
  171324. /*** End of inlined file: jdmainct.c ***/
  171325. /*** Start of inlined file: jdmarker.c ***/
  171326. #define JPEG_INTERNALS
  171327. /* Private state */
  171328. typedef struct {
  171329. struct jpeg_marker_reader pub; /* public fields */
  171330. /* Application-overridable marker processing methods */
  171331. jpeg_marker_parser_method process_COM;
  171332. jpeg_marker_parser_method process_APPn[16];
  171333. /* Limit on marker data length to save for each marker type */
  171334. unsigned int length_limit_COM;
  171335. unsigned int length_limit_APPn[16];
  171336. /* Status of COM/APPn marker saving */
  171337. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171338. unsigned int bytes_read; /* data bytes read so far in marker */
  171339. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171340. } my_marker_reader;
  171341. typedef my_marker_reader * my_marker_ptr2;
  171342. /*
  171343. * Macros for fetching data from the data source module.
  171344. *
  171345. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171346. * the current restart point; we update them only when we have reached a
  171347. * suitable place to restart if a suspension occurs.
  171348. */
  171349. /* Declare and initialize local copies of input pointer/count */
  171350. #define INPUT_VARS(cinfo) \
  171351. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171352. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171353. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171354. /* Unload the local copies --- do this only at a restart boundary */
  171355. #define INPUT_SYNC(cinfo) \
  171356. ( datasrc->next_input_byte = next_input_byte, \
  171357. datasrc->bytes_in_buffer = bytes_in_buffer )
  171358. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171359. #define INPUT_RELOAD(cinfo) \
  171360. ( next_input_byte = datasrc->next_input_byte, \
  171361. bytes_in_buffer = datasrc->bytes_in_buffer )
  171362. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171363. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171364. * but we must reload the local copies after a successful fill.
  171365. */
  171366. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171367. if (bytes_in_buffer == 0) { \
  171368. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171369. { action; } \
  171370. INPUT_RELOAD(cinfo); \
  171371. }
  171372. /* Read a byte into variable V.
  171373. * If must suspend, take the specified action (typically "return FALSE").
  171374. */
  171375. #define INPUT_BYTE(cinfo,V,action) \
  171376. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171377. bytes_in_buffer--; \
  171378. V = GETJOCTET(*next_input_byte++); )
  171379. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171380. * V should be declared unsigned int or perhaps INT32.
  171381. */
  171382. #define INPUT_2BYTES(cinfo,V,action) \
  171383. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171384. bytes_in_buffer--; \
  171385. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171386. MAKE_BYTE_AVAIL(cinfo,action); \
  171387. bytes_in_buffer--; \
  171388. V += GETJOCTET(*next_input_byte++); )
  171389. /*
  171390. * Routines to process JPEG markers.
  171391. *
  171392. * Entry condition: JPEG marker itself has been read and its code saved
  171393. * in cinfo->unread_marker; input restart point is just after the marker.
  171394. *
  171395. * Exit: if return TRUE, have read and processed any parameters, and have
  171396. * updated the restart point to point after the parameters.
  171397. * If return FALSE, was forced to suspend before reaching end of
  171398. * marker parameters; restart point has not been moved. Same routine
  171399. * will be called again after application supplies more input data.
  171400. *
  171401. * This approach to suspension assumes that all of a marker's parameters
  171402. * can fit into a single input bufferload. This should hold for "normal"
  171403. * markers. Some COM/APPn markers might have large parameter segments
  171404. * that might not fit. If we are simply dropping such a marker, we use
  171405. * skip_input_data to get past it, and thereby put the problem on the
  171406. * source manager's shoulders. If we are saving the marker's contents
  171407. * into memory, we use a slightly different convention: when forced to
  171408. * suspend, the marker processor updates the restart point to the end of
  171409. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171410. * On resumption, cinfo->unread_marker still contains the marker code,
  171411. * but the data source will point to the next chunk of marker data.
  171412. * The marker processor must retain internal state to deal with this.
  171413. *
  171414. * Note that we don't bother to avoid duplicate trace messages if a
  171415. * suspension occurs within marker parameters. Other side effects
  171416. * require more care.
  171417. */
  171418. LOCAL(boolean)
  171419. get_soi (j_decompress_ptr cinfo)
  171420. /* Process an SOI marker */
  171421. {
  171422. int i;
  171423. TRACEMS(cinfo, 1, JTRC_SOI);
  171424. if (cinfo->marker->saw_SOI)
  171425. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171426. /* Reset all parameters that are defined to be reset by SOI */
  171427. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171428. cinfo->arith_dc_L[i] = 0;
  171429. cinfo->arith_dc_U[i] = 1;
  171430. cinfo->arith_ac_K[i] = 5;
  171431. }
  171432. cinfo->restart_interval = 0;
  171433. /* Set initial assumptions for colorspace etc */
  171434. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171435. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171436. cinfo->saw_JFIF_marker = FALSE;
  171437. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171438. cinfo->JFIF_minor_version = 1;
  171439. cinfo->density_unit = 0;
  171440. cinfo->X_density = 1;
  171441. cinfo->Y_density = 1;
  171442. cinfo->saw_Adobe_marker = FALSE;
  171443. cinfo->Adobe_transform = 0;
  171444. cinfo->marker->saw_SOI = TRUE;
  171445. return TRUE;
  171446. }
  171447. LOCAL(boolean)
  171448. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171449. /* Process a SOFn marker */
  171450. {
  171451. INT32 length;
  171452. int c, ci;
  171453. jpeg_component_info * compptr;
  171454. INPUT_VARS(cinfo);
  171455. cinfo->progressive_mode = is_prog;
  171456. cinfo->arith_code = is_arith;
  171457. INPUT_2BYTES(cinfo, length, return FALSE);
  171458. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171459. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171460. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171461. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171462. length -= 8;
  171463. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171464. (int) cinfo->image_width, (int) cinfo->image_height,
  171465. cinfo->num_components);
  171466. if (cinfo->marker->saw_SOF)
  171467. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171468. /* We don't support files in which the image height is initially specified */
  171469. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171470. /* might as well have a general sanity check. */
  171471. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171472. || cinfo->num_components <= 0)
  171473. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171474. if (length != (cinfo->num_components * 3))
  171475. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171476. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171477. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171478. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171479. cinfo->num_components * SIZEOF(jpeg_component_info));
  171480. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171481. ci++, compptr++) {
  171482. compptr->component_index = ci;
  171483. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171484. INPUT_BYTE(cinfo, c, return FALSE);
  171485. compptr->h_samp_factor = (c >> 4) & 15;
  171486. compptr->v_samp_factor = (c ) & 15;
  171487. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171488. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171489. compptr->component_id, compptr->h_samp_factor,
  171490. compptr->v_samp_factor, compptr->quant_tbl_no);
  171491. }
  171492. cinfo->marker->saw_SOF = TRUE;
  171493. INPUT_SYNC(cinfo);
  171494. return TRUE;
  171495. }
  171496. LOCAL(boolean)
  171497. get_sos (j_decompress_ptr cinfo)
  171498. /* Process a SOS marker */
  171499. {
  171500. INT32 length;
  171501. int i, ci, n, c, cc;
  171502. jpeg_component_info * compptr;
  171503. INPUT_VARS(cinfo);
  171504. if (! cinfo->marker->saw_SOF)
  171505. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171506. INPUT_2BYTES(cinfo, length, return FALSE);
  171507. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171508. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171509. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171510. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171511. cinfo->comps_in_scan = n;
  171512. /* Collect the component-spec parameters */
  171513. for (i = 0; i < n; i++) {
  171514. INPUT_BYTE(cinfo, cc, return FALSE);
  171515. INPUT_BYTE(cinfo, c, return FALSE);
  171516. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171517. ci++, compptr++) {
  171518. if (cc == compptr->component_id)
  171519. goto id_found;
  171520. }
  171521. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171522. id_found:
  171523. cinfo->cur_comp_info[i] = compptr;
  171524. compptr->dc_tbl_no = (c >> 4) & 15;
  171525. compptr->ac_tbl_no = (c ) & 15;
  171526. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171527. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171528. }
  171529. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171530. INPUT_BYTE(cinfo, c, return FALSE);
  171531. cinfo->Ss = c;
  171532. INPUT_BYTE(cinfo, c, return FALSE);
  171533. cinfo->Se = c;
  171534. INPUT_BYTE(cinfo, c, return FALSE);
  171535. cinfo->Ah = (c >> 4) & 15;
  171536. cinfo->Al = (c ) & 15;
  171537. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171538. cinfo->Ah, cinfo->Al);
  171539. /* Prepare to scan data & restart markers */
  171540. cinfo->marker->next_restart_num = 0;
  171541. /* Count another SOS marker */
  171542. cinfo->input_scan_number++;
  171543. INPUT_SYNC(cinfo);
  171544. return TRUE;
  171545. }
  171546. #ifdef D_ARITH_CODING_SUPPORTED
  171547. LOCAL(boolean)
  171548. get_dac (j_decompress_ptr cinfo)
  171549. /* Process a DAC marker */
  171550. {
  171551. INT32 length;
  171552. int index, val;
  171553. INPUT_VARS(cinfo);
  171554. INPUT_2BYTES(cinfo, length, return FALSE);
  171555. length -= 2;
  171556. while (length > 0) {
  171557. INPUT_BYTE(cinfo, index, return FALSE);
  171558. INPUT_BYTE(cinfo, val, return FALSE);
  171559. length -= 2;
  171560. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171561. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171562. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171563. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171564. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171565. } else { /* define DC table */
  171566. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171567. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171568. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171569. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171570. }
  171571. }
  171572. if (length != 0)
  171573. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171574. INPUT_SYNC(cinfo);
  171575. return TRUE;
  171576. }
  171577. #else /* ! D_ARITH_CODING_SUPPORTED */
  171578. #define get_dac(cinfo) skip_variable(cinfo)
  171579. #endif /* D_ARITH_CODING_SUPPORTED */
  171580. LOCAL(boolean)
  171581. get_dht (j_decompress_ptr cinfo)
  171582. /* Process a DHT marker */
  171583. {
  171584. INT32 length;
  171585. UINT8 bits[17];
  171586. UINT8 huffval[256];
  171587. int i, index, count;
  171588. JHUFF_TBL **htblptr;
  171589. INPUT_VARS(cinfo);
  171590. INPUT_2BYTES(cinfo, length, return FALSE);
  171591. length -= 2;
  171592. while (length > 16) {
  171593. INPUT_BYTE(cinfo, index, return FALSE);
  171594. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171595. bits[0] = 0;
  171596. count = 0;
  171597. for (i = 1; i <= 16; i++) {
  171598. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171599. count += bits[i];
  171600. }
  171601. length -= 1 + 16;
  171602. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171603. bits[1], bits[2], bits[3], bits[4],
  171604. bits[5], bits[6], bits[7], bits[8]);
  171605. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171606. bits[9], bits[10], bits[11], bits[12],
  171607. bits[13], bits[14], bits[15], bits[16]);
  171608. /* Here we just do minimal validation of the counts to avoid walking
  171609. * off the end of our table space. jdhuff.c will check more carefully.
  171610. */
  171611. if (count > 256 || ((INT32) count) > length)
  171612. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171613. for (i = 0; i < count; i++)
  171614. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171615. length -= count;
  171616. if (index & 0x10) { /* AC table definition */
  171617. index -= 0x10;
  171618. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171619. } else { /* DC table definition */
  171620. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171621. }
  171622. if (index < 0 || index >= NUM_HUFF_TBLS)
  171623. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171624. if (*htblptr == NULL)
  171625. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171626. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171627. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171628. }
  171629. if (length != 0)
  171630. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171631. INPUT_SYNC(cinfo);
  171632. return TRUE;
  171633. }
  171634. LOCAL(boolean)
  171635. get_dqt (j_decompress_ptr cinfo)
  171636. /* Process a DQT marker */
  171637. {
  171638. INT32 length;
  171639. int n, i, prec;
  171640. unsigned int tmp;
  171641. JQUANT_TBL *quant_ptr;
  171642. INPUT_VARS(cinfo);
  171643. INPUT_2BYTES(cinfo, length, return FALSE);
  171644. length -= 2;
  171645. while (length > 0) {
  171646. INPUT_BYTE(cinfo, n, return FALSE);
  171647. prec = n >> 4;
  171648. n &= 0x0F;
  171649. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171650. if (n >= NUM_QUANT_TBLS)
  171651. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171652. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171653. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171654. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171655. for (i = 0; i < DCTSIZE2; i++) {
  171656. if (prec)
  171657. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171658. else
  171659. INPUT_BYTE(cinfo, tmp, return FALSE);
  171660. /* We convert the zigzag-order table to natural array order. */
  171661. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171662. }
  171663. if (cinfo->err->trace_level >= 2) {
  171664. for (i = 0; i < DCTSIZE2; i += 8) {
  171665. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171666. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171667. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171668. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171669. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171670. }
  171671. }
  171672. length -= DCTSIZE2+1;
  171673. if (prec) length -= DCTSIZE2;
  171674. }
  171675. if (length != 0)
  171676. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171677. INPUT_SYNC(cinfo);
  171678. return TRUE;
  171679. }
  171680. LOCAL(boolean)
  171681. get_dri (j_decompress_ptr cinfo)
  171682. /* Process a DRI marker */
  171683. {
  171684. INT32 length;
  171685. unsigned int tmp;
  171686. INPUT_VARS(cinfo);
  171687. INPUT_2BYTES(cinfo, length, return FALSE);
  171688. if (length != 4)
  171689. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171690. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171691. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171692. cinfo->restart_interval = tmp;
  171693. INPUT_SYNC(cinfo);
  171694. return TRUE;
  171695. }
  171696. /*
  171697. * Routines for processing APPn and COM markers.
  171698. * These are either saved in memory or discarded, per application request.
  171699. * APP0 and APP14 are specially checked to see if they are
  171700. * JFIF and Adobe markers, respectively.
  171701. */
  171702. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171703. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171704. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171705. LOCAL(void)
  171706. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171707. unsigned int datalen, INT32 remaining)
  171708. /* Examine first few bytes from an APP0.
  171709. * Take appropriate action if it is a JFIF marker.
  171710. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171711. */
  171712. {
  171713. INT32 totallen = (INT32) datalen + remaining;
  171714. if (datalen >= APP0_DATA_LEN &&
  171715. GETJOCTET(data[0]) == 0x4A &&
  171716. GETJOCTET(data[1]) == 0x46 &&
  171717. GETJOCTET(data[2]) == 0x49 &&
  171718. GETJOCTET(data[3]) == 0x46 &&
  171719. GETJOCTET(data[4]) == 0) {
  171720. /* Found JFIF APP0 marker: save info */
  171721. cinfo->saw_JFIF_marker = TRUE;
  171722. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171723. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171724. cinfo->density_unit = GETJOCTET(data[7]);
  171725. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171726. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171727. /* Check version.
  171728. * Major version must be 1, anything else signals an incompatible change.
  171729. * (We used to treat this as an error, but now it's a nonfatal warning,
  171730. * because some bozo at Hijaak couldn't read the spec.)
  171731. * Minor version should be 0..2, but process anyway if newer.
  171732. */
  171733. if (cinfo->JFIF_major_version != 1)
  171734. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171735. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171736. /* Generate trace messages */
  171737. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171738. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171739. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171740. /* Validate thumbnail dimensions and issue appropriate messages */
  171741. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171742. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171743. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171744. totallen -= APP0_DATA_LEN;
  171745. if (totallen !=
  171746. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171747. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171748. } else if (datalen >= 6 &&
  171749. GETJOCTET(data[0]) == 0x4A &&
  171750. GETJOCTET(data[1]) == 0x46 &&
  171751. GETJOCTET(data[2]) == 0x58 &&
  171752. GETJOCTET(data[3]) == 0x58 &&
  171753. GETJOCTET(data[4]) == 0) {
  171754. /* Found JFIF "JFXX" extension APP0 marker */
  171755. /* The library doesn't actually do anything with these,
  171756. * but we try to produce a helpful trace message.
  171757. */
  171758. switch (GETJOCTET(data[5])) {
  171759. case 0x10:
  171760. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171761. break;
  171762. case 0x11:
  171763. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171764. break;
  171765. case 0x13:
  171766. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171767. break;
  171768. default:
  171769. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171770. GETJOCTET(data[5]), (int) totallen);
  171771. break;
  171772. }
  171773. } else {
  171774. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171775. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171776. }
  171777. }
  171778. LOCAL(void)
  171779. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171780. unsigned int datalen, INT32 remaining)
  171781. /* Examine first few bytes from an APP14.
  171782. * Take appropriate action if it is an Adobe marker.
  171783. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171784. */
  171785. {
  171786. unsigned int version, flags0, flags1, transform;
  171787. if (datalen >= APP14_DATA_LEN &&
  171788. GETJOCTET(data[0]) == 0x41 &&
  171789. GETJOCTET(data[1]) == 0x64 &&
  171790. GETJOCTET(data[2]) == 0x6F &&
  171791. GETJOCTET(data[3]) == 0x62 &&
  171792. GETJOCTET(data[4]) == 0x65) {
  171793. /* Found Adobe APP14 marker */
  171794. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171795. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171796. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171797. transform = GETJOCTET(data[11]);
  171798. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171799. cinfo->saw_Adobe_marker = TRUE;
  171800. cinfo->Adobe_transform = (UINT8) transform;
  171801. } else {
  171802. /* Start of APP14 does not match "Adobe", or too short */
  171803. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171804. }
  171805. }
  171806. METHODDEF(boolean)
  171807. get_interesting_appn (j_decompress_ptr cinfo)
  171808. /* Process an APP0 or APP14 marker without saving it */
  171809. {
  171810. INT32 length;
  171811. JOCTET b[APPN_DATA_LEN];
  171812. unsigned int i, numtoread;
  171813. INPUT_VARS(cinfo);
  171814. INPUT_2BYTES(cinfo, length, return FALSE);
  171815. length -= 2;
  171816. /* get the interesting part of the marker data */
  171817. if (length >= APPN_DATA_LEN)
  171818. numtoread = APPN_DATA_LEN;
  171819. else if (length > 0)
  171820. numtoread = (unsigned int) length;
  171821. else
  171822. numtoread = 0;
  171823. for (i = 0; i < numtoread; i++)
  171824. INPUT_BYTE(cinfo, b[i], return FALSE);
  171825. length -= numtoread;
  171826. /* process it */
  171827. switch (cinfo->unread_marker) {
  171828. case M_APP0:
  171829. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171830. break;
  171831. case M_APP14:
  171832. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171833. break;
  171834. default:
  171835. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171836. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171837. break;
  171838. }
  171839. /* skip any remaining data -- could be lots */
  171840. INPUT_SYNC(cinfo);
  171841. if (length > 0)
  171842. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171843. return TRUE;
  171844. }
  171845. #ifdef SAVE_MARKERS_SUPPORTED
  171846. METHODDEF(boolean)
  171847. save_marker (j_decompress_ptr cinfo)
  171848. /* Save an APPn or COM marker into the marker list */
  171849. {
  171850. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171851. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171852. unsigned int bytes_read, data_length;
  171853. JOCTET FAR * data;
  171854. INT32 length = 0;
  171855. INPUT_VARS(cinfo);
  171856. if (cur_marker == NULL) {
  171857. /* begin reading a marker */
  171858. INPUT_2BYTES(cinfo, length, return FALSE);
  171859. length -= 2;
  171860. if (length >= 0) { /* watch out for bogus length word */
  171861. /* figure out how much we want to save */
  171862. unsigned int limit;
  171863. if (cinfo->unread_marker == (int) M_COM)
  171864. limit = marker->length_limit_COM;
  171865. else
  171866. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171867. if ((unsigned int) length < limit)
  171868. limit = (unsigned int) length;
  171869. /* allocate and initialize the marker item */
  171870. cur_marker = (jpeg_saved_marker_ptr)
  171871. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171872. SIZEOF(struct jpeg_marker_struct) + limit);
  171873. cur_marker->next = NULL;
  171874. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171875. cur_marker->original_length = (unsigned int) length;
  171876. cur_marker->data_length = limit;
  171877. /* data area is just beyond the jpeg_marker_struct */
  171878. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171879. marker->cur_marker = cur_marker;
  171880. marker->bytes_read = 0;
  171881. bytes_read = 0;
  171882. data_length = limit;
  171883. } else {
  171884. /* deal with bogus length word */
  171885. bytes_read = data_length = 0;
  171886. data = NULL;
  171887. }
  171888. } else {
  171889. /* resume reading a marker */
  171890. bytes_read = marker->bytes_read;
  171891. data_length = cur_marker->data_length;
  171892. data = cur_marker->data + bytes_read;
  171893. }
  171894. while (bytes_read < data_length) {
  171895. INPUT_SYNC(cinfo); /* move the restart point to here */
  171896. marker->bytes_read = bytes_read;
  171897. /* If there's not at least one byte in buffer, suspend */
  171898. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171899. /* Copy bytes with reasonable rapidity */
  171900. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171901. *data++ = *next_input_byte++;
  171902. bytes_in_buffer--;
  171903. bytes_read++;
  171904. }
  171905. }
  171906. /* Done reading what we want to read */
  171907. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171908. /* Add new marker to end of list */
  171909. if (cinfo->marker_list == NULL) {
  171910. cinfo->marker_list = cur_marker;
  171911. } else {
  171912. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171913. while (prev->next != NULL)
  171914. prev = prev->next;
  171915. prev->next = cur_marker;
  171916. }
  171917. /* Reset pointer & calc remaining data length */
  171918. data = cur_marker->data;
  171919. length = cur_marker->original_length - data_length;
  171920. }
  171921. /* Reset to initial state for next marker */
  171922. marker->cur_marker = NULL;
  171923. /* Process the marker if interesting; else just make a generic trace msg */
  171924. switch (cinfo->unread_marker) {
  171925. case M_APP0:
  171926. examine_app0(cinfo, data, data_length, length);
  171927. break;
  171928. case M_APP14:
  171929. examine_app14(cinfo, data, data_length, length);
  171930. break;
  171931. default:
  171932. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171933. (int) (data_length + length));
  171934. break;
  171935. }
  171936. /* skip any remaining data -- could be lots */
  171937. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171938. if (length > 0)
  171939. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171940. return TRUE;
  171941. }
  171942. #endif /* SAVE_MARKERS_SUPPORTED */
  171943. METHODDEF(boolean)
  171944. skip_variable (j_decompress_ptr cinfo)
  171945. /* Skip over an unknown or uninteresting variable-length marker */
  171946. {
  171947. INT32 length;
  171948. INPUT_VARS(cinfo);
  171949. INPUT_2BYTES(cinfo, length, return FALSE);
  171950. length -= 2;
  171951. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171952. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171953. if (length > 0)
  171954. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171955. return TRUE;
  171956. }
  171957. /*
  171958. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171959. * Returns FALSE if had to suspend before reaching a marker;
  171960. * in that case cinfo->unread_marker is unchanged.
  171961. *
  171962. * Note that the result might not be a valid marker code,
  171963. * but it will never be 0 or FF.
  171964. */
  171965. LOCAL(boolean)
  171966. next_marker (j_decompress_ptr cinfo)
  171967. {
  171968. int c;
  171969. INPUT_VARS(cinfo);
  171970. for (;;) {
  171971. INPUT_BYTE(cinfo, c, return FALSE);
  171972. /* Skip any non-FF bytes.
  171973. * This may look a bit inefficient, but it will not occur in a valid file.
  171974. * We sync after each discarded byte so that a suspending data source
  171975. * can discard the byte from its buffer.
  171976. */
  171977. while (c != 0xFF) {
  171978. cinfo->marker->discarded_bytes++;
  171979. INPUT_SYNC(cinfo);
  171980. INPUT_BYTE(cinfo, c, return FALSE);
  171981. }
  171982. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171983. * pad bytes, so don't count them in discarded_bytes. We assume there
  171984. * will not be so many consecutive FF bytes as to overflow a suspending
  171985. * data source's input buffer.
  171986. */
  171987. do {
  171988. INPUT_BYTE(cinfo, c, return FALSE);
  171989. } while (c == 0xFF);
  171990. if (c != 0)
  171991. break; /* found a valid marker, exit loop */
  171992. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171993. * Discard it and loop back to try again.
  171994. */
  171995. cinfo->marker->discarded_bytes += 2;
  171996. INPUT_SYNC(cinfo);
  171997. }
  171998. if (cinfo->marker->discarded_bytes != 0) {
  171999. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  172000. cinfo->marker->discarded_bytes = 0;
  172001. }
  172002. cinfo->unread_marker = c;
  172003. INPUT_SYNC(cinfo);
  172004. return TRUE;
  172005. }
  172006. LOCAL(boolean)
  172007. first_marker (j_decompress_ptr cinfo)
  172008. /* Like next_marker, but used to obtain the initial SOI marker. */
  172009. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  172010. * we might well scan an entire input file before realizing it ain't JPEG.
  172011. * If an application wants to process non-JFIF files, it must seek to the
  172012. * SOI before calling the JPEG library.
  172013. */
  172014. {
  172015. int c, c2;
  172016. INPUT_VARS(cinfo);
  172017. INPUT_BYTE(cinfo, c, return FALSE);
  172018. INPUT_BYTE(cinfo, c2, return FALSE);
  172019. if (c != 0xFF || c2 != (int) M_SOI)
  172020. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  172021. cinfo->unread_marker = c2;
  172022. INPUT_SYNC(cinfo);
  172023. return TRUE;
  172024. }
  172025. /*
  172026. * Read markers until SOS or EOI.
  172027. *
  172028. * Returns same codes as are defined for jpeg_consume_input:
  172029. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  172030. */
  172031. METHODDEF(int)
  172032. read_markers (j_decompress_ptr cinfo)
  172033. {
  172034. /* Outer loop repeats once for each marker. */
  172035. for (;;) {
  172036. /* Collect the marker proper, unless we already did. */
  172037. /* NB: first_marker() enforces the requirement that SOI appear first. */
  172038. if (cinfo->unread_marker == 0) {
  172039. if (! cinfo->marker->saw_SOI) {
  172040. if (! first_marker(cinfo))
  172041. return JPEG_SUSPENDED;
  172042. } else {
  172043. if (! next_marker(cinfo))
  172044. return JPEG_SUSPENDED;
  172045. }
  172046. }
  172047. /* At this point cinfo->unread_marker contains the marker code and the
  172048. * input point is just past the marker proper, but before any parameters.
  172049. * A suspension will cause us to return with this state still true.
  172050. */
  172051. switch (cinfo->unread_marker) {
  172052. case M_SOI:
  172053. if (! get_soi(cinfo))
  172054. return JPEG_SUSPENDED;
  172055. break;
  172056. case M_SOF0: /* Baseline */
  172057. case M_SOF1: /* Extended sequential, Huffman */
  172058. if (! get_sof(cinfo, FALSE, FALSE))
  172059. return JPEG_SUSPENDED;
  172060. break;
  172061. case M_SOF2: /* Progressive, Huffman */
  172062. if (! get_sof(cinfo, TRUE, FALSE))
  172063. return JPEG_SUSPENDED;
  172064. break;
  172065. case M_SOF9: /* Extended sequential, arithmetic */
  172066. if (! get_sof(cinfo, FALSE, TRUE))
  172067. return JPEG_SUSPENDED;
  172068. break;
  172069. case M_SOF10: /* Progressive, arithmetic */
  172070. if (! get_sof(cinfo, TRUE, TRUE))
  172071. return JPEG_SUSPENDED;
  172072. break;
  172073. /* Currently unsupported SOFn types */
  172074. case M_SOF3: /* Lossless, Huffman */
  172075. case M_SOF5: /* Differential sequential, Huffman */
  172076. case M_SOF6: /* Differential progressive, Huffman */
  172077. case M_SOF7: /* Differential lossless, Huffman */
  172078. case M_JPG: /* Reserved for JPEG extensions */
  172079. case M_SOF11: /* Lossless, arithmetic */
  172080. case M_SOF13: /* Differential sequential, arithmetic */
  172081. case M_SOF14: /* Differential progressive, arithmetic */
  172082. case M_SOF15: /* Differential lossless, arithmetic */
  172083. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  172084. break;
  172085. case M_SOS:
  172086. if (! get_sos(cinfo))
  172087. return JPEG_SUSPENDED;
  172088. cinfo->unread_marker = 0; /* processed the marker */
  172089. return JPEG_REACHED_SOS;
  172090. case M_EOI:
  172091. TRACEMS(cinfo, 1, JTRC_EOI);
  172092. cinfo->unread_marker = 0; /* processed the marker */
  172093. return JPEG_REACHED_EOI;
  172094. case M_DAC:
  172095. if (! get_dac(cinfo))
  172096. return JPEG_SUSPENDED;
  172097. break;
  172098. case M_DHT:
  172099. if (! get_dht(cinfo))
  172100. return JPEG_SUSPENDED;
  172101. break;
  172102. case M_DQT:
  172103. if (! get_dqt(cinfo))
  172104. return JPEG_SUSPENDED;
  172105. break;
  172106. case M_DRI:
  172107. if (! get_dri(cinfo))
  172108. return JPEG_SUSPENDED;
  172109. break;
  172110. case M_APP0:
  172111. case M_APP1:
  172112. case M_APP2:
  172113. case M_APP3:
  172114. case M_APP4:
  172115. case M_APP5:
  172116. case M_APP6:
  172117. case M_APP7:
  172118. case M_APP8:
  172119. case M_APP9:
  172120. case M_APP10:
  172121. case M_APP11:
  172122. case M_APP12:
  172123. case M_APP13:
  172124. case M_APP14:
  172125. case M_APP15:
  172126. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172127. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172128. return JPEG_SUSPENDED;
  172129. break;
  172130. case M_COM:
  172131. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172132. return JPEG_SUSPENDED;
  172133. break;
  172134. case M_RST0: /* these are all parameterless */
  172135. case M_RST1:
  172136. case M_RST2:
  172137. case M_RST3:
  172138. case M_RST4:
  172139. case M_RST5:
  172140. case M_RST6:
  172141. case M_RST7:
  172142. case M_TEM:
  172143. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172144. break;
  172145. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172146. if (! skip_variable(cinfo))
  172147. return JPEG_SUSPENDED;
  172148. break;
  172149. default: /* must be DHP, EXP, JPGn, or RESn */
  172150. /* For now, we treat the reserved markers as fatal errors since they are
  172151. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172152. * Once the JPEG 3 version-number marker is well defined, this code
  172153. * ought to change!
  172154. */
  172155. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172156. break;
  172157. }
  172158. /* Successfully processed marker, so reset state variable */
  172159. cinfo->unread_marker = 0;
  172160. } /* end loop */
  172161. }
  172162. /*
  172163. * Read a restart marker, which is expected to appear next in the datastream;
  172164. * if the marker is not there, take appropriate recovery action.
  172165. * Returns FALSE if suspension is required.
  172166. *
  172167. * This is called by the entropy decoder after it has read an appropriate
  172168. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172169. * has already read a marker from the data source. Under normal conditions
  172170. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172171. * it holds a marker which the decoder will be unable to read past.
  172172. */
  172173. METHODDEF(boolean)
  172174. read_restart_marker (j_decompress_ptr cinfo)
  172175. {
  172176. /* Obtain a marker unless we already did. */
  172177. /* Note that next_marker will complain if it skips any data. */
  172178. if (cinfo->unread_marker == 0) {
  172179. if (! next_marker(cinfo))
  172180. return FALSE;
  172181. }
  172182. if (cinfo->unread_marker ==
  172183. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172184. /* Normal case --- swallow the marker and let entropy decoder continue */
  172185. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172186. cinfo->unread_marker = 0;
  172187. } else {
  172188. /* Uh-oh, the restart markers have been messed up. */
  172189. /* Let the data source manager determine how to resync. */
  172190. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172191. cinfo->marker->next_restart_num))
  172192. return FALSE;
  172193. }
  172194. /* Update next-restart state */
  172195. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172196. return TRUE;
  172197. }
  172198. /*
  172199. * This is the default resync_to_restart method for data source managers
  172200. * to use if they don't have any better approach. Some data source managers
  172201. * may be able to back up, or may have additional knowledge about the data
  172202. * which permits a more intelligent recovery strategy; such managers would
  172203. * presumably supply their own resync method.
  172204. *
  172205. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172206. * the restart marker it was expecting. (This code is *not* used unless
  172207. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172208. * the marker code actually found (might be anything, except 0 or FF).
  172209. * The desired restart marker number (0..7) is passed as a parameter.
  172210. * This routine is supposed to apply whatever error recovery strategy seems
  172211. * appropriate in order to position the input stream to the next data segment.
  172212. * Note that cinfo->unread_marker is treated as a marker appearing before
  172213. * the current data-source input point; usually it should be reset to zero
  172214. * before returning.
  172215. * Returns FALSE if suspension is required.
  172216. *
  172217. * This implementation is substantially constrained by wanting to treat the
  172218. * input as a data stream; this means we can't back up. Therefore, we have
  172219. * only the following actions to work with:
  172220. * 1. Simply discard the marker and let the entropy decoder resume at next
  172221. * byte of file.
  172222. * 2. Read forward until we find another marker, discarding intervening
  172223. * data. (In theory we could look ahead within the current bufferload,
  172224. * without having to discard data if we don't find the desired marker.
  172225. * This idea is not implemented here, in part because it makes behavior
  172226. * dependent on buffer size and chance buffer-boundary positions.)
  172227. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172228. * This will cause the entropy decoder to process an empty data segment,
  172229. * inserting dummy zeroes, and then we will reprocess the marker.
  172230. *
  172231. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172232. * appropriate if the found marker is a future restart marker (indicating
  172233. * that we have missed the desired restart marker, probably because it got
  172234. * corrupted).
  172235. * We apply #2 or #3 if the found marker is a restart marker no more than
  172236. * two counts behind or ahead of the expected one. We also apply #2 if the
  172237. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172238. * If the found marker is a restart marker more than 2 counts away, we do #1
  172239. * (too much risk that the marker is erroneous; with luck we will be able to
  172240. * resync at some future point).
  172241. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172242. * overrunning the end of a scan. An implementation limited to single-scan
  172243. * files might find it better to apply #2 for markers other than EOI, since
  172244. * any other marker would have to be bogus data in that case.
  172245. */
  172246. GLOBAL(boolean)
  172247. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172248. {
  172249. int marker = cinfo->unread_marker;
  172250. int action = 1;
  172251. /* Always put up a warning. */
  172252. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172253. /* Outer loop handles repeated decision after scanning forward. */
  172254. for (;;) {
  172255. if (marker < (int) M_SOF0)
  172256. action = 2; /* invalid marker */
  172257. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172258. action = 3; /* valid non-restart marker */
  172259. else {
  172260. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172261. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172262. action = 3; /* one of the next two expected restarts */
  172263. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172264. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172265. action = 2; /* a prior restart, so advance */
  172266. else
  172267. action = 1; /* desired restart or too far away */
  172268. }
  172269. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172270. switch (action) {
  172271. case 1:
  172272. /* Discard marker and let entropy decoder resume processing. */
  172273. cinfo->unread_marker = 0;
  172274. return TRUE;
  172275. case 2:
  172276. /* Scan to the next marker, and repeat the decision loop. */
  172277. if (! next_marker(cinfo))
  172278. return FALSE;
  172279. marker = cinfo->unread_marker;
  172280. break;
  172281. case 3:
  172282. /* Return without advancing past this marker. */
  172283. /* Entropy decoder will be forced to process an empty segment. */
  172284. return TRUE;
  172285. }
  172286. } /* end loop */
  172287. }
  172288. /*
  172289. * Reset marker processing state to begin a fresh datastream.
  172290. */
  172291. METHODDEF(void)
  172292. reset_marker_reader (j_decompress_ptr cinfo)
  172293. {
  172294. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172295. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172296. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172297. cinfo->unread_marker = 0; /* no pending marker */
  172298. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172299. marker->pub.saw_SOF = FALSE;
  172300. marker->pub.discarded_bytes = 0;
  172301. marker->cur_marker = NULL;
  172302. }
  172303. /*
  172304. * Initialize the marker reader module.
  172305. * This is called only once, when the decompression object is created.
  172306. */
  172307. GLOBAL(void)
  172308. jinit_marker_reader (j_decompress_ptr cinfo)
  172309. {
  172310. my_marker_ptr2 marker;
  172311. int i;
  172312. /* Create subobject in permanent pool */
  172313. marker = (my_marker_ptr2)
  172314. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172315. SIZEOF(my_marker_reader));
  172316. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172317. /* Initialize public method pointers */
  172318. marker->pub.reset_marker_reader = reset_marker_reader;
  172319. marker->pub.read_markers = read_markers;
  172320. marker->pub.read_restart_marker = read_restart_marker;
  172321. /* Initialize COM/APPn processing.
  172322. * By default, we examine and then discard APP0 and APP14,
  172323. * but simply discard COM and all other APPn.
  172324. */
  172325. marker->process_COM = skip_variable;
  172326. marker->length_limit_COM = 0;
  172327. for (i = 0; i < 16; i++) {
  172328. marker->process_APPn[i] = skip_variable;
  172329. marker->length_limit_APPn[i] = 0;
  172330. }
  172331. marker->process_APPn[0] = get_interesting_appn;
  172332. marker->process_APPn[14] = get_interesting_appn;
  172333. /* Reset marker processing state */
  172334. reset_marker_reader(cinfo);
  172335. }
  172336. /*
  172337. * Control saving of COM and APPn markers into marker_list.
  172338. */
  172339. #ifdef SAVE_MARKERS_SUPPORTED
  172340. GLOBAL(void)
  172341. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172342. unsigned int length_limit)
  172343. {
  172344. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172345. long maxlength;
  172346. jpeg_marker_parser_method processor;
  172347. /* Length limit mustn't be larger than what we can allocate
  172348. * (should only be a concern in a 16-bit environment).
  172349. */
  172350. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172351. if (((long) length_limit) > maxlength)
  172352. length_limit = (unsigned int) maxlength;
  172353. /* Choose processor routine to use.
  172354. * APP0/APP14 have special requirements.
  172355. */
  172356. if (length_limit) {
  172357. processor = save_marker;
  172358. /* If saving APP0/APP14, save at least enough for our internal use. */
  172359. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172360. length_limit = APP0_DATA_LEN;
  172361. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172362. length_limit = APP14_DATA_LEN;
  172363. } else {
  172364. processor = skip_variable;
  172365. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172366. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172367. processor = get_interesting_appn;
  172368. }
  172369. if (marker_code == (int) M_COM) {
  172370. marker->process_COM = processor;
  172371. marker->length_limit_COM = length_limit;
  172372. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172373. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172374. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172375. } else
  172376. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172377. }
  172378. #endif /* SAVE_MARKERS_SUPPORTED */
  172379. /*
  172380. * Install a special processing method for COM or APPn markers.
  172381. */
  172382. GLOBAL(void)
  172383. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172384. jpeg_marker_parser_method routine)
  172385. {
  172386. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172387. if (marker_code == (int) M_COM)
  172388. marker->process_COM = routine;
  172389. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172390. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172391. else
  172392. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172393. }
  172394. /*** End of inlined file: jdmarker.c ***/
  172395. /*** Start of inlined file: jdmaster.c ***/
  172396. #define JPEG_INTERNALS
  172397. /* Private state */
  172398. typedef struct {
  172399. struct jpeg_decomp_master pub; /* public fields */
  172400. int pass_number; /* # of passes completed */
  172401. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172402. /* Saved references to initialized quantizer modules,
  172403. * in case we need to switch modes.
  172404. */
  172405. struct jpeg_color_quantizer * quantizer_1pass;
  172406. struct jpeg_color_quantizer * quantizer_2pass;
  172407. } my_decomp_master;
  172408. typedef my_decomp_master * my_master_ptr6;
  172409. /*
  172410. * Determine whether merged upsample/color conversion should be used.
  172411. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172412. */
  172413. LOCAL(boolean)
  172414. use_merged_upsample (j_decompress_ptr cinfo)
  172415. {
  172416. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172417. /* Merging is the equivalent of plain box-filter upsampling */
  172418. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172419. return FALSE;
  172420. /* jdmerge.c only supports YCC=>RGB color conversion */
  172421. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172422. cinfo->out_color_space != JCS_RGB ||
  172423. cinfo->out_color_components != RGB_PIXELSIZE)
  172424. return FALSE;
  172425. /* and it only handles 2h1v or 2h2v sampling ratios */
  172426. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172427. cinfo->comp_info[1].h_samp_factor != 1 ||
  172428. cinfo->comp_info[2].h_samp_factor != 1 ||
  172429. cinfo->comp_info[0].v_samp_factor > 2 ||
  172430. cinfo->comp_info[1].v_samp_factor != 1 ||
  172431. cinfo->comp_info[2].v_samp_factor != 1)
  172432. return FALSE;
  172433. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172434. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172435. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172436. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172437. return FALSE;
  172438. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172439. return TRUE; /* by golly, it'll work... */
  172440. #else
  172441. return FALSE;
  172442. #endif
  172443. }
  172444. /*
  172445. * Compute output image dimensions and related values.
  172446. * NOTE: this is exported for possible use by application.
  172447. * Hence it mustn't do anything that can't be done twice.
  172448. * Also note that it may be called before the master module is initialized!
  172449. */
  172450. GLOBAL(void)
  172451. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172452. /* Do computations that are needed before master selection phase */
  172453. {
  172454. #ifdef IDCT_SCALING_SUPPORTED
  172455. int ci;
  172456. jpeg_component_info *compptr;
  172457. #endif
  172458. /* Prevent application from calling me at wrong times */
  172459. if (cinfo->global_state != DSTATE_READY)
  172460. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172461. #ifdef IDCT_SCALING_SUPPORTED
  172462. /* Compute actual output image dimensions and DCT scaling choices. */
  172463. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172464. /* Provide 1/8 scaling */
  172465. cinfo->output_width = (JDIMENSION)
  172466. jdiv_round_up((long) cinfo->image_width, 8L);
  172467. cinfo->output_height = (JDIMENSION)
  172468. jdiv_round_up((long) cinfo->image_height, 8L);
  172469. cinfo->min_DCT_scaled_size = 1;
  172470. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172471. /* Provide 1/4 scaling */
  172472. cinfo->output_width = (JDIMENSION)
  172473. jdiv_round_up((long) cinfo->image_width, 4L);
  172474. cinfo->output_height = (JDIMENSION)
  172475. jdiv_round_up((long) cinfo->image_height, 4L);
  172476. cinfo->min_DCT_scaled_size = 2;
  172477. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172478. /* Provide 1/2 scaling */
  172479. cinfo->output_width = (JDIMENSION)
  172480. jdiv_round_up((long) cinfo->image_width, 2L);
  172481. cinfo->output_height = (JDIMENSION)
  172482. jdiv_round_up((long) cinfo->image_height, 2L);
  172483. cinfo->min_DCT_scaled_size = 4;
  172484. } else {
  172485. /* Provide 1/1 scaling */
  172486. cinfo->output_width = cinfo->image_width;
  172487. cinfo->output_height = cinfo->image_height;
  172488. cinfo->min_DCT_scaled_size = DCTSIZE;
  172489. }
  172490. /* In selecting the actual DCT scaling for each component, we try to
  172491. * scale up the chroma components via IDCT scaling rather than upsampling.
  172492. * This saves time if the upsampler gets to use 1:1 scaling.
  172493. * Note this code assumes that the supported DCT scalings are powers of 2.
  172494. */
  172495. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172496. ci++, compptr++) {
  172497. int ssize = cinfo->min_DCT_scaled_size;
  172498. while (ssize < DCTSIZE &&
  172499. (compptr->h_samp_factor * ssize * 2 <=
  172500. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172501. (compptr->v_samp_factor * ssize * 2 <=
  172502. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172503. ssize = ssize * 2;
  172504. }
  172505. compptr->DCT_scaled_size = ssize;
  172506. }
  172507. /* Recompute downsampled dimensions of components;
  172508. * application needs to know these if using raw downsampled data.
  172509. */
  172510. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172511. ci++, compptr++) {
  172512. /* Size in samples, after IDCT scaling */
  172513. compptr->downsampled_width = (JDIMENSION)
  172514. jdiv_round_up((long) cinfo->image_width *
  172515. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172516. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172517. compptr->downsampled_height = (JDIMENSION)
  172518. jdiv_round_up((long) cinfo->image_height *
  172519. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172520. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172521. }
  172522. #else /* !IDCT_SCALING_SUPPORTED */
  172523. /* Hardwire it to "no scaling" */
  172524. cinfo->output_width = cinfo->image_width;
  172525. cinfo->output_height = cinfo->image_height;
  172526. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172527. * and has computed unscaled downsampled_width and downsampled_height.
  172528. */
  172529. #endif /* IDCT_SCALING_SUPPORTED */
  172530. /* Report number of components in selected colorspace. */
  172531. /* Probably this should be in the color conversion module... */
  172532. switch (cinfo->out_color_space) {
  172533. case JCS_GRAYSCALE:
  172534. cinfo->out_color_components = 1;
  172535. break;
  172536. case JCS_RGB:
  172537. #if RGB_PIXELSIZE != 3
  172538. cinfo->out_color_components = RGB_PIXELSIZE;
  172539. break;
  172540. #endif /* else share code with YCbCr */
  172541. case JCS_YCbCr:
  172542. cinfo->out_color_components = 3;
  172543. break;
  172544. case JCS_CMYK:
  172545. case JCS_YCCK:
  172546. cinfo->out_color_components = 4;
  172547. break;
  172548. default: /* else must be same colorspace as in file */
  172549. cinfo->out_color_components = cinfo->num_components;
  172550. break;
  172551. }
  172552. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172553. cinfo->out_color_components);
  172554. /* See if upsampler will want to emit more than one row at a time */
  172555. if (use_merged_upsample(cinfo))
  172556. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172557. else
  172558. cinfo->rec_outbuf_height = 1;
  172559. }
  172560. /*
  172561. * Several decompression processes need to range-limit values to the range
  172562. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172563. * due to noise introduced by quantization, roundoff error, etc. These
  172564. * processes are inner loops and need to be as fast as possible. On most
  172565. * machines, particularly CPUs with pipelines or instruction prefetch,
  172566. * a (subscript-check-less) C table lookup
  172567. * x = sample_range_limit[x];
  172568. * is faster than explicit tests
  172569. * if (x < 0) x = 0;
  172570. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172571. * These processes all use a common table prepared by the routine below.
  172572. *
  172573. * For most steps we can mathematically guarantee that the initial value
  172574. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172575. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172576. * limiting step (just after the IDCT), a wildly out-of-range value is
  172577. * possible if the input data is corrupt. To avoid any chance of indexing
  172578. * off the end of memory and getting a bad-pointer trap, we perform the
  172579. * post-IDCT limiting thus:
  172580. * x = range_limit[x & MASK];
  172581. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172582. * samples. Under normal circumstances this is more than enough range and
  172583. * a correct output will be generated; with bogus input data the mask will
  172584. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172585. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172586. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172587. * So the post-IDCT limiting table ends up looking like this:
  172588. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172589. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172590. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172591. * 0,1,...,CENTERJSAMPLE-1
  172592. * Negative inputs select values from the upper half of the table after
  172593. * masking.
  172594. *
  172595. * We can save some space by overlapping the start of the post-IDCT table
  172596. * with the simpler range limiting table. The post-IDCT table begins at
  172597. * sample_range_limit + CENTERJSAMPLE.
  172598. *
  172599. * Note that the table is allocated in near data space on PCs; it's small
  172600. * enough and used often enough to justify this.
  172601. */
  172602. LOCAL(void)
  172603. prepare_range_limit_table (j_decompress_ptr cinfo)
  172604. /* Allocate and fill in the sample_range_limit table */
  172605. {
  172606. JSAMPLE * table;
  172607. int i;
  172608. table = (JSAMPLE *)
  172609. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172610. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172611. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172612. cinfo->sample_range_limit = table;
  172613. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172614. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172615. /* Main part of "simple" table: limit[x] = x */
  172616. for (i = 0; i <= MAXJSAMPLE; i++)
  172617. table[i] = (JSAMPLE) i;
  172618. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172619. /* End of simple table, rest of first half of post-IDCT table */
  172620. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172621. table[i] = MAXJSAMPLE;
  172622. /* Second half of post-IDCT table */
  172623. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172624. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172625. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172626. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172627. }
  172628. /*
  172629. * Master selection of decompression modules.
  172630. * This is done once at jpeg_start_decompress time. We determine
  172631. * which modules will be used and give them appropriate initialization calls.
  172632. * We also initialize the decompressor input side to begin consuming data.
  172633. *
  172634. * Since jpeg_read_header has finished, we know what is in the SOF
  172635. * and (first) SOS markers. We also have all the application parameter
  172636. * settings.
  172637. */
  172638. LOCAL(void)
  172639. master_selection (j_decompress_ptr cinfo)
  172640. {
  172641. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172642. boolean use_c_buffer;
  172643. long samplesperrow;
  172644. JDIMENSION jd_samplesperrow;
  172645. /* Initialize dimensions and other stuff */
  172646. jpeg_calc_output_dimensions(cinfo);
  172647. prepare_range_limit_table(cinfo);
  172648. /* Width of an output scanline must be representable as JDIMENSION. */
  172649. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172650. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172651. if ((long) jd_samplesperrow != samplesperrow)
  172652. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172653. /* Initialize my private state */
  172654. master->pass_number = 0;
  172655. master->using_merged_upsample = use_merged_upsample(cinfo);
  172656. /* Color quantizer selection */
  172657. master->quantizer_1pass = NULL;
  172658. master->quantizer_2pass = NULL;
  172659. /* No mode changes if not using buffered-image mode. */
  172660. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172661. cinfo->enable_1pass_quant = FALSE;
  172662. cinfo->enable_external_quant = FALSE;
  172663. cinfo->enable_2pass_quant = FALSE;
  172664. }
  172665. if (cinfo->quantize_colors) {
  172666. if (cinfo->raw_data_out)
  172667. ERREXIT(cinfo, JERR_NOTIMPL);
  172668. /* 2-pass quantizer only works in 3-component color space. */
  172669. if (cinfo->out_color_components != 3) {
  172670. cinfo->enable_1pass_quant = TRUE;
  172671. cinfo->enable_external_quant = FALSE;
  172672. cinfo->enable_2pass_quant = FALSE;
  172673. cinfo->colormap = NULL;
  172674. } else if (cinfo->colormap != NULL) {
  172675. cinfo->enable_external_quant = TRUE;
  172676. } else if (cinfo->two_pass_quantize) {
  172677. cinfo->enable_2pass_quant = TRUE;
  172678. } else {
  172679. cinfo->enable_1pass_quant = TRUE;
  172680. }
  172681. if (cinfo->enable_1pass_quant) {
  172682. #ifdef QUANT_1PASS_SUPPORTED
  172683. jinit_1pass_quantizer(cinfo);
  172684. master->quantizer_1pass = cinfo->cquantize;
  172685. #else
  172686. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172687. #endif
  172688. }
  172689. /* We use the 2-pass code to map to external colormaps. */
  172690. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172691. #ifdef QUANT_2PASS_SUPPORTED
  172692. jinit_2pass_quantizer(cinfo);
  172693. master->quantizer_2pass = cinfo->cquantize;
  172694. #else
  172695. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172696. #endif
  172697. }
  172698. /* If both quantizers are initialized, the 2-pass one is left active;
  172699. * this is necessary for starting with quantization to an external map.
  172700. */
  172701. }
  172702. /* Post-processing: in particular, color conversion first */
  172703. if (! cinfo->raw_data_out) {
  172704. if (master->using_merged_upsample) {
  172705. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172706. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172707. #else
  172708. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172709. #endif
  172710. } else {
  172711. jinit_color_deconverter(cinfo);
  172712. jinit_upsampler(cinfo);
  172713. }
  172714. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172715. }
  172716. /* Inverse DCT */
  172717. jinit_inverse_dct(cinfo);
  172718. /* Entropy decoding: either Huffman or arithmetic coding. */
  172719. if (cinfo->arith_code) {
  172720. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172721. } else {
  172722. if (cinfo->progressive_mode) {
  172723. #ifdef D_PROGRESSIVE_SUPPORTED
  172724. jinit_phuff_decoder(cinfo);
  172725. #else
  172726. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172727. #endif
  172728. } else
  172729. jinit_huff_decoder(cinfo);
  172730. }
  172731. /* Initialize principal buffer controllers. */
  172732. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172733. jinit_d_coef_controller(cinfo, use_c_buffer);
  172734. if (! cinfo->raw_data_out)
  172735. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172736. /* We can now tell the memory manager to allocate virtual arrays. */
  172737. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172738. /* Initialize input side of decompressor to consume first scan. */
  172739. (*cinfo->inputctl->start_input_pass) (cinfo);
  172740. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172741. /* If jpeg_start_decompress will read the whole file, initialize
  172742. * progress monitoring appropriately. The input step is counted
  172743. * as one pass.
  172744. */
  172745. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172746. cinfo->inputctl->has_multiple_scans) {
  172747. int nscans;
  172748. /* Estimate number of scans to set pass_limit. */
  172749. if (cinfo->progressive_mode) {
  172750. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172751. nscans = 2 + 3 * cinfo->num_components;
  172752. } else {
  172753. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172754. nscans = cinfo->num_components;
  172755. }
  172756. cinfo->progress->pass_counter = 0L;
  172757. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172758. cinfo->progress->completed_passes = 0;
  172759. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172760. /* Count the input pass as done */
  172761. master->pass_number++;
  172762. }
  172763. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172764. }
  172765. /*
  172766. * Per-pass setup.
  172767. * This is called at the beginning of each output pass. We determine which
  172768. * modules will be active during this pass and give them appropriate
  172769. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172770. * is a "real" output pass or a dummy pass for color quantization.
  172771. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172772. */
  172773. METHODDEF(void)
  172774. prepare_for_output_pass (j_decompress_ptr cinfo)
  172775. {
  172776. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172777. if (master->pub.is_dummy_pass) {
  172778. #ifdef QUANT_2PASS_SUPPORTED
  172779. /* Final pass of 2-pass quantization */
  172780. master->pub.is_dummy_pass = FALSE;
  172781. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172782. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172783. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172784. #else
  172785. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172786. #endif /* QUANT_2PASS_SUPPORTED */
  172787. } else {
  172788. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172789. /* Select new quantization method */
  172790. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172791. cinfo->cquantize = master->quantizer_2pass;
  172792. master->pub.is_dummy_pass = TRUE;
  172793. } else if (cinfo->enable_1pass_quant) {
  172794. cinfo->cquantize = master->quantizer_1pass;
  172795. } else {
  172796. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172797. }
  172798. }
  172799. (*cinfo->idct->start_pass) (cinfo);
  172800. (*cinfo->coef->start_output_pass) (cinfo);
  172801. if (! cinfo->raw_data_out) {
  172802. if (! master->using_merged_upsample)
  172803. (*cinfo->cconvert->start_pass) (cinfo);
  172804. (*cinfo->upsample->start_pass) (cinfo);
  172805. if (cinfo->quantize_colors)
  172806. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172807. (*cinfo->post->start_pass) (cinfo,
  172808. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172809. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172810. }
  172811. }
  172812. /* Set up progress monitor's pass info if present */
  172813. if (cinfo->progress != NULL) {
  172814. cinfo->progress->completed_passes = master->pass_number;
  172815. cinfo->progress->total_passes = master->pass_number +
  172816. (master->pub.is_dummy_pass ? 2 : 1);
  172817. /* In buffered-image mode, we assume one more output pass if EOI not
  172818. * yet reached, but no more passes if EOI has been reached.
  172819. */
  172820. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172821. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172822. }
  172823. }
  172824. }
  172825. /*
  172826. * Finish up at end of an output pass.
  172827. */
  172828. METHODDEF(void)
  172829. finish_output_pass (j_decompress_ptr cinfo)
  172830. {
  172831. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172832. if (cinfo->quantize_colors)
  172833. (*cinfo->cquantize->finish_pass) (cinfo);
  172834. master->pass_number++;
  172835. }
  172836. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172837. /*
  172838. * Switch to a new external colormap between output passes.
  172839. */
  172840. GLOBAL(void)
  172841. jpeg_new_colormap (j_decompress_ptr cinfo)
  172842. {
  172843. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172844. /* Prevent application from calling me at wrong times */
  172845. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172846. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172847. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172848. cinfo->colormap != NULL) {
  172849. /* Select 2-pass quantizer for external colormap use */
  172850. cinfo->cquantize = master->quantizer_2pass;
  172851. /* Notify quantizer of colormap change */
  172852. (*cinfo->cquantize->new_color_map) (cinfo);
  172853. master->pub.is_dummy_pass = FALSE; /* just in case */
  172854. } else
  172855. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172856. }
  172857. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172858. /*
  172859. * Initialize master decompression control and select active modules.
  172860. * This is performed at the start of jpeg_start_decompress.
  172861. */
  172862. GLOBAL(void)
  172863. jinit_master_decompress (j_decompress_ptr cinfo)
  172864. {
  172865. my_master_ptr6 master;
  172866. master = (my_master_ptr6)
  172867. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172868. SIZEOF(my_decomp_master));
  172869. cinfo->master = (struct jpeg_decomp_master *) master;
  172870. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172871. master->pub.finish_output_pass = finish_output_pass;
  172872. master->pub.is_dummy_pass = FALSE;
  172873. master_selection(cinfo);
  172874. }
  172875. /*** End of inlined file: jdmaster.c ***/
  172876. #undef FIX
  172877. /*** Start of inlined file: jdmerge.c ***/
  172878. #define JPEG_INTERNALS
  172879. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172880. /* Private subobject */
  172881. typedef struct {
  172882. struct jpeg_upsampler pub; /* public fields */
  172883. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172884. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172885. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172886. JSAMPARRAY output_buf));
  172887. /* Private state for YCC->RGB conversion */
  172888. int * Cr_r_tab; /* => table for Cr to R conversion */
  172889. int * Cb_b_tab; /* => table for Cb to B conversion */
  172890. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172891. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172892. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172893. * We need a "spare" row buffer to hold the second output row if the
  172894. * application provides just a one-row buffer; we also use the spare
  172895. * to discard the dummy last row if the image height is odd.
  172896. */
  172897. JSAMPROW spare_row;
  172898. boolean spare_full; /* T if spare buffer is occupied */
  172899. JDIMENSION out_row_width; /* samples per output row */
  172900. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172901. } my_upsampler;
  172902. typedef my_upsampler * my_upsample_ptr;
  172903. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172904. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172905. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172906. /*
  172907. * Initialize tables for YCC->RGB colorspace conversion.
  172908. * This is taken directly from jdcolor.c; see that file for more info.
  172909. */
  172910. LOCAL(void)
  172911. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172912. {
  172913. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172914. int i;
  172915. INT32 x;
  172916. SHIFT_TEMPS
  172917. upsample->Cr_r_tab = (int *)
  172918. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172919. (MAXJSAMPLE+1) * SIZEOF(int));
  172920. upsample->Cb_b_tab = (int *)
  172921. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172922. (MAXJSAMPLE+1) * SIZEOF(int));
  172923. upsample->Cr_g_tab = (INT32 *)
  172924. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172925. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172926. upsample->Cb_g_tab = (INT32 *)
  172927. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172928. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172929. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172930. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172931. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172932. /* Cr=>R value is nearest int to 1.40200 * x */
  172933. upsample->Cr_r_tab[i] = (int)
  172934. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172935. /* Cb=>B value is nearest int to 1.77200 * x */
  172936. upsample->Cb_b_tab[i] = (int)
  172937. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172938. /* Cr=>G value is scaled-up -0.71414 * x */
  172939. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172940. /* Cb=>G value is scaled-up -0.34414 * x */
  172941. /* We also add in ONE_HALF so that need not do it in inner loop */
  172942. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172943. }
  172944. }
  172945. /*
  172946. * Initialize for an upsampling pass.
  172947. */
  172948. METHODDEF(void)
  172949. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172950. {
  172951. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172952. /* Mark the spare buffer empty */
  172953. upsample->spare_full = FALSE;
  172954. /* Initialize total-height counter for detecting bottom of image */
  172955. upsample->rows_to_go = cinfo->output_height;
  172956. }
  172957. /*
  172958. * Control routine to do upsampling (and color conversion).
  172959. *
  172960. * The control routine just handles the row buffering considerations.
  172961. */
  172962. METHODDEF(void)
  172963. merged_2v_upsample (j_decompress_ptr cinfo,
  172964. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172965. JDIMENSION,
  172966. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172967. JDIMENSION out_rows_avail)
  172968. /* 2:1 vertical sampling case: may need a spare row. */
  172969. {
  172970. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172971. JSAMPROW work_ptrs[2];
  172972. JDIMENSION num_rows; /* number of rows returned to caller */
  172973. if (upsample->spare_full) {
  172974. /* If we have a spare row saved from a previous cycle, just return it. */
  172975. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172976. 1, upsample->out_row_width);
  172977. num_rows = 1;
  172978. upsample->spare_full = FALSE;
  172979. } else {
  172980. /* Figure number of rows to return to caller. */
  172981. num_rows = 2;
  172982. /* Not more than the distance to the end of the image. */
  172983. if (num_rows > upsample->rows_to_go)
  172984. num_rows = upsample->rows_to_go;
  172985. /* And not more than what the client can accept: */
  172986. out_rows_avail -= *out_row_ctr;
  172987. if (num_rows > out_rows_avail)
  172988. num_rows = out_rows_avail;
  172989. /* Create output pointer array for upsampler. */
  172990. work_ptrs[0] = output_buf[*out_row_ctr];
  172991. if (num_rows > 1) {
  172992. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172993. } else {
  172994. work_ptrs[1] = upsample->spare_row;
  172995. upsample->spare_full = TRUE;
  172996. }
  172997. /* Now do the upsampling. */
  172998. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172999. }
  173000. /* Adjust counts */
  173001. *out_row_ctr += num_rows;
  173002. upsample->rows_to_go -= num_rows;
  173003. /* When the buffer is emptied, declare this input row group consumed */
  173004. if (! upsample->spare_full)
  173005. (*in_row_group_ctr)++;
  173006. }
  173007. METHODDEF(void)
  173008. merged_1v_upsample (j_decompress_ptr cinfo,
  173009. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173010. JDIMENSION,
  173011. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173012. JDIMENSION)
  173013. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  173014. {
  173015. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173016. /* Just do the upsampling. */
  173017. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  173018. output_buf + *out_row_ctr);
  173019. /* Adjust counts */
  173020. (*out_row_ctr)++;
  173021. (*in_row_group_ctr)++;
  173022. }
  173023. /*
  173024. * These are the routines invoked by the control routines to do
  173025. * the actual upsampling/conversion. One row group is processed per call.
  173026. *
  173027. * Note: since we may be writing directly into application-supplied buffers,
  173028. * we have to be honest about the output width; we can't assume the buffer
  173029. * has been rounded up to an even width.
  173030. */
  173031. /*
  173032. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  173033. */
  173034. METHODDEF(void)
  173035. h2v1_merged_upsample (j_decompress_ptr cinfo,
  173036. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173037. JSAMPARRAY output_buf)
  173038. {
  173039. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173040. register int y, cred, cgreen, cblue;
  173041. int cb, cr;
  173042. register JSAMPROW outptr;
  173043. JSAMPROW inptr0, inptr1, inptr2;
  173044. JDIMENSION col;
  173045. /* copy these pointers into registers if possible */
  173046. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173047. int * Crrtab = upsample->Cr_r_tab;
  173048. int * Cbbtab = upsample->Cb_b_tab;
  173049. INT32 * Crgtab = upsample->Cr_g_tab;
  173050. INT32 * Cbgtab = upsample->Cb_g_tab;
  173051. SHIFT_TEMPS
  173052. inptr0 = input_buf[0][in_row_group_ctr];
  173053. inptr1 = input_buf[1][in_row_group_ctr];
  173054. inptr2 = input_buf[2][in_row_group_ctr];
  173055. outptr = output_buf[0];
  173056. /* Loop for each pair of output pixels */
  173057. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173058. /* Do the chroma part of the calculation */
  173059. cb = GETJSAMPLE(*inptr1++);
  173060. cr = GETJSAMPLE(*inptr2++);
  173061. cred = Crrtab[cr];
  173062. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173063. cblue = Cbbtab[cb];
  173064. /* Fetch 2 Y values and emit 2 pixels */
  173065. y = GETJSAMPLE(*inptr0++);
  173066. outptr[RGB_RED] = range_limit[y + cred];
  173067. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173068. outptr[RGB_BLUE] = range_limit[y + cblue];
  173069. outptr += RGB_PIXELSIZE;
  173070. y = GETJSAMPLE(*inptr0++);
  173071. outptr[RGB_RED] = range_limit[y + cred];
  173072. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173073. outptr[RGB_BLUE] = range_limit[y + cblue];
  173074. outptr += RGB_PIXELSIZE;
  173075. }
  173076. /* If image width is odd, do the last output column separately */
  173077. if (cinfo->output_width & 1) {
  173078. cb = GETJSAMPLE(*inptr1);
  173079. cr = GETJSAMPLE(*inptr2);
  173080. cred = Crrtab[cr];
  173081. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173082. cblue = Cbbtab[cb];
  173083. y = GETJSAMPLE(*inptr0);
  173084. outptr[RGB_RED] = range_limit[y + cred];
  173085. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173086. outptr[RGB_BLUE] = range_limit[y + cblue];
  173087. }
  173088. }
  173089. /*
  173090. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  173091. */
  173092. METHODDEF(void)
  173093. h2v2_merged_upsample (j_decompress_ptr cinfo,
  173094. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173095. JSAMPARRAY output_buf)
  173096. {
  173097. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173098. register int y, cred, cgreen, cblue;
  173099. int cb, cr;
  173100. register JSAMPROW outptr0, outptr1;
  173101. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  173102. JDIMENSION col;
  173103. /* copy these pointers into registers if possible */
  173104. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173105. int * Crrtab = upsample->Cr_r_tab;
  173106. int * Cbbtab = upsample->Cb_b_tab;
  173107. INT32 * Crgtab = upsample->Cr_g_tab;
  173108. INT32 * Cbgtab = upsample->Cb_g_tab;
  173109. SHIFT_TEMPS
  173110. inptr00 = input_buf[0][in_row_group_ctr*2];
  173111. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  173112. inptr1 = input_buf[1][in_row_group_ctr];
  173113. inptr2 = input_buf[2][in_row_group_ctr];
  173114. outptr0 = output_buf[0];
  173115. outptr1 = output_buf[1];
  173116. /* Loop for each group of output pixels */
  173117. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173118. /* Do the chroma part of the calculation */
  173119. cb = GETJSAMPLE(*inptr1++);
  173120. cr = GETJSAMPLE(*inptr2++);
  173121. cred = Crrtab[cr];
  173122. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173123. cblue = Cbbtab[cb];
  173124. /* Fetch 4 Y values and emit 4 pixels */
  173125. y = GETJSAMPLE(*inptr00++);
  173126. outptr0[RGB_RED] = range_limit[y + cred];
  173127. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173128. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173129. outptr0 += RGB_PIXELSIZE;
  173130. y = GETJSAMPLE(*inptr00++);
  173131. outptr0[RGB_RED] = range_limit[y + cred];
  173132. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173133. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173134. outptr0 += RGB_PIXELSIZE;
  173135. y = GETJSAMPLE(*inptr01++);
  173136. outptr1[RGB_RED] = range_limit[y + cred];
  173137. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173138. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173139. outptr1 += RGB_PIXELSIZE;
  173140. y = GETJSAMPLE(*inptr01++);
  173141. outptr1[RGB_RED] = range_limit[y + cred];
  173142. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173143. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173144. outptr1 += RGB_PIXELSIZE;
  173145. }
  173146. /* If image width is odd, do the last output column separately */
  173147. if (cinfo->output_width & 1) {
  173148. cb = GETJSAMPLE(*inptr1);
  173149. cr = GETJSAMPLE(*inptr2);
  173150. cred = Crrtab[cr];
  173151. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173152. cblue = Cbbtab[cb];
  173153. y = GETJSAMPLE(*inptr00);
  173154. outptr0[RGB_RED] = range_limit[y + cred];
  173155. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173156. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173157. y = GETJSAMPLE(*inptr01);
  173158. outptr1[RGB_RED] = range_limit[y + cred];
  173159. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173160. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173161. }
  173162. }
  173163. /*
  173164. * Module initialization routine for merged upsampling/color conversion.
  173165. *
  173166. * NB: this is called under the conditions determined by use_merged_upsample()
  173167. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173168. * of this module; no safety checks are made here.
  173169. */
  173170. GLOBAL(void)
  173171. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173172. {
  173173. my_upsample_ptr upsample;
  173174. upsample = (my_upsample_ptr)
  173175. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173176. SIZEOF(my_upsampler));
  173177. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173178. upsample->pub.start_pass = start_pass_merged_upsample;
  173179. upsample->pub.need_context_rows = FALSE;
  173180. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173181. if (cinfo->max_v_samp_factor == 2) {
  173182. upsample->pub.upsample = merged_2v_upsample;
  173183. upsample->upmethod = h2v2_merged_upsample;
  173184. /* Allocate a spare row buffer */
  173185. upsample->spare_row = (JSAMPROW)
  173186. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173187. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173188. } else {
  173189. upsample->pub.upsample = merged_1v_upsample;
  173190. upsample->upmethod = h2v1_merged_upsample;
  173191. /* No spare row needed */
  173192. upsample->spare_row = NULL;
  173193. }
  173194. build_ycc_rgb_table2(cinfo);
  173195. }
  173196. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173197. /*** End of inlined file: jdmerge.c ***/
  173198. #undef ASSIGN_STATE
  173199. /*** Start of inlined file: jdphuff.c ***/
  173200. #define JPEG_INTERNALS
  173201. #ifdef D_PROGRESSIVE_SUPPORTED
  173202. /*
  173203. * Expanded entropy decoder object for progressive Huffman decoding.
  173204. *
  173205. * The savable_state subrecord contains fields that change within an MCU,
  173206. * but must not be updated permanently until we complete the MCU.
  173207. */
  173208. typedef struct {
  173209. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173210. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173211. } savable_state3;
  173212. /* This macro is to work around compilers with missing or broken
  173213. * structure assignment. You'll need to fix this code if you have
  173214. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173215. */
  173216. #ifndef NO_STRUCT_ASSIGN
  173217. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173218. #else
  173219. #if MAX_COMPS_IN_SCAN == 4
  173220. #define ASSIGN_STATE(dest,src) \
  173221. ((dest).EOBRUN = (src).EOBRUN, \
  173222. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173223. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173224. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173225. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173226. #endif
  173227. #endif
  173228. typedef struct {
  173229. struct jpeg_entropy_decoder pub; /* public fields */
  173230. /* These fields are loaded into local variables at start of each MCU.
  173231. * In case of suspension, we exit WITHOUT updating them.
  173232. */
  173233. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173234. savable_state3 saved; /* Other state at start of MCU */
  173235. /* These fields are NOT loaded into local working state. */
  173236. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173237. /* Pointers to derived tables (these workspaces have image lifespan) */
  173238. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173239. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173240. } phuff_entropy_decoder;
  173241. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173242. /* Forward declarations */
  173243. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173244. JBLOCKROW *MCU_data));
  173245. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173246. JBLOCKROW *MCU_data));
  173247. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173248. JBLOCKROW *MCU_data));
  173249. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173250. JBLOCKROW *MCU_data));
  173251. /*
  173252. * Initialize for a Huffman-compressed scan.
  173253. */
  173254. METHODDEF(void)
  173255. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173256. {
  173257. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173258. boolean is_DC_band, bad;
  173259. int ci, coefi, tbl;
  173260. int *coef_bit_ptr;
  173261. jpeg_component_info * compptr;
  173262. is_DC_band = (cinfo->Ss == 0);
  173263. /* Validate scan parameters */
  173264. bad = FALSE;
  173265. if (is_DC_band) {
  173266. if (cinfo->Se != 0)
  173267. bad = TRUE;
  173268. } else {
  173269. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173270. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173271. bad = TRUE;
  173272. /* AC scans may have only one component */
  173273. if (cinfo->comps_in_scan != 1)
  173274. bad = TRUE;
  173275. }
  173276. if (cinfo->Ah != 0) {
  173277. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173278. if (cinfo->Al != cinfo->Ah-1)
  173279. bad = TRUE;
  173280. }
  173281. if (cinfo->Al > 13) /* need not check for < 0 */
  173282. bad = TRUE;
  173283. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173284. * but the spec doesn't say so, and we try to be liberal about what we
  173285. * accept. Note: large Al values could result in out-of-range DC
  173286. * coefficients during early scans, leading to bizarre displays due to
  173287. * overflows in the IDCT math. But we won't crash.
  173288. */
  173289. if (bad)
  173290. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173291. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173292. /* Update progression status, and verify that scan order is legal.
  173293. * Note that inter-scan inconsistencies are treated as warnings
  173294. * not fatal errors ... not clear if this is right way to behave.
  173295. */
  173296. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173297. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173298. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173299. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173300. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173301. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173302. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173303. if (cinfo->Ah != expected)
  173304. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173305. coef_bit_ptr[coefi] = cinfo->Al;
  173306. }
  173307. }
  173308. /* Select MCU decoding routine */
  173309. if (cinfo->Ah == 0) {
  173310. if (is_DC_band)
  173311. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173312. else
  173313. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173314. } else {
  173315. if (is_DC_band)
  173316. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173317. else
  173318. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173319. }
  173320. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173321. compptr = cinfo->cur_comp_info[ci];
  173322. /* Make sure requested tables are present, and compute derived tables.
  173323. * We may build same derived table more than once, but it's not expensive.
  173324. */
  173325. if (is_DC_band) {
  173326. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173327. tbl = compptr->dc_tbl_no;
  173328. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173329. & entropy->derived_tbls[tbl]);
  173330. }
  173331. } else {
  173332. tbl = compptr->ac_tbl_no;
  173333. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173334. & entropy->derived_tbls[tbl]);
  173335. /* remember the single active table */
  173336. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173337. }
  173338. /* Initialize DC predictions to 0 */
  173339. entropy->saved.last_dc_val[ci] = 0;
  173340. }
  173341. /* Initialize bitread state variables */
  173342. entropy->bitstate.bits_left = 0;
  173343. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173344. entropy->pub.insufficient_data = FALSE;
  173345. /* Initialize private state variables */
  173346. entropy->saved.EOBRUN = 0;
  173347. /* Initialize restart counter */
  173348. entropy->restarts_to_go = cinfo->restart_interval;
  173349. }
  173350. /*
  173351. * Check for a restart marker & resynchronize decoder.
  173352. * Returns FALSE if must suspend.
  173353. */
  173354. LOCAL(boolean)
  173355. process_restartp (j_decompress_ptr cinfo)
  173356. {
  173357. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173358. int ci;
  173359. /* Throw away any unused bits remaining in bit buffer; */
  173360. /* include any full bytes in next_marker's count of discarded bytes */
  173361. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173362. entropy->bitstate.bits_left = 0;
  173363. /* Advance past the RSTn marker */
  173364. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173365. return FALSE;
  173366. /* Re-initialize DC predictions to 0 */
  173367. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173368. entropy->saved.last_dc_val[ci] = 0;
  173369. /* Re-init EOB run count, too */
  173370. entropy->saved.EOBRUN = 0;
  173371. /* Reset restart counter */
  173372. entropy->restarts_to_go = cinfo->restart_interval;
  173373. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173374. * against a marker. In that case we will end up treating the next data
  173375. * segment as empty, and we can avoid producing bogus output pixels by
  173376. * leaving the flag set.
  173377. */
  173378. if (cinfo->unread_marker == 0)
  173379. entropy->pub.insufficient_data = FALSE;
  173380. return TRUE;
  173381. }
  173382. /*
  173383. * Huffman MCU decoding.
  173384. * Each of these routines decodes and returns one MCU's worth of
  173385. * Huffman-compressed coefficients.
  173386. * The coefficients are reordered from zigzag order into natural array order,
  173387. * but are not dequantized.
  173388. *
  173389. * The i'th block of the MCU is stored into the block pointed to by
  173390. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173391. *
  173392. * We return FALSE if data source requested suspension. In that case no
  173393. * changes have been made to permanent state. (Exception: some output
  173394. * coefficients may already have been assigned. This is harmless for
  173395. * spectral selection, since we'll just re-assign them on the next call.
  173396. * Successive approximation AC refinement has to be more careful, however.)
  173397. */
  173398. /*
  173399. * MCU decoding for DC initial scan (either spectral selection,
  173400. * or first pass of successive approximation).
  173401. */
  173402. METHODDEF(boolean)
  173403. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173404. {
  173405. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173406. int Al = cinfo->Al;
  173407. register int s, r;
  173408. int blkn, ci;
  173409. JBLOCKROW block;
  173410. BITREAD_STATE_VARS;
  173411. savable_state3 state;
  173412. d_derived_tbl * tbl;
  173413. jpeg_component_info * compptr;
  173414. /* Process restart marker if needed; may have to suspend */
  173415. if (cinfo->restart_interval) {
  173416. if (entropy->restarts_to_go == 0)
  173417. if (! process_restartp(cinfo))
  173418. return FALSE;
  173419. }
  173420. /* If we've run out of data, just leave the MCU set to zeroes.
  173421. * This way, we return uniform gray for the remainder of the segment.
  173422. */
  173423. if (! entropy->pub.insufficient_data) {
  173424. /* Load up working state */
  173425. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173426. ASSIGN_STATE(state, entropy->saved);
  173427. /* Outer loop handles each block in the MCU */
  173428. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173429. block = MCU_data[blkn];
  173430. ci = cinfo->MCU_membership[blkn];
  173431. compptr = cinfo->cur_comp_info[ci];
  173432. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173433. /* Decode a single block's worth of coefficients */
  173434. /* Section F.2.2.1: decode the DC coefficient difference */
  173435. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173436. if (s) {
  173437. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173438. r = GET_BITS(s);
  173439. s = HUFF_EXTEND(r, s);
  173440. }
  173441. /* Convert DC difference to actual value, update last_dc_val */
  173442. s += state.last_dc_val[ci];
  173443. state.last_dc_val[ci] = s;
  173444. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173445. (*block)[0] = (JCOEF) (s << Al);
  173446. }
  173447. /* Completed MCU, so update state */
  173448. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173449. ASSIGN_STATE(entropy->saved, state);
  173450. }
  173451. /* Account for restart interval (no-op if not using restarts) */
  173452. entropy->restarts_to_go--;
  173453. return TRUE;
  173454. }
  173455. /*
  173456. * MCU decoding for AC initial scan (either spectral selection,
  173457. * or first pass of successive approximation).
  173458. */
  173459. METHODDEF(boolean)
  173460. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173461. {
  173462. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173463. int Se = cinfo->Se;
  173464. int Al = cinfo->Al;
  173465. register int s, k, r;
  173466. unsigned int EOBRUN;
  173467. JBLOCKROW block;
  173468. BITREAD_STATE_VARS;
  173469. d_derived_tbl * tbl;
  173470. /* Process restart marker if needed; may have to suspend */
  173471. if (cinfo->restart_interval) {
  173472. if (entropy->restarts_to_go == 0)
  173473. if (! process_restartp(cinfo))
  173474. return FALSE;
  173475. }
  173476. /* If we've run out of data, just leave the MCU set to zeroes.
  173477. * This way, we return uniform gray for the remainder of the segment.
  173478. */
  173479. if (! entropy->pub.insufficient_data) {
  173480. /* Load up working state.
  173481. * We can avoid loading/saving bitread state if in an EOB run.
  173482. */
  173483. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173484. /* There is always only one block per MCU */
  173485. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173486. EOBRUN--; /* ...process it now (we do nothing) */
  173487. else {
  173488. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173489. block = MCU_data[0];
  173490. tbl = entropy->ac_derived_tbl;
  173491. for (k = cinfo->Ss; k <= Se; k++) {
  173492. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173493. r = s >> 4;
  173494. s &= 15;
  173495. if (s) {
  173496. k += r;
  173497. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173498. r = GET_BITS(s);
  173499. s = HUFF_EXTEND(r, s);
  173500. /* Scale and output coefficient in natural (dezigzagged) order */
  173501. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173502. } else {
  173503. if (r == 15) { /* ZRL */
  173504. k += 15; /* skip 15 zeroes in band */
  173505. } else { /* EOBr, run length is 2^r + appended bits */
  173506. EOBRUN = 1 << r;
  173507. if (r) { /* EOBr, r > 0 */
  173508. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173509. r = GET_BITS(r);
  173510. EOBRUN += r;
  173511. }
  173512. EOBRUN--; /* this band is processed at this moment */
  173513. break; /* force end-of-band */
  173514. }
  173515. }
  173516. }
  173517. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173518. }
  173519. /* Completed MCU, so update state */
  173520. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173521. }
  173522. /* Account for restart interval (no-op if not using restarts) */
  173523. entropy->restarts_to_go--;
  173524. return TRUE;
  173525. }
  173526. /*
  173527. * MCU decoding for DC successive approximation refinement scan.
  173528. * Note: we assume such scans can be multi-component, although the spec
  173529. * is not very clear on the point.
  173530. */
  173531. METHODDEF(boolean)
  173532. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173533. {
  173534. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173535. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173536. int blkn;
  173537. JBLOCKROW block;
  173538. BITREAD_STATE_VARS;
  173539. /* Process restart marker if needed; may have to suspend */
  173540. if (cinfo->restart_interval) {
  173541. if (entropy->restarts_to_go == 0)
  173542. if (! process_restartp(cinfo))
  173543. return FALSE;
  173544. }
  173545. /* Not worth the cycles to check insufficient_data here,
  173546. * since we will not change the data anyway if we read zeroes.
  173547. */
  173548. /* Load up working state */
  173549. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173550. /* Outer loop handles each block in the MCU */
  173551. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173552. block = MCU_data[blkn];
  173553. /* Encoded data is simply the next bit of the two's-complement DC value */
  173554. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173555. if (GET_BITS(1))
  173556. (*block)[0] |= p1;
  173557. /* Note: since we use |=, repeating the assignment later is safe */
  173558. }
  173559. /* Completed MCU, so update state */
  173560. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173561. /* Account for restart interval (no-op if not using restarts) */
  173562. entropy->restarts_to_go--;
  173563. return TRUE;
  173564. }
  173565. /*
  173566. * MCU decoding for AC successive approximation refinement scan.
  173567. */
  173568. METHODDEF(boolean)
  173569. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173570. {
  173571. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173572. int Se = cinfo->Se;
  173573. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173574. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173575. register int s, k, r;
  173576. unsigned int EOBRUN;
  173577. JBLOCKROW block;
  173578. JCOEFPTR thiscoef;
  173579. BITREAD_STATE_VARS;
  173580. d_derived_tbl * tbl;
  173581. int num_newnz;
  173582. int newnz_pos[DCTSIZE2];
  173583. /* Process restart marker if needed; may have to suspend */
  173584. if (cinfo->restart_interval) {
  173585. if (entropy->restarts_to_go == 0)
  173586. if (! process_restartp(cinfo))
  173587. return FALSE;
  173588. }
  173589. /* If we've run out of data, don't modify the MCU.
  173590. */
  173591. if (! entropy->pub.insufficient_data) {
  173592. /* Load up working state */
  173593. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173594. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173595. /* There is always only one block per MCU */
  173596. block = MCU_data[0];
  173597. tbl = entropy->ac_derived_tbl;
  173598. /* If we are forced to suspend, we must undo the assignments to any newly
  173599. * nonzero coefficients in the block, because otherwise we'd get confused
  173600. * next time about which coefficients were already nonzero.
  173601. * But we need not undo addition of bits to already-nonzero coefficients;
  173602. * instead, we can test the current bit to see if we already did it.
  173603. */
  173604. num_newnz = 0;
  173605. /* initialize coefficient loop counter to start of band */
  173606. k = cinfo->Ss;
  173607. if (EOBRUN == 0) {
  173608. for (; k <= Se; k++) {
  173609. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173610. r = s >> 4;
  173611. s &= 15;
  173612. if (s) {
  173613. if (s != 1) /* size of new coef should always be 1 */
  173614. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173615. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173616. if (GET_BITS(1))
  173617. s = p1; /* newly nonzero coef is positive */
  173618. else
  173619. s = m1; /* newly nonzero coef is negative */
  173620. } else {
  173621. if (r != 15) {
  173622. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173623. if (r) {
  173624. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173625. r = GET_BITS(r);
  173626. EOBRUN += r;
  173627. }
  173628. break; /* rest of block is handled by EOB logic */
  173629. }
  173630. /* note s = 0 for processing ZRL */
  173631. }
  173632. /* Advance over already-nonzero coefs and r still-zero coefs,
  173633. * appending correction bits to the nonzeroes. A correction bit is 1
  173634. * if the absolute value of the coefficient must be increased.
  173635. */
  173636. do {
  173637. thiscoef = *block + jpeg_natural_order[k];
  173638. if (*thiscoef != 0) {
  173639. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173640. if (GET_BITS(1)) {
  173641. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173642. if (*thiscoef >= 0)
  173643. *thiscoef += p1;
  173644. else
  173645. *thiscoef += m1;
  173646. }
  173647. }
  173648. } else {
  173649. if (--r < 0)
  173650. break; /* reached target zero coefficient */
  173651. }
  173652. k++;
  173653. } while (k <= Se);
  173654. if (s) {
  173655. int pos = jpeg_natural_order[k];
  173656. /* Output newly nonzero coefficient */
  173657. (*block)[pos] = (JCOEF) s;
  173658. /* Remember its position in case we have to suspend */
  173659. newnz_pos[num_newnz++] = pos;
  173660. }
  173661. }
  173662. }
  173663. if (EOBRUN > 0) {
  173664. /* Scan any remaining coefficient positions after the end-of-band
  173665. * (the last newly nonzero coefficient, if any). Append a correction
  173666. * bit to each already-nonzero coefficient. A correction bit is 1
  173667. * if the absolute value of the coefficient must be increased.
  173668. */
  173669. for (; k <= Se; k++) {
  173670. thiscoef = *block + jpeg_natural_order[k];
  173671. if (*thiscoef != 0) {
  173672. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173673. if (GET_BITS(1)) {
  173674. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173675. if (*thiscoef >= 0)
  173676. *thiscoef += p1;
  173677. else
  173678. *thiscoef += m1;
  173679. }
  173680. }
  173681. }
  173682. }
  173683. /* Count one block completed in EOB run */
  173684. EOBRUN--;
  173685. }
  173686. /* Completed MCU, so update state */
  173687. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173688. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173689. }
  173690. /* Account for restart interval (no-op if not using restarts) */
  173691. entropy->restarts_to_go--;
  173692. return TRUE;
  173693. undoit:
  173694. /* Re-zero any output coefficients that we made newly nonzero */
  173695. while (num_newnz > 0)
  173696. (*block)[newnz_pos[--num_newnz]] = 0;
  173697. return FALSE;
  173698. }
  173699. /*
  173700. * Module initialization routine for progressive Huffman entropy decoding.
  173701. */
  173702. GLOBAL(void)
  173703. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173704. {
  173705. phuff_entropy_ptr2 entropy;
  173706. int *coef_bit_ptr;
  173707. int ci, i;
  173708. entropy = (phuff_entropy_ptr2)
  173709. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173710. SIZEOF(phuff_entropy_decoder));
  173711. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173712. entropy->pub.start_pass = start_pass_phuff_decoder;
  173713. /* Mark derived tables unallocated */
  173714. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173715. entropy->derived_tbls[i] = NULL;
  173716. }
  173717. /* Create progression status table */
  173718. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173719. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173720. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173721. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173722. for (ci = 0; ci < cinfo->num_components; ci++)
  173723. for (i = 0; i < DCTSIZE2; i++)
  173724. *coef_bit_ptr++ = -1;
  173725. }
  173726. #endif /* D_PROGRESSIVE_SUPPORTED */
  173727. /*** End of inlined file: jdphuff.c ***/
  173728. /*** Start of inlined file: jdpostct.c ***/
  173729. #define JPEG_INTERNALS
  173730. /* Private buffer controller object */
  173731. typedef struct {
  173732. struct jpeg_d_post_controller pub; /* public fields */
  173733. /* Color quantization source buffer: this holds output data from
  173734. * the upsample/color conversion step to be passed to the quantizer.
  173735. * For two-pass color quantization, we need a full-image buffer;
  173736. * for one-pass operation, a strip buffer is sufficient.
  173737. */
  173738. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173739. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173740. JDIMENSION strip_height; /* buffer size in rows */
  173741. /* for two-pass mode only: */
  173742. JDIMENSION starting_row; /* row # of first row in current strip */
  173743. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173744. } my_post_controller;
  173745. typedef my_post_controller * my_post_ptr;
  173746. /* Forward declarations */
  173747. METHODDEF(void) post_process_1pass
  173748. JPP((j_decompress_ptr cinfo,
  173749. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173750. JDIMENSION in_row_groups_avail,
  173751. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173752. JDIMENSION out_rows_avail));
  173753. #ifdef QUANT_2PASS_SUPPORTED
  173754. METHODDEF(void) post_process_prepass
  173755. JPP((j_decompress_ptr cinfo,
  173756. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173757. JDIMENSION in_row_groups_avail,
  173758. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173759. JDIMENSION out_rows_avail));
  173760. METHODDEF(void) post_process_2pass
  173761. JPP((j_decompress_ptr cinfo,
  173762. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173763. JDIMENSION in_row_groups_avail,
  173764. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173765. JDIMENSION out_rows_avail));
  173766. #endif
  173767. /*
  173768. * Initialize for a processing pass.
  173769. */
  173770. METHODDEF(void)
  173771. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173772. {
  173773. my_post_ptr post = (my_post_ptr) cinfo->post;
  173774. switch (pass_mode) {
  173775. case JBUF_PASS_THRU:
  173776. if (cinfo->quantize_colors) {
  173777. /* Single-pass processing with color quantization. */
  173778. post->pub.post_process_data = post_process_1pass;
  173779. /* We could be doing buffered-image output before starting a 2-pass
  173780. * color quantization; in that case, jinit_d_post_controller did not
  173781. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173782. */
  173783. if (post->buffer == NULL) {
  173784. post->buffer = (*cinfo->mem->access_virt_sarray)
  173785. ((j_common_ptr) cinfo, post->whole_image,
  173786. (JDIMENSION) 0, post->strip_height, TRUE);
  173787. }
  173788. } else {
  173789. /* For single-pass processing without color quantization,
  173790. * I have no work to do; just call the upsampler directly.
  173791. */
  173792. post->pub.post_process_data = cinfo->upsample->upsample;
  173793. }
  173794. break;
  173795. #ifdef QUANT_2PASS_SUPPORTED
  173796. case JBUF_SAVE_AND_PASS:
  173797. /* First pass of 2-pass quantization */
  173798. if (post->whole_image == NULL)
  173799. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173800. post->pub.post_process_data = post_process_prepass;
  173801. break;
  173802. case JBUF_CRANK_DEST:
  173803. /* Second pass of 2-pass quantization */
  173804. if (post->whole_image == NULL)
  173805. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173806. post->pub.post_process_data = post_process_2pass;
  173807. break;
  173808. #endif /* QUANT_2PASS_SUPPORTED */
  173809. default:
  173810. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173811. break;
  173812. }
  173813. post->starting_row = post->next_row = 0;
  173814. }
  173815. /*
  173816. * Process some data in the one-pass (strip buffer) case.
  173817. * This is used for color precision reduction as well as one-pass quantization.
  173818. */
  173819. METHODDEF(void)
  173820. post_process_1pass (j_decompress_ptr cinfo,
  173821. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173822. JDIMENSION in_row_groups_avail,
  173823. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173824. JDIMENSION out_rows_avail)
  173825. {
  173826. my_post_ptr post = (my_post_ptr) cinfo->post;
  173827. JDIMENSION num_rows, max_rows;
  173828. /* Fill the buffer, but not more than what we can dump out in one go. */
  173829. /* Note we rely on the upsampler to detect bottom of image. */
  173830. max_rows = out_rows_avail - *out_row_ctr;
  173831. if (max_rows > post->strip_height)
  173832. max_rows = post->strip_height;
  173833. num_rows = 0;
  173834. (*cinfo->upsample->upsample) (cinfo,
  173835. input_buf, in_row_group_ctr, in_row_groups_avail,
  173836. post->buffer, &num_rows, max_rows);
  173837. /* Quantize and emit data. */
  173838. (*cinfo->cquantize->color_quantize) (cinfo,
  173839. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173840. *out_row_ctr += num_rows;
  173841. }
  173842. #ifdef QUANT_2PASS_SUPPORTED
  173843. /*
  173844. * Process some data in the first pass of 2-pass quantization.
  173845. */
  173846. METHODDEF(void)
  173847. post_process_prepass (j_decompress_ptr cinfo,
  173848. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173849. JDIMENSION in_row_groups_avail,
  173850. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173851. JDIMENSION)
  173852. {
  173853. my_post_ptr post = (my_post_ptr) cinfo->post;
  173854. JDIMENSION old_next_row, num_rows;
  173855. /* Reposition virtual buffer if at start of strip. */
  173856. if (post->next_row == 0) {
  173857. post->buffer = (*cinfo->mem->access_virt_sarray)
  173858. ((j_common_ptr) cinfo, post->whole_image,
  173859. post->starting_row, post->strip_height, TRUE);
  173860. }
  173861. /* Upsample some data (up to a strip height's worth). */
  173862. old_next_row = post->next_row;
  173863. (*cinfo->upsample->upsample) (cinfo,
  173864. input_buf, in_row_group_ctr, in_row_groups_avail,
  173865. post->buffer, &post->next_row, post->strip_height);
  173866. /* Allow quantizer to scan new data. No data is emitted, */
  173867. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173868. if (post->next_row > old_next_row) {
  173869. num_rows = post->next_row - old_next_row;
  173870. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173871. (JSAMPARRAY) NULL, (int) num_rows);
  173872. *out_row_ctr += num_rows;
  173873. }
  173874. /* Advance if we filled the strip. */
  173875. if (post->next_row >= post->strip_height) {
  173876. post->starting_row += post->strip_height;
  173877. post->next_row = 0;
  173878. }
  173879. }
  173880. /*
  173881. * Process some data in the second pass of 2-pass quantization.
  173882. */
  173883. METHODDEF(void)
  173884. post_process_2pass (j_decompress_ptr cinfo,
  173885. JSAMPIMAGE, JDIMENSION *,
  173886. JDIMENSION,
  173887. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173888. JDIMENSION out_rows_avail)
  173889. {
  173890. my_post_ptr post = (my_post_ptr) cinfo->post;
  173891. JDIMENSION num_rows, max_rows;
  173892. /* Reposition virtual buffer if at start of strip. */
  173893. if (post->next_row == 0) {
  173894. post->buffer = (*cinfo->mem->access_virt_sarray)
  173895. ((j_common_ptr) cinfo, post->whole_image,
  173896. post->starting_row, post->strip_height, FALSE);
  173897. }
  173898. /* Determine number of rows to emit. */
  173899. num_rows = post->strip_height - post->next_row; /* available in strip */
  173900. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173901. if (num_rows > max_rows)
  173902. num_rows = max_rows;
  173903. /* We have to check bottom of image here, can't depend on upsampler. */
  173904. max_rows = cinfo->output_height - post->starting_row;
  173905. if (num_rows > max_rows)
  173906. num_rows = max_rows;
  173907. /* Quantize and emit data. */
  173908. (*cinfo->cquantize->color_quantize) (cinfo,
  173909. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173910. (int) num_rows);
  173911. *out_row_ctr += num_rows;
  173912. /* Advance if we filled the strip. */
  173913. post->next_row += num_rows;
  173914. if (post->next_row >= post->strip_height) {
  173915. post->starting_row += post->strip_height;
  173916. post->next_row = 0;
  173917. }
  173918. }
  173919. #endif /* QUANT_2PASS_SUPPORTED */
  173920. /*
  173921. * Initialize postprocessing controller.
  173922. */
  173923. GLOBAL(void)
  173924. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173925. {
  173926. my_post_ptr post;
  173927. post = (my_post_ptr)
  173928. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173929. SIZEOF(my_post_controller));
  173930. cinfo->post = (struct jpeg_d_post_controller *) post;
  173931. post->pub.start_pass = start_pass_dpost;
  173932. post->whole_image = NULL; /* flag for no virtual arrays */
  173933. post->buffer = NULL; /* flag for no strip buffer */
  173934. /* Create the quantization buffer, if needed */
  173935. if (cinfo->quantize_colors) {
  173936. /* The buffer strip height is max_v_samp_factor, which is typically
  173937. * an efficient number of rows for upsampling to return.
  173938. * (In the presence of output rescaling, we might want to be smarter?)
  173939. */
  173940. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173941. if (need_full_buffer) {
  173942. /* Two-pass color quantization: need full-image storage. */
  173943. /* We round up the number of rows to a multiple of the strip height. */
  173944. #ifdef QUANT_2PASS_SUPPORTED
  173945. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173946. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173947. cinfo->output_width * cinfo->out_color_components,
  173948. (JDIMENSION) jround_up((long) cinfo->output_height,
  173949. (long) post->strip_height),
  173950. post->strip_height);
  173951. #else
  173952. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173953. #endif /* QUANT_2PASS_SUPPORTED */
  173954. } else {
  173955. /* One-pass color quantization: just make a strip buffer. */
  173956. post->buffer = (*cinfo->mem->alloc_sarray)
  173957. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173958. cinfo->output_width * cinfo->out_color_components,
  173959. post->strip_height);
  173960. }
  173961. }
  173962. }
  173963. /*** End of inlined file: jdpostct.c ***/
  173964. #undef FIX
  173965. /*** Start of inlined file: jdsample.c ***/
  173966. #define JPEG_INTERNALS
  173967. /* Pointer to routine to upsample a single component */
  173968. typedef JMETHOD(void, upsample1_ptr,
  173969. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173970. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173971. /* Private subobject */
  173972. typedef struct {
  173973. struct jpeg_upsampler pub; /* public fields */
  173974. /* Color conversion buffer. When using separate upsampling and color
  173975. * conversion steps, this buffer holds one upsampled row group until it
  173976. * has been color converted and output.
  173977. * Note: we do not allocate any storage for component(s) which are full-size,
  173978. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173979. * simply set to point to the input data array, thereby avoiding copying.
  173980. */
  173981. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173982. /* Per-component upsampling method pointers */
  173983. upsample1_ptr methods[MAX_COMPONENTS];
  173984. int next_row_out; /* counts rows emitted from color_buf */
  173985. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173986. /* Height of an input row group for each component. */
  173987. int rowgroup_height[MAX_COMPONENTS];
  173988. /* These arrays save pixel expansion factors so that int_expand need not
  173989. * recompute them each time. They are unused for other upsampling methods.
  173990. */
  173991. UINT8 h_expand[MAX_COMPONENTS];
  173992. UINT8 v_expand[MAX_COMPONENTS];
  173993. } my_upsampler2;
  173994. typedef my_upsampler2 * my_upsample_ptr2;
  173995. /*
  173996. * Initialize for an upsampling pass.
  173997. */
  173998. METHODDEF(void)
  173999. start_pass_upsample (j_decompress_ptr cinfo)
  174000. {
  174001. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174002. /* Mark the conversion buffer empty */
  174003. upsample->next_row_out = cinfo->max_v_samp_factor;
  174004. /* Initialize total-height counter for detecting bottom of image */
  174005. upsample->rows_to_go = cinfo->output_height;
  174006. }
  174007. /*
  174008. * Control routine to do upsampling (and color conversion).
  174009. *
  174010. * In this version we upsample each component independently.
  174011. * We upsample one row group into the conversion buffer, then apply
  174012. * color conversion a row at a time.
  174013. */
  174014. METHODDEF(void)
  174015. sep_upsample (j_decompress_ptr cinfo,
  174016. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174017. JDIMENSION,
  174018. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174019. JDIMENSION out_rows_avail)
  174020. {
  174021. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174022. int ci;
  174023. jpeg_component_info * compptr;
  174024. JDIMENSION num_rows;
  174025. /* Fill the conversion buffer, if it's empty */
  174026. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  174027. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174028. ci++, compptr++) {
  174029. /* Invoke per-component upsample method. Notice we pass a POINTER
  174030. * to color_buf[ci], so that fullsize_upsample can change it.
  174031. */
  174032. (*upsample->methods[ci]) (cinfo, compptr,
  174033. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  174034. upsample->color_buf + ci);
  174035. }
  174036. upsample->next_row_out = 0;
  174037. }
  174038. /* Color-convert and emit rows */
  174039. /* How many we have in the buffer: */
  174040. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  174041. /* Not more than the distance to the end of the image. Need this test
  174042. * in case the image height is not a multiple of max_v_samp_factor:
  174043. */
  174044. if (num_rows > upsample->rows_to_go)
  174045. num_rows = upsample->rows_to_go;
  174046. /* And not more than what the client can accept: */
  174047. out_rows_avail -= *out_row_ctr;
  174048. if (num_rows > out_rows_avail)
  174049. num_rows = out_rows_avail;
  174050. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  174051. (JDIMENSION) upsample->next_row_out,
  174052. output_buf + *out_row_ctr,
  174053. (int) num_rows);
  174054. /* Adjust counts */
  174055. *out_row_ctr += num_rows;
  174056. upsample->rows_to_go -= num_rows;
  174057. upsample->next_row_out += num_rows;
  174058. /* When the buffer is emptied, declare this input row group consumed */
  174059. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  174060. (*in_row_group_ctr)++;
  174061. }
  174062. /*
  174063. * These are the routines invoked by sep_upsample to upsample pixel values
  174064. * of a single component. One row group is processed per call.
  174065. */
  174066. /*
  174067. * For full-size components, we just make color_buf[ci] point at the
  174068. * input buffer, and thus avoid copying any data. Note that this is
  174069. * safe only because sep_upsample doesn't declare the input row group
  174070. * "consumed" until we are done color converting and emitting it.
  174071. */
  174072. METHODDEF(void)
  174073. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  174074. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174075. {
  174076. *output_data_ptr = input_data;
  174077. }
  174078. /*
  174079. * This is a no-op version used for "uninteresting" components.
  174080. * These components will not be referenced by color conversion.
  174081. */
  174082. METHODDEF(void)
  174083. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  174084. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  174085. {
  174086. *output_data_ptr = NULL; /* safety check */
  174087. }
  174088. /*
  174089. * This version handles any integral sampling ratios.
  174090. * This is not used for typical JPEG files, so it need not be fast.
  174091. * Nor, for that matter, is it particularly accurate: the algorithm is
  174092. * simple replication of the input pixel onto the corresponding output
  174093. * pixels. The hi-falutin sampling literature refers to this as a
  174094. * "box filter". A box filter tends to introduce visible artifacts,
  174095. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  174096. * you would be well advised to improve this code.
  174097. */
  174098. METHODDEF(void)
  174099. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174100. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174101. {
  174102. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174103. JSAMPARRAY output_data = *output_data_ptr;
  174104. register JSAMPROW inptr, outptr;
  174105. register JSAMPLE invalue;
  174106. register int h;
  174107. JSAMPROW outend;
  174108. int h_expand, v_expand;
  174109. int inrow, outrow;
  174110. h_expand = upsample->h_expand[compptr->component_index];
  174111. v_expand = upsample->v_expand[compptr->component_index];
  174112. inrow = outrow = 0;
  174113. while (outrow < cinfo->max_v_samp_factor) {
  174114. /* Generate one output row with proper horizontal expansion */
  174115. inptr = input_data[inrow];
  174116. outptr = output_data[outrow];
  174117. outend = outptr + cinfo->output_width;
  174118. while (outptr < outend) {
  174119. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174120. for (h = h_expand; h > 0; h--) {
  174121. *outptr++ = invalue;
  174122. }
  174123. }
  174124. /* Generate any additional output rows by duplicating the first one */
  174125. if (v_expand > 1) {
  174126. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174127. v_expand-1, cinfo->output_width);
  174128. }
  174129. inrow++;
  174130. outrow += v_expand;
  174131. }
  174132. }
  174133. /*
  174134. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174135. * It's still a box filter.
  174136. */
  174137. METHODDEF(void)
  174138. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174139. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174140. {
  174141. JSAMPARRAY output_data = *output_data_ptr;
  174142. register JSAMPROW inptr, outptr;
  174143. register JSAMPLE invalue;
  174144. JSAMPROW outend;
  174145. int inrow;
  174146. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174147. inptr = input_data[inrow];
  174148. outptr = output_data[inrow];
  174149. outend = outptr + cinfo->output_width;
  174150. while (outptr < outend) {
  174151. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174152. *outptr++ = invalue;
  174153. *outptr++ = invalue;
  174154. }
  174155. }
  174156. }
  174157. /*
  174158. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174159. * It's still a box filter.
  174160. */
  174161. METHODDEF(void)
  174162. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174163. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174164. {
  174165. JSAMPARRAY output_data = *output_data_ptr;
  174166. register JSAMPROW inptr, outptr;
  174167. register JSAMPLE invalue;
  174168. JSAMPROW outend;
  174169. int inrow, outrow;
  174170. inrow = outrow = 0;
  174171. while (outrow < cinfo->max_v_samp_factor) {
  174172. inptr = input_data[inrow];
  174173. outptr = output_data[outrow];
  174174. outend = outptr + cinfo->output_width;
  174175. while (outptr < outend) {
  174176. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174177. *outptr++ = invalue;
  174178. *outptr++ = invalue;
  174179. }
  174180. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174181. 1, cinfo->output_width);
  174182. inrow++;
  174183. outrow += 2;
  174184. }
  174185. }
  174186. /*
  174187. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174188. *
  174189. * The upsampling algorithm is linear interpolation between pixel centers,
  174190. * also known as a "triangle filter". This is a good compromise between
  174191. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174192. * of the way between input pixel centers.
  174193. *
  174194. * A note about the "bias" calculations: when rounding fractional values to
  174195. * integer, we do not want to always round 0.5 up to the next integer.
  174196. * If we did that, we'd introduce a noticeable bias towards larger values.
  174197. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174198. * alternate pixel locations (a simple ordered dither pattern).
  174199. */
  174200. METHODDEF(void)
  174201. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174202. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174203. {
  174204. JSAMPARRAY output_data = *output_data_ptr;
  174205. register JSAMPROW inptr, outptr;
  174206. register int invalue;
  174207. register JDIMENSION colctr;
  174208. int inrow;
  174209. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174210. inptr = input_data[inrow];
  174211. outptr = output_data[inrow];
  174212. /* Special case for first column */
  174213. invalue = GETJSAMPLE(*inptr++);
  174214. *outptr++ = (JSAMPLE) invalue;
  174215. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174216. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174217. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174218. invalue = GETJSAMPLE(*inptr++) * 3;
  174219. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174220. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174221. }
  174222. /* Special case for last column */
  174223. invalue = GETJSAMPLE(*inptr);
  174224. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174225. *outptr++ = (JSAMPLE) invalue;
  174226. }
  174227. }
  174228. /*
  174229. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174230. * Again a triangle filter; see comments for h2v1 case, above.
  174231. *
  174232. * It is OK for us to reference the adjacent input rows because we demanded
  174233. * context from the main buffer controller (see initialization code).
  174234. */
  174235. METHODDEF(void)
  174236. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174237. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174238. {
  174239. JSAMPARRAY output_data = *output_data_ptr;
  174240. register JSAMPROW inptr0, inptr1, outptr;
  174241. #if BITS_IN_JSAMPLE == 8
  174242. register int thiscolsum, lastcolsum, nextcolsum;
  174243. #else
  174244. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174245. #endif
  174246. register JDIMENSION colctr;
  174247. int inrow, outrow, v;
  174248. inrow = outrow = 0;
  174249. while (outrow < cinfo->max_v_samp_factor) {
  174250. for (v = 0; v < 2; v++) {
  174251. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174252. inptr0 = input_data[inrow];
  174253. if (v == 0) /* next nearest is row above */
  174254. inptr1 = input_data[inrow-1];
  174255. else /* next nearest is row below */
  174256. inptr1 = input_data[inrow+1];
  174257. outptr = output_data[outrow++];
  174258. /* Special case for first column */
  174259. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174260. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174261. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174262. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174263. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174264. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174265. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174266. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174267. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174268. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174269. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174270. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174271. }
  174272. /* Special case for last column */
  174273. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174274. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174275. }
  174276. inrow++;
  174277. }
  174278. }
  174279. /*
  174280. * Module initialization routine for upsampling.
  174281. */
  174282. GLOBAL(void)
  174283. jinit_upsampler (j_decompress_ptr cinfo)
  174284. {
  174285. my_upsample_ptr2 upsample;
  174286. int ci;
  174287. jpeg_component_info * compptr;
  174288. boolean need_buffer, do_fancy;
  174289. int h_in_group, v_in_group, h_out_group, v_out_group;
  174290. upsample = (my_upsample_ptr2)
  174291. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174292. SIZEOF(my_upsampler2));
  174293. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174294. upsample->pub.start_pass = start_pass_upsample;
  174295. upsample->pub.upsample = sep_upsample;
  174296. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174297. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174298. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174299. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174300. * so don't ask for it.
  174301. */
  174302. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174303. /* Verify we can handle the sampling factors, select per-component methods,
  174304. * and create storage as needed.
  174305. */
  174306. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174307. ci++, compptr++) {
  174308. /* Compute size of an "input group" after IDCT scaling. This many samples
  174309. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174310. */
  174311. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174312. cinfo->min_DCT_scaled_size;
  174313. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174314. cinfo->min_DCT_scaled_size;
  174315. h_out_group = cinfo->max_h_samp_factor;
  174316. v_out_group = cinfo->max_v_samp_factor;
  174317. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174318. need_buffer = TRUE;
  174319. if (! compptr->component_needed) {
  174320. /* Don't bother to upsample an uninteresting component. */
  174321. upsample->methods[ci] = noop_upsample;
  174322. need_buffer = FALSE;
  174323. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174324. /* Fullsize components can be processed without any work. */
  174325. upsample->methods[ci] = fullsize_upsample;
  174326. need_buffer = FALSE;
  174327. } else if (h_in_group * 2 == h_out_group &&
  174328. v_in_group == v_out_group) {
  174329. /* Special cases for 2h1v upsampling */
  174330. if (do_fancy && compptr->downsampled_width > 2)
  174331. upsample->methods[ci] = h2v1_fancy_upsample;
  174332. else
  174333. upsample->methods[ci] = h2v1_upsample;
  174334. } else if (h_in_group * 2 == h_out_group &&
  174335. v_in_group * 2 == v_out_group) {
  174336. /* Special cases for 2h2v upsampling */
  174337. if (do_fancy && compptr->downsampled_width > 2) {
  174338. upsample->methods[ci] = h2v2_fancy_upsample;
  174339. upsample->pub.need_context_rows = TRUE;
  174340. } else
  174341. upsample->methods[ci] = h2v2_upsample;
  174342. } else if ((h_out_group % h_in_group) == 0 &&
  174343. (v_out_group % v_in_group) == 0) {
  174344. /* Generic integral-factors upsampling method */
  174345. upsample->methods[ci] = int_upsample;
  174346. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174347. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174348. } else
  174349. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174350. if (need_buffer) {
  174351. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174352. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174353. (JDIMENSION) jround_up((long) cinfo->output_width,
  174354. (long) cinfo->max_h_samp_factor),
  174355. (JDIMENSION) cinfo->max_v_samp_factor);
  174356. }
  174357. }
  174358. }
  174359. /*** End of inlined file: jdsample.c ***/
  174360. /*** Start of inlined file: jdtrans.c ***/
  174361. #define JPEG_INTERNALS
  174362. /* Forward declarations */
  174363. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174364. /*
  174365. * Read the coefficient arrays from a JPEG file.
  174366. * jpeg_read_header must be completed before calling this.
  174367. *
  174368. * The entire image is read into a set of virtual coefficient-block arrays,
  174369. * one per component. The return value is a pointer to the array of
  174370. * virtual-array descriptors. These can be manipulated directly via the
  174371. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174372. * To release the memory occupied by the virtual arrays, call
  174373. * jpeg_finish_decompress() when done with the data.
  174374. *
  174375. * An alternative usage is to simply obtain access to the coefficient arrays
  174376. * during a buffered-image-mode decompression operation. This is allowed
  174377. * after any jpeg_finish_output() call. The arrays can be accessed until
  174378. * jpeg_finish_decompress() is called. (Note that any call to the library
  174379. * may reposition the arrays, so don't rely on access_virt_barray() results
  174380. * to stay valid across library calls.)
  174381. *
  174382. * Returns NULL if suspended. This case need be checked only if
  174383. * a suspending data source is used.
  174384. */
  174385. GLOBAL(jvirt_barray_ptr *)
  174386. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174387. {
  174388. if (cinfo->global_state == DSTATE_READY) {
  174389. /* First call: initialize active modules */
  174390. transdecode_master_selection(cinfo);
  174391. cinfo->global_state = DSTATE_RDCOEFS;
  174392. }
  174393. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174394. /* Absorb whole file into the coef buffer */
  174395. for (;;) {
  174396. int retcode;
  174397. /* Call progress monitor hook if present */
  174398. if (cinfo->progress != NULL)
  174399. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174400. /* Absorb some more input */
  174401. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174402. if (retcode == JPEG_SUSPENDED)
  174403. return NULL;
  174404. if (retcode == JPEG_REACHED_EOI)
  174405. break;
  174406. /* Advance progress counter if appropriate */
  174407. if (cinfo->progress != NULL &&
  174408. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174409. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174410. /* startup underestimated number of scans; ratchet up one scan */
  174411. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174412. }
  174413. }
  174414. }
  174415. /* Set state so that jpeg_finish_decompress does the right thing */
  174416. cinfo->global_state = DSTATE_STOPPING;
  174417. }
  174418. /* At this point we should be in state DSTATE_STOPPING if being used
  174419. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174420. * to the coefficients during a full buffered-image-mode decompression.
  174421. */
  174422. if ((cinfo->global_state == DSTATE_STOPPING ||
  174423. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174424. return cinfo->coef->coef_arrays;
  174425. }
  174426. /* Oops, improper usage */
  174427. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174428. return NULL; /* keep compiler happy */
  174429. }
  174430. /*
  174431. * Master selection of decompression modules for transcoding.
  174432. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174433. */
  174434. LOCAL(void)
  174435. transdecode_master_selection (j_decompress_ptr cinfo)
  174436. {
  174437. /* This is effectively a buffered-image operation. */
  174438. cinfo->buffered_image = TRUE;
  174439. /* Entropy decoding: either Huffman or arithmetic coding. */
  174440. if (cinfo->arith_code) {
  174441. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174442. } else {
  174443. if (cinfo->progressive_mode) {
  174444. #ifdef D_PROGRESSIVE_SUPPORTED
  174445. jinit_phuff_decoder(cinfo);
  174446. #else
  174447. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174448. #endif
  174449. } else
  174450. jinit_huff_decoder(cinfo);
  174451. }
  174452. /* Always get a full-image coefficient buffer. */
  174453. jinit_d_coef_controller(cinfo, TRUE);
  174454. /* We can now tell the memory manager to allocate virtual arrays. */
  174455. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174456. /* Initialize input side of decompressor to consume first scan. */
  174457. (*cinfo->inputctl->start_input_pass) (cinfo);
  174458. /* Initialize progress monitoring. */
  174459. if (cinfo->progress != NULL) {
  174460. int nscans;
  174461. /* Estimate number of scans to set pass_limit. */
  174462. if (cinfo->progressive_mode) {
  174463. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174464. nscans = 2 + 3 * cinfo->num_components;
  174465. } else if (cinfo->inputctl->has_multiple_scans) {
  174466. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174467. nscans = cinfo->num_components;
  174468. } else {
  174469. nscans = 1;
  174470. }
  174471. cinfo->progress->pass_counter = 0L;
  174472. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174473. cinfo->progress->completed_passes = 0;
  174474. cinfo->progress->total_passes = 1;
  174475. }
  174476. }
  174477. /*** End of inlined file: jdtrans.c ***/
  174478. /*** Start of inlined file: jfdctflt.c ***/
  174479. #define JPEG_INTERNALS
  174480. #ifdef DCT_FLOAT_SUPPORTED
  174481. /*
  174482. * This module is specialized to the case DCTSIZE = 8.
  174483. */
  174484. #if DCTSIZE != 8
  174485. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174486. #endif
  174487. /*
  174488. * Perform the forward DCT on one block of samples.
  174489. */
  174490. GLOBAL(void)
  174491. jpeg_fdct_float (FAST_FLOAT * data)
  174492. {
  174493. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174494. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174495. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174496. FAST_FLOAT *dataptr;
  174497. int ctr;
  174498. /* Pass 1: process rows. */
  174499. dataptr = data;
  174500. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174501. tmp0 = dataptr[0] + dataptr[7];
  174502. tmp7 = dataptr[0] - dataptr[7];
  174503. tmp1 = dataptr[1] + dataptr[6];
  174504. tmp6 = dataptr[1] - dataptr[6];
  174505. tmp2 = dataptr[2] + dataptr[5];
  174506. tmp5 = dataptr[2] - dataptr[5];
  174507. tmp3 = dataptr[3] + dataptr[4];
  174508. tmp4 = dataptr[3] - dataptr[4];
  174509. /* Even part */
  174510. tmp10 = tmp0 + tmp3; /* phase 2 */
  174511. tmp13 = tmp0 - tmp3;
  174512. tmp11 = tmp1 + tmp2;
  174513. tmp12 = tmp1 - tmp2;
  174514. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174515. dataptr[4] = tmp10 - tmp11;
  174516. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174517. dataptr[2] = tmp13 + z1; /* phase 5 */
  174518. dataptr[6] = tmp13 - z1;
  174519. /* Odd part */
  174520. tmp10 = tmp4 + tmp5; /* phase 2 */
  174521. tmp11 = tmp5 + tmp6;
  174522. tmp12 = tmp6 + tmp7;
  174523. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174524. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174525. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174526. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174527. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174528. z11 = tmp7 + z3; /* phase 5 */
  174529. z13 = tmp7 - z3;
  174530. dataptr[5] = z13 + z2; /* phase 6 */
  174531. dataptr[3] = z13 - z2;
  174532. dataptr[1] = z11 + z4;
  174533. dataptr[7] = z11 - z4;
  174534. dataptr += DCTSIZE; /* advance pointer to next row */
  174535. }
  174536. /* Pass 2: process columns. */
  174537. dataptr = data;
  174538. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174539. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174540. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174541. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174542. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174543. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174544. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174545. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174546. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174547. /* Even part */
  174548. tmp10 = tmp0 + tmp3; /* phase 2 */
  174549. tmp13 = tmp0 - tmp3;
  174550. tmp11 = tmp1 + tmp2;
  174551. tmp12 = tmp1 - tmp2;
  174552. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174553. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174554. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174555. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174556. dataptr[DCTSIZE*6] = tmp13 - z1;
  174557. /* Odd part */
  174558. tmp10 = tmp4 + tmp5; /* phase 2 */
  174559. tmp11 = tmp5 + tmp6;
  174560. tmp12 = tmp6 + tmp7;
  174561. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174562. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174563. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174564. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174565. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174566. z11 = tmp7 + z3; /* phase 5 */
  174567. z13 = tmp7 - z3;
  174568. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174569. dataptr[DCTSIZE*3] = z13 - z2;
  174570. dataptr[DCTSIZE*1] = z11 + z4;
  174571. dataptr[DCTSIZE*7] = z11 - z4;
  174572. dataptr++; /* advance pointer to next column */
  174573. }
  174574. }
  174575. #endif /* DCT_FLOAT_SUPPORTED */
  174576. /*** End of inlined file: jfdctflt.c ***/
  174577. /*** Start of inlined file: jfdctint.c ***/
  174578. #define JPEG_INTERNALS
  174579. #ifdef DCT_ISLOW_SUPPORTED
  174580. /*
  174581. * This module is specialized to the case DCTSIZE = 8.
  174582. */
  174583. #if DCTSIZE != 8
  174584. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174585. #endif
  174586. /*
  174587. * The poop on this scaling stuff is as follows:
  174588. *
  174589. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174590. * larger than the true DCT outputs. The final outputs are therefore
  174591. * a factor of N larger than desired; since N=8 this can be cured by
  174592. * a simple right shift at the end of the algorithm. The advantage of
  174593. * this arrangement is that we save two multiplications per 1-D DCT,
  174594. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174595. * In the IJG code, this factor of 8 is removed by the quantization step
  174596. * (in jcdctmgr.c), NOT in this module.
  174597. *
  174598. * We have to do addition and subtraction of the integer inputs, which
  174599. * is no problem, and multiplication by fractional constants, which is
  174600. * a problem to do in integer arithmetic. We multiply all the constants
  174601. * by CONST_SCALE and convert them to integer constants (thus retaining
  174602. * CONST_BITS bits of precision in the constants). After doing a
  174603. * multiplication we have to divide the product by CONST_SCALE, with proper
  174604. * rounding, to produce the correct output. This division can be done
  174605. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174606. * as long as possible so that partial sums can be added together with
  174607. * full fractional precision.
  174608. *
  174609. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174610. * they are represented to better-than-integral precision. These outputs
  174611. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174612. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174613. * array is INT32 anyway.)
  174614. *
  174615. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174616. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174617. * shows that the values given below are the most effective.
  174618. */
  174619. #if BITS_IN_JSAMPLE == 8
  174620. #define CONST_BITS 13
  174621. #define PASS1_BITS 2
  174622. #else
  174623. #define CONST_BITS 13
  174624. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174625. #endif
  174626. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174627. * causing a lot of useless floating-point operations at run time.
  174628. * To get around this we use the following pre-calculated constants.
  174629. * If you change CONST_BITS you may want to add appropriate values.
  174630. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174631. */
  174632. #if CONST_BITS == 13
  174633. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174634. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174635. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174636. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174637. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174638. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174639. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174640. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174641. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174642. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174643. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174644. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174645. #else
  174646. #define FIX_0_298631336 FIX(0.298631336)
  174647. #define FIX_0_390180644 FIX(0.390180644)
  174648. #define FIX_0_541196100 FIX(0.541196100)
  174649. #define FIX_0_765366865 FIX(0.765366865)
  174650. #define FIX_0_899976223 FIX(0.899976223)
  174651. #define FIX_1_175875602 FIX(1.175875602)
  174652. #define FIX_1_501321110 FIX(1.501321110)
  174653. #define FIX_1_847759065 FIX(1.847759065)
  174654. #define FIX_1_961570560 FIX(1.961570560)
  174655. #define FIX_2_053119869 FIX(2.053119869)
  174656. #define FIX_2_562915447 FIX(2.562915447)
  174657. #define FIX_3_072711026 FIX(3.072711026)
  174658. #endif
  174659. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174660. * For 8-bit samples with the recommended scaling, all the variable
  174661. * and constant values involved are no more than 16 bits wide, so a
  174662. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174663. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174664. */
  174665. #if BITS_IN_JSAMPLE == 8
  174666. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174667. #else
  174668. #define MULTIPLY(var,const) ((var) * (const))
  174669. #endif
  174670. /*
  174671. * Perform the forward DCT on one block of samples.
  174672. */
  174673. GLOBAL(void)
  174674. jpeg_fdct_islow (DCTELEM * data)
  174675. {
  174676. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174677. INT32 tmp10, tmp11, tmp12, tmp13;
  174678. INT32 z1, z2, z3, z4, z5;
  174679. DCTELEM *dataptr;
  174680. int ctr;
  174681. SHIFT_TEMPS
  174682. /* Pass 1: process rows. */
  174683. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174684. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174685. dataptr = data;
  174686. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174687. tmp0 = dataptr[0] + dataptr[7];
  174688. tmp7 = dataptr[0] - dataptr[7];
  174689. tmp1 = dataptr[1] + dataptr[6];
  174690. tmp6 = dataptr[1] - dataptr[6];
  174691. tmp2 = dataptr[2] + dataptr[5];
  174692. tmp5 = dataptr[2] - dataptr[5];
  174693. tmp3 = dataptr[3] + dataptr[4];
  174694. tmp4 = dataptr[3] - dataptr[4];
  174695. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174696. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174697. */
  174698. tmp10 = tmp0 + tmp3;
  174699. tmp13 = tmp0 - tmp3;
  174700. tmp11 = tmp1 + tmp2;
  174701. tmp12 = tmp1 - tmp2;
  174702. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174703. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174704. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174705. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174706. CONST_BITS-PASS1_BITS);
  174707. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174708. CONST_BITS-PASS1_BITS);
  174709. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174710. * cK represents cos(K*pi/16).
  174711. * i0..i3 in the paper are tmp4..tmp7 here.
  174712. */
  174713. z1 = tmp4 + tmp7;
  174714. z2 = tmp5 + tmp6;
  174715. z3 = tmp4 + tmp6;
  174716. z4 = tmp5 + tmp7;
  174717. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174718. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174719. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174720. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174721. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174722. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174723. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174724. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174725. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174726. z3 += z5;
  174727. z4 += z5;
  174728. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174729. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174730. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174731. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174732. dataptr += DCTSIZE; /* advance pointer to next row */
  174733. }
  174734. /* Pass 2: process columns.
  174735. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174736. * by an overall factor of 8.
  174737. */
  174738. dataptr = data;
  174739. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174740. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174741. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174742. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174743. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174744. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174745. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174746. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174747. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174748. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174749. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174750. */
  174751. tmp10 = tmp0 + tmp3;
  174752. tmp13 = tmp0 - tmp3;
  174753. tmp11 = tmp1 + tmp2;
  174754. tmp12 = tmp1 - tmp2;
  174755. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174756. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174757. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174758. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174759. CONST_BITS+PASS1_BITS);
  174760. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174761. CONST_BITS+PASS1_BITS);
  174762. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174763. * cK represents cos(K*pi/16).
  174764. * i0..i3 in the paper are tmp4..tmp7 here.
  174765. */
  174766. z1 = tmp4 + tmp7;
  174767. z2 = tmp5 + tmp6;
  174768. z3 = tmp4 + tmp6;
  174769. z4 = tmp5 + tmp7;
  174770. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174771. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174772. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174773. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174774. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174775. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174776. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174777. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174778. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174779. z3 += z5;
  174780. z4 += z5;
  174781. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174782. CONST_BITS+PASS1_BITS);
  174783. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174784. CONST_BITS+PASS1_BITS);
  174785. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174786. CONST_BITS+PASS1_BITS);
  174787. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174788. CONST_BITS+PASS1_BITS);
  174789. dataptr++; /* advance pointer to next column */
  174790. }
  174791. }
  174792. #endif /* DCT_ISLOW_SUPPORTED */
  174793. /*** End of inlined file: jfdctint.c ***/
  174794. #undef CONST_BITS
  174795. #undef MULTIPLY
  174796. #undef FIX_0_541196100
  174797. /*** Start of inlined file: jfdctfst.c ***/
  174798. #define JPEG_INTERNALS
  174799. #ifdef DCT_IFAST_SUPPORTED
  174800. /*
  174801. * This module is specialized to the case DCTSIZE = 8.
  174802. */
  174803. #if DCTSIZE != 8
  174804. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174805. #endif
  174806. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174807. * see jfdctint.c for more details. However, we choose to descale
  174808. * (right shift) multiplication products as soon as they are formed,
  174809. * rather than carrying additional fractional bits into subsequent additions.
  174810. * This compromises accuracy slightly, but it lets us save a few shifts.
  174811. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174812. * everywhere except in the multiplications proper; this saves a good deal
  174813. * of work on 16-bit-int machines.
  174814. *
  174815. * Again to save a few shifts, the intermediate results between pass 1 and
  174816. * pass 2 are not upscaled, but are represented only to integral precision.
  174817. *
  174818. * A final compromise is to represent the multiplicative constants to only
  174819. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174820. * machines, and may also reduce the cost of multiplication (since there
  174821. * are fewer one-bits in the constants).
  174822. */
  174823. #define CONST_BITS 8
  174824. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174825. * causing a lot of useless floating-point operations at run time.
  174826. * To get around this we use the following pre-calculated constants.
  174827. * If you change CONST_BITS you may want to add appropriate values.
  174828. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174829. */
  174830. #if CONST_BITS == 8
  174831. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174832. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174833. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174834. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174835. #else
  174836. #define FIX_0_382683433 FIX(0.382683433)
  174837. #define FIX_0_541196100 FIX(0.541196100)
  174838. #define FIX_0_707106781 FIX(0.707106781)
  174839. #define FIX_1_306562965 FIX(1.306562965)
  174840. #endif
  174841. /* We can gain a little more speed, with a further compromise in accuracy,
  174842. * by omitting the addition in a descaling shift. This yields an incorrectly
  174843. * rounded result half the time...
  174844. */
  174845. #ifndef USE_ACCURATE_ROUNDING
  174846. #undef DESCALE
  174847. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174848. #endif
  174849. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174850. * descale to yield a DCTELEM result.
  174851. */
  174852. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174853. /*
  174854. * Perform the forward DCT on one block of samples.
  174855. */
  174856. GLOBAL(void)
  174857. jpeg_fdct_ifast (DCTELEM * data)
  174858. {
  174859. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174860. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174861. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174862. DCTELEM *dataptr;
  174863. int ctr;
  174864. SHIFT_TEMPS
  174865. /* Pass 1: process rows. */
  174866. dataptr = data;
  174867. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174868. tmp0 = dataptr[0] + dataptr[7];
  174869. tmp7 = dataptr[0] - dataptr[7];
  174870. tmp1 = dataptr[1] + dataptr[6];
  174871. tmp6 = dataptr[1] - dataptr[6];
  174872. tmp2 = dataptr[2] + dataptr[5];
  174873. tmp5 = dataptr[2] - dataptr[5];
  174874. tmp3 = dataptr[3] + dataptr[4];
  174875. tmp4 = dataptr[3] - dataptr[4];
  174876. /* Even part */
  174877. tmp10 = tmp0 + tmp3; /* phase 2 */
  174878. tmp13 = tmp0 - tmp3;
  174879. tmp11 = tmp1 + tmp2;
  174880. tmp12 = tmp1 - tmp2;
  174881. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174882. dataptr[4] = tmp10 - tmp11;
  174883. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174884. dataptr[2] = tmp13 + z1; /* phase 5 */
  174885. dataptr[6] = tmp13 - z1;
  174886. /* Odd part */
  174887. tmp10 = tmp4 + tmp5; /* phase 2 */
  174888. tmp11 = tmp5 + tmp6;
  174889. tmp12 = tmp6 + tmp7;
  174890. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174891. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174892. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174893. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174894. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174895. z11 = tmp7 + z3; /* phase 5 */
  174896. z13 = tmp7 - z3;
  174897. dataptr[5] = z13 + z2; /* phase 6 */
  174898. dataptr[3] = z13 - z2;
  174899. dataptr[1] = z11 + z4;
  174900. dataptr[7] = z11 - z4;
  174901. dataptr += DCTSIZE; /* advance pointer to next row */
  174902. }
  174903. /* Pass 2: process columns. */
  174904. dataptr = data;
  174905. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174906. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174907. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174908. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174909. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174910. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174911. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174912. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174913. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174914. /* Even part */
  174915. tmp10 = tmp0 + tmp3; /* phase 2 */
  174916. tmp13 = tmp0 - tmp3;
  174917. tmp11 = tmp1 + tmp2;
  174918. tmp12 = tmp1 - tmp2;
  174919. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174920. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174921. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174922. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174923. dataptr[DCTSIZE*6] = tmp13 - z1;
  174924. /* Odd part */
  174925. tmp10 = tmp4 + tmp5; /* phase 2 */
  174926. tmp11 = tmp5 + tmp6;
  174927. tmp12 = tmp6 + tmp7;
  174928. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174929. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174930. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174931. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174932. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174933. z11 = tmp7 + z3; /* phase 5 */
  174934. z13 = tmp7 - z3;
  174935. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174936. dataptr[DCTSIZE*3] = z13 - z2;
  174937. dataptr[DCTSIZE*1] = z11 + z4;
  174938. dataptr[DCTSIZE*7] = z11 - z4;
  174939. dataptr++; /* advance pointer to next column */
  174940. }
  174941. }
  174942. #endif /* DCT_IFAST_SUPPORTED */
  174943. /*** End of inlined file: jfdctfst.c ***/
  174944. #undef FIX_0_541196100
  174945. /*** Start of inlined file: jidctflt.c ***/
  174946. #define JPEG_INTERNALS
  174947. #ifdef DCT_FLOAT_SUPPORTED
  174948. /*
  174949. * This module is specialized to the case DCTSIZE = 8.
  174950. */
  174951. #if DCTSIZE != 8
  174952. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174953. #endif
  174954. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174955. * entry; produce a float result.
  174956. */
  174957. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174958. /*
  174959. * Perform dequantization and inverse DCT on one block of coefficients.
  174960. */
  174961. GLOBAL(void)
  174962. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174963. JCOEFPTR coef_block,
  174964. JSAMPARRAY output_buf, JDIMENSION output_col)
  174965. {
  174966. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174967. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174968. FAST_FLOAT z5, z10, z11, z12, z13;
  174969. JCOEFPTR inptr;
  174970. FLOAT_MULT_TYPE * quantptr;
  174971. FAST_FLOAT * wsptr;
  174972. JSAMPROW outptr;
  174973. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174974. int ctr;
  174975. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174976. SHIFT_TEMPS
  174977. /* Pass 1: process columns from input, store into work array. */
  174978. inptr = coef_block;
  174979. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174980. wsptr = workspace;
  174981. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174982. /* Due to quantization, we will usually find that many of the input
  174983. * coefficients are zero, especially the AC terms. We can exploit this
  174984. * by short-circuiting the IDCT calculation for any column in which all
  174985. * the AC terms are zero. In that case each output is equal to the
  174986. * DC coefficient (with scale factor as needed).
  174987. * With typical images and quantization tables, half or more of the
  174988. * column DCT calculations can be simplified this way.
  174989. */
  174990. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174991. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174992. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174993. inptr[DCTSIZE*7] == 0) {
  174994. /* AC terms all zero */
  174995. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174996. wsptr[DCTSIZE*0] = dcval;
  174997. wsptr[DCTSIZE*1] = dcval;
  174998. wsptr[DCTSIZE*2] = dcval;
  174999. wsptr[DCTSIZE*3] = dcval;
  175000. wsptr[DCTSIZE*4] = dcval;
  175001. wsptr[DCTSIZE*5] = dcval;
  175002. wsptr[DCTSIZE*6] = dcval;
  175003. wsptr[DCTSIZE*7] = dcval;
  175004. inptr++; /* advance pointers to next column */
  175005. quantptr++;
  175006. wsptr++;
  175007. continue;
  175008. }
  175009. /* Even part */
  175010. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175011. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175012. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175013. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175014. tmp10 = tmp0 + tmp2; /* phase 3 */
  175015. tmp11 = tmp0 - tmp2;
  175016. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175017. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  175018. tmp0 = tmp10 + tmp13; /* phase 2 */
  175019. tmp3 = tmp10 - tmp13;
  175020. tmp1 = tmp11 + tmp12;
  175021. tmp2 = tmp11 - tmp12;
  175022. /* Odd part */
  175023. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175024. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175025. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175026. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175027. z13 = tmp6 + tmp5; /* phase 6 */
  175028. z10 = tmp6 - tmp5;
  175029. z11 = tmp4 + tmp7;
  175030. z12 = tmp4 - tmp7;
  175031. tmp7 = z11 + z13; /* phase 5 */
  175032. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  175033. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175034. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175035. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175036. tmp6 = tmp12 - tmp7; /* phase 2 */
  175037. tmp5 = tmp11 - tmp6;
  175038. tmp4 = tmp10 + tmp5;
  175039. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  175040. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  175041. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  175042. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  175043. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  175044. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  175045. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  175046. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  175047. inptr++; /* advance pointers to next column */
  175048. quantptr++;
  175049. wsptr++;
  175050. }
  175051. /* Pass 2: process rows from work array, store into output array. */
  175052. /* Note that we must descale the results by a factor of 8 == 2**3. */
  175053. wsptr = workspace;
  175054. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175055. outptr = output_buf[ctr] + output_col;
  175056. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175057. * However, the column calculation has created many nonzero AC terms, so
  175058. * the simplification applies less often (typically 5% to 10% of the time).
  175059. * And testing floats for zero is relatively expensive, so we don't bother.
  175060. */
  175061. /* Even part */
  175062. tmp10 = wsptr[0] + wsptr[4];
  175063. tmp11 = wsptr[0] - wsptr[4];
  175064. tmp13 = wsptr[2] + wsptr[6];
  175065. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  175066. tmp0 = tmp10 + tmp13;
  175067. tmp3 = tmp10 - tmp13;
  175068. tmp1 = tmp11 + tmp12;
  175069. tmp2 = tmp11 - tmp12;
  175070. /* Odd part */
  175071. z13 = wsptr[5] + wsptr[3];
  175072. z10 = wsptr[5] - wsptr[3];
  175073. z11 = wsptr[1] + wsptr[7];
  175074. z12 = wsptr[1] - wsptr[7];
  175075. tmp7 = z11 + z13;
  175076. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  175077. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175078. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175079. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175080. tmp6 = tmp12 - tmp7;
  175081. tmp5 = tmp11 - tmp6;
  175082. tmp4 = tmp10 + tmp5;
  175083. /* Final output stage: scale down by a factor of 8 and range-limit */
  175084. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  175085. & RANGE_MASK];
  175086. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  175087. & RANGE_MASK];
  175088. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  175089. & RANGE_MASK];
  175090. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  175091. & RANGE_MASK];
  175092. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  175093. & RANGE_MASK];
  175094. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  175095. & RANGE_MASK];
  175096. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  175097. & RANGE_MASK];
  175098. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  175099. & RANGE_MASK];
  175100. wsptr += DCTSIZE; /* advance pointer to next row */
  175101. }
  175102. }
  175103. #endif /* DCT_FLOAT_SUPPORTED */
  175104. /*** End of inlined file: jidctflt.c ***/
  175105. #undef CONST_BITS
  175106. #undef FIX_1_847759065
  175107. #undef MULTIPLY
  175108. #undef DEQUANTIZE
  175109. #undef DESCALE
  175110. /*** Start of inlined file: jidctfst.c ***/
  175111. #define JPEG_INTERNALS
  175112. #ifdef DCT_IFAST_SUPPORTED
  175113. /*
  175114. * This module is specialized to the case DCTSIZE = 8.
  175115. */
  175116. #if DCTSIZE != 8
  175117. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175118. #endif
  175119. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175120. * see jidctint.c for more details. However, we choose to descale
  175121. * (right shift) multiplication products as soon as they are formed,
  175122. * rather than carrying additional fractional bits into subsequent additions.
  175123. * This compromises accuracy slightly, but it lets us save a few shifts.
  175124. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175125. * everywhere except in the multiplications proper; this saves a good deal
  175126. * of work on 16-bit-int machines.
  175127. *
  175128. * The dequantized coefficients are not integers because the AA&N scaling
  175129. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175130. * so that the first and second IDCT rounds have the same input scaling.
  175131. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175132. * avoid a descaling shift; this compromises accuracy rather drastically
  175133. * for small quantization table entries, but it saves a lot of shifts.
  175134. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175135. * so we use a much larger scaling factor to preserve accuracy.
  175136. *
  175137. * A final compromise is to represent the multiplicative constants to only
  175138. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175139. * machines, and may also reduce the cost of multiplication (since there
  175140. * are fewer one-bits in the constants).
  175141. */
  175142. #if BITS_IN_JSAMPLE == 8
  175143. #define CONST_BITS 8
  175144. #define PASS1_BITS 2
  175145. #else
  175146. #define CONST_BITS 8
  175147. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175148. #endif
  175149. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175150. * causing a lot of useless floating-point operations at run time.
  175151. * To get around this we use the following pre-calculated constants.
  175152. * If you change CONST_BITS you may want to add appropriate values.
  175153. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175154. */
  175155. #if CONST_BITS == 8
  175156. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175157. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175158. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175159. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175160. #else
  175161. #define FIX_1_082392200 FIX(1.082392200)
  175162. #define FIX_1_414213562 FIX(1.414213562)
  175163. #define FIX_1_847759065 FIX(1.847759065)
  175164. #define FIX_2_613125930 FIX(2.613125930)
  175165. #endif
  175166. /* We can gain a little more speed, with a further compromise in accuracy,
  175167. * by omitting the addition in a descaling shift. This yields an incorrectly
  175168. * rounded result half the time...
  175169. */
  175170. #ifndef USE_ACCURATE_ROUNDING
  175171. #undef DESCALE
  175172. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175173. #endif
  175174. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175175. * descale to yield a DCTELEM result.
  175176. */
  175177. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175178. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175179. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175180. * multiplication will do. For 12-bit data, the multiplier table is
  175181. * declared INT32, so a 32-bit multiply will be used.
  175182. */
  175183. #if BITS_IN_JSAMPLE == 8
  175184. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175185. #else
  175186. #define DEQUANTIZE(coef,quantval) \
  175187. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175188. #endif
  175189. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175190. * We assume that int right shift is unsigned if INT32 right shift is.
  175191. */
  175192. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175193. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175194. #if BITS_IN_JSAMPLE == 8
  175195. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175196. #else
  175197. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175198. #endif
  175199. #define IRIGHT_SHIFT(x,shft) \
  175200. ((ishift_temp = (x)) < 0 ? \
  175201. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175202. (ishift_temp >> (shft)))
  175203. #else
  175204. #define ISHIFT_TEMPS
  175205. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175206. #endif
  175207. #ifdef USE_ACCURATE_ROUNDING
  175208. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175209. #else
  175210. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175211. #endif
  175212. /*
  175213. * Perform dequantization and inverse DCT on one block of coefficients.
  175214. */
  175215. GLOBAL(void)
  175216. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175217. JCOEFPTR coef_block,
  175218. JSAMPARRAY output_buf, JDIMENSION output_col)
  175219. {
  175220. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175221. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175222. DCTELEM z5, z10, z11, z12, z13;
  175223. JCOEFPTR inptr;
  175224. IFAST_MULT_TYPE * quantptr;
  175225. int * wsptr;
  175226. JSAMPROW outptr;
  175227. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175228. int ctr;
  175229. int workspace[DCTSIZE2]; /* buffers data between passes */
  175230. SHIFT_TEMPS /* for DESCALE */
  175231. ISHIFT_TEMPS /* for IDESCALE */
  175232. /* Pass 1: process columns from input, store into work array. */
  175233. inptr = coef_block;
  175234. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175235. wsptr = workspace;
  175236. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175237. /* Due to quantization, we will usually find that many of the input
  175238. * coefficients are zero, especially the AC terms. We can exploit this
  175239. * by short-circuiting the IDCT calculation for any column in which all
  175240. * the AC terms are zero. In that case each output is equal to the
  175241. * DC coefficient (with scale factor as needed).
  175242. * With typical images and quantization tables, half or more of the
  175243. * column DCT calculations can be simplified this way.
  175244. */
  175245. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175246. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175247. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175248. inptr[DCTSIZE*7] == 0) {
  175249. /* AC terms all zero */
  175250. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175251. wsptr[DCTSIZE*0] = dcval;
  175252. wsptr[DCTSIZE*1] = dcval;
  175253. wsptr[DCTSIZE*2] = dcval;
  175254. wsptr[DCTSIZE*3] = dcval;
  175255. wsptr[DCTSIZE*4] = dcval;
  175256. wsptr[DCTSIZE*5] = dcval;
  175257. wsptr[DCTSIZE*6] = dcval;
  175258. wsptr[DCTSIZE*7] = dcval;
  175259. inptr++; /* advance pointers to next column */
  175260. quantptr++;
  175261. wsptr++;
  175262. continue;
  175263. }
  175264. /* Even part */
  175265. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175266. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175267. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175268. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175269. tmp10 = tmp0 + tmp2; /* phase 3 */
  175270. tmp11 = tmp0 - tmp2;
  175271. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175272. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175273. tmp0 = tmp10 + tmp13; /* phase 2 */
  175274. tmp3 = tmp10 - tmp13;
  175275. tmp1 = tmp11 + tmp12;
  175276. tmp2 = tmp11 - tmp12;
  175277. /* Odd part */
  175278. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175279. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175280. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175281. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175282. z13 = tmp6 + tmp5; /* phase 6 */
  175283. z10 = tmp6 - tmp5;
  175284. z11 = tmp4 + tmp7;
  175285. z12 = tmp4 - tmp7;
  175286. tmp7 = z11 + z13; /* phase 5 */
  175287. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175288. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175289. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175290. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175291. tmp6 = tmp12 - tmp7; /* phase 2 */
  175292. tmp5 = tmp11 - tmp6;
  175293. tmp4 = tmp10 + tmp5;
  175294. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175295. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175296. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175297. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175298. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175299. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175300. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175301. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175302. inptr++; /* advance pointers to next column */
  175303. quantptr++;
  175304. wsptr++;
  175305. }
  175306. /* Pass 2: process rows from work array, store into output array. */
  175307. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175308. /* and also undo the PASS1_BITS scaling. */
  175309. wsptr = workspace;
  175310. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175311. outptr = output_buf[ctr] + output_col;
  175312. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175313. * However, the column calculation has created many nonzero AC terms, so
  175314. * the simplification applies less often (typically 5% to 10% of the time).
  175315. * On machines with very fast multiplication, it's possible that the
  175316. * test takes more time than it's worth. In that case this section
  175317. * may be commented out.
  175318. */
  175319. #ifndef NO_ZERO_ROW_TEST
  175320. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175321. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175322. /* AC terms all zero */
  175323. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175324. & RANGE_MASK];
  175325. outptr[0] = dcval;
  175326. outptr[1] = dcval;
  175327. outptr[2] = dcval;
  175328. outptr[3] = dcval;
  175329. outptr[4] = dcval;
  175330. outptr[5] = dcval;
  175331. outptr[6] = dcval;
  175332. outptr[7] = dcval;
  175333. wsptr += DCTSIZE; /* advance pointer to next row */
  175334. continue;
  175335. }
  175336. #endif
  175337. /* Even part */
  175338. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175339. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175340. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175341. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175342. - tmp13;
  175343. tmp0 = tmp10 + tmp13;
  175344. tmp3 = tmp10 - tmp13;
  175345. tmp1 = tmp11 + tmp12;
  175346. tmp2 = tmp11 - tmp12;
  175347. /* Odd part */
  175348. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175349. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175350. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175351. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175352. tmp7 = z11 + z13; /* phase 5 */
  175353. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175354. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175355. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175356. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175357. tmp6 = tmp12 - tmp7; /* phase 2 */
  175358. tmp5 = tmp11 - tmp6;
  175359. tmp4 = tmp10 + tmp5;
  175360. /* Final output stage: scale down by a factor of 8 and range-limit */
  175361. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175362. & RANGE_MASK];
  175363. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175364. & RANGE_MASK];
  175365. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175366. & RANGE_MASK];
  175367. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175368. & RANGE_MASK];
  175369. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175370. & RANGE_MASK];
  175371. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175372. & RANGE_MASK];
  175373. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175374. & RANGE_MASK];
  175375. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175376. & RANGE_MASK];
  175377. wsptr += DCTSIZE; /* advance pointer to next row */
  175378. }
  175379. }
  175380. #endif /* DCT_IFAST_SUPPORTED */
  175381. /*** End of inlined file: jidctfst.c ***/
  175382. #undef CONST_BITS
  175383. #undef FIX_1_847759065
  175384. #undef MULTIPLY
  175385. #undef DEQUANTIZE
  175386. /*** Start of inlined file: jidctint.c ***/
  175387. #define JPEG_INTERNALS
  175388. #ifdef DCT_ISLOW_SUPPORTED
  175389. /*
  175390. * This module is specialized to the case DCTSIZE = 8.
  175391. */
  175392. #if DCTSIZE != 8
  175393. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175394. #endif
  175395. /*
  175396. * The poop on this scaling stuff is as follows:
  175397. *
  175398. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175399. * larger than the true IDCT outputs. The final outputs are therefore
  175400. * a factor of N larger than desired; since N=8 this can be cured by
  175401. * a simple right shift at the end of the algorithm. The advantage of
  175402. * this arrangement is that we save two multiplications per 1-D IDCT,
  175403. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175404. *
  175405. * We have to do addition and subtraction of the integer inputs, which
  175406. * is no problem, and multiplication by fractional constants, which is
  175407. * a problem to do in integer arithmetic. We multiply all the constants
  175408. * by CONST_SCALE and convert them to integer constants (thus retaining
  175409. * CONST_BITS bits of precision in the constants). After doing a
  175410. * multiplication we have to divide the product by CONST_SCALE, with proper
  175411. * rounding, to produce the correct output. This division can be done
  175412. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175413. * as long as possible so that partial sums can be added together with
  175414. * full fractional precision.
  175415. *
  175416. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175417. * they are represented to better-than-integral precision. These outputs
  175418. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175419. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175420. * intermediate INT32 array would be needed.)
  175421. *
  175422. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175423. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175424. * shows that the values given below are the most effective.
  175425. */
  175426. #if BITS_IN_JSAMPLE == 8
  175427. #define CONST_BITS 13
  175428. #define PASS1_BITS 2
  175429. #else
  175430. #define CONST_BITS 13
  175431. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175432. #endif
  175433. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175434. * causing a lot of useless floating-point operations at run time.
  175435. * To get around this we use the following pre-calculated constants.
  175436. * If you change CONST_BITS you may want to add appropriate values.
  175437. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175438. */
  175439. #if CONST_BITS == 13
  175440. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175441. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175442. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175443. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175444. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175445. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175446. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175447. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175448. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175449. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175450. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175451. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175452. #else
  175453. #define FIX_0_298631336 FIX(0.298631336)
  175454. #define FIX_0_390180644 FIX(0.390180644)
  175455. #define FIX_0_541196100 FIX(0.541196100)
  175456. #define FIX_0_765366865 FIX(0.765366865)
  175457. #define FIX_0_899976223 FIX(0.899976223)
  175458. #define FIX_1_175875602 FIX(1.175875602)
  175459. #define FIX_1_501321110 FIX(1.501321110)
  175460. #define FIX_1_847759065 FIX(1.847759065)
  175461. #define FIX_1_961570560 FIX(1.961570560)
  175462. #define FIX_2_053119869 FIX(2.053119869)
  175463. #define FIX_2_562915447 FIX(2.562915447)
  175464. #define FIX_3_072711026 FIX(3.072711026)
  175465. #endif
  175466. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175467. * For 8-bit samples with the recommended scaling, all the variable
  175468. * and constant values involved are no more than 16 bits wide, so a
  175469. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175470. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175471. */
  175472. #if BITS_IN_JSAMPLE == 8
  175473. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175474. #else
  175475. #define MULTIPLY(var,const) ((var) * (const))
  175476. #endif
  175477. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175478. * entry; produce an int result. In this module, both inputs and result
  175479. * are 16 bits or less, so either int or short multiply will work.
  175480. */
  175481. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175482. /*
  175483. * Perform dequantization and inverse DCT on one block of coefficients.
  175484. */
  175485. GLOBAL(void)
  175486. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175487. JCOEFPTR coef_block,
  175488. JSAMPARRAY output_buf, JDIMENSION output_col)
  175489. {
  175490. INT32 tmp0, tmp1, tmp2, tmp3;
  175491. INT32 tmp10, tmp11, tmp12, tmp13;
  175492. INT32 z1, z2, z3, z4, z5;
  175493. JCOEFPTR inptr;
  175494. ISLOW_MULT_TYPE * quantptr;
  175495. int * wsptr;
  175496. JSAMPROW outptr;
  175497. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175498. int ctr;
  175499. int workspace[DCTSIZE2]; /* buffers data between passes */
  175500. SHIFT_TEMPS
  175501. /* Pass 1: process columns from input, store into work array. */
  175502. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175503. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175504. inptr = coef_block;
  175505. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175506. wsptr = workspace;
  175507. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175508. /* Due to quantization, we will usually find that many of the input
  175509. * coefficients are zero, especially the AC terms. We can exploit this
  175510. * by short-circuiting the IDCT calculation for any column in which all
  175511. * the AC terms are zero. In that case each output is equal to the
  175512. * DC coefficient (with scale factor as needed).
  175513. * With typical images and quantization tables, half or more of the
  175514. * column DCT calculations can be simplified this way.
  175515. */
  175516. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175517. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175518. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175519. inptr[DCTSIZE*7] == 0) {
  175520. /* AC terms all zero */
  175521. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175522. wsptr[DCTSIZE*0] = dcval;
  175523. wsptr[DCTSIZE*1] = dcval;
  175524. wsptr[DCTSIZE*2] = dcval;
  175525. wsptr[DCTSIZE*3] = dcval;
  175526. wsptr[DCTSIZE*4] = dcval;
  175527. wsptr[DCTSIZE*5] = dcval;
  175528. wsptr[DCTSIZE*6] = dcval;
  175529. wsptr[DCTSIZE*7] = dcval;
  175530. inptr++; /* advance pointers to next column */
  175531. quantptr++;
  175532. wsptr++;
  175533. continue;
  175534. }
  175535. /* Even part: reverse the even part of the forward DCT. */
  175536. /* The rotator is sqrt(2)*c(-6). */
  175537. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175538. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175539. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175540. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175541. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175542. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175543. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175544. tmp0 = (z2 + z3) << CONST_BITS;
  175545. tmp1 = (z2 - z3) << CONST_BITS;
  175546. tmp10 = tmp0 + tmp3;
  175547. tmp13 = tmp0 - tmp3;
  175548. tmp11 = tmp1 + tmp2;
  175549. tmp12 = tmp1 - tmp2;
  175550. /* Odd part per figure 8; the matrix is unitary and hence its
  175551. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175552. */
  175553. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175554. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175555. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175556. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175557. z1 = tmp0 + tmp3;
  175558. z2 = tmp1 + tmp2;
  175559. z3 = tmp0 + tmp2;
  175560. z4 = tmp1 + tmp3;
  175561. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175562. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175563. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175564. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175565. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175566. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175567. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175568. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175569. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175570. z3 += z5;
  175571. z4 += z5;
  175572. tmp0 += z1 + z3;
  175573. tmp1 += z2 + z4;
  175574. tmp2 += z2 + z3;
  175575. tmp3 += z1 + z4;
  175576. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175577. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175578. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175579. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175580. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175581. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175582. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175583. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175584. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175585. inptr++; /* advance pointers to next column */
  175586. quantptr++;
  175587. wsptr++;
  175588. }
  175589. /* Pass 2: process rows from work array, store into output array. */
  175590. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175591. /* and also undo the PASS1_BITS scaling. */
  175592. wsptr = workspace;
  175593. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175594. outptr = output_buf[ctr] + output_col;
  175595. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175596. * However, the column calculation has created many nonzero AC terms, so
  175597. * the simplification applies less often (typically 5% to 10% of the time).
  175598. * On machines with very fast multiplication, it's possible that the
  175599. * test takes more time than it's worth. In that case this section
  175600. * may be commented out.
  175601. */
  175602. #ifndef NO_ZERO_ROW_TEST
  175603. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175604. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175605. /* AC terms all zero */
  175606. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175607. & RANGE_MASK];
  175608. outptr[0] = dcval;
  175609. outptr[1] = dcval;
  175610. outptr[2] = dcval;
  175611. outptr[3] = dcval;
  175612. outptr[4] = dcval;
  175613. outptr[5] = dcval;
  175614. outptr[6] = dcval;
  175615. outptr[7] = dcval;
  175616. wsptr += DCTSIZE; /* advance pointer to next row */
  175617. continue;
  175618. }
  175619. #endif
  175620. /* Even part: reverse the even part of the forward DCT. */
  175621. /* The rotator is sqrt(2)*c(-6). */
  175622. z2 = (INT32) wsptr[2];
  175623. z3 = (INT32) wsptr[6];
  175624. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175625. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175626. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175627. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175628. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175629. tmp10 = tmp0 + tmp3;
  175630. tmp13 = tmp0 - tmp3;
  175631. tmp11 = tmp1 + tmp2;
  175632. tmp12 = tmp1 - tmp2;
  175633. /* Odd part per figure 8; the matrix is unitary and hence its
  175634. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175635. */
  175636. tmp0 = (INT32) wsptr[7];
  175637. tmp1 = (INT32) wsptr[5];
  175638. tmp2 = (INT32) wsptr[3];
  175639. tmp3 = (INT32) wsptr[1];
  175640. z1 = tmp0 + tmp3;
  175641. z2 = tmp1 + tmp2;
  175642. z3 = tmp0 + tmp2;
  175643. z4 = tmp1 + tmp3;
  175644. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175645. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175646. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175647. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175648. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175649. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175650. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175651. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175652. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175653. z3 += z5;
  175654. z4 += z5;
  175655. tmp0 += z1 + z3;
  175656. tmp1 += z2 + z4;
  175657. tmp2 += z2 + z3;
  175658. tmp3 += z1 + z4;
  175659. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175660. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175661. CONST_BITS+PASS1_BITS+3)
  175662. & RANGE_MASK];
  175663. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175664. CONST_BITS+PASS1_BITS+3)
  175665. & RANGE_MASK];
  175666. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175667. CONST_BITS+PASS1_BITS+3)
  175668. & RANGE_MASK];
  175669. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175670. CONST_BITS+PASS1_BITS+3)
  175671. & RANGE_MASK];
  175672. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175673. CONST_BITS+PASS1_BITS+3)
  175674. & RANGE_MASK];
  175675. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175676. CONST_BITS+PASS1_BITS+3)
  175677. & RANGE_MASK];
  175678. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175679. CONST_BITS+PASS1_BITS+3)
  175680. & RANGE_MASK];
  175681. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175682. CONST_BITS+PASS1_BITS+3)
  175683. & RANGE_MASK];
  175684. wsptr += DCTSIZE; /* advance pointer to next row */
  175685. }
  175686. }
  175687. #endif /* DCT_ISLOW_SUPPORTED */
  175688. /*** End of inlined file: jidctint.c ***/
  175689. /*** Start of inlined file: jidctred.c ***/
  175690. #define JPEG_INTERNALS
  175691. #ifdef IDCT_SCALING_SUPPORTED
  175692. /*
  175693. * This module is specialized to the case DCTSIZE = 8.
  175694. */
  175695. #if DCTSIZE != 8
  175696. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175697. #endif
  175698. /* Scaling is the same as in jidctint.c. */
  175699. #if BITS_IN_JSAMPLE == 8
  175700. #define CONST_BITS 13
  175701. #define PASS1_BITS 2
  175702. #else
  175703. #define CONST_BITS 13
  175704. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175705. #endif
  175706. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175707. * causing a lot of useless floating-point operations at run time.
  175708. * To get around this we use the following pre-calculated constants.
  175709. * If you change CONST_BITS you may want to add appropriate values.
  175710. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175711. */
  175712. #if CONST_BITS == 13
  175713. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175714. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175715. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175716. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175717. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175718. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175719. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175720. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175721. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175722. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175723. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175724. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175725. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175726. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175727. #else
  175728. #define FIX_0_211164243 FIX(0.211164243)
  175729. #define FIX_0_509795579 FIX(0.509795579)
  175730. #define FIX_0_601344887 FIX(0.601344887)
  175731. #define FIX_0_720959822 FIX(0.720959822)
  175732. #define FIX_0_765366865 FIX(0.765366865)
  175733. #define FIX_0_850430095 FIX(0.850430095)
  175734. #define FIX_0_899976223 FIX(0.899976223)
  175735. #define FIX_1_061594337 FIX(1.061594337)
  175736. #define FIX_1_272758580 FIX(1.272758580)
  175737. #define FIX_1_451774981 FIX(1.451774981)
  175738. #define FIX_1_847759065 FIX(1.847759065)
  175739. #define FIX_2_172734803 FIX(2.172734803)
  175740. #define FIX_2_562915447 FIX(2.562915447)
  175741. #define FIX_3_624509785 FIX(3.624509785)
  175742. #endif
  175743. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175744. * For 8-bit samples with the recommended scaling, all the variable
  175745. * and constant values involved are no more than 16 bits wide, so a
  175746. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175747. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175748. */
  175749. #if BITS_IN_JSAMPLE == 8
  175750. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175751. #else
  175752. #define MULTIPLY(var,const) ((var) * (const))
  175753. #endif
  175754. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175755. * entry; produce an int result. In this module, both inputs and result
  175756. * are 16 bits or less, so either int or short multiply will work.
  175757. */
  175758. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175759. /*
  175760. * Perform dequantization and inverse DCT on one block of coefficients,
  175761. * producing a reduced-size 4x4 output block.
  175762. */
  175763. GLOBAL(void)
  175764. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175765. JCOEFPTR coef_block,
  175766. JSAMPARRAY output_buf, JDIMENSION output_col)
  175767. {
  175768. INT32 tmp0, tmp2, tmp10, tmp12;
  175769. INT32 z1, z2, z3, z4;
  175770. JCOEFPTR inptr;
  175771. ISLOW_MULT_TYPE * quantptr;
  175772. int * wsptr;
  175773. JSAMPROW outptr;
  175774. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175775. int ctr;
  175776. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175777. SHIFT_TEMPS
  175778. /* Pass 1: process columns from input, store into work array. */
  175779. inptr = coef_block;
  175780. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175781. wsptr = workspace;
  175782. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175783. /* Don't bother to process column 4, because second pass won't use it */
  175784. if (ctr == DCTSIZE-4)
  175785. continue;
  175786. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175787. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175788. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175789. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175790. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175791. wsptr[DCTSIZE*0] = dcval;
  175792. wsptr[DCTSIZE*1] = dcval;
  175793. wsptr[DCTSIZE*2] = dcval;
  175794. wsptr[DCTSIZE*3] = dcval;
  175795. continue;
  175796. }
  175797. /* Even part */
  175798. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175799. tmp0 <<= (CONST_BITS+1);
  175800. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175801. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175802. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175803. tmp10 = tmp0 + tmp2;
  175804. tmp12 = tmp0 - tmp2;
  175805. /* Odd part */
  175806. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175807. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175808. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175809. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175810. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175811. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175812. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175813. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175814. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175815. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175816. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175817. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175818. /* Final output stage */
  175819. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175820. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175821. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175822. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175823. }
  175824. /* Pass 2: process 4 rows from work array, store into output array. */
  175825. wsptr = workspace;
  175826. for (ctr = 0; ctr < 4; ctr++) {
  175827. outptr = output_buf[ctr] + output_col;
  175828. /* It's not clear whether a zero row test is worthwhile here ... */
  175829. #ifndef NO_ZERO_ROW_TEST
  175830. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175831. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175832. /* AC terms all zero */
  175833. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175834. & RANGE_MASK];
  175835. outptr[0] = dcval;
  175836. outptr[1] = dcval;
  175837. outptr[2] = dcval;
  175838. outptr[3] = dcval;
  175839. wsptr += DCTSIZE; /* advance pointer to next row */
  175840. continue;
  175841. }
  175842. #endif
  175843. /* Even part */
  175844. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175845. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175846. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175847. tmp10 = tmp0 + tmp2;
  175848. tmp12 = tmp0 - tmp2;
  175849. /* Odd part */
  175850. z1 = (INT32) wsptr[7];
  175851. z2 = (INT32) wsptr[5];
  175852. z3 = (INT32) wsptr[3];
  175853. z4 = (INT32) wsptr[1];
  175854. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175855. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175856. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175857. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175858. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175859. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175860. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175861. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175862. /* Final output stage */
  175863. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175864. CONST_BITS+PASS1_BITS+3+1)
  175865. & RANGE_MASK];
  175866. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175867. CONST_BITS+PASS1_BITS+3+1)
  175868. & RANGE_MASK];
  175869. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175870. CONST_BITS+PASS1_BITS+3+1)
  175871. & RANGE_MASK];
  175872. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175873. CONST_BITS+PASS1_BITS+3+1)
  175874. & RANGE_MASK];
  175875. wsptr += DCTSIZE; /* advance pointer to next row */
  175876. }
  175877. }
  175878. /*
  175879. * Perform dequantization and inverse DCT on one block of coefficients,
  175880. * producing a reduced-size 2x2 output block.
  175881. */
  175882. GLOBAL(void)
  175883. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175884. JCOEFPTR coef_block,
  175885. JSAMPARRAY output_buf, JDIMENSION output_col)
  175886. {
  175887. INT32 tmp0, tmp10, z1;
  175888. JCOEFPTR inptr;
  175889. ISLOW_MULT_TYPE * quantptr;
  175890. int * wsptr;
  175891. JSAMPROW outptr;
  175892. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175893. int ctr;
  175894. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175895. SHIFT_TEMPS
  175896. /* Pass 1: process columns from input, store into work array. */
  175897. inptr = coef_block;
  175898. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175899. wsptr = workspace;
  175900. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175901. /* Don't bother to process columns 2,4,6 */
  175902. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175903. continue;
  175904. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175905. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175906. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175907. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175908. wsptr[DCTSIZE*0] = dcval;
  175909. wsptr[DCTSIZE*1] = dcval;
  175910. continue;
  175911. }
  175912. /* Even part */
  175913. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175914. tmp10 = z1 << (CONST_BITS+2);
  175915. /* Odd part */
  175916. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175917. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175918. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175919. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175920. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175921. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175922. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175923. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175924. /* Final output stage */
  175925. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175926. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175927. }
  175928. /* Pass 2: process 2 rows from work array, store into output array. */
  175929. wsptr = workspace;
  175930. for (ctr = 0; ctr < 2; ctr++) {
  175931. outptr = output_buf[ctr] + output_col;
  175932. /* It's not clear whether a zero row test is worthwhile here ... */
  175933. #ifndef NO_ZERO_ROW_TEST
  175934. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175935. /* AC terms all zero */
  175936. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175937. & RANGE_MASK];
  175938. outptr[0] = dcval;
  175939. outptr[1] = dcval;
  175940. wsptr += DCTSIZE; /* advance pointer to next row */
  175941. continue;
  175942. }
  175943. #endif
  175944. /* Even part */
  175945. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175946. /* Odd part */
  175947. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175948. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175949. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175950. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175951. /* Final output stage */
  175952. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175953. CONST_BITS+PASS1_BITS+3+2)
  175954. & RANGE_MASK];
  175955. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175956. CONST_BITS+PASS1_BITS+3+2)
  175957. & RANGE_MASK];
  175958. wsptr += DCTSIZE; /* advance pointer to next row */
  175959. }
  175960. }
  175961. /*
  175962. * Perform dequantization and inverse DCT on one block of coefficients,
  175963. * producing a reduced-size 1x1 output block.
  175964. */
  175965. GLOBAL(void)
  175966. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175967. JCOEFPTR coef_block,
  175968. JSAMPARRAY output_buf, JDIMENSION output_col)
  175969. {
  175970. int dcval;
  175971. ISLOW_MULT_TYPE * quantptr;
  175972. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175973. SHIFT_TEMPS
  175974. /* We hardly need an inverse DCT routine for this: just take the
  175975. * average pixel value, which is one-eighth of the DC coefficient.
  175976. */
  175977. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175978. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175979. dcval = (int) DESCALE((INT32) dcval, 3);
  175980. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175981. }
  175982. #endif /* IDCT_SCALING_SUPPORTED */
  175983. /*** End of inlined file: jidctred.c ***/
  175984. /*** Start of inlined file: jmemmgr.c ***/
  175985. #define JPEG_INTERNALS
  175986. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175987. /*** Start of inlined file: jmemsys.h ***/
  175988. #ifndef __jmemsys_h__
  175989. #define __jmemsys_h__
  175990. /* Short forms of external names for systems with brain-damaged linkers. */
  175991. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175992. #define jpeg_get_small jGetSmall
  175993. #define jpeg_free_small jFreeSmall
  175994. #define jpeg_get_large jGetLarge
  175995. #define jpeg_free_large jFreeLarge
  175996. #define jpeg_mem_available jMemAvail
  175997. #define jpeg_open_backing_store jOpenBackStore
  175998. #define jpeg_mem_init jMemInit
  175999. #define jpeg_mem_term jMemTerm
  176000. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  176001. /*
  176002. * These two functions are used to allocate and release small chunks of
  176003. * memory. (Typically the total amount requested through jpeg_get_small is
  176004. * no more than 20K or so; this will be requested in chunks of a few K each.)
  176005. * Behavior should be the same as for the standard library functions malloc
  176006. * and free; in particular, jpeg_get_small must return NULL on failure.
  176007. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  176008. * size of the object being freed, just in case it's needed.
  176009. * On an 80x86 machine using small-data memory model, these manage near heap.
  176010. */
  176011. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  176012. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  176013. size_t sizeofobject));
  176014. /*
  176015. * These two functions are used to allocate and release large chunks of
  176016. * memory (up to the total free space designated by jpeg_mem_available).
  176017. * The interface is the same as above, except that on an 80x86 machine,
  176018. * far pointers are used. On most other machines these are identical to
  176019. * the jpeg_get/free_small routines; but we keep them separate anyway,
  176020. * in case a different allocation strategy is desirable for large chunks.
  176021. */
  176022. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  176023. size_t sizeofobject));
  176024. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  176025. size_t sizeofobject));
  176026. /*
  176027. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  176028. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  176029. * matter, but that case should never come into play). This macro is needed
  176030. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  176031. * On those machines, we expect that jconfig.h will provide a proper value.
  176032. * On machines with 32-bit flat address spaces, any large constant may be used.
  176033. *
  176034. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  176035. * size_t and will be a multiple of sizeof(align_type).
  176036. */
  176037. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  176038. #define MAX_ALLOC_CHUNK 1000000000L
  176039. #endif
  176040. /*
  176041. * This routine computes the total space still available for allocation by
  176042. * jpeg_get_large. If more space than this is needed, backing store will be
  176043. * used. NOTE: any memory already allocated must not be counted.
  176044. *
  176045. * There is a minimum space requirement, corresponding to the minimum
  176046. * feasible buffer sizes; jmemmgr.c will request that much space even if
  176047. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  176048. * all working storage in memory, is also passed in case it is useful.
  176049. * Finally, the total space already allocated is passed. If no better
  176050. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  176051. * is often a suitable calculation.
  176052. *
  176053. * It is OK for jpeg_mem_available to underestimate the space available
  176054. * (that'll just lead to more backing-store access than is really necessary).
  176055. * However, an overestimate will lead to failure. Hence it's wise to subtract
  176056. * a slop factor from the true available space. 5% should be enough.
  176057. *
  176058. * On machines with lots of virtual memory, any large constant may be returned.
  176059. * Conversely, zero may be returned to always use the minimum amount of memory.
  176060. */
  176061. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  176062. long min_bytes_needed,
  176063. long max_bytes_needed,
  176064. long already_allocated));
  176065. /*
  176066. * This structure holds whatever state is needed to access a single
  176067. * backing-store object. The read/write/close method pointers are called
  176068. * by jmemmgr.c to manipulate the backing-store object; all other fields
  176069. * are private to the system-dependent backing store routines.
  176070. */
  176071. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  176072. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  176073. typedef unsigned short XMSH; /* type of extended-memory handles */
  176074. typedef unsigned short EMSH; /* type of expanded-memory handles */
  176075. typedef union {
  176076. short file_handle; /* DOS file handle if it's a temp file */
  176077. XMSH xms_handle; /* handle if it's a chunk of XMS */
  176078. EMSH ems_handle; /* handle if it's a chunk of EMS */
  176079. } handle_union;
  176080. #endif /* USE_MSDOS_MEMMGR */
  176081. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  176082. #include <Files.h>
  176083. #endif /* USE_MAC_MEMMGR */
  176084. //typedef struct backing_store_struct * backing_store_ptr;
  176085. typedef struct backing_store_struct {
  176086. /* Methods for reading/writing/closing this backing-store object */
  176087. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  176088. struct backing_store_struct *info,
  176089. void FAR * buffer_address,
  176090. long file_offset, long byte_count));
  176091. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  176092. struct backing_store_struct *info,
  176093. void FAR * buffer_address,
  176094. long file_offset, long byte_count));
  176095. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  176096. struct backing_store_struct *info));
  176097. /* Private fields for system-dependent backing-store management */
  176098. #ifdef USE_MSDOS_MEMMGR
  176099. /* For the MS-DOS manager (jmemdos.c), we need: */
  176100. handle_union handle; /* reference to backing-store storage object */
  176101. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176102. #else
  176103. #ifdef USE_MAC_MEMMGR
  176104. /* For the Mac manager (jmemmac.c), we need: */
  176105. short temp_file; /* file reference number to temp file */
  176106. FSSpec tempSpec; /* the FSSpec for the temp file */
  176107. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176108. #else
  176109. /* For a typical implementation with temp files, we need: */
  176110. FILE * temp_file; /* stdio reference to temp file */
  176111. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  176112. #endif
  176113. #endif
  176114. } backing_store_info;
  176115. /*
  176116. * Initial opening of a backing-store object. This must fill in the
  176117. * read/write/close pointers in the object. The read/write routines
  176118. * may take an error exit if the specified maximum file size is exceeded.
  176119. * (If jpeg_mem_available always returns a large value, this routine can
  176120. * just take an error exit.)
  176121. */
  176122. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176123. struct backing_store_struct *info,
  176124. long total_bytes_needed));
  176125. /*
  176126. * These routines take care of any system-dependent initialization and
  176127. * cleanup required. jpeg_mem_init will be called before anything is
  176128. * allocated (and, therefore, nothing in cinfo is of use except the error
  176129. * manager pointer). It should return a suitable default value for
  176130. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176131. * application. (Note that max_memory_to_use is only important if
  176132. * jpeg_mem_available chooses to consult it ... no one else will.)
  176133. * jpeg_mem_term may assume that all requested memory has been freed and that
  176134. * all opened backing-store objects have been closed.
  176135. */
  176136. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176137. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176138. #endif
  176139. /*** End of inlined file: jmemsys.h ***/
  176140. /* import the system-dependent declarations */
  176141. #ifndef NO_GETENV
  176142. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176143. extern char * getenv JPP((const char * name));
  176144. #endif
  176145. #endif
  176146. /*
  176147. * Some important notes:
  176148. * The allocation routines provided here must never return NULL.
  176149. * They should exit to error_exit if unsuccessful.
  176150. *
  176151. * It's not a good idea to try to merge the sarray and barray routines,
  176152. * even though they are textually almost the same, because samples are
  176153. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176154. * in machines where byte pointers have a different representation from
  176155. * word pointers, the resulting machine code could not be the same.
  176156. */
  176157. /*
  176158. * Many machines require storage alignment: longs must start on 4-byte
  176159. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176160. * always returns pointers that are multiples of the worst-case alignment
  176161. * requirement, and we had better do so too.
  176162. * There isn't any really portable way to determine the worst-case alignment
  176163. * requirement. This module assumes that the alignment requirement is
  176164. * multiples of sizeof(ALIGN_TYPE).
  176165. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176166. * workstations (where doubles really do need 8-byte alignment) and will work
  176167. * fine on nearly everything. If your machine has lesser alignment needs,
  176168. * you can save a few bytes by making ALIGN_TYPE smaller.
  176169. * The only place I know of where this will NOT work is certain Macintosh
  176170. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176171. * Doing 10-byte alignment is counterproductive because longwords won't be
  176172. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176173. * such a compiler.
  176174. */
  176175. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176176. #define ALIGN_TYPE double
  176177. #endif
  176178. /*
  176179. * We allocate objects from "pools", where each pool is gotten with a single
  176180. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176181. * overhead within a pool, except for alignment padding. Each pool has a
  176182. * header with a link to the next pool of the same class.
  176183. * Small and large pool headers are identical except that the latter's
  176184. * link pointer must be FAR on 80x86 machines.
  176185. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176186. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176187. * of the alignment requirement of ALIGN_TYPE.
  176188. */
  176189. typedef union small_pool_struct * small_pool_ptr;
  176190. typedef union small_pool_struct {
  176191. struct {
  176192. small_pool_ptr next; /* next in list of pools */
  176193. size_t bytes_used; /* how many bytes already used within pool */
  176194. size_t bytes_left; /* bytes still available in this pool */
  176195. } hdr;
  176196. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176197. } small_pool_hdr;
  176198. typedef union large_pool_struct FAR * large_pool_ptr;
  176199. typedef union large_pool_struct {
  176200. struct {
  176201. large_pool_ptr next; /* next in list of pools */
  176202. size_t bytes_used; /* how many bytes already used within pool */
  176203. size_t bytes_left; /* bytes still available in this pool */
  176204. } hdr;
  176205. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176206. } large_pool_hdr;
  176207. /*
  176208. * Here is the full definition of a memory manager object.
  176209. */
  176210. typedef struct {
  176211. struct jpeg_memory_mgr pub; /* public fields */
  176212. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176213. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176214. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176215. /* Since we only have one lifetime class of virtual arrays, only one
  176216. * linked list is necessary (for each datatype). Note that the virtual
  176217. * array control blocks being linked together are actually stored somewhere
  176218. * in the small-pool list.
  176219. */
  176220. jvirt_sarray_ptr virt_sarray_list;
  176221. jvirt_barray_ptr virt_barray_list;
  176222. /* This counts total space obtained from jpeg_get_small/large */
  176223. long total_space_allocated;
  176224. /* alloc_sarray and alloc_barray set this value for use by virtual
  176225. * array routines.
  176226. */
  176227. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176228. } my_memory_mgr;
  176229. typedef my_memory_mgr * my_mem_ptr;
  176230. /*
  176231. * The control blocks for virtual arrays.
  176232. * Note that these blocks are allocated in the "small" pool area.
  176233. * System-dependent info for the associated backing store (if any) is hidden
  176234. * inside the backing_store_info struct.
  176235. */
  176236. struct jvirt_sarray_control {
  176237. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176238. JDIMENSION rows_in_array; /* total virtual array height */
  176239. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176240. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176241. JDIMENSION rows_in_mem; /* height of memory buffer */
  176242. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176243. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176244. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176245. boolean pre_zero; /* pre-zero mode requested? */
  176246. boolean dirty; /* do current buffer contents need written? */
  176247. boolean b_s_open; /* is backing-store data valid? */
  176248. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176249. backing_store_info b_s_info; /* System-dependent control info */
  176250. };
  176251. struct jvirt_barray_control {
  176252. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176253. JDIMENSION rows_in_array; /* total virtual array height */
  176254. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176255. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176256. JDIMENSION rows_in_mem; /* height of memory buffer */
  176257. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176258. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176259. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176260. boolean pre_zero; /* pre-zero mode requested? */
  176261. boolean dirty; /* do current buffer contents need written? */
  176262. boolean b_s_open; /* is backing-store data valid? */
  176263. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176264. backing_store_info b_s_info; /* System-dependent control info */
  176265. };
  176266. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176267. LOCAL(void)
  176268. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176269. {
  176270. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176271. small_pool_ptr shdr_ptr;
  176272. large_pool_ptr lhdr_ptr;
  176273. /* Since this is only a debugging stub, we can cheat a little by using
  176274. * fprintf directly rather than going through the trace message code.
  176275. * This is helpful because message parm array can't handle longs.
  176276. */
  176277. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176278. pool_id, mem->total_space_allocated);
  176279. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176280. lhdr_ptr = lhdr_ptr->hdr.next) {
  176281. fprintf(stderr, " Large chunk used %ld\n",
  176282. (long) lhdr_ptr->hdr.bytes_used);
  176283. }
  176284. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176285. shdr_ptr = shdr_ptr->hdr.next) {
  176286. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176287. (long) shdr_ptr->hdr.bytes_used,
  176288. (long) shdr_ptr->hdr.bytes_left);
  176289. }
  176290. }
  176291. #endif /* MEM_STATS */
  176292. LOCAL(void)
  176293. out_of_memory (j_common_ptr cinfo, int which)
  176294. /* Report an out-of-memory error and stop execution */
  176295. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176296. {
  176297. #ifdef MEM_STATS
  176298. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176299. #endif
  176300. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176301. }
  176302. /*
  176303. * Allocation of "small" objects.
  176304. *
  176305. * For these, we use pooled storage. When a new pool must be created,
  176306. * we try to get enough space for the current request plus a "slop" factor,
  176307. * where the slop will be the amount of leftover space in the new pool.
  176308. * The speed vs. space tradeoff is largely determined by the slop values.
  176309. * A different slop value is provided for each pool class (lifetime),
  176310. * and we also distinguish the first pool of a class from later ones.
  176311. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176312. * machines, but may be too small if longs are 64 bits or more.
  176313. */
  176314. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176315. {
  176316. 1600, /* first PERMANENT pool */
  176317. 16000 /* first IMAGE pool */
  176318. };
  176319. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176320. {
  176321. 0, /* additional PERMANENT pools */
  176322. 5000 /* additional IMAGE pools */
  176323. };
  176324. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176325. METHODDEF(void *)
  176326. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176327. /* Allocate a "small" object */
  176328. {
  176329. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176330. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176331. char * data_ptr;
  176332. size_t odd_bytes, min_request, slop;
  176333. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176334. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176335. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176336. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176337. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176338. if (odd_bytes > 0)
  176339. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176340. /* See if space is available in any existing pool */
  176341. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176342. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176343. prev_hdr_ptr = NULL;
  176344. hdr_ptr = mem->small_list[pool_id];
  176345. while (hdr_ptr != NULL) {
  176346. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176347. break; /* found pool with enough space */
  176348. prev_hdr_ptr = hdr_ptr;
  176349. hdr_ptr = hdr_ptr->hdr.next;
  176350. }
  176351. /* Time to make a new pool? */
  176352. if (hdr_ptr == NULL) {
  176353. /* min_request is what we need now, slop is what will be leftover */
  176354. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176355. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176356. slop = first_pool_slop[pool_id];
  176357. else
  176358. slop = extra_pool_slop[pool_id];
  176359. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176360. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176361. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176362. /* Try to get space, if fail reduce slop and try again */
  176363. for (;;) {
  176364. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176365. if (hdr_ptr != NULL)
  176366. break;
  176367. slop /= 2;
  176368. if (slop < MIN_SLOP) /* give up when it gets real small */
  176369. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176370. }
  176371. mem->total_space_allocated += min_request + slop;
  176372. /* Success, initialize the new pool header and add to end of list */
  176373. hdr_ptr->hdr.next = NULL;
  176374. hdr_ptr->hdr.bytes_used = 0;
  176375. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176376. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176377. mem->small_list[pool_id] = hdr_ptr;
  176378. else
  176379. prev_hdr_ptr->hdr.next = hdr_ptr;
  176380. }
  176381. /* OK, allocate the object from the current pool */
  176382. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176383. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176384. hdr_ptr->hdr.bytes_used += sizeofobject;
  176385. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176386. return (void *) data_ptr;
  176387. }
  176388. /*
  176389. * Allocation of "large" objects.
  176390. *
  176391. * The external semantics of these are the same as "small" objects,
  176392. * except that FAR pointers are used on 80x86. However the pool
  176393. * management heuristics are quite different. We assume that each
  176394. * request is large enough that it may as well be passed directly to
  176395. * jpeg_get_large; the pool management just links everything together
  176396. * so that we can free it all on demand.
  176397. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176398. * structures. The routines that create these structures (see below)
  176399. * deliberately bunch rows together to ensure a large request size.
  176400. */
  176401. METHODDEF(void FAR *)
  176402. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176403. /* Allocate a "large" object */
  176404. {
  176405. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176406. large_pool_ptr hdr_ptr;
  176407. size_t odd_bytes;
  176408. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176409. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176410. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176411. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176412. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176413. if (odd_bytes > 0)
  176414. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176415. /* Always make a new pool */
  176416. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176417. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176418. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176419. SIZEOF(large_pool_hdr));
  176420. if (hdr_ptr == NULL)
  176421. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176422. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176423. /* Success, initialize the new pool header and add to list */
  176424. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176425. /* We maintain space counts in each pool header for statistical purposes,
  176426. * even though they are not needed for allocation.
  176427. */
  176428. hdr_ptr->hdr.bytes_used = sizeofobject;
  176429. hdr_ptr->hdr.bytes_left = 0;
  176430. mem->large_list[pool_id] = hdr_ptr;
  176431. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176432. }
  176433. /*
  176434. * Creation of 2-D sample arrays.
  176435. * The pointers are in near heap, the samples themselves in FAR heap.
  176436. *
  176437. * To minimize allocation overhead and to allow I/O of large contiguous
  176438. * blocks, we allocate the sample rows in groups of as many rows as possible
  176439. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176440. * NB: the virtual array control routines, later in this file, know about
  176441. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176442. * object so that it can be saved away if this sarray is the workspace for
  176443. * a virtual array.
  176444. */
  176445. METHODDEF(JSAMPARRAY)
  176446. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176447. JDIMENSION samplesperrow, JDIMENSION numrows)
  176448. /* Allocate a 2-D sample array */
  176449. {
  176450. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176451. JSAMPARRAY result;
  176452. JSAMPROW workspace;
  176453. JDIMENSION rowsperchunk, currow, i;
  176454. long ltemp;
  176455. /* Calculate max # of rows allowed in one allocation chunk */
  176456. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176457. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176458. if (ltemp <= 0)
  176459. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176460. if (ltemp < (long) numrows)
  176461. rowsperchunk = (JDIMENSION) ltemp;
  176462. else
  176463. rowsperchunk = numrows;
  176464. mem->last_rowsperchunk = rowsperchunk;
  176465. /* Get space for row pointers (small object) */
  176466. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176467. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176468. /* Get the rows themselves (large objects) */
  176469. currow = 0;
  176470. while (currow < numrows) {
  176471. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176472. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176473. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176474. * SIZEOF(JSAMPLE)));
  176475. for (i = rowsperchunk; i > 0; i--) {
  176476. result[currow++] = workspace;
  176477. workspace += samplesperrow;
  176478. }
  176479. }
  176480. return result;
  176481. }
  176482. /*
  176483. * Creation of 2-D coefficient-block arrays.
  176484. * This is essentially the same as the code for sample arrays, above.
  176485. */
  176486. METHODDEF(JBLOCKARRAY)
  176487. alloc_barray (j_common_ptr cinfo, int pool_id,
  176488. JDIMENSION blocksperrow, JDIMENSION numrows)
  176489. /* Allocate a 2-D coefficient-block array */
  176490. {
  176491. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176492. JBLOCKARRAY result;
  176493. JBLOCKROW workspace;
  176494. JDIMENSION rowsperchunk, currow, i;
  176495. long ltemp;
  176496. /* Calculate max # of rows allowed in one allocation chunk */
  176497. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176498. ((long) blocksperrow * SIZEOF(JBLOCK));
  176499. if (ltemp <= 0)
  176500. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176501. if (ltemp < (long) numrows)
  176502. rowsperchunk = (JDIMENSION) ltemp;
  176503. else
  176504. rowsperchunk = numrows;
  176505. mem->last_rowsperchunk = rowsperchunk;
  176506. /* Get space for row pointers (small object) */
  176507. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176508. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176509. /* Get the rows themselves (large objects) */
  176510. currow = 0;
  176511. while (currow < numrows) {
  176512. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176513. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176514. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176515. * SIZEOF(JBLOCK)));
  176516. for (i = rowsperchunk; i > 0; i--) {
  176517. result[currow++] = workspace;
  176518. workspace += blocksperrow;
  176519. }
  176520. }
  176521. return result;
  176522. }
  176523. /*
  176524. * About virtual array management:
  176525. *
  176526. * The above "normal" array routines are only used to allocate strip buffers
  176527. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176528. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176529. * time, but the memory manager must save the whole array for repeated
  176530. * accesses. The intended implementation is that there is a strip buffer in
  176531. * memory (as high as is possible given the desired memory limit), plus a
  176532. * backing file that holds the rest of the array.
  176533. *
  176534. * The request_virt_array routines are told the total size of the image and
  176535. * the maximum number of rows that will be accessed at once. The in-memory
  176536. * buffer must be at least as large as the maxaccess value.
  176537. *
  176538. * The request routines create control blocks but not the in-memory buffers.
  176539. * That is postponed until realize_virt_arrays is called. At that time the
  176540. * total amount of space needed is known (approximately, anyway), so free
  176541. * memory can be divided up fairly.
  176542. *
  176543. * The access_virt_array routines are responsible for making a specific strip
  176544. * area accessible (after reading or writing the backing file, if necessary).
  176545. * Note that the access routines are told whether the caller intends to modify
  176546. * the accessed strip; during a read-only pass this saves having to rewrite
  176547. * data to disk. The access routines are also responsible for pre-zeroing
  176548. * any newly accessed rows, if pre-zeroing was requested.
  176549. *
  176550. * In current usage, the access requests are usually for nonoverlapping
  176551. * strips; that is, successive access start_row numbers differ by exactly
  176552. * num_rows = maxaccess. This means we can get good performance with simple
  176553. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176554. * of the access height; then there will never be accesses across bufferload
  176555. * boundaries. The code will still work with overlapping access requests,
  176556. * but it doesn't handle bufferload overlaps very efficiently.
  176557. */
  176558. METHODDEF(jvirt_sarray_ptr)
  176559. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176560. JDIMENSION samplesperrow, JDIMENSION numrows,
  176561. JDIMENSION maxaccess)
  176562. /* Request a virtual 2-D sample array */
  176563. {
  176564. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176565. jvirt_sarray_ptr result;
  176566. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176567. if (pool_id != JPOOL_IMAGE)
  176568. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176569. /* get control block */
  176570. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176571. SIZEOF(struct jvirt_sarray_control));
  176572. result->mem_buffer = NULL; /* marks array not yet realized */
  176573. result->rows_in_array = numrows;
  176574. result->samplesperrow = samplesperrow;
  176575. result->maxaccess = maxaccess;
  176576. result->pre_zero = pre_zero;
  176577. result->b_s_open = FALSE; /* no associated backing-store object */
  176578. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176579. mem->virt_sarray_list = result;
  176580. return result;
  176581. }
  176582. METHODDEF(jvirt_barray_ptr)
  176583. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176584. JDIMENSION blocksperrow, JDIMENSION numrows,
  176585. JDIMENSION maxaccess)
  176586. /* Request a virtual 2-D coefficient-block array */
  176587. {
  176588. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176589. jvirt_barray_ptr result;
  176590. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176591. if (pool_id != JPOOL_IMAGE)
  176592. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176593. /* get control block */
  176594. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176595. SIZEOF(struct jvirt_barray_control));
  176596. result->mem_buffer = NULL; /* marks array not yet realized */
  176597. result->rows_in_array = numrows;
  176598. result->blocksperrow = blocksperrow;
  176599. result->maxaccess = maxaccess;
  176600. result->pre_zero = pre_zero;
  176601. result->b_s_open = FALSE; /* no associated backing-store object */
  176602. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176603. mem->virt_barray_list = result;
  176604. return result;
  176605. }
  176606. METHODDEF(void)
  176607. realize_virt_arrays (j_common_ptr cinfo)
  176608. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176609. {
  176610. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176611. long space_per_minheight, maximum_space, avail_mem;
  176612. long minheights, max_minheights;
  176613. jvirt_sarray_ptr sptr;
  176614. jvirt_barray_ptr bptr;
  176615. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176616. * and the maximum space needed (full image height in each buffer).
  176617. * These may be of use to the system-dependent jpeg_mem_available routine.
  176618. */
  176619. space_per_minheight = 0;
  176620. maximum_space = 0;
  176621. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176622. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176623. space_per_minheight += (long) sptr->maxaccess *
  176624. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176625. maximum_space += (long) sptr->rows_in_array *
  176626. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176627. }
  176628. }
  176629. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176630. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176631. space_per_minheight += (long) bptr->maxaccess *
  176632. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176633. maximum_space += (long) bptr->rows_in_array *
  176634. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176635. }
  176636. }
  176637. if (space_per_minheight <= 0)
  176638. return; /* no unrealized arrays, no work */
  176639. /* Determine amount of memory to actually use; this is system-dependent. */
  176640. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176641. mem->total_space_allocated);
  176642. /* If the maximum space needed is available, make all the buffers full
  176643. * height; otherwise parcel it out with the same number of minheights
  176644. * in each buffer.
  176645. */
  176646. if (avail_mem >= maximum_space)
  176647. max_minheights = 1000000000L;
  176648. else {
  176649. max_minheights = avail_mem / space_per_minheight;
  176650. /* If there doesn't seem to be enough space, try to get the minimum
  176651. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176652. */
  176653. if (max_minheights <= 0)
  176654. max_minheights = 1;
  176655. }
  176656. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176657. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176658. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176659. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176660. if (minheights <= max_minheights) {
  176661. /* This buffer fits in memory */
  176662. sptr->rows_in_mem = sptr->rows_in_array;
  176663. } else {
  176664. /* It doesn't fit in memory, create backing store. */
  176665. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176666. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176667. (long) sptr->rows_in_array *
  176668. (long) sptr->samplesperrow *
  176669. (long) SIZEOF(JSAMPLE));
  176670. sptr->b_s_open = TRUE;
  176671. }
  176672. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176673. sptr->samplesperrow, sptr->rows_in_mem);
  176674. sptr->rowsperchunk = mem->last_rowsperchunk;
  176675. sptr->cur_start_row = 0;
  176676. sptr->first_undef_row = 0;
  176677. sptr->dirty = FALSE;
  176678. }
  176679. }
  176680. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176681. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176682. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176683. if (minheights <= max_minheights) {
  176684. /* This buffer fits in memory */
  176685. bptr->rows_in_mem = bptr->rows_in_array;
  176686. } else {
  176687. /* It doesn't fit in memory, create backing store. */
  176688. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176689. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176690. (long) bptr->rows_in_array *
  176691. (long) bptr->blocksperrow *
  176692. (long) SIZEOF(JBLOCK));
  176693. bptr->b_s_open = TRUE;
  176694. }
  176695. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176696. bptr->blocksperrow, bptr->rows_in_mem);
  176697. bptr->rowsperchunk = mem->last_rowsperchunk;
  176698. bptr->cur_start_row = 0;
  176699. bptr->first_undef_row = 0;
  176700. bptr->dirty = FALSE;
  176701. }
  176702. }
  176703. }
  176704. LOCAL(void)
  176705. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176706. /* Do backing store read or write of a virtual sample array */
  176707. {
  176708. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176709. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176710. file_offset = ptr->cur_start_row * bytesperrow;
  176711. /* Loop to read or write each allocation chunk in mem_buffer */
  176712. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176713. /* One chunk, but check for short chunk at end of buffer */
  176714. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176715. /* Transfer no more than is currently defined */
  176716. thisrow = (long) ptr->cur_start_row + i;
  176717. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176718. /* Transfer no more than fits in file */
  176719. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176720. if (rows <= 0) /* this chunk might be past end of file! */
  176721. break;
  176722. byte_count = rows * bytesperrow;
  176723. if (writing)
  176724. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176725. (void FAR *) ptr->mem_buffer[i],
  176726. file_offset, byte_count);
  176727. else
  176728. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176729. (void FAR *) ptr->mem_buffer[i],
  176730. file_offset, byte_count);
  176731. file_offset += byte_count;
  176732. }
  176733. }
  176734. LOCAL(void)
  176735. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176736. /* Do backing store read or write of a virtual coefficient-block array */
  176737. {
  176738. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176739. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176740. file_offset = ptr->cur_start_row * bytesperrow;
  176741. /* Loop to read or write each allocation chunk in mem_buffer */
  176742. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176743. /* One chunk, but check for short chunk at end of buffer */
  176744. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176745. /* Transfer no more than is currently defined */
  176746. thisrow = (long) ptr->cur_start_row + i;
  176747. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176748. /* Transfer no more than fits in file */
  176749. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176750. if (rows <= 0) /* this chunk might be past end of file! */
  176751. break;
  176752. byte_count = rows * bytesperrow;
  176753. if (writing)
  176754. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176755. (void FAR *) ptr->mem_buffer[i],
  176756. file_offset, byte_count);
  176757. else
  176758. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176759. (void FAR *) ptr->mem_buffer[i],
  176760. file_offset, byte_count);
  176761. file_offset += byte_count;
  176762. }
  176763. }
  176764. METHODDEF(JSAMPARRAY)
  176765. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176766. JDIMENSION start_row, JDIMENSION num_rows,
  176767. boolean writable)
  176768. /* Access the part of a virtual sample array starting at start_row */
  176769. /* and extending for num_rows rows. writable is true if */
  176770. /* caller intends to modify the accessed area. */
  176771. {
  176772. JDIMENSION end_row = start_row + num_rows;
  176773. JDIMENSION undef_row;
  176774. /* debugging check */
  176775. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176776. ptr->mem_buffer == NULL)
  176777. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176778. /* Make the desired part of the virtual array accessible */
  176779. if (start_row < ptr->cur_start_row ||
  176780. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176781. if (! ptr->b_s_open)
  176782. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176783. /* Flush old buffer contents if necessary */
  176784. if (ptr->dirty) {
  176785. do_sarray_io(cinfo, ptr, TRUE);
  176786. ptr->dirty = FALSE;
  176787. }
  176788. /* Decide what part of virtual array to access.
  176789. * Algorithm: if target address > current window, assume forward scan,
  176790. * load starting at target address. If target address < current window,
  176791. * assume backward scan, load so that target area is top of window.
  176792. * Note that when switching from forward write to forward read, will have
  176793. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176794. */
  176795. if (start_row > ptr->cur_start_row) {
  176796. ptr->cur_start_row = start_row;
  176797. } else {
  176798. /* use long arithmetic here to avoid overflow & unsigned problems */
  176799. long ltemp;
  176800. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176801. if (ltemp < 0)
  176802. ltemp = 0; /* don't fall off front end of file */
  176803. ptr->cur_start_row = (JDIMENSION) ltemp;
  176804. }
  176805. /* Read in the selected part of the array.
  176806. * During the initial write pass, we will do no actual read
  176807. * because the selected part is all undefined.
  176808. */
  176809. do_sarray_io(cinfo, ptr, FALSE);
  176810. }
  176811. /* Ensure the accessed part of the array is defined; prezero if needed.
  176812. * To improve locality of access, we only prezero the part of the array
  176813. * that the caller is about to access, not the entire in-memory array.
  176814. */
  176815. if (ptr->first_undef_row < end_row) {
  176816. if (ptr->first_undef_row < start_row) {
  176817. if (writable) /* writer skipped over a section of array */
  176818. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176819. undef_row = start_row; /* but reader is allowed to read ahead */
  176820. } else {
  176821. undef_row = ptr->first_undef_row;
  176822. }
  176823. if (writable)
  176824. ptr->first_undef_row = end_row;
  176825. if (ptr->pre_zero) {
  176826. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176827. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176828. end_row -= ptr->cur_start_row;
  176829. while (undef_row < end_row) {
  176830. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176831. undef_row++;
  176832. }
  176833. } else {
  176834. if (! writable) /* reader looking at undefined data */
  176835. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176836. }
  176837. }
  176838. /* Flag the buffer dirty if caller will write in it */
  176839. if (writable)
  176840. ptr->dirty = TRUE;
  176841. /* Return address of proper part of the buffer */
  176842. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176843. }
  176844. METHODDEF(JBLOCKARRAY)
  176845. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176846. JDIMENSION start_row, JDIMENSION num_rows,
  176847. boolean writable)
  176848. /* Access the part of a virtual block array starting at start_row */
  176849. /* and extending for num_rows rows. writable is true if */
  176850. /* caller intends to modify the accessed area. */
  176851. {
  176852. JDIMENSION end_row = start_row + num_rows;
  176853. JDIMENSION undef_row;
  176854. /* debugging check */
  176855. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176856. ptr->mem_buffer == NULL)
  176857. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176858. /* Make the desired part of the virtual array accessible */
  176859. if (start_row < ptr->cur_start_row ||
  176860. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176861. if (! ptr->b_s_open)
  176862. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176863. /* Flush old buffer contents if necessary */
  176864. if (ptr->dirty) {
  176865. do_barray_io(cinfo, ptr, TRUE);
  176866. ptr->dirty = FALSE;
  176867. }
  176868. /* Decide what part of virtual array to access.
  176869. * Algorithm: if target address > current window, assume forward scan,
  176870. * load starting at target address. If target address < current window,
  176871. * assume backward scan, load so that target area is top of window.
  176872. * Note that when switching from forward write to forward read, will have
  176873. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176874. */
  176875. if (start_row > ptr->cur_start_row) {
  176876. ptr->cur_start_row = start_row;
  176877. } else {
  176878. /* use long arithmetic here to avoid overflow & unsigned problems */
  176879. long ltemp;
  176880. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176881. if (ltemp < 0)
  176882. ltemp = 0; /* don't fall off front end of file */
  176883. ptr->cur_start_row = (JDIMENSION) ltemp;
  176884. }
  176885. /* Read in the selected part of the array.
  176886. * During the initial write pass, we will do no actual read
  176887. * because the selected part is all undefined.
  176888. */
  176889. do_barray_io(cinfo, ptr, FALSE);
  176890. }
  176891. /* Ensure the accessed part of the array is defined; prezero if needed.
  176892. * To improve locality of access, we only prezero the part of the array
  176893. * that the caller is about to access, not the entire in-memory array.
  176894. */
  176895. if (ptr->first_undef_row < end_row) {
  176896. if (ptr->first_undef_row < start_row) {
  176897. if (writable) /* writer skipped over a section of array */
  176898. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176899. undef_row = start_row; /* but reader is allowed to read ahead */
  176900. } else {
  176901. undef_row = ptr->first_undef_row;
  176902. }
  176903. if (writable)
  176904. ptr->first_undef_row = end_row;
  176905. if (ptr->pre_zero) {
  176906. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176907. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176908. end_row -= ptr->cur_start_row;
  176909. while (undef_row < end_row) {
  176910. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176911. undef_row++;
  176912. }
  176913. } else {
  176914. if (! writable) /* reader looking at undefined data */
  176915. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176916. }
  176917. }
  176918. /* Flag the buffer dirty if caller will write in it */
  176919. if (writable)
  176920. ptr->dirty = TRUE;
  176921. /* Return address of proper part of the buffer */
  176922. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176923. }
  176924. /*
  176925. * Release all objects belonging to a specified pool.
  176926. */
  176927. METHODDEF(void)
  176928. free_pool (j_common_ptr cinfo, int pool_id)
  176929. {
  176930. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176931. small_pool_ptr shdr_ptr;
  176932. large_pool_ptr lhdr_ptr;
  176933. size_t space_freed;
  176934. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176935. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176936. #ifdef MEM_STATS
  176937. if (cinfo->err->trace_level > 1)
  176938. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176939. #endif
  176940. /* If freeing IMAGE pool, close any virtual arrays first */
  176941. if (pool_id == JPOOL_IMAGE) {
  176942. jvirt_sarray_ptr sptr;
  176943. jvirt_barray_ptr bptr;
  176944. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176945. if (sptr->b_s_open) { /* there may be no backing store */
  176946. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176947. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176948. }
  176949. }
  176950. mem->virt_sarray_list = NULL;
  176951. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176952. if (bptr->b_s_open) { /* there may be no backing store */
  176953. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176954. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176955. }
  176956. }
  176957. mem->virt_barray_list = NULL;
  176958. }
  176959. /* Release large objects */
  176960. lhdr_ptr = mem->large_list[pool_id];
  176961. mem->large_list[pool_id] = NULL;
  176962. while (lhdr_ptr != NULL) {
  176963. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176964. space_freed = lhdr_ptr->hdr.bytes_used +
  176965. lhdr_ptr->hdr.bytes_left +
  176966. SIZEOF(large_pool_hdr);
  176967. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176968. mem->total_space_allocated -= space_freed;
  176969. lhdr_ptr = next_lhdr_ptr;
  176970. }
  176971. /* Release small objects */
  176972. shdr_ptr = mem->small_list[pool_id];
  176973. mem->small_list[pool_id] = NULL;
  176974. while (shdr_ptr != NULL) {
  176975. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176976. space_freed = shdr_ptr->hdr.bytes_used +
  176977. shdr_ptr->hdr.bytes_left +
  176978. SIZEOF(small_pool_hdr);
  176979. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176980. mem->total_space_allocated -= space_freed;
  176981. shdr_ptr = next_shdr_ptr;
  176982. }
  176983. }
  176984. /*
  176985. * Close up shop entirely.
  176986. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176987. */
  176988. METHODDEF(void)
  176989. self_destruct (j_common_ptr cinfo)
  176990. {
  176991. int pool;
  176992. /* Close all backing store, release all memory.
  176993. * Releasing pools in reverse order might help avoid fragmentation
  176994. * with some (brain-damaged) malloc libraries.
  176995. */
  176996. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176997. free_pool(cinfo, pool);
  176998. }
  176999. /* Release the memory manager control block too. */
  177000. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  177001. cinfo->mem = NULL; /* ensures I will be called only once */
  177002. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177003. }
  177004. /*
  177005. * Memory manager initialization.
  177006. * When this is called, only the error manager pointer is valid in cinfo!
  177007. */
  177008. GLOBAL(void)
  177009. jinit_memory_mgr (j_common_ptr cinfo)
  177010. {
  177011. my_mem_ptr mem;
  177012. long max_to_use;
  177013. int pool;
  177014. size_t test_mac;
  177015. cinfo->mem = NULL; /* for safety if init fails */
  177016. /* Check for configuration errors.
  177017. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  177018. * doesn't reflect any real hardware alignment requirement.
  177019. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  177020. * in common if and only if X is a power of 2, ie has only one one-bit.
  177021. * Some compilers may give an "unreachable code" warning here; ignore it.
  177022. */
  177023. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  177024. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  177025. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  177026. * a multiple of SIZEOF(ALIGN_TYPE).
  177027. * Again, an "unreachable code" warning may be ignored here.
  177028. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  177029. */
  177030. test_mac = (size_t) MAX_ALLOC_CHUNK;
  177031. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  177032. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  177033. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  177034. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  177035. /* Attempt to allocate memory manager's control block */
  177036. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  177037. if (mem == NULL) {
  177038. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177039. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  177040. }
  177041. /* OK, fill in the method pointers */
  177042. mem->pub.alloc_small = alloc_small;
  177043. mem->pub.alloc_large = alloc_large;
  177044. mem->pub.alloc_sarray = alloc_sarray;
  177045. mem->pub.alloc_barray = alloc_barray;
  177046. mem->pub.request_virt_sarray = request_virt_sarray;
  177047. mem->pub.request_virt_barray = request_virt_barray;
  177048. mem->pub.realize_virt_arrays = realize_virt_arrays;
  177049. mem->pub.access_virt_sarray = access_virt_sarray;
  177050. mem->pub.access_virt_barray = access_virt_barray;
  177051. mem->pub.free_pool = free_pool;
  177052. mem->pub.self_destruct = self_destruct;
  177053. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  177054. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  177055. /* Initialize working state */
  177056. mem->pub.max_memory_to_use = max_to_use;
  177057. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177058. mem->small_list[pool] = NULL;
  177059. mem->large_list[pool] = NULL;
  177060. }
  177061. mem->virt_sarray_list = NULL;
  177062. mem->virt_barray_list = NULL;
  177063. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  177064. /* Declare ourselves open for business */
  177065. cinfo->mem = & mem->pub;
  177066. /* Check for an environment variable JPEGMEM; if found, override the
  177067. * default max_memory setting from jpeg_mem_init. Note that the
  177068. * surrounding application may again override this value.
  177069. * If your system doesn't support getenv(), define NO_GETENV to disable
  177070. * this feature.
  177071. */
  177072. #ifndef NO_GETENV
  177073. { char * memenv;
  177074. if ((memenv = getenv("JPEGMEM")) != NULL) {
  177075. char ch = 'x';
  177076. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  177077. if (ch == 'm' || ch == 'M')
  177078. max_to_use *= 1000L;
  177079. mem->pub.max_memory_to_use = max_to_use * 1000L;
  177080. }
  177081. }
  177082. }
  177083. #endif
  177084. }
  177085. /*** End of inlined file: jmemmgr.c ***/
  177086. /*** Start of inlined file: jmemnobs.c ***/
  177087. #define JPEG_INTERNALS
  177088. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  177089. extern void * malloc JPP((size_t size));
  177090. extern void free JPP((void *ptr));
  177091. #endif
  177092. /*
  177093. * Memory allocation and freeing are controlled by the regular library
  177094. * routines malloc() and free().
  177095. */
  177096. GLOBAL(void *)
  177097. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  177098. {
  177099. return (void *) malloc(sizeofobject);
  177100. }
  177101. GLOBAL(void)
  177102. jpeg_free_small (j_common_ptr , void * object, size_t)
  177103. {
  177104. free(object);
  177105. }
  177106. /*
  177107. * "Large" objects are treated the same as "small" ones.
  177108. * NB: although we include FAR keywords in the routine declarations,
  177109. * this file won't actually work in 80x86 small/medium model; at least,
  177110. * you probably won't be able to process useful-size images in only 64KB.
  177111. */
  177112. GLOBAL(void FAR *)
  177113. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  177114. {
  177115. return (void FAR *) malloc(sizeofobject);
  177116. }
  177117. GLOBAL(void)
  177118. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  177119. {
  177120. free(object);
  177121. }
  177122. /*
  177123. * This routine computes the total memory space available for allocation.
  177124. * Here we always say, "we got all you want bud!"
  177125. */
  177126. GLOBAL(long)
  177127. jpeg_mem_available (j_common_ptr, long,
  177128. long max_bytes_needed, long)
  177129. {
  177130. return max_bytes_needed;
  177131. }
  177132. /*
  177133. * Backing store (temporary file) management.
  177134. * Since jpeg_mem_available always promised the moon,
  177135. * this should never be called and we can just error out.
  177136. */
  177137. GLOBAL(void)
  177138. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  177139. long )
  177140. {
  177141. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177142. }
  177143. /*
  177144. * These routines take care of any system-dependent initialization and
  177145. * cleanup required. Here, there isn't any.
  177146. */
  177147. GLOBAL(long)
  177148. jpeg_mem_init (j_common_ptr)
  177149. {
  177150. return 0; /* just set max_memory_to_use to 0 */
  177151. }
  177152. GLOBAL(void)
  177153. jpeg_mem_term (j_common_ptr)
  177154. {
  177155. /* no work */
  177156. }
  177157. /*** End of inlined file: jmemnobs.c ***/
  177158. /*** Start of inlined file: jquant1.c ***/
  177159. #define JPEG_INTERNALS
  177160. #ifdef QUANT_1PASS_SUPPORTED
  177161. /*
  177162. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177163. * high quality, colormapped output capability. A 2-pass quantizer usually
  177164. * gives better visual quality; however, for quantized grayscale output this
  177165. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177166. * quantizer, though you can turn it off if you really want to.
  177167. *
  177168. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177169. * image. We use a map consisting of all combinations of Ncolors[i] color
  177170. * values for the i'th component. The Ncolors[] values are chosen so that
  177171. * their product, the total number of colors, is no more than that requested.
  177172. * (In most cases, the product will be somewhat less.)
  177173. *
  177174. * Since the colormap is orthogonal, the representative value for each color
  177175. * component can be determined without considering the other components;
  177176. * then these indexes can be combined into a colormap index by a standard
  177177. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177178. * can be precalculated and stored in the lookup table colorindex[].
  177179. * colorindex[i][j] maps pixel value j in component i to the nearest
  177180. * representative value (grid plane) for that component; this index is
  177181. * multiplied by the array stride for component i, so that the
  177182. * index of the colormap entry closest to a given pixel value is just
  177183. * sum( colorindex[component-number][pixel-component-value] )
  177184. * Aside from being fast, this scheme allows for variable spacing between
  177185. * representative values with no additional lookup cost.
  177186. *
  177187. * If gamma correction has been applied in color conversion, it might be wise
  177188. * to adjust the color grid spacing so that the representative colors are
  177189. * equidistant in linear space. At this writing, gamma correction is not
  177190. * implemented by jdcolor, so nothing is done here.
  177191. */
  177192. /* Declarations for ordered dithering.
  177193. *
  177194. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177195. * dithering is described in many references, for instance Dale Schumacher's
  177196. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177197. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177198. * "dither" value to the input pixel and then round the result to the nearest
  177199. * output value. The dither value is equivalent to (0.5 - threshold) times
  177200. * the distance between output values. For ordered dithering, we assume that
  177201. * the output colors are equally spaced; if not, results will probably be
  177202. * worse, since the dither may be too much or too little at a given point.
  177203. *
  177204. * The normal calculation would be to form pixel value + dither, range-limit
  177205. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177206. * We can skip the separate range-limiting step by extending the colorindex
  177207. * table in both directions.
  177208. */
  177209. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177210. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177211. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177212. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177213. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177214. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177215. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177216. /* Bayer's order-4 dither array. Generated by the code given in
  177217. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177218. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177219. */
  177220. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177221. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177222. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177223. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177224. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177225. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177226. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177227. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177228. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177229. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177230. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177231. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177232. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177233. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177234. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177235. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177236. };
  177237. /* Declarations for Floyd-Steinberg dithering.
  177238. *
  177239. * Errors are accumulated into the array fserrors[], at a resolution of
  177240. * 1/16th of a pixel count. The error at a given pixel is propagated
  177241. * to its not-yet-processed neighbors using the standard F-S fractions,
  177242. * ... (here) 7/16
  177243. * 3/16 5/16 1/16
  177244. * We work left-to-right on even rows, right-to-left on odd rows.
  177245. *
  177246. * We can get away with a single array (holding one row's worth of errors)
  177247. * by using it to store the current row's errors at pixel columns not yet
  177248. * processed, but the next row's errors at columns already processed. We
  177249. * need only a few extra variables to hold the errors immediately around the
  177250. * current column. (If we are lucky, those variables are in registers, but
  177251. * even if not, they're probably cheaper to access than array elements are.)
  177252. *
  177253. * The fserrors[] array is indexed [component#][position].
  177254. * We provide (#columns + 2) entries per component; the extra entry at each
  177255. * end saves us from special-casing the first and last pixels.
  177256. *
  177257. * Note: on a wide image, we might not have enough room in a PC's near data
  177258. * segment to hold the error array; so it is allocated with alloc_large.
  177259. */
  177260. #if BITS_IN_JSAMPLE == 8
  177261. typedef INT16 FSERROR; /* 16 bits should be enough */
  177262. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177263. #else
  177264. typedef INT32 FSERROR; /* may need more than 16 bits */
  177265. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177266. #endif
  177267. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177268. /* Private subobject */
  177269. #define MAX_Q_COMPS 4 /* max components I can handle */
  177270. typedef struct {
  177271. struct jpeg_color_quantizer pub; /* public fields */
  177272. /* Initially allocated colormap is saved here */
  177273. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177274. int sv_actual; /* number of entries in use */
  177275. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177276. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177277. * premultiplied as described above. Since colormap indexes must fit into
  177278. * JSAMPLEs, the entries of this array will too.
  177279. */
  177280. boolean is_padded; /* is the colorindex padded for odither? */
  177281. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177282. /* Variables for ordered dithering */
  177283. int row_index; /* cur row's vertical index in dither matrix */
  177284. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177285. /* Variables for Floyd-Steinberg dithering */
  177286. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177287. boolean on_odd_row; /* flag to remember which row we are on */
  177288. } my_cquantizer;
  177289. typedef my_cquantizer * my_cquantize_ptr;
  177290. /*
  177291. * Policy-making subroutines for create_colormap and create_colorindex.
  177292. * These routines determine the colormap to be used. The rest of the module
  177293. * only assumes that the colormap is orthogonal.
  177294. *
  177295. * * select_ncolors decides how to divvy up the available colors
  177296. * among the components.
  177297. * * output_value defines the set of representative values for a component.
  177298. * * largest_input_value defines the mapping from input values to
  177299. * representative values for a component.
  177300. * Note that the latter two routines may impose different policies for
  177301. * different components, though this is not currently done.
  177302. */
  177303. LOCAL(int)
  177304. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177305. /* Determine allocation of desired colors to components, */
  177306. /* and fill in Ncolors[] array to indicate choice. */
  177307. /* Return value is total number of colors (product of Ncolors[] values). */
  177308. {
  177309. int nc = cinfo->out_color_components; /* number of color components */
  177310. int max_colors = cinfo->desired_number_of_colors;
  177311. int total_colors, iroot, i, j;
  177312. boolean changed;
  177313. long temp;
  177314. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177315. /* We can allocate at least the nc'th root of max_colors per component. */
  177316. /* Compute floor(nc'th root of max_colors). */
  177317. iroot = 1;
  177318. do {
  177319. iroot++;
  177320. temp = iroot; /* set temp = iroot ** nc */
  177321. for (i = 1; i < nc; i++)
  177322. temp *= iroot;
  177323. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177324. iroot--; /* now iroot = floor(root) */
  177325. /* Must have at least 2 color values per component */
  177326. if (iroot < 2)
  177327. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177328. /* Initialize to iroot color values for each component */
  177329. total_colors = 1;
  177330. for (i = 0; i < nc; i++) {
  177331. Ncolors[i] = iroot;
  177332. total_colors *= iroot;
  177333. }
  177334. /* We may be able to increment the count for one or more components without
  177335. * exceeding max_colors, though we know not all can be incremented.
  177336. * Sometimes, the first component can be incremented more than once!
  177337. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177338. * In RGB colorspace, try to increment G first, then R, then B.
  177339. */
  177340. do {
  177341. changed = FALSE;
  177342. for (i = 0; i < nc; i++) {
  177343. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177344. /* calculate new total_colors if Ncolors[j] is incremented */
  177345. temp = total_colors / Ncolors[j];
  177346. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177347. if (temp > (long) max_colors)
  177348. break; /* won't fit, done with this pass */
  177349. Ncolors[j]++; /* OK, apply the increment */
  177350. total_colors = (int) temp;
  177351. changed = TRUE;
  177352. }
  177353. } while (changed);
  177354. return total_colors;
  177355. }
  177356. LOCAL(int)
  177357. output_value (j_decompress_ptr, int, int j, int maxj)
  177358. /* Return j'th output value, where j will range from 0 to maxj */
  177359. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177360. {
  177361. /* We always provide values 0 and MAXJSAMPLE for each component;
  177362. * any additional values are equally spaced between these limits.
  177363. * (Forcing the upper and lower values to the limits ensures that
  177364. * dithering can't produce a color outside the selected gamut.)
  177365. */
  177366. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177367. }
  177368. LOCAL(int)
  177369. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177370. /* Return largest input value that should map to j'th output value */
  177371. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177372. {
  177373. /* Breakpoints are halfway between values returned by output_value */
  177374. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177375. }
  177376. /*
  177377. * Create the colormap.
  177378. */
  177379. LOCAL(void)
  177380. create_colormap (j_decompress_ptr cinfo)
  177381. {
  177382. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177383. JSAMPARRAY colormap; /* Created colormap */
  177384. int total_colors; /* Number of distinct output colors */
  177385. int i,j,k, nci, blksize, blkdist, ptr, val;
  177386. /* Select number of colors for each component */
  177387. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177388. /* Report selected color counts */
  177389. if (cinfo->out_color_components == 3)
  177390. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177391. total_colors, cquantize->Ncolors[0],
  177392. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177393. else
  177394. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177395. /* Allocate and fill in the colormap. */
  177396. /* The colors are ordered in the map in standard row-major order, */
  177397. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177398. colormap = (*cinfo->mem->alloc_sarray)
  177399. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177400. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177401. /* blksize is number of adjacent repeated entries for a component */
  177402. /* blkdist is distance between groups of identical entries for a component */
  177403. blkdist = total_colors;
  177404. for (i = 0; i < cinfo->out_color_components; i++) {
  177405. /* fill in colormap entries for i'th color component */
  177406. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177407. blksize = blkdist / nci;
  177408. for (j = 0; j < nci; j++) {
  177409. /* Compute j'th output value (out of nci) for component */
  177410. val = output_value(cinfo, i, j, nci-1);
  177411. /* Fill in all colormap entries that have this value of this component */
  177412. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177413. /* fill in blksize entries beginning at ptr */
  177414. for (k = 0; k < blksize; k++)
  177415. colormap[i][ptr+k] = (JSAMPLE) val;
  177416. }
  177417. }
  177418. blkdist = blksize; /* blksize of this color is blkdist of next */
  177419. }
  177420. /* Save the colormap in private storage,
  177421. * where it will survive color quantization mode changes.
  177422. */
  177423. cquantize->sv_colormap = colormap;
  177424. cquantize->sv_actual = total_colors;
  177425. }
  177426. /*
  177427. * Create the color index table.
  177428. */
  177429. LOCAL(void)
  177430. create_colorindex (j_decompress_ptr cinfo)
  177431. {
  177432. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177433. JSAMPROW indexptr;
  177434. int i,j,k, nci, blksize, val, pad;
  177435. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177436. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177437. * This is not necessary in the other dithering modes. However, we
  177438. * flag whether it was done in case user changes dithering mode.
  177439. */
  177440. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177441. pad = MAXJSAMPLE*2;
  177442. cquantize->is_padded = TRUE;
  177443. } else {
  177444. pad = 0;
  177445. cquantize->is_padded = FALSE;
  177446. }
  177447. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177448. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177449. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177450. (JDIMENSION) cinfo->out_color_components);
  177451. /* blksize is number of adjacent repeated entries for a component */
  177452. blksize = cquantize->sv_actual;
  177453. for (i = 0; i < cinfo->out_color_components; i++) {
  177454. /* fill in colorindex entries for i'th color component */
  177455. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177456. blksize = blksize / nci;
  177457. /* adjust colorindex pointers to provide padding at negative indexes. */
  177458. if (pad)
  177459. cquantize->colorindex[i] += MAXJSAMPLE;
  177460. /* in loop, val = index of current output value, */
  177461. /* and k = largest j that maps to current val */
  177462. indexptr = cquantize->colorindex[i];
  177463. val = 0;
  177464. k = largest_input_value(cinfo, i, 0, nci-1);
  177465. for (j = 0; j <= MAXJSAMPLE; j++) {
  177466. while (j > k) /* advance val if past boundary */
  177467. k = largest_input_value(cinfo, i, ++val, nci-1);
  177468. /* premultiply so that no multiplication needed in main processing */
  177469. indexptr[j] = (JSAMPLE) (val * blksize);
  177470. }
  177471. /* Pad at both ends if necessary */
  177472. if (pad)
  177473. for (j = 1; j <= MAXJSAMPLE; j++) {
  177474. indexptr[-j] = indexptr[0];
  177475. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177476. }
  177477. }
  177478. }
  177479. /*
  177480. * Create an ordered-dither array for a component having ncolors
  177481. * distinct output values.
  177482. */
  177483. LOCAL(ODITHER_MATRIX_PTR)
  177484. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177485. {
  177486. ODITHER_MATRIX_PTR odither;
  177487. int j,k;
  177488. INT32 num,den;
  177489. odither = (ODITHER_MATRIX_PTR)
  177490. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177491. SIZEOF(ODITHER_MATRIX));
  177492. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177493. * Hence the dither value for the matrix cell with fill order f
  177494. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177495. * On 16-bit-int machine, be careful to avoid overflow.
  177496. */
  177497. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177498. for (j = 0; j < ODITHER_SIZE; j++) {
  177499. for (k = 0; k < ODITHER_SIZE; k++) {
  177500. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177501. * MAXJSAMPLE;
  177502. /* Ensure round towards zero despite C's lack of consistency
  177503. * about rounding negative values in integer division...
  177504. */
  177505. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177506. }
  177507. }
  177508. return odither;
  177509. }
  177510. /*
  177511. * Create the ordered-dither tables.
  177512. * Components having the same number of representative colors may
  177513. * share a dither table.
  177514. */
  177515. LOCAL(void)
  177516. create_odither_tables (j_decompress_ptr cinfo)
  177517. {
  177518. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177519. ODITHER_MATRIX_PTR odither;
  177520. int i, j, nci;
  177521. for (i = 0; i < cinfo->out_color_components; i++) {
  177522. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177523. odither = NULL; /* search for matching prior component */
  177524. for (j = 0; j < i; j++) {
  177525. if (nci == cquantize->Ncolors[j]) {
  177526. odither = cquantize->odither[j];
  177527. break;
  177528. }
  177529. }
  177530. if (odither == NULL) /* need a new table? */
  177531. odither = make_odither_array(cinfo, nci);
  177532. cquantize->odither[i] = odither;
  177533. }
  177534. }
  177535. /*
  177536. * Map some rows of pixels to the output colormapped representation.
  177537. */
  177538. METHODDEF(void)
  177539. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177540. JSAMPARRAY output_buf, int num_rows)
  177541. /* General case, no dithering */
  177542. {
  177543. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177544. JSAMPARRAY colorindex = cquantize->colorindex;
  177545. register int pixcode, ci;
  177546. register JSAMPROW ptrin, ptrout;
  177547. int row;
  177548. JDIMENSION col;
  177549. JDIMENSION width = cinfo->output_width;
  177550. register int nc = cinfo->out_color_components;
  177551. for (row = 0; row < num_rows; row++) {
  177552. ptrin = input_buf[row];
  177553. ptrout = output_buf[row];
  177554. for (col = width; col > 0; col--) {
  177555. pixcode = 0;
  177556. for (ci = 0; ci < nc; ci++) {
  177557. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177558. }
  177559. *ptrout++ = (JSAMPLE) pixcode;
  177560. }
  177561. }
  177562. }
  177563. METHODDEF(void)
  177564. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177565. JSAMPARRAY output_buf, int num_rows)
  177566. /* Fast path for out_color_components==3, no dithering */
  177567. {
  177568. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177569. register int pixcode;
  177570. register JSAMPROW ptrin, ptrout;
  177571. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177572. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177573. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177574. int row;
  177575. JDIMENSION col;
  177576. JDIMENSION width = cinfo->output_width;
  177577. for (row = 0; row < num_rows; row++) {
  177578. ptrin = input_buf[row];
  177579. ptrout = output_buf[row];
  177580. for (col = width; col > 0; col--) {
  177581. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177582. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177583. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177584. *ptrout++ = (JSAMPLE) pixcode;
  177585. }
  177586. }
  177587. }
  177588. METHODDEF(void)
  177589. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177590. JSAMPARRAY output_buf, int num_rows)
  177591. /* General case, with ordered dithering */
  177592. {
  177593. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177594. register JSAMPROW input_ptr;
  177595. register JSAMPROW output_ptr;
  177596. JSAMPROW colorindex_ci;
  177597. int * dither; /* points to active row of dither matrix */
  177598. int row_index, col_index; /* current indexes into dither matrix */
  177599. int nc = cinfo->out_color_components;
  177600. int ci;
  177601. int row;
  177602. JDIMENSION col;
  177603. JDIMENSION width = cinfo->output_width;
  177604. for (row = 0; row < num_rows; row++) {
  177605. /* Initialize output values to 0 so can process components separately */
  177606. jzero_far((void FAR *) output_buf[row],
  177607. (size_t) (width * SIZEOF(JSAMPLE)));
  177608. row_index = cquantize->row_index;
  177609. for (ci = 0; ci < nc; ci++) {
  177610. input_ptr = input_buf[row] + ci;
  177611. output_ptr = output_buf[row];
  177612. colorindex_ci = cquantize->colorindex[ci];
  177613. dither = cquantize->odither[ci][row_index];
  177614. col_index = 0;
  177615. for (col = width; col > 0; col--) {
  177616. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177617. * select output value, accumulate into output code for this pixel.
  177618. * Range-limiting need not be done explicitly, as we have extended
  177619. * the colorindex table to produce the right answers for out-of-range
  177620. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177621. * required amount of padding.
  177622. */
  177623. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177624. input_ptr += nc;
  177625. output_ptr++;
  177626. col_index = (col_index + 1) & ODITHER_MASK;
  177627. }
  177628. }
  177629. /* Advance row index for next row */
  177630. row_index = (row_index + 1) & ODITHER_MASK;
  177631. cquantize->row_index = row_index;
  177632. }
  177633. }
  177634. METHODDEF(void)
  177635. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177636. JSAMPARRAY output_buf, int num_rows)
  177637. /* Fast path for out_color_components==3, with ordered dithering */
  177638. {
  177639. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177640. register int pixcode;
  177641. register JSAMPROW input_ptr;
  177642. register JSAMPROW output_ptr;
  177643. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177644. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177645. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177646. int * dither0; /* points to active row of dither matrix */
  177647. int * dither1;
  177648. int * dither2;
  177649. int row_index, col_index; /* current indexes into dither matrix */
  177650. int row;
  177651. JDIMENSION col;
  177652. JDIMENSION width = cinfo->output_width;
  177653. for (row = 0; row < num_rows; row++) {
  177654. row_index = cquantize->row_index;
  177655. input_ptr = input_buf[row];
  177656. output_ptr = output_buf[row];
  177657. dither0 = cquantize->odither[0][row_index];
  177658. dither1 = cquantize->odither[1][row_index];
  177659. dither2 = cquantize->odither[2][row_index];
  177660. col_index = 0;
  177661. for (col = width; col > 0; col--) {
  177662. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177663. dither0[col_index]]);
  177664. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177665. dither1[col_index]]);
  177666. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177667. dither2[col_index]]);
  177668. *output_ptr++ = (JSAMPLE) pixcode;
  177669. col_index = (col_index + 1) & ODITHER_MASK;
  177670. }
  177671. row_index = (row_index + 1) & ODITHER_MASK;
  177672. cquantize->row_index = row_index;
  177673. }
  177674. }
  177675. METHODDEF(void)
  177676. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177677. JSAMPARRAY output_buf, int num_rows)
  177678. /* General case, with Floyd-Steinberg dithering */
  177679. {
  177680. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177681. register LOCFSERROR cur; /* current error or pixel value */
  177682. LOCFSERROR belowerr; /* error for pixel below cur */
  177683. LOCFSERROR bpreverr; /* error for below/prev col */
  177684. LOCFSERROR bnexterr; /* error for below/next col */
  177685. LOCFSERROR delta;
  177686. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177687. register JSAMPROW input_ptr;
  177688. register JSAMPROW output_ptr;
  177689. JSAMPROW colorindex_ci;
  177690. JSAMPROW colormap_ci;
  177691. int pixcode;
  177692. int nc = cinfo->out_color_components;
  177693. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177694. int dirnc; /* dir * nc */
  177695. int ci;
  177696. int row;
  177697. JDIMENSION col;
  177698. JDIMENSION width = cinfo->output_width;
  177699. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177700. SHIFT_TEMPS
  177701. for (row = 0; row < num_rows; row++) {
  177702. /* Initialize output values to 0 so can process components separately */
  177703. jzero_far((void FAR *) output_buf[row],
  177704. (size_t) (width * SIZEOF(JSAMPLE)));
  177705. for (ci = 0; ci < nc; ci++) {
  177706. input_ptr = input_buf[row] + ci;
  177707. output_ptr = output_buf[row];
  177708. if (cquantize->on_odd_row) {
  177709. /* work right to left in this row */
  177710. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177711. output_ptr += width-1;
  177712. dir = -1;
  177713. dirnc = -nc;
  177714. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177715. } else {
  177716. /* work left to right in this row */
  177717. dir = 1;
  177718. dirnc = nc;
  177719. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177720. }
  177721. colorindex_ci = cquantize->colorindex[ci];
  177722. colormap_ci = cquantize->sv_colormap[ci];
  177723. /* Preset error values: no error propagated to first pixel from left */
  177724. cur = 0;
  177725. /* and no error propagated to row below yet */
  177726. belowerr = bpreverr = 0;
  177727. for (col = width; col > 0; col--) {
  177728. /* cur holds the error propagated from the previous pixel on the
  177729. * current line. Add the error propagated from the previous line
  177730. * to form the complete error correction term for this pixel, and
  177731. * round the error term (which is expressed * 16) to an integer.
  177732. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177733. * for either sign of the error value.
  177734. * Note: errorptr points to *previous* column's array entry.
  177735. */
  177736. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177737. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177738. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177739. * of the range_limit array.
  177740. */
  177741. cur += GETJSAMPLE(*input_ptr);
  177742. cur = GETJSAMPLE(range_limit[cur]);
  177743. /* Select output value, accumulate into output code for this pixel */
  177744. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177745. *output_ptr += (JSAMPLE) pixcode;
  177746. /* Compute actual representation error at this pixel */
  177747. /* Note: we can do this even though we don't have the final */
  177748. /* pixel code, because the colormap is orthogonal. */
  177749. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177750. /* Compute error fractions to be propagated to adjacent pixels.
  177751. * Add these into the running sums, and simultaneously shift the
  177752. * next-line error sums left by 1 column.
  177753. */
  177754. bnexterr = cur;
  177755. delta = cur * 2;
  177756. cur += delta; /* form error * 3 */
  177757. errorptr[0] = (FSERROR) (bpreverr + cur);
  177758. cur += delta; /* form error * 5 */
  177759. bpreverr = belowerr + cur;
  177760. belowerr = bnexterr;
  177761. cur += delta; /* form error * 7 */
  177762. /* At this point cur contains the 7/16 error value to be propagated
  177763. * to the next pixel on the current line, and all the errors for the
  177764. * next line have been shifted over. We are therefore ready to move on.
  177765. */
  177766. input_ptr += dirnc; /* advance input ptr to next column */
  177767. output_ptr += dir; /* advance output ptr to next column */
  177768. errorptr += dir; /* advance errorptr to current column */
  177769. }
  177770. /* Post-loop cleanup: we must unload the final error value into the
  177771. * final fserrors[] entry. Note we need not unload belowerr because
  177772. * it is for the dummy column before or after the actual array.
  177773. */
  177774. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177775. }
  177776. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177777. }
  177778. }
  177779. /*
  177780. * Allocate workspace for Floyd-Steinberg errors.
  177781. */
  177782. LOCAL(void)
  177783. alloc_fs_workspace (j_decompress_ptr cinfo)
  177784. {
  177785. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177786. size_t arraysize;
  177787. int i;
  177788. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177789. for (i = 0; i < cinfo->out_color_components; i++) {
  177790. cquantize->fserrors[i] = (FSERRPTR)
  177791. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177792. }
  177793. }
  177794. /*
  177795. * Initialize for one-pass color quantization.
  177796. */
  177797. METHODDEF(void)
  177798. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177799. {
  177800. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177801. size_t arraysize;
  177802. int i;
  177803. /* Install my colormap. */
  177804. cinfo->colormap = cquantize->sv_colormap;
  177805. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177806. /* Initialize for desired dithering mode. */
  177807. switch (cinfo->dither_mode) {
  177808. case JDITHER_NONE:
  177809. if (cinfo->out_color_components == 3)
  177810. cquantize->pub.color_quantize = color_quantize3;
  177811. else
  177812. cquantize->pub.color_quantize = color_quantize;
  177813. break;
  177814. case JDITHER_ORDERED:
  177815. if (cinfo->out_color_components == 3)
  177816. cquantize->pub.color_quantize = quantize3_ord_dither;
  177817. else
  177818. cquantize->pub.color_quantize = quantize_ord_dither;
  177819. cquantize->row_index = 0; /* initialize state for ordered dither */
  177820. /* If user changed to ordered dither from another mode,
  177821. * we must recreate the color index table with padding.
  177822. * This will cost extra space, but probably isn't very likely.
  177823. */
  177824. if (! cquantize->is_padded)
  177825. create_colorindex(cinfo);
  177826. /* Create ordered-dither tables if we didn't already. */
  177827. if (cquantize->odither[0] == NULL)
  177828. create_odither_tables(cinfo);
  177829. break;
  177830. case JDITHER_FS:
  177831. cquantize->pub.color_quantize = quantize_fs_dither;
  177832. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177833. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177834. if (cquantize->fserrors[0] == NULL)
  177835. alloc_fs_workspace(cinfo);
  177836. /* Initialize the propagated errors to zero. */
  177837. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177838. for (i = 0; i < cinfo->out_color_components; i++)
  177839. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177840. break;
  177841. default:
  177842. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177843. break;
  177844. }
  177845. }
  177846. /*
  177847. * Finish up at the end of the pass.
  177848. */
  177849. METHODDEF(void)
  177850. finish_pass_1_quant (j_decompress_ptr)
  177851. {
  177852. /* no work in 1-pass case */
  177853. }
  177854. /*
  177855. * Switch to a new external colormap between output passes.
  177856. * Shouldn't get to this module!
  177857. */
  177858. METHODDEF(void)
  177859. new_color_map_1_quant (j_decompress_ptr cinfo)
  177860. {
  177861. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177862. }
  177863. /*
  177864. * Module initialization routine for 1-pass color quantization.
  177865. */
  177866. GLOBAL(void)
  177867. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177868. {
  177869. my_cquantize_ptr cquantize;
  177870. cquantize = (my_cquantize_ptr)
  177871. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177872. SIZEOF(my_cquantizer));
  177873. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177874. cquantize->pub.start_pass = start_pass_1_quant;
  177875. cquantize->pub.finish_pass = finish_pass_1_quant;
  177876. cquantize->pub.new_color_map = new_color_map_1_quant;
  177877. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177878. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177879. /* Make sure my internal arrays won't overflow */
  177880. if (cinfo->out_color_components > MAX_Q_COMPS)
  177881. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177882. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177883. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177884. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177885. /* Create the colormap and color index table. */
  177886. create_colormap(cinfo);
  177887. create_colorindex(cinfo);
  177888. /* Allocate Floyd-Steinberg workspace now if requested.
  177889. * We do this now since it is FAR storage and may affect the memory
  177890. * manager's space calculations. If the user changes to FS dither
  177891. * mode in a later pass, we will allocate the space then, and will
  177892. * possibly overrun the max_memory_to_use setting.
  177893. */
  177894. if (cinfo->dither_mode == JDITHER_FS)
  177895. alloc_fs_workspace(cinfo);
  177896. }
  177897. #endif /* QUANT_1PASS_SUPPORTED */
  177898. /*** End of inlined file: jquant1.c ***/
  177899. /*** Start of inlined file: jquant2.c ***/
  177900. #define JPEG_INTERNALS
  177901. #ifdef QUANT_2PASS_SUPPORTED
  177902. /*
  177903. * This module implements the well-known Heckbert paradigm for color
  177904. * quantization. Most of the ideas used here can be traced back to
  177905. * Heckbert's seminal paper
  177906. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177907. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177908. *
  177909. * In the first pass over the image, we accumulate a histogram showing the
  177910. * usage count of each possible color. To keep the histogram to a reasonable
  177911. * size, we reduce the precision of the input; typical practice is to retain
  177912. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177913. * in the same histogram cell.
  177914. *
  177915. * Next, the color-selection step begins with a box representing the whole
  177916. * color space, and repeatedly splits the "largest" remaining box until we
  177917. * have as many boxes as desired colors. Then the mean color in each
  177918. * remaining box becomes one of the possible output colors.
  177919. *
  177920. * The second pass over the image maps each input pixel to the closest output
  177921. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177922. * This mapping is logically trivial, but making it go fast enough requires
  177923. * considerable care.
  177924. *
  177925. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177926. * the "largest" box and deciding where to cut it. The particular policies
  177927. * used here have proved out well in experimental comparisons, but better ones
  177928. * may yet be found.
  177929. *
  177930. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177931. * space, processing the raw upsampled data without a color conversion step.
  177932. * This allowed the color conversion math to be done only once per colormap
  177933. * entry, not once per pixel. However, that optimization precluded other
  177934. * useful optimizations (such as merging color conversion with upsampling)
  177935. * and it also interfered with desired capabilities such as quantizing to an
  177936. * externally-supplied colormap. We have therefore abandoned that approach.
  177937. * The present code works in the post-conversion color space, typically RGB.
  177938. *
  177939. * To improve the visual quality of the results, we actually work in scaled
  177940. * RGB space, giving G distances more weight than R, and R in turn more than
  177941. * B. To do everything in integer math, we must use integer scale factors.
  177942. * The 2/3/1 scale factors used here correspond loosely to the relative
  177943. * weights of the colors in the NTSC grayscale equation.
  177944. * If you want to use this code to quantize a non-RGB color space, you'll
  177945. * probably need to change these scale factors.
  177946. */
  177947. #define R_SCALE 2 /* scale R distances by this much */
  177948. #define G_SCALE 3 /* scale G distances by this much */
  177949. #define B_SCALE 1 /* and B by this much */
  177950. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177951. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177952. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177953. * you'll get compile errors until you extend this logic. In that case
  177954. * you'll probably want to tweak the histogram sizes too.
  177955. */
  177956. #if RGB_RED == 0
  177957. #define C0_SCALE R_SCALE
  177958. #endif
  177959. #if RGB_BLUE == 0
  177960. #define C0_SCALE B_SCALE
  177961. #endif
  177962. #if RGB_GREEN == 1
  177963. #define C1_SCALE G_SCALE
  177964. #endif
  177965. #if RGB_RED == 2
  177966. #define C2_SCALE R_SCALE
  177967. #endif
  177968. #if RGB_BLUE == 2
  177969. #define C2_SCALE B_SCALE
  177970. #endif
  177971. /*
  177972. * First we have the histogram data structure and routines for creating it.
  177973. *
  177974. * The number of bits of precision can be adjusted by changing these symbols.
  177975. * We recommend keeping 6 bits for G and 5 each for R and B.
  177976. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177977. * better results; if you are short of memory, 5 bits all around will save
  177978. * some space but degrade the results.
  177979. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177980. * (preferably unsigned long) for each cell. In practice this is overkill;
  177981. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177982. * and clamping those that do overflow to the maximum value will give close-
  177983. * enough results. This reduces the recommended histogram size from 256Kb
  177984. * to 128Kb, which is a useful savings on PC-class machines.
  177985. * (In the second pass the histogram space is re-used for pixel mapping data;
  177986. * in that capacity, each cell must be able to store zero to the number of
  177987. * desired colors. 16 bits/cell is plenty for that too.)
  177988. * Since the JPEG code is intended to run in small memory model on 80x86
  177989. * machines, we can't just allocate the histogram in one chunk. Instead
  177990. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177991. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177992. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177993. * on 80x86 machines, the pointer row is in near memory but the actual
  177994. * arrays are in far memory (same arrangement as we use for image arrays).
  177995. */
  177996. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177997. /* These will do the right thing for either R,G,B or B,G,R color order,
  177998. * but you may not like the results for other color orders.
  177999. */
  178000. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  178001. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  178002. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  178003. /* Number of elements along histogram axes. */
  178004. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  178005. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  178006. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  178007. /* These are the amounts to shift an input value to get a histogram index. */
  178008. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  178009. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  178010. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  178011. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  178012. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  178013. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  178014. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  178015. typedef hist2d * hist3d; /* type for top-level pointer */
  178016. /* Declarations for Floyd-Steinberg dithering.
  178017. *
  178018. * Errors are accumulated into the array fserrors[], at a resolution of
  178019. * 1/16th of a pixel count. The error at a given pixel is propagated
  178020. * to its not-yet-processed neighbors using the standard F-S fractions,
  178021. * ... (here) 7/16
  178022. * 3/16 5/16 1/16
  178023. * We work left-to-right on even rows, right-to-left on odd rows.
  178024. *
  178025. * We can get away with a single array (holding one row's worth of errors)
  178026. * by using it to store the current row's errors at pixel columns not yet
  178027. * processed, but the next row's errors at columns already processed. We
  178028. * need only a few extra variables to hold the errors immediately around the
  178029. * current column. (If we are lucky, those variables are in registers, but
  178030. * even if not, they're probably cheaper to access than array elements are.)
  178031. *
  178032. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  178033. * each end saves us from special-casing the first and last pixels.
  178034. * Each entry is three values long, one value for each color component.
  178035. *
  178036. * Note: on a wide image, we might not have enough room in a PC's near data
  178037. * segment to hold the error array; so it is allocated with alloc_large.
  178038. */
  178039. #if BITS_IN_JSAMPLE == 8
  178040. typedef INT16 FSERROR; /* 16 bits should be enough */
  178041. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  178042. #else
  178043. typedef INT32 FSERROR; /* may need more than 16 bits */
  178044. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178045. #endif
  178046. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178047. /* Private subobject */
  178048. typedef struct {
  178049. struct jpeg_color_quantizer pub; /* public fields */
  178050. /* Space for the eventually created colormap is stashed here */
  178051. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  178052. int desired; /* desired # of colors = size of colormap */
  178053. /* Variables for accumulating image statistics */
  178054. hist3d histogram; /* pointer to the histogram */
  178055. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  178056. /* Variables for Floyd-Steinberg dithering */
  178057. FSERRPTR fserrors; /* accumulated errors */
  178058. boolean on_odd_row; /* flag to remember which row we are on */
  178059. int * error_limiter; /* table for clamping the applied error */
  178060. } my_cquantizer2;
  178061. typedef my_cquantizer2 * my_cquantize_ptr2;
  178062. /*
  178063. * Prescan some rows of pixels.
  178064. * In this module the prescan simply updates the histogram, which has been
  178065. * initialized to zeroes by start_pass.
  178066. * An output_buf parameter is required by the method signature, but no data
  178067. * is actually output (in fact the buffer controller is probably passing a
  178068. * NULL pointer).
  178069. */
  178070. METHODDEF(void)
  178071. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178072. JSAMPARRAY, int num_rows)
  178073. {
  178074. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178075. register JSAMPROW ptr;
  178076. register histptr histp;
  178077. register hist3d histogram = cquantize->histogram;
  178078. int row;
  178079. JDIMENSION col;
  178080. JDIMENSION width = cinfo->output_width;
  178081. for (row = 0; row < num_rows; row++) {
  178082. ptr = input_buf[row];
  178083. for (col = width; col > 0; col--) {
  178084. /* get pixel value and index into the histogram */
  178085. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  178086. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  178087. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  178088. /* increment, check for overflow and undo increment if so. */
  178089. if (++(*histp) <= 0)
  178090. (*histp)--;
  178091. ptr += 3;
  178092. }
  178093. }
  178094. }
  178095. /*
  178096. * Next we have the really interesting routines: selection of a colormap
  178097. * given the completed histogram.
  178098. * These routines work with a list of "boxes", each representing a rectangular
  178099. * subset of the input color space (to histogram precision).
  178100. */
  178101. typedef struct {
  178102. /* The bounds of the box (inclusive); expressed as histogram indexes */
  178103. int c0min, c0max;
  178104. int c1min, c1max;
  178105. int c2min, c2max;
  178106. /* The volume (actually 2-norm) of the box */
  178107. INT32 volume;
  178108. /* The number of nonzero histogram cells within this box */
  178109. long colorcount;
  178110. } box;
  178111. typedef box * boxptr;
  178112. LOCAL(boxptr)
  178113. find_biggest_color_pop (boxptr boxlist, int numboxes)
  178114. /* Find the splittable box with the largest color population */
  178115. /* Returns NULL if no splittable boxes remain */
  178116. {
  178117. register boxptr boxp;
  178118. register int i;
  178119. register long maxc = 0;
  178120. boxptr which = NULL;
  178121. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178122. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178123. which = boxp;
  178124. maxc = boxp->colorcount;
  178125. }
  178126. }
  178127. return which;
  178128. }
  178129. LOCAL(boxptr)
  178130. find_biggest_volume (boxptr boxlist, int numboxes)
  178131. /* Find the splittable box with the largest (scaled) volume */
  178132. /* Returns NULL if no splittable boxes remain */
  178133. {
  178134. register boxptr boxp;
  178135. register int i;
  178136. register INT32 maxv = 0;
  178137. boxptr which = NULL;
  178138. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178139. if (boxp->volume > maxv) {
  178140. which = boxp;
  178141. maxv = boxp->volume;
  178142. }
  178143. }
  178144. return which;
  178145. }
  178146. LOCAL(void)
  178147. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178148. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178149. /* and recompute its volume and population */
  178150. {
  178151. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178152. hist3d histogram = cquantize->histogram;
  178153. histptr histp;
  178154. int c0,c1,c2;
  178155. int c0min,c0max,c1min,c1max,c2min,c2max;
  178156. INT32 dist0,dist1,dist2;
  178157. long ccount;
  178158. c0min = boxp->c0min; c0max = boxp->c0max;
  178159. c1min = boxp->c1min; c1max = boxp->c1max;
  178160. c2min = boxp->c2min; c2max = boxp->c2max;
  178161. if (c0max > c0min)
  178162. for (c0 = c0min; c0 <= c0max; c0++)
  178163. for (c1 = c1min; c1 <= c1max; c1++) {
  178164. histp = & histogram[c0][c1][c2min];
  178165. for (c2 = c2min; c2 <= c2max; c2++)
  178166. if (*histp++ != 0) {
  178167. boxp->c0min = c0min = c0;
  178168. goto have_c0min;
  178169. }
  178170. }
  178171. have_c0min:
  178172. if (c0max > c0min)
  178173. for (c0 = c0max; c0 >= c0min; c0--)
  178174. for (c1 = c1min; c1 <= c1max; c1++) {
  178175. histp = & histogram[c0][c1][c2min];
  178176. for (c2 = c2min; c2 <= c2max; c2++)
  178177. if (*histp++ != 0) {
  178178. boxp->c0max = c0max = c0;
  178179. goto have_c0max;
  178180. }
  178181. }
  178182. have_c0max:
  178183. if (c1max > c1min)
  178184. for (c1 = c1min; c1 <= c1max; c1++)
  178185. for (c0 = c0min; c0 <= c0max; c0++) {
  178186. histp = & histogram[c0][c1][c2min];
  178187. for (c2 = c2min; c2 <= c2max; c2++)
  178188. if (*histp++ != 0) {
  178189. boxp->c1min = c1min = c1;
  178190. goto have_c1min;
  178191. }
  178192. }
  178193. have_c1min:
  178194. if (c1max > c1min)
  178195. for (c1 = c1max; c1 >= c1min; c1--)
  178196. for (c0 = c0min; c0 <= c0max; c0++) {
  178197. histp = & histogram[c0][c1][c2min];
  178198. for (c2 = c2min; c2 <= c2max; c2++)
  178199. if (*histp++ != 0) {
  178200. boxp->c1max = c1max = c1;
  178201. goto have_c1max;
  178202. }
  178203. }
  178204. have_c1max:
  178205. if (c2max > c2min)
  178206. for (c2 = c2min; c2 <= c2max; c2++)
  178207. for (c0 = c0min; c0 <= c0max; c0++) {
  178208. histp = & histogram[c0][c1min][c2];
  178209. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178210. if (*histp != 0) {
  178211. boxp->c2min = c2min = c2;
  178212. goto have_c2min;
  178213. }
  178214. }
  178215. have_c2min:
  178216. if (c2max > c2min)
  178217. for (c2 = c2max; c2 >= c2min; c2--)
  178218. for (c0 = c0min; c0 <= c0max; c0++) {
  178219. histp = & histogram[c0][c1min][c2];
  178220. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178221. if (*histp != 0) {
  178222. boxp->c2max = c2max = c2;
  178223. goto have_c2max;
  178224. }
  178225. }
  178226. have_c2max:
  178227. /* Update box volume.
  178228. * We use 2-norm rather than real volume here; this biases the method
  178229. * against making long narrow boxes, and it has the side benefit that
  178230. * a box is splittable iff norm > 0.
  178231. * Since the differences are expressed in histogram-cell units,
  178232. * we have to shift back to JSAMPLE units to get consistent distances;
  178233. * after which, we scale according to the selected distance scale factors.
  178234. */
  178235. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178236. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178237. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178238. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178239. /* Now scan remaining volume of box and compute population */
  178240. ccount = 0;
  178241. for (c0 = c0min; c0 <= c0max; c0++)
  178242. for (c1 = c1min; c1 <= c1max; c1++) {
  178243. histp = & histogram[c0][c1][c2min];
  178244. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178245. if (*histp != 0) {
  178246. ccount++;
  178247. }
  178248. }
  178249. boxp->colorcount = ccount;
  178250. }
  178251. LOCAL(int)
  178252. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178253. int desired_colors)
  178254. /* Repeatedly select and split the largest box until we have enough boxes */
  178255. {
  178256. int n,lb;
  178257. int c0,c1,c2,cmax;
  178258. register boxptr b1,b2;
  178259. while (numboxes < desired_colors) {
  178260. /* Select box to split.
  178261. * Current algorithm: by population for first half, then by volume.
  178262. */
  178263. if (numboxes*2 <= desired_colors) {
  178264. b1 = find_biggest_color_pop(boxlist, numboxes);
  178265. } else {
  178266. b1 = find_biggest_volume(boxlist, numboxes);
  178267. }
  178268. if (b1 == NULL) /* no splittable boxes left! */
  178269. break;
  178270. b2 = &boxlist[numboxes]; /* where new box will go */
  178271. /* Copy the color bounds to the new box. */
  178272. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178273. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178274. /* Choose which axis to split the box on.
  178275. * Current algorithm: longest scaled axis.
  178276. * See notes in update_box about scaling distances.
  178277. */
  178278. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178279. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178280. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178281. /* We want to break any ties in favor of green, then red, blue last.
  178282. * This code does the right thing for R,G,B or B,G,R color orders only.
  178283. */
  178284. #if RGB_RED == 0
  178285. cmax = c1; n = 1;
  178286. if (c0 > cmax) { cmax = c0; n = 0; }
  178287. if (c2 > cmax) { n = 2; }
  178288. #else
  178289. cmax = c1; n = 1;
  178290. if (c2 > cmax) { cmax = c2; n = 2; }
  178291. if (c0 > cmax) { n = 0; }
  178292. #endif
  178293. /* Choose split point along selected axis, and update box bounds.
  178294. * Current algorithm: split at halfway point.
  178295. * (Since the box has been shrunk to minimum volume,
  178296. * any split will produce two nonempty subboxes.)
  178297. * Note that lb value is max for lower box, so must be < old max.
  178298. */
  178299. switch (n) {
  178300. case 0:
  178301. lb = (b1->c0max + b1->c0min) / 2;
  178302. b1->c0max = lb;
  178303. b2->c0min = lb+1;
  178304. break;
  178305. case 1:
  178306. lb = (b1->c1max + b1->c1min) / 2;
  178307. b1->c1max = lb;
  178308. b2->c1min = lb+1;
  178309. break;
  178310. case 2:
  178311. lb = (b1->c2max + b1->c2min) / 2;
  178312. b1->c2max = lb;
  178313. b2->c2min = lb+1;
  178314. break;
  178315. }
  178316. /* Update stats for boxes */
  178317. update_box(cinfo, b1);
  178318. update_box(cinfo, b2);
  178319. numboxes++;
  178320. }
  178321. return numboxes;
  178322. }
  178323. LOCAL(void)
  178324. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178325. /* Compute representative color for a box, put it in colormap[icolor] */
  178326. {
  178327. /* Current algorithm: mean weighted by pixels (not colors) */
  178328. /* Note it is important to get the rounding correct! */
  178329. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178330. hist3d histogram = cquantize->histogram;
  178331. histptr histp;
  178332. int c0,c1,c2;
  178333. int c0min,c0max,c1min,c1max,c2min,c2max;
  178334. long count;
  178335. long total = 0;
  178336. long c0total = 0;
  178337. long c1total = 0;
  178338. long c2total = 0;
  178339. c0min = boxp->c0min; c0max = boxp->c0max;
  178340. c1min = boxp->c1min; c1max = boxp->c1max;
  178341. c2min = boxp->c2min; c2max = boxp->c2max;
  178342. for (c0 = c0min; c0 <= c0max; c0++)
  178343. for (c1 = c1min; c1 <= c1max; c1++) {
  178344. histp = & histogram[c0][c1][c2min];
  178345. for (c2 = c2min; c2 <= c2max; c2++) {
  178346. if ((count = *histp++) != 0) {
  178347. total += count;
  178348. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178349. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178350. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178351. }
  178352. }
  178353. }
  178354. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178355. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178356. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178357. }
  178358. LOCAL(void)
  178359. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178360. /* Master routine for color selection */
  178361. {
  178362. boxptr boxlist;
  178363. int numboxes;
  178364. int i;
  178365. /* Allocate workspace for box list */
  178366. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178367. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178368. /* Initialize one box containing whole space */
  178369. numboxes = 1;
  178370. boxlist[0].c0min = 0;
  178371. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178372. boxlist[0].c1min = 0;
  178373. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178374. boxlist[0].c2min = 0;
  178375. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178376. /* Shrink it to actually-used volume and set its statistics */
  178377. update_box(cinfo, & boxlist[0]);
  178378. /* Perform median-cut to produce final box list */
  178379. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178380. /* Compute the representative color for each box, fill colormap */
  178381. for (i = 0; i < numboxes; i++)
  178382. compute_color(cinfo, & boxlist[i], i);
  178383. cinfo->actual_number_of_colors = numboxes;
  178384. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178385. }
  178386. /*
  178387. * These routines are concerned with the time-critical task of mapping input
  178388. * colors to the nearest color in the selected colormap.
  178389. *
  178390. * We re-use the histogram space as an "inverse color map", essentially a
  178391. * cache for the results of nearest-color searches. All colors within a
  178392. * histogram cell will be mapped to the same colormap entry, namely the one
  178393. * closest to the cell's center. This may not be quite the closest entry to
  178394. * the actual input color, but it's almost as good. A zero in the cache
  178395. * indicates we haven't found the nearest color for that cell yet; the array
  178396. * is cleared to zeroes before starting the mapping pass. When we find the
  178397. * nearest color for a cell, its colormap index plus one is recorded in the
  178398. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178399. * when they need to use an unfilled entry in the cache.
  178400. *
  178401. * Our method of efficiently finding nearest colors is based on the "locally
  178402. * sorted search" idea described by Heckbert and on the incremental distance
  178403. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178404. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178405. * the distances from a given colormap entry to each cell of the histogram can
  178406. * be computed quickly using an incremental method: the differences between
  178407. * distances to adjacent cells themselves differ by a constant. This allows a
  178408. * fairly fast implementation of the "brute force" approach of computing the
  178409. * distance from every colormap entry to every histogram cell. Unfortunately,
  178410. * it needs a work array to hold the best-distance-so-far for each histogram
  178411. * cell (because the inner loop has to be over cells, not colormap entries).
  178412. * The work array elements have to be INT32s, so the work array would need
  178413. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178414. *
  178415. * To get around these problems, we apply Thomas' method to compute the
  178416. * nearest colors for only the cells within a small subbox of the histogram.
  178417. * The work array need be only as big as the subbox, so the memory usage
  178418. * problem is solved. Furthermore, we need not fill subboxes that are never
  178419. * referenced in pass2; many images use only part of the color gamut, so a
  178420. * fair amount of work is saved. An additional advantage of this
  178421. * approach is that we can apply Heckbert's locality criterion to quickly
  178422. * eliminate colormap entries that are far away from the subbox; typically
  178423. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178424. * and we need not compute their distances to individual cells in the subbox.
  178425. * The speed of this approach is heavily influenced by the subbox size: too
  178426. * small means too much overhead, too big loses because Heckbert's criterion
  178427. * can't eliminate as many colormap entries. Empirically the best subbox
  178428. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178429. *
  178430. * Thomas' article also describes a refined method which is asymptotically
  178431. * faster than the brute-force method, but it is also far more complex and
  178432. * cannot efficiently be applied to small subboxes. It is therefore not
  178433. * useful for programs intended to be portable to DOS machines. On machines
  178434. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178435. * refined method might be faster than the present code --- but then again,
  178436. * it might not be any faster, and it's certainly more complicated.
  178437. */
  178438. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178439. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178440. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178441. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178442. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178443. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178444. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178445. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178446. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178447. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178448. /*
  178449. * The next three routines implement inverse colormap filling. They could
  178450. * all be folded into one big routine, but splitting them up this way saves
  178451. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178452. * and may allow some compilers to produce better code by registerizing more
  178453. * inner-loop variables.
  178454. */
  178455. LOCAL(int)
  178456. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178457. JSAMPLE colorlist[])
  178458. /* Locate the colormap entries close enough to an update box to be candidates
  178459. * for the nearest entry to some cell(s) in the update box. The update box
  178460. * is specified by the center coordinates of its first cell. The number of
  178461. * candidate colormap entries is returned, and their colormap indexes are
  178462. * placed in colorlist[].
  178463. * This routine uses Heckbert's "locally sorted search" criterion to select
  178464. * the colors that need further consideration.
  178465. */
  178466. {
  178467. int numcolors = cinfo->actual_number_of_colors;
  178468. int maxc0, maxc1, maxc2;
  178469. int centerc0, centerc1, centerc2;
  178470. int i, x, ncolors;
  178471. INT32 minmaxdist, min_dist, max_dist, tdist;
  178472. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178473. /* Compute true coordinates of update box's upper corner and center.
  178474. * Actually we compute the coordinates of the center of the upper-corner
  178475. * histogram cell, which are the upper bounds of the volume we care about.
  178476. * Note that since ">>" rounds down, the "center" values may be closer to
  178477. * min than to max; hence comparisons to them must be "<=", not "<".
  178478. */
  178479. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178480. centerc0 = (minc0 + maxc0) >> 1;
  178481. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178482. centerc1 = (minc1 + maxc1) >> 1;
  178483. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178484. centerc2 = (minc2 + maxc2) >> 1;
  178485. /* For each color in colormap, find:
  178486. * 1. its minimum squared-distance to any point in the update box
  178487. * (zero if color is within update box);
  178488. * 2. its maximum squared-distance to any point in the update box.
  178489. * Both of these can be found by considering only the corners of the box.
  178490. * We save the minimum distance for each color in mindist[];
  178491. * only the smallest maximum distance is of interest.
  178492. */
  178493. minmaxdist = 0x7FFFFFFFL;
  178494. for (i = 0; i < numcolors; i++) {
  178495. /* We compute the squared-c0-distance term, then add in the other two. */
  178496. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178497. if (x < minc0) {
  178498. tdist = (x - minc0) * C0_SCALE;
  178499. min_dist = tdist*tdist;
  178500. tdist = (x - maxc0) * C0_SCALE;
  178501. max_dist = tdist*tdist;
  178502. } else if (x > maxc0) {
  178503. tdist = (x - maxc0) * C0_SCALE;
  178504. min_dist = tdist*tdist;
  178505. tdist = (x - minc0) * C0_SCALE;
  178506. max_dist = tdist*tdist;
  178507. } else {
  178508. /* within cell range so no contribution to min_dist */
  178509. min_dist = 0;
  178510. if (x <= centerc0) {
  178511. tdist = (x - maxc0) * C0_SCALE;
  178512. max_dist = tdist*tdist;
  178513. } else {
  178514. tdist = (x - minc0) * C0_SCALE;
  178515. max_dist = tdist*tdist;
  178516. }
  178517. }
  178518. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178519. if (x < minc1) {
  178520. tdist = (x - minc1) * C1_SCALE;
  178521. min_dist += tdist*tdist;
  178522. tdist = (x - maxc1) * C1_SCALE;
  178523. max_dist += tdist*tdist;
  178524. } else if (x > maxc1) {
  178525. tdist = (x - maxc1) * C1_SCALE;
  178526. min_dist += tdist*tdist;
  178527. tdist = (x - minc1) * C1_SCALE;
  178528. max_dist += tdist*tdist;
  178529. } else {
  178530. /* within cell range so no contribution to min_dist */
  178531. if (x <= centerc1) {
  178532. tdist = (x - maxc1) * C1_SCALE;
  178533. max_dist += tdist*tdist;
  178534. } else {
  178535. tdist = (x - minc1) * C1_SCALE;
  178536. max_dist += tdist*tdist;
  178537. }
  178538. }
  178539. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178540. if (x < minc2) {
  178541. tdist = (x - minc2) * C2_SCALE;
  178542. min_dist += tdist*tdist;
  178543. tdist = (x - maxc2) * C2_SCALE;
  178544. max_dist += tdist*tdist;
  178545. } else if (x > maxc2) {
  178546. tdist = (x - maxc2) * C2_SCALE;
  178547. min_dist += tdist*tdist;
  178548. tdist = (x - minc2) * C2_SCALE;
  178549. max_dist += tdist*tdist;
  178550. } else {
  178551. /* within cell range so no contribution to min_dist */
  178552. if (x <= centerc2) {
  178553. tdist = (x - maxc2) * C2_SCALE;
  178554. max_dist += tdist*tdist;
  178555. } else {
  178556. tdist = (x - minc2) * C2_SCALE;
  178557. max_dist += tdist*tdist;
  178558. }
  178559. }
  178560. mindist[i] = min_dist; /* save away the results */
  178561. if (max_dist < minmaxdist)
  178562. minmaxdist = max_dist;
  178563. }
  178564. /* Now we know that no cell in the update box is more than minmaxdist
  178565. * away from some colormap entry. Therefore, only colors that are
  178566. * within minmaxdist of some part of the box need be considered.
  178567. */
  178568. ncolors = 0;
  178569. for (i = 0; i < numcolors; i++) {
  178570. if (mindist[i] <= minmaxdist)
  178571. colorlist[ncolors++] = (JSAMPLE) i;
  178572. }
  178573. return ncolors;
  178574. }
  178575. LOCAL(void)
  178576. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178577. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178578. /* Find the closest colormap entry for each cell in the update box,
  178579. * given the list of candidate colors prepared by find_nearby_colors.
  178580. * Return the indexes of the closest entries in the bestcolor[] array.
  178581. * This routine uses Thomas' incremental distance calculation method to
  178582. * find the distance from a colormap entry to successive cells in the box.
  178583. */
  178584. {
  178585. int ic0, ic1, ic2;
  178586. int i, icolor;
  178587. register INT32 * bptr; /* pointer into bestdist[] array */
  178588. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178589. INT32 dist0, dist1; /* initial distance values */
  178590. register INT32 dist2; /* current distance in inner loop */
  178591. INT32 xx0, xx1; /* distance increments */
  178592. register INT32 xx2;
  178593. INT32 inc0, inc1, inc2; /* initial values for increments */
  178594. /* This array holds the distance to the nearest-so-far color for each cell */
  178595. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178596. /* Initialize best-distance for each cell of the update box */
  178597. bptr = bestdist;
  178598. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178599. *bptr++ = 0x7FFFFFFFL;
  178600. /* For each color selected by find_nearby_colors,
  178601. * compute its distance to the center of each cell in the box.
  178602. * If that's less than best-so-far, update best distance and color number.
  178603. */
  178604. /* Nominal steps between cell centers ("x" in Thomas article) */
  178605. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178606. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178607. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178608. for (i = 0; i < numcolors; i++) {
  178609. icolor = GETJSAMPLE(colorlist[i]);
  178610. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178611. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178612. dist0 = inc0*inc0;
  178613. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178614. dist0 += inc1*inc1;
  178615. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178616. dist0 += inc2*inc2;
  178617. /* Form the initial difference increments */
  178618. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178619. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178620. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178621. /* Now loop over all cells in box, updating distance per Thomas method */
  178622. bptr = bestdist;
  178623. cptr = bestcolor;
  178624. xx0 = inc0;
  178625. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178626. dist1 = dist0;
  178627. xx1 = inc1;
  178628. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178629. dist2 = dist1;
  178630. xx2 = inc2;
  178631. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178632. if (dist2 < *bptr) {
  178633. *bptr = dist2;
  178634. *cptr = (JSAMPLE) icolor;
  178635. }
  178636. dist2 += xx2;
  178637. xx2 += 2 * STEP_C2 * STEP_C2;
  178638. bptr++;
  178639. cptr++;
  178640. }
  178641. dist1 += xx1;
  178642. xx1 += 2 * STEP_C1 * STEP_C1;
  178643. }
  178644. dist0 += xx0;
  178645. xx0 += 2 * STEP_C0 * STEP_C0;
  178646. }
  178647. }
  178648. }
  178649. LOCAL(void)
  178650. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178651. /* Fill the inverse-colormap entries in the update box that contains */
  178652. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178653. /* we can fill as many others as we wish.) */
  178654. {
  178655. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178656. hist3d histogram = cquantize->histogram;
  178657. int minc0, minc1, minc2; /* lower left corner of update box */
  178658. int ic0, ic1, ic2;
  178659. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178660. register histptr cachep; /* pointer into main cache array */
  178661. /* This array lists the candidate colormap indexes. */
  178662. JSAMPLE colorlist[MAXNUMCOLORS];
  178663. int numcolors; /* number of candidate colors */
  178664. /* This array holds the actually closest colormap index for each cell. */
  178665. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178666. /* Convert cell coordinates to update box ID */
  178667. c0 >>= BOX_C0_LOG;
  178668. c1 >>= BOX_C1_LOG;
  178669. c2 >>= BOX_C2_LOG;
  178670. /* Compute true coordinates of update box's origin corner.
  178671. * Actually we compute the coordinates of the center of the corner
  178672. * histogram cell, which are the lower bounds of the volume we care about.
  178673. */
  178674. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178675. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178676. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178677. /* Determine which colormap entries are close enough to be candidates
  178678. * for the nearest entry to some cell in the update box.
  178679. */
  178680. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178681. /* Determine the actually nearest colors. */
  178682. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178683. bestcolor);
  178684. /* Save the best color numbers (plus 1) in the main cache array */
  178685. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178686. c1 <<= BOX_C1_LOG;
  178687. c2 <<= BOX_C2_LOG;
  178688. cptr = bestcolor;
  178689. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178690. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178691. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178692. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178693. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178694. }
  178695. }
  178696. }
  178697. }
  178698. /*
  178699. * Map some rows of pixels to the output colormapped representation.
  178700. */
  178701. METHODDEF(void)
  178702. pass2_no_dither (j_decompress_ptr cinfo,
  178703. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178704. /* This version performs no dithering */
  178705. {
  178706. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178707. hist3d histogram = cquantize->histogram;
  178708. register JSAMPROW inptr, outptr;
  178709. register histptr cachep;
  178710. register int c0, c1, c2;
  178711. int row;
  178712. JDIMENSION col;
  178713. JDIMENSION width = cinfo->output_width;
  178714. for (row = 0; row < num_rows; row++) {
  178715. inptr = input_buf[row];
  178716. outptr = output_buf[row];
  178717. for (col = width; col > 0; col--) {
  178718. /* get pixel value and index into the cache */
  178719. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178720. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178721. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178722. cachep = & histogram[c0][c1][c2];
  178723. /* If we have not seen this color before, find nearest colormap entry */
  178724. /* and update the cache */
  178725. if (*cachep == 0)
  178726. fill_inverse_cmap(cinfo, c0,c1,c2);
  178727. /* Now emit the colormap index for this cell */
  178728. *outptr++ = (JSAMPLE) (*cachep - 1);
  178729. }
  178730. }
  178731. }
  178732. METHODDEF(void)
  178733. pass2_fs_dither (j_decompress_ptr cinfo,
  178734. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178735. /* This version performs Floyd-Steinberg dithering */
  178736. {
  178737. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178738. hist3d histogram = cquantize->histogram;
  178739. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178740. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178741. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178742. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178743. JSAMPROW inptr; /* => current input pixel */
  178744. JSAMPROW outptr; /* => current output pixel */
  178745. histptr cachep;
  178746. int dir; /* +1 or -1 depending on direction */
  178747. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178748. int row;
  178749. JDIMENSION col;
  178750. JDIMENSION width = cinfo->output_width;
  178751. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178752. int *error_limit = cquantize->error_limiter;
  178753. JSAMPROW colormap0 = cinfo->colormap[0];
  178754. JSAMPROW colormap1 = cinfo->colormap[1];
  178755. JSAMPROW colormap2 = cinfo->colormap[2];
  178756. SHIFT_TEMPS
  178757. for (row = 0; row < num_rows; row++) {
  178758. inptr = input_buf[row];
  178759. outptr = output_buf[row];
  178760. if (cquantize->on_odd_row) {
  178761. /* work right to left in this row */
  178762. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178763. outptr += width-1;
  178764. dir = -1;
  178765. dir3 = -3;
  178766. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178767. cquantize->on_odd_row = FALSE; /* flip for next time */
  178768. } else {
  178769. /* work left to right in this row */
  178770. dir = 1;
  178771. dir3 = 3;
  178772. errorptr = cquantize->fserrors; /* => entry before first real column */
  178773. cquantize->on_odd_row = TRUE; /* flip for next time */
  178774. }
  178775. /* Preset error values: no error propagated to first pixel from left */
  178776. cur0 = cur1 = cur2 = 0;
  178777. /* and no error propagated to row below yet */
  178778. belowerr0 = belowerr1 = belowerr2 = 0;
  178779. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178780. for (col = width; col > 0; col--) {
  178781. /* curN holds the error propagated from the previous pixel on the
  178782. * current line. Add the error propagated from the previous line
  178783. * to form the complete error correction term for this pixel, and
  178784. * round the error term (which is expressed * 16) to an integer.
  178785. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178786. * for either sign of the error value.
  178787. * Note: errorptr points to *previous* column's array entry.
  178788. */
  178789. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178790. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178791. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178792. /* Limit the error using transfer function set by init_error_limit.
  178793. * See comments with init_error_limit for rationale.
  178794. */
  178795. cur0 = error_limit[cur0];
  178796. cur1 = error_limit[cur1];
  178797. cur2 = error_limit[cur2];
  178798. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178799. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178800. * this sets the required size of the range_limit array.
  178801. */
  178802. cur0 += GETJSAMPLE(inptr[0]);
  178803. cur1 += GETJSAMPLE(inptr[1]);
  178804. cur2 += GETJSAMPLE(inptr[2]);
  178805. cur0 = GETJSAMPLE(range_limit[cur0]);
  178806. cur1 = GETJSAMPLE(range_limit[cur1]);
  178807. cur2 = GETJSAMPLE(range_limit[cur2]);
  178808. /* Index into the cache with adjusted pixel value */
  178809. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178810. /* If we have not seen this color before, find nearest colormap */
  178811. /* entry and update the cache */
  178812. if (*cachep == 0)
  178813. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178814. /* Now emit the colormap index for this cell */
  178815. { register int pixcode = *cachep - 1;
  178816. *outptr = (JSAMPLE) pixcode;
  178817. /* Compute representation error for this pixel */
  178818. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178819. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178820. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178821. }
  178822. /* Compute error fractions to be propagated to adjacent pixels.
  178823. * Add these into the running sums, and simultaneously shift the
  178824. * next-line error sums left by 1 column.
  178825. */
  178826. { register LOCFSERROR bnexterr, delta;
  178827. bnexterr = cur0; /* Process component 0 */
  178828. delta = cur0 * 2;
  178829. cur0 += delta; /* form error * 3 */
  178830. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178831. cur0 += delta; /* form error * 5 */
  178832. bpreverr0 = belowerr0 + cur0;
  178833. belowerr0 = bnexterr;
  178834. cur0 += delta; /* form error * 7 */
  178835. bnexterr = cur1; /* Process component 1 */
  178836. delta = cur1 * 2;
  178837. cur1 += delta; /* form error * 3 */
  178838. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178839. cur1 += delta; /* form error * 5 */
  178840. bpreverr1 = belowerr1 + cur1;
  178841. belowerr1 = bnexterr;
  178842. cur1 += delta; /* form error * 7 */
  178843. bnexterr = cur2; /* Process component 2 */
  178844. delta = cur2 * 2;
  178845. cur2 += delta; /* form error * 3 */
  178846. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178847. cur2 += delta; /* form error * 5 */
  178848. bpreverr2 = belowerr2 + cur2;
  178849. belowerr2 = bnexterr;
  178850. cur2 += delta; /* form error * 7 */
  178851. }
  178852. /* At this point curN contains the 7/16 error value to be propagated
  178853. * to the next pixel on the current line, and all the errors for the
  178854. * next line have been shifted over. We are therefore ready to move on.
  178855. */
  178856. inptr += dir3; /* Advance pixel pointers to next column */
  178857. outptr += dir;
  178858. errorptr += dir3; /* advance errorptr to current column */
  178859. }
  178860. /* Post-loop cleanup: we must unload the final error values into the
  178861. * final fserrors[] entry. Note we need not unload belowerrN because
  178862. * it is for the dummy column before or after the actual array.
  178863. */
  178864. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178865. errorptr[1] = (FSERROR) bpreverr1;
  178866. errorptr[2] = (FSERROR) bpreverr2;
  178867. }
  178868. }
  178869. /*
  178870. * Initialize the error-limiting transfer function (lookup table).
  178871. * The raw F-S error computation can potentially compute error values of up to
  178872. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178873. * much less, otherwise obviously wrong pixels will be created. (Typical
  178874. * effects include weird fringes at color-area boundaries, isolated bright
  178875. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178876. * is to ensure that the "corners" of the color cube are allocated as output
  178877. * colors; then repeated errors in the same direction cannot cause cascading
  178878. * error buildup. However, that only prevents the error from getting
  178879. * completely out of hand; Aaron Giles reports that error limiting improves
  178880. * the results even with corner colors allocated.
  178881. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178882. * well, but the smoother transfer function used below is even better. Thanks
  178883. * to Aaron Giles for this idea.
  178884. */
  178885. LOCAL(void)
  178886. init_error_limit (j_decompress_ptr cinfo)
  178887. /* Allocate and fill in the error_limiter table */
  178888. {
  178889. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178890. int * table;
  178891. int in, out;
  178892. table = (int *) (*cinfo->mem->alloc_small)
  178893. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178894. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178895. cquantize->error_limiter = table;
  178896. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178897. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178898. out = 0;
  178899. for (in = 0; in < STEPSIZE; in++, out++) {
  178900. table[in] = out; table[-in] = -out;
  178901. }
  178902. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178903. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178904. table[in] = out; table[-in] = -out;
  178905. }
  178906. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178907. for (; in <= MAXJSAMPLE; in++) {
  178908. table[in] = out; table[-in] = -out;
  178909. }
  178910. #undef STEPSIZE
  178911. }
  178912. /*
  178913. * Finish up at the end of each pass.
  178914. */
  178915. METHODDEF(void)
  178916. finish_pass1 (j_decompress_ptr cinfo)
  178917. {
  178918. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178919. /* Select the representative colors and fill in cinfo->colormap */
  178920. cinfo->colormap = cquantize->sv_colormap;
  178921. select_colors(cinfo, cquantize->desired);
  178922. /* Force next pass to zero the color index table */
  178923. cquantize->needs_zeroed = TRUE;
  178924. }
  178925. METHODDEF(void)
  178926. finish_pass2 (j_decompress_ptr)
  178927. {
  178928. /* no work */
  178929. }
  178930. /*
  178931. * Initialize for each processing pass.
  178932. */
  178933. METHODDEF(void)
  178934. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178935. {
  178936. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178937. hist3d histogram = cquantize->histogram;
  178938. int i;
  178939. /* Only F-S dithering or no dithering is supported. */
  178940. /* If user asks for ordered dither, give him F-S. */
  178941. if (cinfo->dither_mode != JDITHER_NONE)
  178942. cinfo->dither_mode = JDITHER_FS;
  178943. if (is_pre_scan) {
  178944. /* Set up method pointers */
  178945. cquantize->pub.color_quantize = prescan_quantize;
  178946. cquantize->pub.finish_pass = finish_pass1;
  178947. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178948. } else {
  178949. /* Set up method pointers */
  178950. if (cinfo->dither_mode == JDITHER_FS)
  178951. cquantize->pub.color_quantize = pass2_fs_dither;
  178952. else
  178953. cquantize->pub.color_quantize = pass2_no_dither;
  178954. cquantize->pub.finish_pass = finish_pass2;
  178955. /* Make sure color count is acceptable */
  178956. i = cinfo->actual_number_of_colors;
  178957. if (i < 1)
  178958. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178959. if (i > MAXNUMCOLORS)
  178960. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178961. if (cinfo->dither_mode == JDITHER_FS) {
  178962. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178963. (3 * SIZEOF(FSERROR)));
  178964. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178965. if (cquantize->fserrors == NULL)
  178966. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178967. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178968. /* Initialize the propagated errors to zero. */
  178969. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178970. /* Make the error-limit table if we didn't already. */
  178971. if (cquantize->error_limiter == NULL)
  178972. init_error_limit(cinfo);
  178973. cquantize->on_odd_row = FALSE;
  178974. }
  178975. }
  178976. /* Zero the histogram or inverse color map, if necessary */
  178977. if (cquantize->needs_zeroed) {
  178978. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178979. jzero_far((void FAR *) histogram[i],
  178980. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178981. }
  178982. cquantize->needs_zeroed = FALSE;
  178983. }
  178984. }
  178985. /*
  178986. * Switch to a new external colormap between output passes.
  178987. */
  178988. METHODDEF(void)
  178989. new_color_map_2_quant (j_decompress_ptr cinfo)
  178990. {
  178991. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178992. /* Reset the inverse color map */
  178993. cquantize->needs_zeroed = TRUE;
  178994. }
  178995. /*
  178996. * Module initialization routine for 2-pass color quantization.
  178997. */
  178998. GLOBAL(void)
  178999. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  179000. {
  179001. my_cquantize_ptr2 cquantize;
  179002. int i;
  179003. cquantize = (my_cquantize_ptr2)
  179004. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179005. SIZEOF(my_cquantizer2));
  179006. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  179007. cquantize->pub.start_pass = start_pass_2_quant;
  179008. cquantize->pub.new_color_map = new_color_map_2_quant;
  179009. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  179010. cquantize->error_limiter = NULL;
  179011. /* Make sure jdmaster didn't give me a case I can't handle */
  179012. if (cinfo->out_color_components != 3)
  179013. ERREXIT(cinfo, JERR_NOTIMPL);
  179014. /* Allocate the histogram/inverse colormap storage */
  179015. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  179016. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  179017. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179018. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  179019. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179020. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179021. }
  179022. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  179023. /* Allocate storage for the completed colormap, if required.
  179024. * We do this now since it is FAR storage and may affect
  179025. * the memory manager's space calculations.
  179026. */
  179027. if (cinfo->enable_2pass_quant) {
  179028. /* Make sure color count is acceptable */
  179029. int desired = cinfo->desired_number_of_colors;
  179030. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  179031. if (desired < 8)
  179032. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  179033. /* Make sure colormap indexes can be represented by JSAMPLEs */
  179034. if (desired > MAXNUMCOLORS)
  179035. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179036. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  179037. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  179038. cquantize->desired = desired;
  179039. } else
  179040. cquantize->sv_colormap = NULL;
  179041. /* Only F-S dithering or no dithering is supported. */
  179042. /* If user asks for ordered dither, give him F-S. */
  179043. if (cinfo->dither_mode != JDITHER_NONE)
  179044. cinfo->dither_mode = JDITHER_FS;
  179045. /* Allocate Floyd-Steinberg workspace if necessary.
  179046. * This isn't really needed until pass 2, but again it is FAR storage.
  179047. * Although we will cope with a later change in dither_mode,
  179048. * we do not promise to honor max_memory_to_use if dither_mode changes.
  179049. */
  179050. if (cinfo->dither_mode == JDITHER_FS) {
  179051. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179052. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179053. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  179054. /* Might as well create the error-limiting table too. */
  179055. init_error_limit(cinfo);
  179056. }
  179057. }
  179058. #endif /* QUANT_2PASS_SUPPORTED */
  179059. /*** End of inlined file: jquant2.c ***/
  179060. /*** Start of inlined file: jutils.c ***/
  179061. #define JPEG_INTERNALS
  179062. /*
  179063. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  179064. * of a DCT block read in natural order (left to right, top to bottom).
  179065. */
  179066. #if 0 /* This table is not actually needed in v6a */
  179067. const int jpeg_zigzag_order[DCTSIZE2] = {
  179068. 0, 1, 5, 6, 14, 15, 27, 28,
  179069. 2, 4, 7, 13, 16, 26, 29, 42,
  179070. 3, 8, 12, 17, 25, 30, 41, 43,
  179071. 9, 11, 18, 24, 31, 40, 44, 53,
  179072. 10, 19, 23, 32, 39, 45, 52, 54,
  179073. 20, 22, 33, 38, 46, 51, 55, 60,
  179074. 21, 34, 37, 47, 50, 56, 59, 61,
  179075. 35, 36, 48, 49, 57, 58, 62, 63
  179076. };
  179077. #endif
  179078. /*
  179079. * jpeg_natural_order[i] is the natural-order position of the i'th element
  179080. * of zigzag order.
  179081. *
  179082. * When reading corrupted data, the Huffman decoders could attempt
  179083. * to reference an entry beyond the end of this array (if the decoded
  179084. * zero run length reaches past the end of the block). To prevent
  179085. * wild stores without adding an inner-loop test, we put some extra
  179086. * "63"s after the real entries. This will cause the extra coefficient
  179087. * to be stored in location 63 of the block, not somewhere random.
  179088. * The worst case would be a run-length of 15, which means we need 16
  179089. * fake entries.
  179090. */
  179091. const int jpeg_natural_order[DCTSIZE2+16] = {
  179092. 0, 1, 8, 16, 9, 2, 3, 10,
  179093. 17, 24, 32, 25, 18, 11, 4, 5,
  179094. 12, 19, 26, 33, 40, 48, 41, 34,
  179095. 27, 20, 13, 6, 7, 14, 21, 28,
  179096. 35, 42, 49, 56, 57, 50, 43, 36,
  179097. 29, 22, 15, 23, 30, 37, 44, 51,
  179098. 58, 59, 52, 45, 38, 31, 39, 46,
  179099. 53, 60, 61, 54, 47, 55, 62, 63,
  179100. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  179101. 63, 63, 63, 63, 63, 63, 63, 63
  179102. };
  179103. /*
  179104. * Arithmetic utilities
  179105. */
  179106. GLOBAL(long)
  179107. jdiv_round_up (long a, long b)
  179108. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  179109. /* Assumes a >= 0, b > 0 */
  179110. {
  179111. return (a + b - 1L) / b;
  179112. }
  179113. GLOBAL(long)
  179114. jround_up (long a, long b)
  179115. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179116. /* Assumes a >= 0, b > 0 */
  179117. {
  179118. a += b - 1L;
  179119. return a - (a % b);
  179120. }
  179121. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179122. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179123. * are FAR and we're assuming a small-pointer memory model. However, some
  179124. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179125. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179126. * Otherwise, the routines below do it the hard way. (The performance cost
  179127. * is not all that great, because these routines aren't very heavily used.)
  179128. */
  179129. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179130. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179131. #define FMEMZERO(target,size) MEMZERO(target,size)
  179132. #else /* 80x86 case, define if we can */
  179133. #ifdef USE_FMEM
  179134. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179135. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179136. #endif
  179137. #endif
  179138. GLOBAL(void)
  179139. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179140. JSAMPARRAY output_array, int dest_row,
  179141. int num_rows, JDIMENSION num_cols)
  179142. /* Copy some rows of samples from one place to another.
  179143. * num_rows rows are copied from input_array[source_row++]
  179144. * to output_array[dest_row++]; these areas may overlap for duplication.
  179145. * The source and destination arrays must be at least as wide as num_cols.
  179146. */
  179147. {
  179148. register JSAMPROW inptr, outptr;
  179149. #ifdef FMEMCOPY
  179150. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179151. #else
  179152. register JDIMENSION count;
  179153. #endif
  179154. register int row;
  179155. input_array += source_row;
  179156. output_array += dest_row;
  179157. for (row = num_rows; row > 0; row--) {
  179158. inptr = *input_array++;
  179159. outptr = *output_array++;
  179160. #ifdef FMEMCOPY
  179161. FMEMCOPY(outptr, inptr, count);
  179162. #else
  179163. for (count = num_cols; count > 0; count--)
  179164. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179165. #endif
  179166. }
  179167. }
  179168. GLOBAL(void)
  179169. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179170. JDIMENSION num_blocks)
  179171. /* Copy a row of coefficient blocks from one place to another. */
  179172. {
  179173. #ifdef FMEMCOPY
  179174. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179175. #else
  179176. register JCOEFPTR inptr, outptr;
  179177. register long count;
  179178. inptr = (JCOEFPTR) input_row;
  179179. outptr = (JCOEFPTR) output_row;
  179180. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179181. *outptr++ = *inptr++;
  179182. }
  179183. #endif
  179184. }
  179185. GLOBAL(void)
  179186. jzero_far (void FAR * target, size_t bytestozero)
  179187. /* Zero out a chunk of FAR memory. */
  179188. /* This might be sample-array data, block-array data, or alloc_large data. */
  179189. {
  179190. #ifdef FMEMZERO
  179191. FMEMZERO(target, bytestozero);
  179192. #else
  179193. register char FAR * ptr = (char FAR *) target;
  179194. register size_t count;
  179195. for (count = bytestozero; count > 0; count--) {
  179196. *ptr++ = 0;
  179197. }
  179198. #endif
  179199. }
  179200. /*** End of inlined file: jutils.c ***/
  179201. /*** Start of inlined file: transupp.c ***/
  179202. /* Although this file really shouldn't have access to the library internals,
  179203. * it's helpful to let it call jround_up() and jcopy_block_row().
  179204. */
  179205. #define JPEG_INTERNALS
  179206. /*** Start of inlined file: transupp.h ***/
  179207. /* If you happen not to want the image transform support, disable it here */
  179208. #ifndef TRANSFORMS_SUPPORTED
  179209. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179210. #endif
  179211. /* Short forms of external names for systems with brain-damaged linkers. */
  179212. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179213. #define jtransform_request_workspace jTrRequest
  179214. #define jtransform_adjust_parameters jTrAdjust
  179215. #define jtransform_execute_transformation jTrExec
  179216. #define jcopy_markers_setup jCMrkSetup
  179217. #define jcopy_markers_execute jCMrkExec
  179218. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179219. /*
  179220. * Codes for supported types of image transformations.
  179221. */
  179222. typedef enum {
  179223. JXFORM_NONE, /* no transformation */
  179224. JXFORM_FLIP_H, /* horizontal flip */
  179225. JXFORM_FLIP_V, /* vertical flip */
  179226. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179227. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179228. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179229. JXFORM_ROT_180, /* 180-degree rotation */
  179230. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179231. } JXFORM_CODE;
  179232. /*
  179233. * Although rotating and flipping data expressed as DCT coefficients is not
  179234. * hard, there is an asymmetry in the JPEG format specification for images
  179235. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179236. * image edges are padded out to the next iMCU boundary with junk data; but
  179237. * no padding is possible at the top and left edges. If we were to flip
  179238. * the whole image including the pad data, then pad garbage would become
  179239. * visible at the top and/or left, and real pixels would disappear into the
  179240. * pad margins --- perhaps permanently, since encoders & decoders may not
  179241. * bother to preserve DCT blocks that appear to be completely outside the
  179242. * nominal image area. So, we have to exclude any partial iMCUs from the
  179243. * basic transformation.
  179244. *
  179245. * Transpose is the only transformation that can handle partial iMCUs at the
  179246. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179247. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179248. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179249. * The other transforms are defined as combinations of these basic transforms
  179250. * and process edge blocks in a way that preserves the equivalence.
  179251. *
  179252. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179253. * this is not strictly lossless, but it usually gives the best-looking
  179254. * result for odd-size images. Note that when this option is active,
  179255. * the expected mathematical equivalences between the transforms may not hold.
  179256. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179257. * followed by -rot 180 -trim trims both edges.)
  179258. *
  179259. * We also offer a "force to grayscale" option, which simply discards the
  179260. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179261. * the luminance channel is preserved exactly. It's not the same kind of
  179262. * thing as the rotate/flip transformations, but it's convenient to handle it
  179263. * as part of this package, mainly because the transformation routines have to
  179264. * be aware of the option to know how many components to work on.
  179265. */
  179266. typedef struct {
  179267. /* Options: set by caller */
  179268. JXFORM_CODE transform; /* image transform operator */
  179269. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179270. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179271. /* Internal workspace: caller should not touch these */
  179272. int num_components; /* # of components in workspace */
  179273. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179274. } jpeg_transform_info;
  179275. #if TRANSFORMS_SUPPORTED
  179276. /* Request any required workspace */
  179277. EXTERN(void) jtransform_request_workspace
  179278. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179279. /* Adjust output image parameters */
  179280. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179281. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179282. jvirt_barray_ptr *src_coef_arrays,
  179283. jpeg_transform_info *info));
  179284. /* Execute the actual transformation, if any */
  179285. EXTERN(void) jtransform_execute_transformation
  179286. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179287. jvirt_barray_ptr *src_coef_arrays,
  179288. jpeg_transform_info *info));
  179289. #endif /* TRANSFORMS_SUPPORTED */
  179290. /*
  179291. * Support for copying optional markers from source to destination file.
  179292. */
  179293. typedef enum {
  179294. JCOPYOPT_NONE, /* copy no optional markers */
  179295. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179296. JCOPYOPT_ALL /* copy all optional markers */
  179297. } JCOPY_OPTION;
  179298. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179299. /* Setup decompression object to save desired markers in memory */
  179300. EXTERN(void) jcopy_markers_setup
  179301. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179302. /* Copy markers saved in the given source object to the destination object */
  179303. EXTERN(void) jcopy_markers_execute
  179304. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179305. JCOPY_OPTION option));
  179306. /*** End of inlined file: transupp.h ***/
  179307. /* My own external interface */
  179308. #if TRANSFORMS_SUPPORTED
  179309. /*
  179310. * Lossless image transformation routines. These routines work on DCT
  179311. * coefficient arrays and thus do not require any lossy decompression
  179312. * or recompression of the image.
  179313. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179314. *
  179315. * Horizontal flipping is done in-place, using a single top-to-bottom
  179316. * pass through the virtual source array. It will thus be much the
  179317. * fastest option for images larger than main memory.
  179318. *
  179319. * The other routines require a set of destination virtual arrays, so they
  179320. * need twice as much memory as jpegtran normally does. The destination
  179321. * arrays are always written in normal scan order (top to bottom) because
  179322. * the virtual array manager expects this. The source arrays will be scanned
  179323. * in the corresponding order, which means multiple passes through the source
  179324. * arrays for most of the transforms. That could result in much thrashing
  179325. * if the image is larger than main memory.
  179326. *
  179327. * Some notes about the operating environment of the individual transform
  179328. * routines:
  179329. * 1. Both the source and destination virtual arrays are allocated from the
  179330. * source JPEG object, and therefore should be manipulated by calling the
  179331. * source's memory manager.
  179332. * 2. The destination's component count should be used. It may be smaller
  179333. * than the source's when forcing to grayscale.
  179334. * 3. Likewise the destination's sampling factors should be used. When
  179335. * forcing to grayscale the destination's sampling factors will be all 1,
  179336. * and we may as well take that as the effective iMCU size.
  179337. * 4. When "trim" is in effect, the destination's dimensions will be the
  179338. * trimmed values but the source's will be untrimmed.
  179339. * 5. All the routines assume that the source and destination buffers are
  179340. * padded out to a full iMCU boundary. This is true, although for the
  179341. * source buffer it is an undocumented property of jdcoefct.c.
  179342. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179343. * dimensions and ignore the source's.
  179344. */
  179345. LOCAL(void)
  179346. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179347. jvirt_barray_ptr *src_coef_arrays)
  179348. /* Horizontal flip; done in-place, so no separate dest array is required */
  179349. {
  179350. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179351. int ci, k, offset_y;
  179352. JBLOCKARRAY buffer;
  179353. JCOEFPTR ptr1, ptr2;
  179354. JCOEF temp1, temp2;
  179355. jpeg_component_info *compptr;
  179356. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179357. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179358. * mirroring by changing the signs of odd-numbered columns.
  179359. * Partial iMCUs at the right edge are left untouched.
  179360. */
  179361. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179362. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179363. compptr = dstinfo->comp_info + ci;
  179364. comp_width = MCU_cols * compptr->h_samp_factor;
  179365. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179366. blk_y += compptr->v_samp_factor) {
  179367. buffer = (*srcinfo->mem->access_virt_barray)
  179368. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179369. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179370. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179371. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179372. ptr1 = buffer[offset_y][blk_x];
  179373. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179374. /* this unrolled loop doesn't need to know which row it's on... */
  179375. for (k = 0; k < DCTSIZE2; k += 2) {
  179376. temp1 = *ptr1; /* swap even column */
  179377. temp2 = *ptr2;
  179378. *ptr1++ = temp2;
  179379. *ptr2++ = temp1;
  179380. temp1 = *ptr1; /* swap odd column with sign change */
  179381. temp2 = *ptr2;
  179382. *ptr1++ = -temp2;
  179383. *ptr2++ = -temp1;
  179384. }
  179385. }
  179386. }
  179387. }
  179388. }
  179389. }
  179390. LOCAL(void)
  179391. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179392. jvirt_barray_ptr *src_coef_arrays,
  179393. jvirt_barray_ptr *dst_coef_arrays)
  179394. /* Vertical flip */
  179395. {
  179396. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179397. int ci, i, j, offset_y;
  179398. JBLOCKARRAY src_buffer, dst_buffer;
  179399. JBLOCKROW src_row_ptr, dst_row_ptr;
  179400. JCOEFPTR src_ptr, dst_ptr;
  179401. jpeg_component_info *compptr;
  179402. /* We output into a separate array because we can't touch different
  179403. * rows of the source virtual array simultaneously. Otherwise, this
  179404. * is a pretty straightforward analog of horizontal flip.
  179405. * Within a DCT block, vertical mirroring is done by changing the signs
  179406. * of odd-numbered rows.
  179407. * Partial iMCUs at the bottom edge are copied verbatim.
  179408. */
  179409. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179410. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179411. compptr = dstinfo->comp_info + ci;
  179412. comp_height = MCU_rows * compptr->v_samp_factor;
  179413. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179414. dst_blk_y += compptr->v_samp_factor) {
  179415. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179416. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179417. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179418. if (dst_blk_y < comp_height) {
  179419. /* Row is within the mirrorable area. */
  179420. src_buffer = (*srcinfo->mem->access_virt_barray)
  179421. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179422. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179423. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179424. } else {
  179425. /* Bottom-edge blocks will be copied verbatim. */
  179426. src_buffer = (*srcinfo->mem->access_virt_barray)
  179427. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179428. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179429. }
  179430. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179431. if (dst_blk_y < comp_height) {
  179432. /* Row is within the mirrorable area. */
  179433. dst_row_ptr = dst_buffer[offset_y];
  179434. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179435. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179436. dst_blk_x++) {
  179437. dst_ptr = dst_row_ptr[dst_blk_x];
  179438. src_ptr = src_row_ptr[dst_blk_x];
  179439. for (i = 0; i < DCTSIZE; i += 2) {
  179440. /* copy even row */
  179441. for (j = 0; j < DCTSIZE; j++)
  179442. *dst_ptr++ = *src_ptr++;
  179443. /* copy odd row with sign change */
  179444. for (j = 0; j < DCTSIZE; j++)
  179445. *dst_ptr++ = - *src_ptr++;
  179446. }
  179447. }
  179448. } else {
  179449. /* Just copy row verbatim. */
  179450. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179451. compptr->width_in_blocks);
  179452. }
  179453. }
  179454. }
  179455. }
  179456. }
  179457. LOCAL(void)
  179458. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179459. jvirt_barray_ptr *src_coef_arrays,
  179460. jvirt_barray_ptr *dst_coef_arrays)
  179461. /* Transpose source into destination */
  179462. {
  179463. JDIMENSION dst_blk_x, dst_blk_y;
  179464. int ci, i, j, offset_x, offset_y;
  179465. JBLOCKARRAY src_buffer, dst_buffer;
  179466. JCOEFPTR src_ptr, dst_ptr;
  179467. jpeg_component_info *compptr;
  179468. /* Transposing pixels within a block just requires transposing the
  179469. * DCT coefficients.
  179470. * Partial iMCUs at the edges require no special treatment; we simply
  179471. * process all the available DCT blocks for every component.
  179472. */
  179473. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179474. compptr = dstinfo->comp_info + ci;
  179475. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179476. dst_blk_y += compptr->v_samp_factor) {
  179477. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179478. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179479. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179480. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179481. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179482. dst_blk_x += compptr->h_samp_factor) {
  179483. src_buffer = (*srcinfo->mem->access_virt_barray)
  179484. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179485. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179486. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179487. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179488. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179489. for (i = 0; i < DCTSIZE; i++)
  179490. for (j = 0; j < DCTSIZE; j++)
  179491. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179492. }
  179493. }
  179494. }
  179495. }
  179496. }
  179497. }
  179498. LOCAL(void)
  179499. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179500. jvirt_barray_ptr *src_coef_arrays,
  179501. jvirt_barray_ptr *dst_coef_arrays)
  179502. /* 90 degree rotation is equivalent to
  179503. * 1. Transposing the image;
  179504. * 2. Horizontal mirroring.
  179505. * These two steps are merged into a single processing routine.
  179506. */
  179507. {
  179508. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179509. int ci, i, j, offset_x, offset_y;
  179510. JBLOCKARRAY src_buffer, dst_buffer;
  179511. JCOEFPTR src_ptr, dst_ptr;
  179512. jpeg_component_info *compptr;
  179513. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179514. * at the (output) right edge properly. They just get transposed and
  179515. * not mirrored.
  179516. */
  179517. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179518. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179519. compptr = dstinfo->comp_info + ci;
  179520. comp_width = MCU_cols * compptr->h_samp_factor;
  179521. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179522. dst_blk_y += compptr->v_samp_factor) {
  179523. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179524. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179525. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179526. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179527. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179528. dst_blk_x += compptr->h_samp_factor) {
  179529. src_buffer = (*srcinfo->mem->access_virt_barray)
  179530. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179531. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179532. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179533. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179534. if (dst_blk_x < comp_width) {
  179535. /* Block is within the mirrorable area. */
  179536. dst_ptr = dst_buffer[offset_y]
  179537. [comp_width - dst_blk_x - offset_x - 1];
  179538. for (i = 0; i < DCTSIZE; i++) {
  179539. for (j = 0; j < DCTSIZE; j++)
  179540. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179541. i++;
  179542. for (j = 0; j < DCTSIZE; j++)
  179543. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179544. }
  179545. } else {
  179546. /* Edge blocks are transposed but not mirrored. */
  179547. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179548. for (i = 0; i < DCTSIZE; i++)
  179549. for (j = 0; j < DCTSIZE; j++)
  179550. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179551. }
  179552. }
  179553. }
  179554. }
  179555. }
  179556. }
  179557. }
  179558. LOCAL(void)
  179559. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179560. jvirt_barray_ptr *src_coef_arrays,
  179561. jvirt_barray_ptr *dst_coef_arrays)
  179562. /* 270 degree rotation is equivalent to
  179563. * 1. Horizontal mirroring;
  179564. * 2. Transposing the image.
  179565. * These two steps are merged into a single processing routine.
  179566. */
  179567. {
  179568. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179569. int ci, i, j, offset_x, offset_y;
  179570. JBLOCKARRAY src_buffer, dst_buffer;
  179571. JCOEFPTR src_ptr, dst_ptr;
  179572. jpeg_component_info *compptr;
  179573. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179574. * at the (output) bottom edge properly. They just get transposed and
  179575. * not mirrored.
  179576. */
  179577. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179578. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179579. compptr = dstinfo->comp_info + ci;
  179580. comp_height = MCU_rows * compptr->v_samp_factor;
  179581. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179582. dst_blk_y += compptr->v_samp_factor) {
  179583. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179584. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179585. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179586. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179587. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179588. dst_blk_x += compptr->h_samp_factor) {
  179589. src_buffer = (*srcinfo->mem->access_virt_barray)
  179590. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179591. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179592. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179593. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179594. if (dst_blk_y < comp_height) {
  179595. /* Block is within the mirrorable area. */
  179596. src_ptr = src_buffer[offset_x]
  179597. [comp_height - dst_blk_y - offset_y - 1];
  179598. for (i = 0; i < DCTSIZE; i++) {
  179599. for (j = 0; j < DCTSIZE; j++) {
  179600. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179601. j++;
  179602. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179603. }
  179604. }
  179605. } else {
  179606. /* Edge blocks are transposed but not mirrored. */
  179607. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179608. for (i = 0; i < DCTSIZE; i++)
  179609. for (j = 0; j < DCTSIZE; j++)
  179610. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179611. }
  179612. }
  179613. }
  179614. }
  179615. }
  179616. }
  179617. }
  179618. LOCAL(void)
  179619. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179620. jvirt_barray_ptr *src_coef_arrays,
  179621. jvirt_barray_ptr *dst_coef_arrays)
  179622. /* 180 degree rotation is equivalent to
  179623. * 1. Vertical mirroring;
  179624. * 2. Horizontal mirroring.
  179625. * These two steps are merged into a single processing routine.
  179626. */
  179627. {
  179628. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179629. int ci, i, j, offset_y;
  179630. JBLOCKARRAY src_buffer, dst_buffer;
  179631. JBLOCKROW src_row_ptr, dst_row_ptr;
  179632. JCOEFPTR src_ptr, dst_ptr;
  179633. jpeg_component_info *compptr;
  179634. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179635. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179636. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179637. compptr = dstinfo->comp_info + ci;
  179638. comp_width = MCU_cols * compptr->h_samp_factor;
  179639. comp_height = MCU_rows * compptr->v_samp_factor;
  179640. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179641. dst_blk_y += compptr->v_samp_factor) {
  179642. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179643. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179644. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179645. if (dst_blk_y < comp_height) {
  179646. /* Row is within the vertically mirrorable area. */
  179647. src_buffer = (*srcinfo->mem->access_virt_barray)
  179648. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179649. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179650. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179651. } else {
  179652. /* Bottom-edge rows are only mirrored horizontally. */
  179653. src_buffer = (*srcinfo->mem->access_virt_barray)
  179654. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179655. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179656. }
  179657. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179658. if (dst_blk_y < comp_height) {
  179659. /* Row is within the mirrorable area. */
  179660. dst_row_ptr = dst_buffer[offset_y];
  179661. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179662. /* Process the blocks that can be mirrored both ways. */
  179663. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179664. dst_ptr = dst_row_ptr[dst_blk_x];
  179665. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179666. for (i = 0; i < DCTSIZE; i += 2) {
  179667. /* For even row, negate every odd column. */
  179668. for (j = 0; j < DCTSIZE; j += 2) {
  179669. *dst_ptr++ = *src_ptr++;
  179670. *dst_ptr++ = - *src_ptr++;
  179671. }
  179672. /* For odd row, negate every even column. */
  179673. for (j = 0; j < DCTSIZE; j += 2) {
  179674. *dst_ptr++ = - *src_ptr++;
  179675. *dst_ptr++ = *src_ptr++;
  179676. }
  179677. }
  179678. }
  179679. /* Any remaining right-edge blocks are only mirrored vertically. */
  179680. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179681. dst_ptr = dst_row_ptr[dst_blk_x];
  179682. src_ptr = src_row_ptr[dst_blk_x];
  179683. for (i = 0; i < DCTSIZE; i += 2) {
  179684. for (j = 0; j < DCTSIZE; j++)
  179685. *dst_ptr++ = *src_ptr++;
  179686. for (j = 0; j < DCTSIZE; j++)
  179687. *dst_ptr++ = - *src_ptr++;
  179688. }
  179689. }
  179690. } else {
  179691. /* Remaining rows are just mirrored horizontally. */
  179692. dst_row_ptr = dst_buffer[offset_y];
  179693. src_row_ptr = src_buffer[offset_y];
  179694. /* Process the blocks that can be mirrored. */
  179695. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179696. dst_ptr = dst_row_ptr[dst_blk_x];
  179697. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179698. for (i = 0; i < DCTSIZE2; i += 2) {
  179699. *dst_ptr++ = *src_ptr++;
  179700. *dst_ptr++ = - *src_ptr++;
  179701. }
  179702. }
  179703. /* Any remaining right-edge blocks are only copied. */
  179704. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179705. dst_ptr = dst_row_ptr[dst_blk_x];
  179706. src_ptr = src_row_ptr[dst_blk_x];
  179707. for (i = 0; i < DCTSIZE2; i++)
  179708. *dst_ptr++ = *src_ptr++;
  179709. }
  179710. }
  179711. }
  179712. }
  179713. }
  179714. }
  179715. LOCAL(void)
  179716. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179717. jvirt_barray_ptr *src_coef_arrays,
  179718. jvirt_barray_ptr *dst_coef_arrays)
  179719. /* Transverse transpose is equivalent to
  179720. * 1. 180 degree rotation;
  179721. * 2. Transposition;
  179722. * or
  179723. * 1. Horizontal mirroring;
  179724. * 2. Transposition;
  179725. * 3. Horizontal mirroring.
  179726. * These steps are merged into a single processing routine.
  179727. */
  179728. {
  179729. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179730. int ci, i, j, offset_x, offset_y;
  179731. JBLOCKARRAY src_buffer, dst_buffer;
  179732. JCOEFPTR src_ptr, dst_ptr;
  179733. jpeg_component_info *compptr;
  179734. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179735. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179736. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179737. compptr = dstinfo->comp_info + ci;
  179738. comp_width = MCU_cols * compptr->h_samp_factor;
  179739. comp_height = MCU_rows * compptr->v_samp_factor;
  179740. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179741. dst_blk_y += compptr->v_samp_factor) {
  179742. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179743. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179744. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179745. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179746. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179747. dst_blk_x += compptr->h_samp_factor) {
  179748. src_buffer = (*srcinfo->mem->access_virt_barray)
  179749. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179750. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179751. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179752. if (dst_blk_y < comp_height) {
  179753. src_ptr = src_buffer[offset_x]
  179754. [comp_height - dst_blk_y - offset_y - 1];
  179755. if (dst_blk_x < comp_width) {
  179756. /* Block is within the mirrorable area. */
  179757. dst_ptr = dst_buffer[offset_y]
  179758. [comp_width - dst_blk_x - offset_x - 1];
  179759. for (i = 0; i < DCTSIZE; i++) {
  179760. for (j = 0; j < DCTSIZE; j++) {
  179761. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179762. j++;
  179763. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179764. }
  179765. i++;
  179766. for (j = 0; j < DCTSIZE; j++) {
  179767. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179768. j++;
  179769. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179770. }
  179771. }
  179772. } else {
  179773. /* Right-edge blocks are mirrored in y only */
  179774. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179775. for (i = 0; i < DCTSIZE; i++) {
  179776. for (j = 0; j < DCTSIZE; j++) {
  179777. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179778. j++;
  179779. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179780. }
  179781. }
  179782. }
  179783. } else {
  179784. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179785. if (dst_blk_x < comp_width) {
  179786. /* Bottom-edge blocks are mirrored in x only */
  179787. dst_ptr = dst_buffer[offset_y]
  179788. [comp_width - dst_blk_x - offset_x - 1];
  179789. for (i = 0; i < DCTSIZE; i++) {
  179790. for (j = 0; j < DCTSIZE; j++)
  179791. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179792. i++;
  179793. for (j = 0; j < DCTSIZE; j++)
  179794. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179795. }
  179796. } else {
  179797. /* At lower right corner, just transpose, no mirroring */
  179798. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179799. for (i = 0; i < DCTSIZE; i++)
  179800. for (j = 0; j < DCTSIZE; j++)
  179801. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179802. }
  179803. }
  179804. }
  179805. }
  179806. }
  179807. }
  179808. }
  179809. }
  179810. /* Request any required workspace.
  179811. *
  179812. * We allocate the workspace virtual arrays from the source decompression
  179813. * object, so that all the arrays (both the original data and the workspace)
  179814. * will be taken into account while making memory management decisions.
  179815. * Hence, this routine must be called after jpeg_read_header (which reads
  179816. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179817. * the source's virtual arrays).
  179818. */
  179819. GLOBAL(void)
  179820. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179821. jpeg_transform_info *info)
  179822. {
  179823. jvirt_barray_ptr *coef_arrays = NULL;
  179824. jpeg_component_info *compptr;
  179825. int ci;
  179826. if (info->force_grayscale &&
  179827. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179828. srcinfo->num_components == 3) {
  179829. /* We'll only process the first component */
  179830. info->num_components = 1;
  179831. } else {
  179832. /* Process all the components */
  179833. info->num_components = srcinfo->num_components;
  179834. }
  179835. switch (info->transform) {
  179836. case JXFORM_NONE:
  179837. case JXFORM_FLIP_H:
  179838. /* Don't need a workspace array */
  179839. break;
  179840. case JXFORM_FLIP_V:
  179841. case JXFORM_ROT_180:
  179842. /* Need workspace arrays having same dimensions as source image.
  179843. * Note that we allocate arrays padded out to the next iMCU boundary,
  179844. * so that transform routines need not worry about missing edge blocks.
  179845. */
  179846. coef_arrays = (jvirt_barray_ptr *)
  179847. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179848. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179849. for (ci = 0; ci < info->num_components; ci++) {
  179850. compptr = srcinfo->comp_info + ci;
  179851. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179852. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179853. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179854. (long) compptr->h_samp_factor),
  179855. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179856. (long) compptr->v_samp_factor),
  179857. (JDIMENSION) compptr->v_samp_factor);
  179858. }
  179859. break;
  179860. case JXFORM_TRANSPOSE:
  179861. case JXFORM_TRANSVERSE:
  179862. case JXFORM_ROT_90:
  179863. case JXFORM_ROT_270:
  179864. /* Need workspace arrays having transposed dimensions.
  179865. * Note that we allocate arrays padded out to the next iMCU boundary,
  179866. * so that transform routines need not worry about missing edge blocks.
  179867. */
  179868. coef_arrays = (jvirt_barray_ptr *)
  179869. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179870. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179871. for (ci = 0; ci < info->num_components; ci++) {
  179872. compptr = srcinfo->comp_info + ci;
  179873. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179874. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179875. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179876. (long) compptr->v_samp_factor),
  179877. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179878. (long) compptr->h_samp_factor),
  179879. (JDIMENSION) compptr->h_samp_factor);
  179880. }
  179881. break;
  179882. }
  179883. info->workspace_coef_arrays = coef_arrays;
  179884. }
  179885. /* Transpose destination image parameters */
  179886. LOCAL(void)
  179887. transpose_critical_parameters (j_compress_ptr dstinfo)
  179888. {
  179889. int tblno, i, j, ci, itemp;
  179890. jpeg_component_info *compptr;
  179891. JQUANT_TBL *qtblptr;
  179892. JDIMENSION dtemp;
  179893. UINT16 qtemp;
  179894. /* Transpose basic image dimensions */
  179895. dtemp = dstinfo->image_width;
  179896. dstinfo->image_width = dstinfo->image_height;
  179897. dstinfo->image_height = dtemp;
  179898. /* Transpose sampling factors */
  179899. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179900. compptr = dstinfo->comp_info + ci;
  179901. itemp = compptr->h_samp_factor;
  179902. compptr->h_samp_factor = compptr->v_samp_factor;
  179903. compptr->v_samp_factor = itemp;
  179904. }
  179905. /* Transpose quantization tables */
  179906. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179907. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179908. if (qtblptr != NULL) {
  179909. for (i = 0; i < DCTSIZE; i++) {
  179910. for (j = 0; j < i; j++) {
  179911. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179912. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179913. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179914. }
  179915. }
  179916. }
  179917. }
  179918. }
  179919. /* Trim off any partial iMCUs on the indicated destination edge */
  179920. LOCAL(void)
  179921. trim_right_edge (j_compress_ptr dstinfo)
  179922. {
  179923. int ci, max_h_samp_factor;
  179924. JDIMENSION MCU_cols;
  179925. /* We have to compute max_h_samp_factor ourselves,
  179926. * because it hasn't been set yet in the destination
  179927. * (and we don't want to use the source's value).
  179928. */
  179929. max_h_samp_factor = 1;
  179930. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179931. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179932. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179933. }
  179934. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179935. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179936. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179937. }
  179938. LOCAL(void)
  179939. trim_bottom_edge (j_compress_ptr dstinfo)
  179940. {
  179941. int ci, max_v_samp_factor;
  179942. JDIMENSION MCU_rows;
  179943. /* We have to compute max_v_samp_factor ourselves,
  179944. * because it hasn't been set yet in the destination
  179945. * (and we don't want to use the source's value).
  179946. */
  179947. max_v_samp_factor = 1;
  179948. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179949. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179950. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179951. }
  179952. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179953. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179954. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179955. }
  179956. /* Adjust output image parameters as needed.
  179957. *
  179958. * This must be called after jpeg_copy_critical_parameters()
  179959. * and before jpeg_write_coefficients().
  179960. *
  179961. * The return value is the set of virtual coefficient arrays to be written
  179962. * (either the ones allocated by jtransform_request_workspace, or the
  179963. * original source data arrays). The caller will need to pass this value
  179964. * to jpeg_write_coefficients().
  179965. */
  179966. GLOBAL(jvirt_barray_ptr *)
  179967. jtransform_adjust_parameters (j_decompress_ptr,
  179968. j_compress_ptr dstinfo,
  179969. jvirt_barray_ptr *src_coef_arrays,
  179970. jpeg_transform_info *info)
  179971. {
  179972. /* If force-to-grayscale is requested, adjust destination parameters */
  179973. if (info->force_grayscale) {
  179974. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179975. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179976. * will get set to 1, which typically won't match the source.
  179977. * In fact we do this even if the source is already grayscale; that
  179978. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179979. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179980. */
  179981. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179982. dstinfo->num_components == 3) ||
  179983. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179984. dstinfo->num_components == 1)) {
  179985. /* We have to preserve the source's quantization table number. */
  179986. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179987. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179988. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179989. } else {
  179990. /* Sorry, can't do it */
  179991. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179992. }
  179993. }
  179994. /* Correct the destination's image dimensions etc if necessary */
  179995. switch (info->transform) {
  179996. case JXFORM_NONE:
  179997. /* Nothing to do */
  179998. break;
  179999. case JXFORM_FLIP_H:
  180000. if (info->trim)
  180001. trim_right_edge(dstinfo);
  180002. break;
  180003. case JXFORM_FLIP_V:
  180004. if (info->trim)
  180005. trim_bottom_edge(dstinfo);
  180006. break;
  180007. case JXFORM_TRANSPOSE:
  180008. transpose_critical_parameters(dstinfo);
  180009. /* transpose does NOT have to trim anything */
  180010. break;
  180011. case JXFORM_TRANSVERSE:
  180012. transpose_critical_parameters(dstinfo);
  180013. if (info->trim) {
  180014. trim_right_edge(dstinfo);
  180015. trim_bottom_edge(dstinfo);
  180016. }
  180017. break;
  180018. case JXFORM_ROT_90:
  180019. transpose_critical_parameters(dstinfo);
  180020. if (info->trim)
  180021. trim_right_edge(dstinfo);
  180022. break;
  180023. case JXFORM_ROT_180:
  180024. if (info->trim) {
  180025. trim_right_edge(dstinfo);
  180026. trim_bottom_edge(dstinfo);
  180027. }
  180028. break;
  180029. case JXFORM_ROT_270:
  180030. transpose_critical_parameters(dstinfo);
  180031. if (info->trim)
  180032. trim_bottom_edge(dstinfo);
  180033. break;
  180034. }
  180035. /* Return the appropriate output data set */
  180036. if (info->workspace_coef_arrays != NULL)
  180037. return info->workspace_coef_arrays;
  180038. return src_coef_arrays;
  180039. }
  180040. /* Execute the actual transformation, if any.
  180041. *
  180042. * This must be called *after* jpeg_write_coefficients, because it depends
  180043. * on jpeg_write_coefficients to have computed subsidiary values such as
  180044. * the per-component width and height fields in the destination object.
  180045. *
  180046. * Note that some transformations will modify the source data arrays!
  180047. */
  180048. GLOBAL(void)
  180049. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  180050. j_compress_ptr dstinfo,
  180051. jvirt_barray_ptr *src_coef_arrays,
  180052. jpeg_transform_info *info)
  180053. {
  180054. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  180055. switch (info->transform) {
  180056. case JXFORM_NONE:
  180057. break;
  180058. case JXFORM_FLIP_H:
  180059. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  180060. break;
  180061. case JXFORM_FLIP_V:
  180062. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180063. break;
  180064. case JXFORM_TRANSPOSE:
  180065. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180066. break;
  180067. case JXFORM_TRANSVERSE:
  180068. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180069. break;
  180070. case JXFORM_ROT_90:
  180071. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180072. break;
  180073. case JXFORM_ROT_180:
  180074. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180075. break;
  180076. case JXFORM_ROT_270:
  180077. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180078. break;
  180079. }
  180080. }
  180081. #endif /* TRANSFORMS_SUPPORTED */
  180082. /* Setup decompression object to save desired markers in memory.
  180083. * This must be called before jpeg_read_header() to have the desired effect.
  180084. */
  180085. GLOBAL(void)
  180086. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  180087. {
  180088. #ifdef SAVE_MARKERS_SUPPORTED
  180089. int m;
  180090. /* Save comments except under NONE option */
  180091. if (option != JCOPYOPT_NONE) {
  180092. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  180093. }
  180094. /* Save all types of APPn markers iff ALL option */
  180095. if (option == JCOPYOPT_ALL) {
  180096. for (m = 0; m < 16; m++)
  180097. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  180098. }
  180099. #endif /* SAVE_MARKERS_SUPPORTED */
  180100. }
  180101. /* Copy markers saved in the given source object to the destination object.
  180102. * This should be called just after jpeg_start_compress() or
  180103. * jpeg_write_coefficients().
  180104. * Note that those routines will have written the SOI, and also the
  180105. * JFIF APP0 or Adobe APP14 markers if selected.
  180106. */
  180107. GLOBAL(void)
  180108. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180109. JCOPY_OPTION)
  180110. {
  180111. jpeg_saved_marker_ptr marker;
  180112. /* In the current implementation, we don't actually need to examine the
  180113. * option flag here; we just copy everything that got saved.
  180114. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  180115. * if the encoder library already wrote one.
  180116. */
  180117. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180118. if (dstinfo->write_JFIF_header &&
  180119. marker->marker == JPEG_APP0 &&
  180120. marker->data_length >= 5 &&
  180121. GETJOCTET(marker->data[0]) == 0x4A &&
  180122. GETJOCTET(marker->data[1]) == 0x46 &&
  180123. GETJOCTET(marker->data[2]) == 0x49 &&
  180124. GETJOCTET(marker->data[3]) == 0x46 &&
  180125. GETJOCTET(marker->data[4]) == 0)
  180126. continue; /* reject duplicate JFIF */
  180127. if (dstinfo->write_Adobe_marker &&
  180128. marker->marker == JPEG_APP0+14 &&
  180129. marker->data_length >= 5 &&
  180130. GETJOCTET(marker->data[0]) == 0x41 &&
  180131. GETJOCTET(marker->data[1]) == 0x64 &&
  180132. GETJOCTET(marker->data[2]) == 0x6F &&
  180133. GETJOCTET(marker->data[3]) == 0x62 &&
  180134. GETJOCTET(marker->data[4]) == 0x65)
  180135. continue; /* reject duplicate Adobe */
  180136. #ifdef NEED_FAR_POINTERS
  180137. /* We could use jpeg_write_marker if the data weren't FAR... */
  180138. {
  180139. unsigned int i;
  180140. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180141. for (i = 0; i < marker->data_length; i++)
  180142. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180143. }
  180144. #else
  180145. jpeg_write_marker(dstinfo, marker->marker,
  180146. marker->data, marker->data_length);
  180147. #endif
  180148. }
  180149. }
  180150. /*** End of inlined file: transupp.c ***/
  180151. #else
  180152. #define JPEG_INTERNALS
  180153. #undef FAR
  180154. #include <jpeglib.h>
  180155. #endif
  180156. }
  180157. #undef max
  180158. #undef min
  180159. #if JUCE_MSVC
  180160. #pragma warning (pop)
  180161. #endif
  180162. BEGIN_JUCE_NAMESPACE
  180163. namespace JPEGHelpers
  180164. {
  180165. using namespace jpeglibNamespace;
  180166. #if ! JUCE_MSVC
  180167. using jpeglibNamespace::boolean;
  180168. #endif
  180169. struct JPEGDecodingFailure {};
  180170. static void fatalErrorHandler (j_common_ptr)
  180171. {
  180172. throw JPEGDecodingFailure();
  180173. }
  180174. static void silentErrorCallback1 (j_common_ptr) {}
  180175. static void silentErrorCallback2 (j_common_ptr, int) {}
  180176. static void silentErrorCallback3 (j_common_ptr, char*) {}
  180177. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180178. {
  180179. zerostruct (err);
  180180. err.error_exit = fatalErrorHandler;
  180181. err.emit_message = silentErrorCallback2;
  180182. err.output_message = silentErrorCallback1;
  180183. err.format_message = silentErrorCallback3;
  180184. err.reset_error_mgr = silentErrorCallback1;
  180185. }
  180186. static void dummyCallback1 (j_decompress_ptr)
  180187. {
  180188. }
  180189. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  180190. {
  180191. decompStruct->src->next_input_byte += num;
  180192. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180193. decompStruct->src->bytes_in_buffer -= num;
  180194. }
  180195. static boolean jpegFill (j_decompress_ptr)
  180196. {
  180197. return 0;
  180198. }
  180199. static const int jpegBufferSize = 512;
  180200. struct JuceJpegDest : public jpeg_destination_mgr
  180201. {
  180202. OutputStream* output;
  180203. char* buffer;
  180204. };
  180205. static void jpegWriteInit (j_compress_ptr)
  180206. {
  180207. }
  180208. static void jpegWriteTerminate (j_compress_ptr cinfo)
  180209. {
  180210. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180211. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180212. dest->output->write (dest->buffer, (int) numToWrite);
  180213. }
  180214. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  180215. {
  180216. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180217. const int numToWrite = jpegBufferSize;
  180218. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180219. dest->free_in_buffer = jpegBufferSize;
  180220. return dest->output->write (dest->buffer, numToWrite);
  180221. }
  180222. }
  180223. JPEGImageFormat::JPEGImageFormat()
  180224. : quality (-1.0f)
  180225. {
  180226. }
  180227. JPEGImageFormat::~JPEGImageFormat() {}
  180228. void JPEGImageFormat::setQuality (const float newQuality)
  180229. {
  180230. quality = newQuality;
  180231. }
  180232. const String JPEGImageFormat::getFormatName()
  180233. {
  180234. return "JPEG";
  180235. }
  180236. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180237. {
  180238. const int bytesNeeded = 10;
  180239. uint8 header [bytesNeeded];
  180240. if (in.read (header, bytesNeeded) == bytesNeeded)
  180241. {
  180242. return header[0] == 0xff
  180243. && header[1] == 0xd8
  180244. && header[2] == 0xff
  180245. && (header[3] == 0xe0 || header[3] == 0xe1);
  180246. }
  180247. return false;
  180248. }
  180249. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180250. const Image juce_loadWithCoreImage (InputStream& input);
  180251. #endif
  180252. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180253. {
  180254. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180255. return juce_loadWithCoreImage (in);
  180256. #else
  180257. using namespace jpeglibNamespace;
  180258. using namespace JPEGHelpers;
  180259. MemoryOutputStream mb;
  180260. mb.writeFromInputStream (in, -1);
  180261. Image image;
  180262. if (mb.getDataSize() > 16)
  180263. {
  180264. struct jpeg_decompress_struct jpegDecompStruct;
  180265. struct jpeg_error_mgr jerr;
  180266. setupSilentErrorHandler (jerr);
  180267. jpegDecompStruct.err = &jerr;
  180268. jpeg_create_decompress (&jpegDecompStruct);
  180269. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180270. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180271. jpegDecompStruct.src->init_source = dummyCallback1;
  180272. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180273. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180274. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180275. jpegDecompStruct.src->term_source = dummyCallback1;
  180276. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180277. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180278. try
  180279. {
  180280. jpeg_read_header (&jpegDecompStruct, TRUE);
  180281. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180282. const int width = jpegDecompStruct.output_width;
  180283. const int height = jpegDecompStruct.output_height;
  180284. jpegDecompStruct.out_color_space = JCS_RGB;
  180285. JSAMPARRAY buffer
  180286. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180287. JPOOL_IMAGE,
  180288. width * 3, 1);
  180289. if (jpeg_start_decompress (&jpegDecompStruct))
  180290. {
  180291. image = Image (Image::RGB, width, height, false);
  180292. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180293. const Image::BitmapData destData (image, true);
  180294. for (int y = 0; y < height; ++y)
  180295. {
  180296. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180297. const uint8* src = *buffer;
  180298. uint8* dest = destData.getLinePointer (y);
  180299. if (hasAlphaChan)
  180300. {
  180301. for (int i = width; --i >= 0;)
  180302. {
  180303. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180304. ((PixelARGB*) dest)->premultiply();
  180305. dest += destData.pixelStride;
  180306. src += 3;
  180307. }
  180308. }
  180309. else
  180310. {
  180311. for (int i = width; --i >= 0;)
  180312. {
  180313. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180314. dest += destData.pixelStride;
  180315. src += 3;
  180316. }
  180317. }
  180318. }
  180319. jpeg_finish_decompress (&jpegDecompStruct);
  180320. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180321. }
  180322. jpeg_destroy_decompress (&jpegDecompStruct);
  180323. }
  180324. catch (...)
  180325. {}
  180326. }
  180327. return image;
  180328. #endif
  180329. }
  180330. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180331. {
  180332. using namespace jpeglibNamespace;
  180333. using namespace JPEGHelpers;
  180334. if (image.hasAlphaChannel())
  180335. {
  180336. // this method could fill the background in white and still save the image..
  180337. jassertfalse;
  180338. return true;
  180339. }
  180340. struct jpeg_compress_struct jpegCompStruct;
  180341. struct jpeg_error_mgr jerr;
  180342. setupSilentErrorHandler (jerr);
  180343. jpegCompStruct.err = &jerr;
  180344. jpeg_create_compress (&jpegCompStruct);
  180345. JuceJpegDest dest;
  180346. jpegCompStruct.dest = &dest;
  180347. dest.output = &out;
  180348. HeapBlock <char> tempBuffer (jpegBufferSize);
  180349. dest.buffer = tempBuffer;
  180350. dest.next_output_byte = (JOCTET*) dest.buffer;
  180351. dest.free_in_buffer = jpegBufferSize;
  180352. dest.init_destination = jpegWriteInit;
  180353. dest.empty_output_buffer = jpegWriteFlush;
  180354. dest.term_destination = jpegWriteTerminate;
  180355. jpegCompStruct.image_width = image.getWidth();
  180356. jpegCompStruct.image_height = image.getHeight();
  180357. jpegCompStruct.input_components = 3;
  180358. jpegCompStruct.in_color_space = JCS_RGB;
  180359. jpegCompStruct.write_JFIF_header = 1;
  180360. jpegCompStruct.X_density = 72;
  180361. jpegCompStruct.Y_density = 72;
  180362. jpeg_set_defaults (&jpegCompStruct);
  180363. jpegCompStruct.dct_method = JDCT_FLOAT;
  180364. jpegCompStruct.optimize_coding = 1;
  180365. //jpegCompStruct.smoothing_factor = 10;
  180366. if (quality < 0.0f)
  180367. quality = 0.85f;
  180368. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180369. jpeg_start_compress (&jpegCompStruct, TRUE);
  180370. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180371. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180372. JPOOL_IMAGE, strideBytes, 1);
  180373. const Image::BitmapData srcData (image, false);
  180374. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180375. {
  180376. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180377. uint8* dst = *buffer;
  180378. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180379. {
  180380. *dst++ = ((const PixelRGB*) src)->getRed();
  180381. *dst++ = ((const PixelRGB*) src)->getGreen();
  180382. *dst++ = ((const PixelRGB*) src)->getBlue();
  180383. src += srcData.pixelStride;
  180384. }
  180385. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180386. }
  180387. jpeg_finish_compress (&jpegCompStruct);
  180388. jpeg_destroy_compress (&jpegCompStruct);
  180389. out.flush();
  180390. return true;
  180391. }
  180392. END_JUCE_NAMESPACE
  180393. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180394. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180395. #if JUCE_MSVC
  180396. #pragma warning (push)
  180397. #pragma warning (disable: 4390 4611)
  180398. #endif
  180399. namespace zlibNamespace
  180400. {
  180401. #if JUCE_INCLUDE_ZLIB_CODE
  180402. #undef OS_CODE
  180403. #undef fdopen
  180404. #undef OS_CODE
  180405. #else
  180406. #include <zlib.h>
  180407. #endif
  180408. }
  180409. namespace pnglibNamespace
  180410. {
  180411. using namespace zlibNamespace;
  180412. #if JUCE_INCLUDE_PNGLIB_CODE
  180413. #if _MSC_VER != 1310
  180414. using ::calloc; // (causes conflict in VS.NET 2003)
  180415. using ::malloc;
  180416. using ::free;
  180417. #endif
  180418. using ::abs;
  180419. #define PNG_INTERNAL
  180420. #define NO_DUMMY_DECL
  180421. #define PNG_SETJMP_NOT_SUPPORTED
  180422. /*** Start of inlined file: png.h ***/
  180423. /* png.h - header file for PNG reference library
  180424. *
  180425. * libpng version 1.2.21 - October 4, 2007
  180426. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180427. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180428. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180429. *
  180430. * Authors and maintainers:
  180431. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180432. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180433. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180434. * See also "Contributing Authors", below.
  180435. *
  180436. * Note about libpng version numbers:
  180437. *
  180438. * Due to various miscommunications, unforeseen code incompatibilities
  180439. * and occasional factors outside the authors' control, version numbering
  180440. * on the library has not always been consistent and straightforward.
  180441. * The following table summarizes matters since version 0.89c, which was
  180442. * the first widely used release:
  180443. *
  180444. * source png.h png.h shared-lib
  180445. * version string int version
  180446. * ------- ------ ----- ----------
  180447. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180448. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180449. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180450. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180451. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180452. * 0.97c 0.97 97 2.0.97
  180453. * 0.98 0.98 98 2.0.98
  180454. * 0.99 0.99 98 2.0.99
  180455. * 0.99a-m 0.99 99 2.0.99
  180456. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180457. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180458. * 1.0.1 png.h string is 10001 2.1.0
  180459. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180460. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180461. * 1.0.2a-b 10003 version, except as noted.
  180462. * 1.0.3 10003
  180463. * 1.0.3a-d 10004
  180464. * 1.0.4 10004
  180465. * 1.0.4a-f 10005
  180466. * 1.0.5 (+ 2 patches) 10005
  180467. * 1.0.5a-d 10006
  180468. * 1.0.5e-r 10100 (not source compatible)
  180469. * 1.0.5s-v 10006 (not binary compatible)
  180470. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180471. * 1.0.6d-f 10007 (still binary incompatible)
  180472. * 1.0.6g 10007
  180473. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180474. * 1.0.6i 10007 10.6i
  180475. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180476. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180477. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180478. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180479. * 1.0.7 1 10007 (still compatible)
  180480. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180481. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180482. * 1.0.8 1 10008 2.1.0.8
  180483. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180484. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180485. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180486. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180487. * 1.0.9 1 10009 2.1.0.9
  180488. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180489. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180490. * 1.0.10 1 10010 2.1.0.10
  180491. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180492. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180493. * 1.0.11 1 10011 2.1.0.11
  180494. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180495. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180496. * 1.0.12 2 10012 2.1.0.12
  180497. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180498. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180499. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180500. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180501. * 1.2.0 3 10200 3.1.2.0
  180502. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180503. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180504. * 1.2.1 3 10201 3.1.2.1
  180505. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180506. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180507. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180508. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180509. * 1.0.13 10 10013 10.so.0.1.0.13
  180510. * 1.2.2 12 10202 12.so.0.1.2.2
  180511. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180512. * 1.2.3 12 10203 12.so.0.1.2.3
  180513. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180514. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180515. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180516. * 1.0.14 10 10014 10.so.0.1.0.14
  180517. * 1.2.4 13 10204 12.so.0.1.2.4
  180518. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180519. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180520. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180521. * 1.0.15 10 10015 10.so.0.1.0.15
  180522. * 1.2.5 13 10205 12.so.0.1.2.5
  180523. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180524. * 1.0.16 10 10016 10.so.0.1.0.16
  180525. * 1.2.6 13 10206 12.so.0.1.2.6
  180526. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180527. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180528. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180529. * 1.0.17 10 10017 10.so.0.1.0.17
  180530. * 1.2.7 13 10207 12.so.0.1.2.7
  180531. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180532. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180533. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180534. * 1.0.18 10 10018 10.so.0.1.0.18
  180535. * 1.2.8 13 10208 12.so.0.1.2.8
  180536. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180537. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180538. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180539. * 1.2.9 13 10209 12.so.0.9[.0]
  180540. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180541. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180542. * 1.2.10 13 10210 12.so.0.10[.0]
  180543. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180544. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180545. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180546. * 1.0.19 10 10019 10.so.0.19[.0]
  180547. * 1.2.11 13 10211 12.so.0.11[.0]
  180548. * 1.0.20 10 10020 10.so.0.20[.0]
  180549. * 1.2.12 13 10212 12.so.0.12[.0]
  180550. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180551. * 1.0.21 10 10021 10.so.0.21[.0]
  180552. * 1.2.13 13 10213 12.so.0.13[.0]
  180553. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180554. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180555. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180556. * 1.0.22 10 10022 10.so.0.22[.0]
  180557. * 1.2.14 13 10214 12.so.0.14[.0]
  180558. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180559. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180560. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180561. * 1.0.23 10 10023 10.so.0.23[.0]
  180562. * 1.2.15 13 10215 12.so.0.15[.0]
  180563. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180564. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180565. * 1.0.24 10 10024 10.so.0.24[.0]
  180566. * 1.2.16 13 10216 12.so.0.16[.0]
  180567. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180568. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180569. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180570. * 1.0.25 10 10025 10.so.0.25[.0]
  180571. * 1.2.17 13 10217 12.so.0.17[.0]
  180572. * 1.0.26 10 10026 10.so.0.26[.0]
  180573. * 1.2.18 13 10218 12.so.0.18[.0]
  180574. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180575. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180576. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180577. * 1.0.27 10 10027 10.so.0.27[.0]
  180578. * 1.2.19 13 10219 12.so.0.19[.0]
  180579. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180580. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180581. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180582. * 1.0.28 10 10028 10.so.0.28[.0]
  180583. * 1.2.20 13 10220 12.so.0.20[.0]
  180584. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180585. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180586. * 1.0.29 10 10029 10.so.0.29[.0]
  180587. * 1.2.21 13 10221 12.so.0.21[.0]
  180588. *
  180589. * Henceforth the source version will match the shared-library major
  180590. * and minor numbers; the shared-library major version number will be
  180591. * used for changes in backward compatibility, as it is intended. The
  180592. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180593. * for applications, is an unsigned integer of the form xyyzz corresponding
  180594. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180595. * were given the previous public release number plus a letter, until
  180596. * version 1.0.6j; from then on they were given the upcoming public
  180597. * release number plus "betaNN" or "rcN".
  180598. *
  180599. * Binary incompatibility exists only when applications make direct access
  180600. * to the info_ptr or png_ptr members through png.h, and the compiled
  180601. * application is loaded with a different version of the library.
  180602. *
  180603. * DLLNUM will change each time there are forward or backward changes
  180604. * in binary compatibility (e.g., when a new feature is added).
  180605. *
  180606. * See libpng.txt or libpng.3 for more information. The PNG specification
  180607. * is available as a W3C Recommendation and as an ISO Specification,
  180608. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180609. */
  180610. /*
  180611. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180612. *
  180613. * If you modify libpng you may insert additional notices immediately following
  180614. * this sentence.
  180615. *
  180616. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180617. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180618. * distributed according to the same disclaimer and license as libpng-1.2.5
  180619. * with the following individual added to the list of Contributing Authors:
  180620. *
  180621. * Cosmin Truta
  180622. *
  180623. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180624. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180625. * distributed according to the same disclaimer and license as libpng-1.0.6
  180626. * with the following individuals added to the list of Contributing Authors:
  180627. *
  180628. * Simon-Pierre Cadieux
  180629. * Eric S. Raymond
  180630. * Gilles Vollant
  180631. *
  180632. * and with the following additions to the disclaimer:
  180633. *
  180634. * There is no warranty against interference with your enjoyment of the
  180635. * library or against infringement. There is no warranty that our
  180636. * efforts or the library will fulfill any of your particular purposes
  180637. * or needs. This library is provided with all faults, and the entire
  180638. * risk of satisfactory quality, performance, accuracy, and effort is with
  180639. * the user.
  180640. *
  180641. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180642. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180643. * distributed according to the same disclaimer and license as libpng-0.96,
  180644. * with the following individuals added to the list of Contributing Authors:
  180645. *
  180646. * Tom Lane
  180647. * Glenn Randers-Pehrson
  180648. * Willem van Schaik
  180649. *
  180650. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180651. * Copyright (c) 1996, 1997 Andreas Dilger
  180652. * Distributed according to the same disclaimer and license as libpng-0.88,
  180653. * with the following individuals added to the list of Contributing Authors:
  180654. *
  180655. * John Bowler
  180656. * Kevin Bracey
  180657. * Sam Bushell
  180658. * Magnus Holmgren
  180659. * Greg Roelofs
  180660. * Tom Tanner
  180661. *
  180662. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180663. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180664. *
  180665. * For the purposes of this copyright and license, "Contributing Authors"
  180666. * is defined as the following set of individuals:
  180667. *
  180668. * Andreas Dilger
  180669. * Dave Martindale
  180670. * Guy Eric Schalnat
  180671. * Paul Schmidt
  180672. * Tim Wegner
  180673. *
  180674. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180675. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180676. * including, without limitation, the warranties of merchantability and of
  180677. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180678. * assume no liability for direct, indirect, incidental, special, exemplary,
  180679. * or consequential damages, which may result from the use of the PNG
  180680. * Reference Library, even if advised of the possibility of such damage.
  180681. *
  180682. * Permission is hereby granted to use, copy, modify, and distribute this
  180683. * source code, or portions hereof, for any purpose, without fee, subject
  180684. * to the following restrictions:
  180685. *
  180686. * 1. The origin of this source code must not be misrepresented.
  180687. *
  180688. * 2. Altered versions must be plainly marked as such and
  180689. * must not be misrepresented as being the original source.
  180690. *
  180691. * 3. This Copyright notice may not be removed or altered from
  180692. * any source or altered source distribution.
  180693. *
  180694. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180695. * fee, and encourage the use of this source code as a component to
  180696. * supporting the PNG file format in commercial products. If you use this
  180697. * source code in a product, acknowledgment is not required but would be
  180698. * appreciated.
  180699. */
  180700. /*
  180701. * A "png_get_copyright" function is available, for convenient use in "about"
  180702. * boxes and the like:
  180703. *
  180704. * printf("%s",png_get_copyright(NULL));
  180705. *
  180706. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180707. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180708. */
  180709. /*
  180710. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180711. * certification mark of the Open Source Initiative.
  180712. */
  180713. /*
  180714. * The contributing authors would like to thank all those who helped
  180715. * with testing, bug fixes, and patience. This wouldn't have been
  180716. * possible without all of you.
  180717. *
  180718. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180719. */
  180720. /*
  180721. * Y2K compliance in libpng:
  180722. * =========================
  180723. *
  180724. * October 4, 2007
  180725. *
  180726. * Since the PNG Development group is an ad-hoc body, we can't make
  180727. * an official declaration.
  180728. *
  180729. * This is your unofficial assurance that libpng from version 0.71 and
  180730. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180731. * versions were also Y2K compliant.
  180732. *
  180733. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180734. * that will hold years up to 65535. The other two hold the date in text
  180735. * format, and will hold years up to 9999.
  180736. *
  180737. * The integer is
  180738. * "png_uint_16 year" in png_time_struct.
  180739. *
  180740. * The strings are
  180741. * "png_charp time_buffer" in png_struct and
  180742. * "near_time_buffer", which is a local character string in png.c.
  180743. *
  180744. * There are seven time-related functions:
  180745. * png.c: png_convert_to_rfc_1123() in png.c
  180746. * (formerly png_convert_to_rfc_1152() in error)
  180747. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180748. * png_convert_from_time_t() in pngwrite.c
  180749. * png_get_tIME() in pngget.c
  180750. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180751. * png_set_tIME() in pngset.c
  180752. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180753. *
  180754. * All handle dates properly in a Y2K environment. The
  180755. * png_convert_from_time_t() function calls gmtime() to convert from system
  180756. * clock time, which returns (year - 1900), which we properly convert to
  180757. * the full 4-digit year. There is a possibility that applications using
  180758. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180759. * function, or that they are incorrectly passing only a 2-digit year
  180760. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180761. * but this is not under our control. The libpng documentation has always
  180762. * stated that it works with 4-digit years, and the APIs have been
  180763. * documented as such.
  180764. *
  180765. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180766. * integer to hold the year, and can hold years as large as 65535.
  180767. *
  180768. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180769. * no date-related code.
  180770. *
  180771. * Glenn Randers-Pehrson
  180772. * libpng maintainer
  180773. * PNG Development Group
  180774. */
  180775. #ifndef PNG_H
  180776. #define PNG_H
  180777. /* This is not the place to learn how to use libpng. The file libpng.txt
  180778. * describes how to use libpng, and the file example.c summarizes it
  180779. * with some code on which to build. This file is useful for looking
  180780. * at the actual function definitions and structure components.
  180781. */
  180782. /* Version information for png.h - this should match the version in png.c */
  180783. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180784. #define PNG_HEADER_VERSION_STRING \
  180785. " libpng version 1.2.21 - October 4, 2007\n"
  180786. #define PNG_LIBPNG_VER_SONUM 0
  180787. #define PNG_LIBPNG_VER_DLLNUM 13
  180788. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180789. #define PNG_LIBPNG_VER_MAJOR 1
  180790. #define PNG_LIBPNG_VER_MINOR 2
  180791. #define PNG_LIBPNG_VER_RELEASE 21
  180792. /* This should match the numeric part of the final component of
  180793. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180794. #define PNG_LIBPNG_VER_BUILD 0
  180795. /* Release Status */
  180796. #define PNG_LIBPNG_BUILD_ALPHA 1
  180797. #define PNG_LIBPNG_BUILD_BETA 2
  180798. #define PNG_LIBPNG_BUILD_RC 3
  180799. #define PNG_LIBPNG_BUILD_STABLE 4
  180800. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180801. /* Release-Specific Flags */
  180802. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180803. PNG_LIBPNG_BUILD_STABLE only */
  180804. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180805. PNG_LIBPNG_BUILD_SPECIAL */
  180806. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180807. PNG_LIBPNG_BUILD_PRIVATE */
  180808. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180809. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180810. * We must not include leading zeros.
  180811. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180812. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180813. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180814. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180815. #ifndef PNG_VERSION_INFO_ONLY
  180816. /* include the compression library's header */
  180817. #endif
  180818. /* include all user configurable info, including optional assembler routines */
  180819. /*** Start of inlined file: pngconf.h ***/
  180820. /* pngconf.h - machine configurable file for libpng
  180821. *
  180822. * libpng version 1.2.21 - October 4, 2007
  180823. * For conditions of distribution and use, see copyright notice in png.h
  180824. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180825. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180826. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180827. */
  180828. /* Any machine specific code is near the front of this file, so if you
  180829. * are configuring libpng for a machine, you may want to read the section
  180830. * starting here down to where it starts to typedef png_color, png_text,
  180831. * and png_info.
  180832. */
  180833. #ifndef PNGCONF_H
  180834. #define PNGCONF_H
  180835. #define PNG_1_2_X
  180836. // These are some Juce config settings that should remove any unnecessary code bloat..
  180837. #define PNG_NO_STDIO 1
  180838. #define PNG_DEBUG 0
  180839. #define PNG_NO_WARNINGS 1
  180840. #define PNG_NO_ERROR_TEXT 1
  180841. #define PNG_NO_ERROR_NUMBERS 1
  180842. #define PNG_NO_USER_MEM 1
  180843. #define PNG_NO_READ_iCCP 1
  180844. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180845. #define PNG_NO_READ_USER_CHUNKS 1
  180846. #define PNG_NO_READ_iTXt 1
  180847. #define PNG_NO_READ_sCAL 1
  180848. #define PNG_NO_READ_sPLT 1
  180849. #define png_error(a, b) png_err(a)
  180850. #define png_warning(a, b)
  180851. #define png_chunk_error(a, b) png_err(a)
  180852. #define png_chunk_warning(a, b)
  180853. /*
  180854. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180855. * includes the resource compiler for Windows DLL configurations.
  180856. */
  180857. #ifdef PNG_USER_CONFIG
  180858. # ifndef PNG_USER_PRIVATEBUILD
  180859. # define PNG_USER_PRIVATEBUILD
  180860. # endif
  180861. #include "pngusr.h"
  180862. #endif
  180863. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180864. #ifdef PNG_CONFIGURE_LIBPNG
  180865. #ifdef HAVE_CONFIG_H
  180866. #include "config.h"
  180867. #endif
  180868. #endif
  180869. /*
  180870. * Added at libpng-1.2.8
  180871. *
  180872. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180873. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180874. * the DLL was built>
  180875. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180876. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180877. * distinguish your DLL from those of the official release. These
  180878. * correspond to the trailing letters that come after the version
  180879. * number and must match your private DLL name>
  180880. * e.g. // private DLL "libpng13gx.dll"
  180881. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180882. *
  180883. * The following macros are also at your disposal if you want to complete the
  180884. * DLL VERSIONINFO structure.
  180885. * - PNG_USER_VERSIONINFO_COMMENTS
  180886. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180887. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180888. */
  180889. #ifdef __STDC__
  180890. #ifdef SPECIALBUILD
  180891. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180892. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180893. #endif
  180894. #ifdef PRIVATEBUILD
  180895. # pragma message("PRIVATEBUILD is deprecated.\
  180896. Use PNG_USER_PRIVATEBUILD instead.")
  180897. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180898. #endif
  180899. #endif /* __STDC__ */
  180900. #ifndef PNG_VERSION_INFO_ONLY
  180901. /* End of material added to libpng-1.2.8 */
  180902. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180903. Restored at libpng-1.2.21 */
  180904. # define PNG_WARN_UNINITIALIZED_ROW 1
  180905. /* End of material added at libpng-1.2.19/1.2.21 */
  180906. /* This is the size of the compression buffer, and thus the size of
  180907. * an IDAT chunk. Make this whatever size you feel is best for your
  180908. * machine. One of these will be allocated per png_struct. When this
  180909. * is full, it writes the data to the disk, and does some other
  180910. * calculations. Making this an extremely small size will slow
  180911. * the library down, but you may want to experiment to determine
  180912. * where it becomes significant, if you are concerned with memory
  180913. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180914. * this describes the size of the buffer available to read the data in.
  180915. * Unless this gets smaller than the size of a row (compressed),
  180916. * it should not make much difference how big this is.
  180917. */
  180918. #ifndef PNG_ZBUF_SIZE
  180919. # define PNG_ZBUF_SIZE 8192
  180920. #endif
  180921. /* Enable if you want a write-only libpng */
  180922. #ifndef PNG_NO_READ_SUPPORTED
  180923. # define PNG_READ_SUPPORTED
  180924. #endif
  180925. /* Enable if you want a read-only libpng */
  180926. #ifndef PNG_NO_WRITE_SUPPORTED
  180927. # define PNG_WRITE_SUPPORTED
  180928. #endif
  180929. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180930. support PNGs that are embedded in MNG datastreams */
  180931. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180932. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180933. # define PNG_MNG_FEATURES_SUPPORTED
  180934. # endif
  180935. #endif
  180936. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180937. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180938. # define PNG_FLOATING_POINT_SUPPORTED
  180939. # endif
  180940. #endif
  180941. /* If you are running on a machine where you cannot allocate more
  180942. * than 64K of memory at once, uncomment this. While libpng will not
  180943. * normally need that much memory in a chunk (unless you load up a very
  180944. * large file), zlib needs to know how big of a chunk it can use, and
  180945. * libpng thus makes sure to check any memory allocation to verify it
  180946. * will fit into memory.
  180947. #define PNG_MAX_MALLOC_64K
  180948. */
  180949. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180950. # define PNG_MAX_MALLOC_64K
  180951. #endif
  180952. /* Special munging to support doing things the 'cygwin' way:
  180953. * 'Normal' png-on-win32 defines/defaults:
  180954. * PNG_BUILD_DLL -- building dll
  180955. * PNG_USE_DLL -- building an application, linking to dll
  180956. * (no define) -- building static library, or building an
  180957. * application and linking to the static lib
  180958. * 'Cygwin' defines/defaults:
  180959. * PNG_BUILD_DLL -- (ignored) building the dll
  180960. * (no define) -- (ignored) building an application, linking to the dll
  180961. * PNG_STATIC -- (ignored) building the static lib, or building an
  180962. * application that links to the static lib.
  180963. * ALL_STATIC -- (ignored) building various static libs, or building an
  180964. * application that links to the static libs.
  180965. * Thus,
  180966. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180967. * this bit of #ifdefs will define the 'correct' config variables based on
  180968. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180969. * unnecessary.
  180970. *
  180971. * Also, the precedence order is:
  180972. * ALL_STATIC (since we can't #undef something outside our namespace)
  180973. * PNG_BUILD_DLL
  180974. * PNG_STATIC
  180975. * (nothing) == PNG_USE_DLL
  180976. *
  180977. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180978. * of auto-import in binutils, we no longer need to worry about
  180979. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180980. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180981. * to __declspec() stuff. However, we DO need to worry about
  180982. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180983. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180984. */
  180985. #if defined(__CYGWIN__)
  180986. # if defined(ALL_STATIC)
  180987. # if defined(PNG_BUILD_DLL)
  180988. # undef PNG_BUILD_DLL
  180989. # endif
  180990. # if defined(PNG_USE_DLL)
  180991. # undef PNG_USE_DLL
  180992. # endif
  180993. # if defined(PNG_DLL)
  180994. # undef PNG_DLL
  180995. # endif
  180996. # if !defined(PNG_STATIC)
  180997. # define PNG_STATIC
  180998. # endif
  180999. # else
  181000. # if defined (PNG_BUILD_DLL)
  181001. # if defined(PNG_STATIC)
  181002. # undef PNG_STATIC
  181003. # endif
  181004. # if defined(PNG_USE_DLL)
  181005. # undef PNG_USE_DLL
  181006. # endif
  181007. # if !defined(PNG_DLL)
  181008. # define PNG_DLL
  181009. # endif
  181010. # else
  181011. # if defined(PNG_STATIC)
  181012. # if defined(PNG_USE_DLL)
  181013. # undef PNG_USE_DLL
  181014. # endif
  181015. # if defined(PNG_DLL)
  181016. # undef PNG_DLL
  181017. # endif
  181018. # else
  181019. # if !defined(PNG_USE_DLL)
  181020. # define PNG_USE_DLL
  181021. # endif
  181022. # if !defined(PNG_DLL)
  181023. # define PNG_DLL
  181024. # endif
  181025. # endif
  181026. # endif
  181027. # endif
  181028. #endif
  181029. /* This protects us against compilers that run on a windowing system
  181030. * and thus don't have or would rather us not use the stdio types:
  181031. * stdin, stdout, and stderr. The only one currently used is stderr
  181032. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  181033. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  181034. * will also prevent these, plus will prevent the entire set of stdio
  181035. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  181036. * unless (PNG_DEBUG > 0) has been #defined.
  181037. *
  181038. * #define PNG_NO_CONSOLE_IO
  181039. * #define PNG_NO_STDIO
  181040. */
  181041. #if defined(_WIN32_WCE)
  181042. # include <windows.h>
  181043. /* Console I/O functions are not supported on WindowsCE */
  181044. # define PNG_NO_CONSOLE_IO
  181045. # ifdef PNG_DEBUG
  181046. # undef PNG_DEBUG
  181047. # endif
  181048. #endif
  181049. #ifdef PNG_BUILD_DLL
  181050. # ifndef PNG_CONSOLE_IO_SUPPORTED
  181051. # ifndef PNG_NO_CONSOLE_IO
  181052. # define PNG_NO_CONSOLE_IO
  181053. # endif
  181054. # endif
  181055. #endif
  181056. # ifdef PNG_NO_STDIO
  181057. # ifndef PNG_NO_CONSOLE_IO
  181058. # define PNG_NO_CONSOLE_IO
  181059. # endif
  181060. # ifdef PNG_DEBUG
  181061. # if (PNG_DEBUG > 0)
  181062. # include <stdio.h>
  181063. # endif
  181064. # endif
  181065. # else
  181066. # if !defined(_WIN32_WCE)
  181067. /* "stdio.h" functions are not supported on WindowsCE */
  181068. # include <stdio.h>
  181069. # endif
  181070. # endif
  181071. /* This macro protects us against machines that don't have function
  181072. * prototypes (ie K&R style headers). If your compiler does not handle
  181073. * function prototypes, define this macro and use the included ansi2knr.
  181074. * I've always been able to use _NO_PROTO as the indicator, but you may
  181075. * need to drag the empty declaration out in front of here, or change the
  181076. * ifdef to suit your own needs.
  181077. */
  181078. #ifndef PNGARG
  181079. #ifdef OF /* zlib prototype munger */
  181080. # define PNGARG(arglist) OF(arglist)
  181081. #else
  181082. #ifdef _NO_PROTO
  181083. # define PNGARG(arglist) ()
  181084. # ifndef PNG_TYPECAST_NULL
  181085. # define PNG_TYPECAST_NULL
  181086. # endif
  181087. #else
  181088. # define PNGARG(arglist) arglist
  181089. #endif /* _NO_PROTO */
  181090. #endif /* OF */
  181091. #endif /* PNGARG */
  181092. /* Try to determine if we are compiling on a Mac. Note that testing for
  181093. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  181094. * on non-Mac platforms.
  181095. */
  181096. #ifndef MACOS
  181097. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  181098. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  181099. # define MACOS
  181100. # endif
  181101. #endif
  181102. /* enough people need this for various reasons to include it here */
  181103. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  181104. # include <sys/types.h>
  181105. #endif
  181106. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  181107. # define PNG_SETJMP_SUPPORTED
  181108. #endif
  181109. #ifdef PNG_SETJMP_SUPPORTED
  181110. /* This is an attempt to force a single setjmp behaviour on Linux. If
  181111. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  181112. */
  181113. # ifdef __linux__
  181114. # ifdef _BSD_SOURCE
  181115. # define PNG_SAVE_BSD_SOURCE
  181116. # undef _BSD_SOURCE
  181117. # endif
  181118. # ifdef _SETJMP_H
  181119. /* If you encounter a compiler error here, see the explanation
  181120. * near the end of INSTALL.
  181121. */
  181122. __png.h__ already includes setjmp.h;
  181123. __dont__ include it again.;
  181124. # endif
  181125. # endif /* __linux__ */
  181126. /* include setjmp.h for error handling */
  181127. # include <setjmp.h>
  181128. # ifdef __linux__
  181129. # ifdef PNG_SAVE_BSD_SOURCE
  181130. # define _BSD_SOURCE
  181131. # undef PNG_SAVE_BSD_SOURCE
  181132. # endif
  181133. # endif /* __linux__ */
  181134. #endif /* PNG_SETJMP_SUPPORTED */
  181135. #ifdef BSD
  181136. #if ! JUCE_MAC
  181137. # include <strings.h>
  181138. #endif
  181139. #else
  181140. # include <string.h>
  181141. #endif
  181142. /* Other defines for things like memory and the like can go here. */
  181143. #ifdef PNG_INTERNAL
  181144. #include <stdlib.h>
  181145. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181146. * aren't usually used outside the library (as far as I know), so it is
  181147. * debatable if they should be exported at all. In the future, when it is
  181148. * possible to have run-time registry of chunk-handling functions, some of
  181149. * these will be made available again.
  181150. #define PNG_EXTERN extern
  181151. */
  181152. #define PNG_EXTERN
  181153. /* Other defines specific to compilers can go here. Try to keep
  181154. * them inside an appropriate ifdef/endif pair for portability.
  181155. */
  181156. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181157. # if defined(MACOS)
  181158. /* We need to check that <math.h> hasn't already been included earlier
  181159. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181160. * <fp.h> if possible.
  181161. */
  181162. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181163. # include <fp.h>
  181164. # endif
  181165. # else
  181166. # include <math.h>
  181167. # endif
  181168. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181169. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181170. * MATH=68881
  181171. */
  181172. # include <m68881.h>
  181173. # endif
  181174. #endif
  181175. /* Codewarrior on NT has linking problems without this. */
  181176. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181177. # define PNG_ALWAYS_EXTERN
  181178. #endif
  181179. /* This provides the non-ANSI (far) memory allocation routines. */
  181180. #if defined(__TURBOC__) && defined(__MSDOS__)
  181181. # include <mem.h>
  181182. # include <alloc.h>
  181183. #endif
  181184. /* I have no idea why is this necessary... */
  181185. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181186. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181187. # include <malloc.h>
  181188. #endif
  181189. /* This controls how fine the dithering gets. As this allocates
  181190. * a largish chunk of memory (32K), those who are not as concerned
  181191. * with dithering quality can decrease some or all of these.
  181192. */
  181193. #ifndef PNG_DITHER_RED_BITS
  181194. # define PNG_DITHER_RED_BITS 5
  181195. #endif
  181196. #ifndef PNG_DITHER_GREEN_BITS
  181197. # define PNG_DITHER_GREEN_BITS 5
  181198. #endif
  181199. #ifndef PNG_DITHER_BLUE_BITS
  181200. # define PNG_DITHER_BLUE_BITS 5
  181201. #endif
  181202. /* This controls how fine the gamma correction becomes when you
  181203. * are only interested in 8 bits anyway. Increasing this value
  181204. * results in more memory being used, and more pow() functions
  181205. * being called to fill in the gamma tables. Don't set this value
  181206. * less then 8, and even that may not work (I haven't tested it).
  181207. */
  181208. #ifndef PNG_MAX_GAMMA_8
  181209. # define PNG_MAX_GAMMA_8 11
  181210. #endif
  181211. /* This controls how much a difference in gamma we can tolerate before
  181212. * we actually start doing gamma conversion.
  181213. */
  181214. #ifndef PNG_GAMMA_THRESHOLD
  181215. # define PNG_GAMMA_THRESHOLD 0.05
  181216. #endif
  181217. #endif /* PNG_INTERNAL */
  181218. /* The following uses const char * instead of char * for error
  181219. * and warning message functions, so some compilers won't complain.
  181220. * If you do not want to use const, define PNG_NO_CONST here.
  181221. */
  181222. #ifndef PNG_NO_CONST
  181223. # define PNG_CONST const
  181224. #else
  181225. # define PNG_CONST
  181226. #endif
  181227. /* The following defines give you the ability to remove code from the
  181228. * library that you will not be using. I wish I could figure out how to
  181229. * automate this, but I can't do that without making it seriously hard
  181230. * on the users. So if you are not using an ability, change the #define
  181231. * to and #undef, and that part of the library will not be compiled. If
  181232. * your linker can't find a function, you may want to make sure the
  181233. * ability is defined here. Some of these depend upon some others being
  181234. * defined. I haven't figured out all the interactions here, so you may
  181235. * have to experiment awhile to get everything to compile. If you are
  181236. * creating or using a shared library, you probably shouldn't touch this,
  181237. * as it will affect the size of the structures, and this will cause bad
  181238. * things to happen if the library and/or application ever change.
  181239. */
  181240. /* Any features you will not be using can be undef'ed here */
  181241. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181242. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181243. * on the compile line, then pick and choose which ones to define without
  181244. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181245. * if you only want to have a png-compliant reader/writer but don't need
  181246. * any of the extra transformations. This saves about 80 kbytes in a
  181247. * typical installation of the library. (PNG_NO_* form added in version
  181248. * 1.0.1c, for consistency)
  181249. */
  181250. /* The size of the png_text structure changed in libpng-1.0.6 when
  181251. * iTXt support was added. iTXt support was turned off by default through
  181252. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181253. * instead of calling png_set_text() and letting libpng malloc it. It
  181254. * was turned on by default in libpng-1.3.0.
  181255. */
  181256. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181257. # ifndef PNG_NO_iTXt_SUPPORTED
  181258. # define PNG_NO_iTXt_SUPPORTED
  181259. # endif
  181260. # ifndef PNG_NO_READ_iTXt
  181261. # define PNG_NO_READ_iTXt
  181262. # endif
  181263. # ifndef PNG_NO_WRITE_iTXt
  181264. # define PNG_NO_WRITE_iTXt
  181265. # endif
  181266. #endif
  181267. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181268. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181269. # define PNG_READ_iTXt
  181270. # endif
  181271. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181272. # define PNG_WRITE_iTXt
  181273. # endif
  181274. #endif
  181275. /* The following support, added after version 1.0.0, can be turned off here en
  181276. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181277. * with old applications that require the length of png_struct and png_info
  181278. * to remain unchanged.
  181279. */
  181280. #ifdef PNG_LEGACY_SUPPORTED
  181281. # define PNG_NO_FREE_ME
  181282. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181283. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181284. # define PNG_NO_READ_USER_CHUNKS
  181285. # define PNG_NO_READ_iCCP
  181286. # define PNG_NO_WRITE_iCCP
  181287. # define PNG_NO_READ_iTXt
  181288. # define PNG_NO_WRITE_iTXt
  181289. # define PNG_NO_READ_sCAL
  181290. # define PNG_NO_WRITE_sCAL
  181291. # define PNG_NO_READ_sPLT
  181292. # define PNG_NO_WRITE_sPLT
  181293. # define PNG_NO_INFO_IMAGE
  181294. # define PNG_NO_READ_RGB_TO_GRAY
  181295. # define PNG_NO_READ_USER_TRANSFORM
  181296. # define PNG_NO_WRITE_USER_TRANSFORM
  181297. # define PNG_NO_USER_MEM
  181298. # define PNG_NO_READ_EMPTY_PLTE
  181299. # define PNG_NO_MNG_FEATURES
  181300. # define PNG_NO_FIXED_POINT_SUPPORTED
  181301. #endif
  181302. /* Ignore attempt to turn off both floating and fixed point support */
  181303. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181304. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181305. # define PNG_FIXED_POINT_SUPPORTED
  181306. #endif
  181307. #ifndef PNG_NO_FREE_ME
  181308. # define PNG_FREE_ME_SUPPORTED
  181309. #endif
  181310. #if defined(PNG_READ_SUPPORTED)
  181311. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181312. !defined(PNG_NO_READ_TRANSFORMS)
  181313. # define PNG_READ_TRANSFORMS_SUPPORTED
  181314. #endif
  181315. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181316. # ifndef PNG_NO_READ_EXPAND
  181317. # define PNG_READ_EXPAND_SUPPORTED
  181318. # endif
  181319. # ifndef PNG_NO_READ_SHIFT
  181320. # define PNG_READ_SHIFT_SUPPORTED
  181321. # endif
  181322. # ifndef PNG_NO_READ_PACK
  181323. # define PNG_READ_PACK_SUPPORTED
  181324. # endif
  181325. # ifndef PNG_NO_READ_BGR
  181326. # define PNG_READ_BGR_SUPPORTED
  181327. # endif
  181328. # ifndef PNG_NO_READ_SWAP
  181329. # define PNG_READ_SWAP_SUPPORTED
  181330. # endif
  181331. # ifndef PNG_NO_READ_PACKSWAP
  181332. # define PNG_READ_PACKSWAP_SUPPORTED
  181333. # endif
  181334. # ifndef PNG_NO_READ_INVERT
  181335. # define PNG_READ_INVERT_SUPPORTED
  181336. # endif
  181337. # ifndef PNG_NO_READ_DITHER
  181338. # define PNG_READ_DITHER_SUPPORTED
  181339. # endif
  181340. # ifndef PNG_NO_READ_BACKGROUND
  181341. # define PNG_READ_BACKGROUND_SUPPORTED
  181342. # endif
  181343. # ifndef PNG_NO_READ_16_TO_8
  181344. # define PNG_READ_16_TO_8_SUPPORTED
  181345. # endif
  181346. # ifndef PNG_NO_READ_FILLER
  181347. # define PNG_READ_FILLER_SUPPORTED
  181348. # endif
  181349. # ifndef PNG_NO_READ_GAMMA
  181350. # define PNG_READ_GAMMA_SUPPORTED
  181351. # endif
  181352. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181353. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181354. # endif
  181355. # ifndef PNG_NO_READ_SWAP_ALPHA
  181356. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181357. # endif
  181358. # ifndef PNG_NO_READ_INVERT_ALPHA
  181359. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181360. # endif
  181361. # ifndef PNG_NO_READ_STRIP_ALPHA
  181362. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181363. # endif
  181364. # ifndef PNG_NO_READ_USER_TRANSFORM
  181365. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181366. # endif
  181367. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181368. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181369. # endif
  181370. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181371. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181372. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181373. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181374. #endif /* about interlacing capability! You'll */
  181375. /* still have interlacing unless you change the following line: */
  181376. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181377. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181378. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181379. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181380. # endif
  181381. #endif
  181382. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181383. /* Deprecated, will be removed from version 2.0.0.
  181384. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181385. #ifndef PNG_NO_READ_EMPTY_PLTE
  181386. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181387. #endif
  181388. #endif
  181389. #endif /* PNG_READ_SUPPORTED */
  181390. #if defined(PNG_WRITE_SUPPORTED)
  181391. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181392. !defined(PNG_NO_WRITE_TRANSFORMS)
  181393. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181394. #endif
  181395. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181396. # ifndef PNG_NO_WRITE_SHIFT
  181397. # define PNG_WRITE_SHIFT_SUPPORTED
  181398. # endif
  181399. # ifndef PNG_NO_WRITE_PACK
  181400. # define PNG_WRITE_PACK_SUPPORTED
  181401. # endif
  181402. # ifndef PNG_NO_WRITE_BGR
  181403. # define PNG_WRITE_BGR_SUPPORTED
  181404. # endif
  181405. # ifndef PNG_NO_WRITE_SWAP
  181406. # define PNG_WRITE_SWAP_SUPPORTED
  181407. # endif
  181408. # ifndef PNG_NO_WRITE_PACKSWAP
  181409. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181410. # endif
  181411. # ifndef PNG_NO_WRITE_INVERT
  181412. # define PNG_WRITE_INVERT_SUPPORTED
  181413. # endif
  181414. # ifndef PNG_NO_WRITE_FILLER
  181415. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181416. # endif
  181417. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181418. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181419. # endif
  181420. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181421. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181422. # endif
  181423. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181424. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181425. # endif
  181426. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181427. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181428. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181429. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181430. encoders, but can cause trouble
  181431. if left undefined */
  181432. #endif
  181433. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181434. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181435. defined(PNG_FLOATING_POINT_SUPPORTED)
  181436. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181437. #endif
  181438. #ifndef PNG_NO_WRITE_FLUSH
  181439. # define PNG_WRITE_FLUSH_SUPPORTED
  181440. #endif
  181441. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181442. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181443. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181444. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181445. #endif
  181446. #endif
  181447. #endif /* PNG_WRITE_SUPPORTED */
  181448. #ifndef PNG_1_0_X
  181449. # ifndef PNG_NO_ERROR_NUMBERS
  181450. # define PNG_ERROR_NUMBERS_SUPPORTED
  181451. # endif
  181452. #endif /* PNG_1_0_X */
  181453. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181454. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181455. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181456. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181457. # endif
  181458. #endif
  181459. #ifndef PNG_NO_STDIO
  181460. # define PNG_TIME_RFC1123_SUPPORTED
  181461. #endif
  181462. /* This adds extra functions in pngget.c for accessing data from the
  181463. * info pointer (added in version 0.99)
  181464. * png_get_image_width()
  181465. * png_get_image_height()
  181466. * png_get_bit_depth()
  181467. * png_get_color_type()
  181468. * png_get_compression_type()
  181469. * png_get_filter_type()
  181470. * png_get_interlace_type()
  181471. * png_get_pixel_aspect_ratio()
  181472. * png_get_pixels_per_meter()
  181473. * png_get_x_offset_pixels()
  181474. * png_get_y_offset_pixels()
  181475. * png_get_x_offset_microns()
  181476. * png_get_y_offset_microns()
  181477. */
  181478. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181479. # define PNG_EASY_ACCESS_SUPPORTED
  181480. #endif
  181481. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181482. * and removed from version 1.2.20. The following will be removed
  181483. * from libpng-1.4.0
  181484. */
  181485. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181486. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181487. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181488. # endif
  181489. #endif
  181490. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181491. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181492. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181493. # endif
  181494. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181495. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181496. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181497. # define PNG_NO_MMX_CODE
  181498. # endif
  181499. # endif
  181500. # if defined(__APPLE__)
  181501. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181502. # define PNG_NO_MMX_CODE
  181503. # endif
  181504. # endif
  181505. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181506. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181507. # define PNG_NO_MMX_CODE
  181508. # endif
  181509. # endif
  181510. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181511. # define PNG_MMX_CODE_SUPPORTED
  181512. # endif
  181513. #endif
  181514. /* end of obsolete code to be removed from libpng-1.4.0 */
  181515. #if !defined(PNG_1_0_X)
  181516. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181517. # define PNG_USER_MEM_SUPPORTED
  181518. #endif
  181519. #endif /* PNG_1_0_X */
  181520. /* Added at libpng-1.2.6 */
  181521. #if !defined(PNG_1_0_X)
  181522. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181523. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181524. # define PNG_SET_USER_LIMITS_SUPPORTED
  181525. #endif
  181526. #endif
  181527. #endif /* PNG_1_0_X */
  181528. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181529. * how large, set these limits to 0x7fffffffL
  181530. */
  181531. #ifndef PNG_USER_WIDTH_MAX
  181532. # define PNG_USER_WIDTH_MAX 1000000L
  181533. #endif
  181534. #ifndef PNG_USER_HEIGHT_MAX
  181535. # define PNG_USER_HEIGHT_MAX 1000000L
  181536. #endif
  181537. /* These are currently experimental features, define them if you want */
  181538. /* very little testing */
  181539. /*
  181540. #ifdef PNG_READ_SUPPORTED
  181541. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181542. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181543. # endif
  181544. #endif
  181545. */
  181546. /* This is only for PowerPC big-endian and 680x0 systems */
  181547. /* some testing */
  181548. /*
  181549. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181550. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181551. #endif
  181552. */
  181553. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181554. /*
  181555. #define PNG_NO_POINTER_INDEXING
  181556. */
  181557. /* These functions are turned off by default, as they will be phased out. */
  181558. /*
  181559. #define PNG_USELESS_TESTS_SUPPORTED
  181560. #define PNG_CORRECT_PALETTE_SUPPORTED
  181561. */
  181562. /* Any chunks you are not interested in, you can undef here. The
  181563. * ones that allocate memory may be expecially important (hIST,
  181564. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181565. * a bit smaller.
  181566. */
  181567. #if defined(PNG_READ_SUPPORTED) && \
  181568. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181569. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181570. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181571. #endif
  181572. #if defined(PNG_WRITE_SUPPORTED) && \
  181573. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181574. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181575. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181576. #endif
  181577. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181578. #ifdef PNG_NO_READ_TEXT
  181579. # define PNG_NO_READ_iTXt
  181580. # define PNG_NO_READ_tEXt
  181581. # define PNG_NO_READ_zTXt
  181582. #endif
  181583. #ifndef PNG_NO_READ_bKGD
  181584. # define PNG_READ_bKGD_SUPPORTED
  181585. # define PNG_bKGD_SUPPORTED
  181586. #endif
  181587. #ifndef PNG_NO_READ_cHRM
  181588. # define PNG_READ_cHRM_SUPPORTED
  181589. # define PNG_cHRM_SUPPORTED
  181590. #endif
  181591. #ifndef PNG_NO_READ_gAMA
  181592. # define PNG_READ_gAMA_SUPPORTED
  181593. # define PNG_gAMA_SUPPORTED
  181594. #endif
  181595. #ifndef PNG_NO_READ_hIST
  181596. # define PNG_READ_hIST_SUPPORTED
  181597. # define PNG_hIST_SUPPORTED
  181598. #endif
  181599. #ifndef PNG_NO_READ_iCCP
  181600. # define PNG_READ_iCCP_SUPPORTED
  181601. # define PNG_iCCP_SUPPORTED
  181602. #endif
  181603. #ifndef PNG_NO_READ_iTXt
  181604. # ifndef PNG_READ_iTXt_SUPPORTED
  181605. # define PNG_READ_iTXt_SUPPORTED
  181606. # endif
  181607. # ifndef PNG_iTXt_SUPPORTED
  181608. # define PNG_iTXt_SUPPORTED
  181609. # endif
  181610. #endif
  181611. #ifndef PNG_NO_READ_oFFs
  181612. # define PNG_READ_oFFs_SUPPORTED
  181613. # define PNG_oFFs_SUPPORTED
  181614. #endif
  181615. #ifndef PNG_NO_READ_pCAL
  181616. # define PNG_READ_pCAL_SUPPORTED
  181617. # define PNG_pCAL_SUPPORTED
  181618. #endif
  181619. #ifndef PNG_NO_READ_sCAL
  181620. # define PNG_READ_sCAL_SUPPORTED
  181621. # define PNG_sCAL_SUPPORTED
  181622. #endif
  181623. #ifndef PNG_NO_READ_pHYs
  181624. # define PNG_READ_pHYs_SUPPORTED
  181625. # define PNG_pHYs_SUPPORTED
  181626. #endif
  181627. #ifndef PNG_NO_READ_sBIT
  181628. # define PNG_READ_sBIT_SUPPORTED
  181629. # define PNG_sBIT_SUPPORTED
  181630. #endif
  181631. #ifndef PNG_NO_READ_sPLT
  181632. # define PNG_READ_sPLT_SUPPORTED
  181633. # define PNG_sPLT_SUPPORTED
  181634. #endif
  181635. #ifndef PNG_NO_READ_sRGB
  181636. # define PNG_READ_sRGB_SUPPORTED
  181637. # define PNG_sRGB_SUPPORTED
  181638. #endif
  181639. #ifndef PNG_NO_READ_tEXt
  181640. # define PNG_READ_tEXt_SUPPORTED
  181641. # define PNG_tEXt_SUPPORTED
  181642. #endif
  181643. #ifndef PNG_NO_READ_tIME
  181644. # define PNG_READ_tIME_SUPPORTED
  181645. # define PNG_tIME_SUPPORTED
  181646. #endif
  181647. #ifndef PNG_NO_READ_tRNS
  181648. # define PNG_READ_tRNS_SUPPORTED
  181649. # define PNG_tRNS_SUPPORTED
  181650. #endif
  181651. #ifndef PNG_NO_READ_zTXt
  181652. # define PNG_READ_zTXt_SUPPORTED
  181653. # define PNG_zTXt_SUPPORTED
  181654. #endif
  181655. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181656. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181657. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181658. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181659. # endif
  181660. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181661. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181662. # endif
  181663. #endif
  181664. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181665. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181666. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181667. # define PNG_USER_CHUNKS_SUPPORTED
  181668. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181669. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181670. # endif
  181671. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181672. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181673. # endif
  181674. #endif
  181675. #ifndef PNG_NO_READ_OPT_PLTE
  181676. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181677. #endif /* optional PLTE chunk in RGB and RGBA images */
  181678. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181679. defined(PNG_READ_zTXt_SUPPORTED)
  181680. # define PNG_READ_TEXT_SUPPORTED
  181681. # define PNG_TEXT_SUPPORTED
  181682. #endif
  181683. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181684. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181685. #ifdef PNG_NO_WRITE_TEXT
  181686. # define PNG_NO_WRITE_iTXt
  181687. # define PNG_NO_WRITE_tEXt
  181688. # define PNG_NO_WRITE_zTXt
  181689. #endif
  181690. #ifndef PNG_NO_WRITE_bKGD
  181691. # define PNG_WRITE_bKGD_SUPPORTED
  181692. # ifndef PNG_bKGD_SUPPORTED
  181693. # define PNG_bKGD_SUPPORTED
  181694. # endif
  181695. #endif
  181696. #ifndef PNG_NO_WRITE_cHRM
  181697. # define PNG_WRITE_cHRM_SUPPORTED
  181698. # ifndef PNG_cHRM_SUPPORTED
  181699. # define PNG_cHRM_SUPPORTED
  181700. # endif
  181701. #endif
  181702. #ifndef PNG_NO_WRITE_gAMA
  181703. # define PNG_WRITE_gAMA_SUPPORTED
  181704. # ifndef PNG_gAMA_SUPPORTED
  181705. # define PNG_gAMA_SUPPORTED
  181706. # endif
  181707. #endif
  181708. #ifndef PNG_NO_WRITE_hIST
  181709. # define PNG_WRITE_hIST_SUPPORTED
  181710. # ifndef PNG_hIST_SUPPORTED
  181711. # define PNG_hIST_SUPPORTED
  181712. # endif
  181713. #endif
  181714. #ifndef PNG_NO_WRITE_iCCP
  181715. # define PNG_WRITE_iCCP_SUPPORTED
  181716. # ifndef PNG_iCCP_SUPPORTED
  181717. # define PNG_iCCP_SUPPORTED
  181718. # endif
  181719. #endif
  181720. #ifndef PNG_NO_WRITE_iTXt
  181721. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181722. # define PNG_WRITE_iTXt_SUPPORTED
  181723. # endif
  181724. # ifndef PNG_iTXt_SUPPORTED
  181725. # define PNG_iTXt_SUPPORTED
  181726. # endif
  181727. #endif
  181728. #ifndef PNG_NO_WRITE_oFFs
  181729. # define PNG_WRITE_oFFs_SUPPORTED
  181730. # ifndef PNG_oFFs_SUPPORTED
  181731. # define PNG_oFFs_SUPPORTED
  181732. # endif
  181733. #endif
  181734. #ifndef PNG_NO_WRITE_pCAL
  181735. # define PNG_WRITE_pCAL_SUPPORTED
  181736. # ifndef PNG_pCAL_SUPPORTED
  181737. # define PNG_pCAL_SUPPORTED
  181738. # endif
  181739. #endif
  181740. #ifndef PNG_NO_WRITE_sCAL
  181741. # define PNG_WRITE_sCAL_SUPPORTED
  181742. # ifndef PNG_sCAL_SUPPORTED
  181743. # define PNG_sCAL_SUPPORTED
  181744. # endif
  181745. #endif
  181746. #ifndef PNG_NO_WRITE_pHYs
  181747. # define PNG_WRITE_pHYs_SUPPORTED
  181748. # ifndef PNG_pHYs_SUPPORTED
  181749. # define PNG_pHYs_SUPPORTED
  181750. # endif
  181751. #endif
  181752. #ifndef PNG_NO_WRITE_sBIT
  181753. # define PNG_WRITE_sBIT_SUPPORTED
  181754. # ifndef PNG_sBIT_SUPPORTED
  181755. # define PNG_sBIT_SUPPORTED
  181756. # endif
  181757. #endif
  181758. #ifndef PNG_NO_WRITE_sPLT
  181759. # define PNG_WRITE_sPLT_SUPPORTED
  181760. # ifndef PNG_sPLT_SUPPORTED
  181761. # define PNG_sPLT_SUPPORTED
  181762. # endif
  181763. #endif
  181764. #ifndef PNG_NO_WRITE_sRGB
  181765. # define PNG_WRITE_sRGB_SUPPORTED
  181766. # ifndef PNG_sRGB_SUPPORTED
  181767. # define PNG_sRGB_SUPPORTED
  181768. # endif
  181769. #endif
  181770. #ifndef PNG_NO_WRITE_tEXt
  181771. # define PNG_WRITE_tEXt_SUPPORTED
  181772. # ifndef PNG_tEXt_SUPPORTED
  181773. # define PNG_tEXt_SUPPORTED
  181774. # endif
  181775. #endif
  181776. #ifndef PNG_NO_WRITE_tIME
  181777. # define PNG_WRITE_tIME_SUPPORTED
  181778. # ifndef PNG_tIME_SUPPORTED
  181779. # define PNG_tIME_SUPPORTED
  181780. # endif
  181781. #endif
  181782. #ifndef PNG_NO_WRITE_tRNS
  181783. # define PNG_WRITE_tRNS_SUPPORTED
  181784. # ifndef PNG_tRNS_SUPPORTED
  181785. # define PNG_tRNS_SUPPORTED
  181786. # endif
  181787. #endif
  181788. #ifndef PNG_NO_WRITE_zTXt
  181789. # define PNG_WRITE_zTXt_SUPPORTED
  181790. # ifndef PNG_zTXt_SUPPORTED
  181791. # define PNG_zTXt_SUPPORTED
  181792. # endif
  181793. #endif
  181794. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181795. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181796. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181797. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181798. # endif
  181799. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181800. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181801. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181802. # endif
  181803. # endif
  181804. #endif
  181805. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181806. defined(PNG_WRITE_zTXt_SUPPORTED)
  181807. # define PNG_WRITE_TEXT_SUPPORTED
  181808. # ifndef PNG_TEXT_SUPPORTED
  181809. # define PNG_TEXT_SUPPORTED
  181810. # endif
  181811. #endif
  181812. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181813. /* Turn this off to disable png_read_png() and
  181814. * png_write_png() and leave the row_pointers member
  181815. * out of the info structure.
  181816. */
  181817. #ifndef PNG_NO_INFO_IMAGE
  181818. # define PNG_INFO_IMAGE_SUPPORTED
  181819. #endif
  181820. /* need the time information for reading tIME chunks */
  181821. #if defined(PNG_tIME_SUPPORTED)
  181822. # if !defined(_WIN32_WCE)
  181823. /* "time.h" functions are not supported on WindowsCE */
  181824. # include <time.h>
  181825. # endif
  181826. #endif
  181827. /* Some typedefs to get us started. These should be safe on most of the
  181828. * common platforms. The typedefs should be at least as large as the
  181829. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181830. * don't have to be exactly that size. Some compilers dislike passing
  181831. * unsigned shorts as function parameters, so you may be better off using
  181832. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181833. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181834. */
  181835. typedef unsigned long png_uint_32;
  181836. typedef long png_int_32;
  181837. typedef unsigned short png_uint_16;
  181838. typedef short png_int_16;
  181839. typedef unsigned char png_byte;
  181840. /* This is usually size_t. It is typedef'ed just in case you need it to
  181841. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181842. #ifdef PNG_SIZE_T
  181843. typedef PNG_SIZE_T png_size_t;
  181844. # define png_sizeof(x) png_convert_size(sizeof (x))
  181845. #else
  181846. typedef size_t png_size_t;
  181847. # define png_sizeof(x) sizeof (x)
  181848. #endif
  181849. /* The following is needed for medium model support. It cannot be in the
  181850. * PNG_INTERNAL section. Needs modification for other compilers besides
  181851. * MSC. Model independent support declares all arrays and pointers to be
  181852. * large using the far keyword. The zlib version used must also support
  181853. * model independent data. As of version zlib 1.0.4, the necessary changes
  181854. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181855. * changes that are needed. (Tim Wegner)
  181856. */
  181857. /* Separate compiler dependencies (problem here is that zlib.h always
  181858. defines FAR. (SJT) */
  181859. #ifdef __BORLANDC__
  181860. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181861. # define LDATA 1
  181862. # else
  181863. # define LDATA 0
  181864. # endif
  181865. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181866. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181867. # define PNG_MAX_MALLOC_64K
  181868. # if (LDATA != 1)
  181869. # ifndef FAR
  181870. # define FAR __far
  181871. # endif
  181872. # define USE_FAR_KEYWORD
  181873. # endif /* LDATA != 1 */
  181874. /* Possibly useful for moving data out of default segment.
  181875. * Uncomment it if you want. Could also define FARDATA as
  181876. * const if your compiler supports it. (SJT)
  181877. # define FARDATA FAR
  181878. */
  181879. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181880. #endif /* __BORLANDC__ */
  181881. /* Suggest testing for specific compiler first before testing for
  181882. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181883. * making reliance oncertain keywords suspect. (SJT)
  181884. */
  181885. /* MSC Medium model */
  181886. #if defined(FAR)
  181887. # if defined(M_I86MM)
  181888. # define USE_FAR_KEYWORD
  181889. # define FARDATA FAR
  181890. # include <dos.h>
  181891. # endif
  181892. #endif
  181893. /* SJT: default case */
  181894. #ifndef FAR
  181895. # define FAR
  181896. #endif
  181897. /* At this point FAR is always defined */
  181898. #ifndef FARDATA
  181899. # define FARDATA
  181900. #endif
  181901. /* Typedef for floating-point numbers that are converted
  181902. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181903. typedef png_int_32 png_fixed_point;
  181904. /* Add typedefs for pointers */
  181905. typedef void FAR * png_voidp;
  181906. typedef png_byte FAR * png_bytep;
  181907. typedef png_uint_32 FAR * png_uint_32p;
  181908. typedef png_int_32 FAR * png_int_32p;
  181909. typedef png_uint_16 FAR * png_uint_16p;
  181910. typedef png_int_16 FAR * png_int_16p;
  181911. typedef PNG_CONST char FAR * png_const_charp;
  181912. typedef char FAR * png_charp;
  181913. typedef png_fixed_point FAR * png_fixed_point_p;
  181914. #ifndef PNG_NO_STDIO
  181915. #if defined(_WIN32_WCE)
  181916. typedef HANDLE png_FILE_p;
  181917. #else
  181918. typedef FILE * png_FILE_p;
  181919. #endif
  181920. #endif
  181921. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181922. typedef double FAR * png_doublep;
  181923. #endif
  181924. /* Pointers to pointers; i.e. arrays */
  181925. typedef png_byte FAR * FAR * png_bytepp;
  181926. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181927. typedef png_int_32 FAR * FAR * png_int_32pp;
  181928. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181929. typedef png_int_16 FAR * FAR * png_int_16pp;
  181930. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181931. typedef char FAR * FAR * png_charpp;
  181932. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181933. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181934. typedef double FAR * FAR * png_doublepp;
  181935. #endif
  181936. /* Pointers to pointers to pointers; i.e., pointer to array */
  181937. typedef char FAR * FAR * FAR * png_charppp;
  181938. #if 0
  181939. /* SPC - Is this stuff deprecated? */
  181940. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181941. /* libpng typedefs for types in zlib. If zlib changes
  181942. * or another compression library is used, then change these.
  181943. * Eliminates need to change all the source files.
  181944. */
  181945. typedef charf * png_zcharp;
  181946. typedef charf * FAR * png_zcharpp;
  181947. typedef z_stream FAR * png_zstreamp;
  181948. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181949. /*
  181950. * Define PNG_BUILD_DLL if the module being built is a Windows
  181951. * LIBPNG DLL.
  181952. *
  181953. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181954. * It is equivalent to Microsoft predefined macro _DLL that is
  181955. * automatically defined when you compile using the share
  181956. * version of the CRT (C Run-Time library)
  181957. *
  181958. * The cygwin mods make this behavior a little different:
  181959. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181960. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181961. * -or- if you are building an application that you want to link to the
  181962. * static library.
  181963. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181964. * the other flags is defined.
  181965. */
  181966. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181967. # define PNG_DLL
  181968. #endif
  181969. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181970. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181971. * command-line override
  181972. */
  181973. #if defined(__CYGWIN__)
  181974. # if !defined(PNG_STATIC)
  181975. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181976. # undef PNG_USE_GLOBAL_ARRAYS
  181977. # endif
  181978. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181979. # define PNG_USE_LOCAL_ARRAYS
  181980. # endif
  181981. # else
  181982. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181983. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181984. # undef PNG_USE_GLOBAL_ARRAYS
  181985. # endif
  181986. # endif
  181987. # endif
  181988. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181989. # define PNG_USE_LOCAL_ARRAYS
  181990. # endif
  181991. #endif
  181992. /* Do not use global arrays (helps with building DLL's)
  181993. * They are no longer used in libpng itself, since version 1.0.5c,
  181994. * but might be required for some pre-1.0.5c applications.
  181995. */
  181996. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181997. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181998. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181999. # define PNG_USE_LOCAL_ARRAYS
  182000. # else
  182001. # define PNG_USE_GLOBAL_ARRAYS
  182002. # endif
  182003. #endif
  182004. #if defined(__CYGWIN__)
  182005. # undef PNGAPI
  182006. # define PNGAPI __cdecl
  182007. # undef PNG_IMPEXP
  182008. # define PNG_IMPEXP
  182009. #endif
  182010. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  182011. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  182012. * Don't ignore those warnings; you must also reset the default calling
  182013. * convention in your compiler to match your PNGAPI, and you must build
  182014. * zlib and your applications the same way you build libpng.
  182015. */
  182016. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  182017. # ifndef PNG_NO_MODULEDEF
  182018. # define PNG_NO_MODULEDEF
  182019. # endif
  182020. #endif
  182021. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  182022. # define PNG_IMPEXP
  182023. #endif
  182024. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  182025. (( defined(_Windows) || defined(_WINDOWS) || \
  182026. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  182027. # ifndef PNGAPI
  182028. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  182029. # define PNGAPI __cdecl
  182030. # else
  182031. # define PNGAPI _cdecl
  182032. # endif
  182033. # endif
  182034. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  182035. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  182036. # define PNG_IMPEXP
  182037. # endif
  182038. # if !defined(PNG_IMPEXP)
  182039. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182040. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  182041. /* Borland/Microsoft */
  182042. # if defined(_MSC_VER) || defined(__BORLANDC__)
  182043. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  182044. # define PNG_EXPORT PNG_EXPORT_TYPE1
  182045. # else
  182046. # define PNG_EXPORT PNG_EXPORT_TYPE2
  182047. # if defined(PNG_BUILD_DLL)
  182048. # define PNG_IMPEXP __export
  182049. # else
  182050. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  182051. VC++ */
  182052. # endif /* Exists in Borland C++ for
  182053. C++ classes (== huge) */
  182054. # endif
  182055. # endif
  182056. # if !defined(PNG_IMPEXP)
  182057. # if defined(PNG_BUILD_DLL)
  182058. # define PNG_IMPEXP __declspec(dllexport)
  182059. # else
  182060. # define PNG_IMPEXP __declspec(dllimport)
  182061. # endif
  182062. # endif
  182063. # endif /* PNG_IMPEXP */
  182064. #else /* !(DLL || non-cygwin WINDOWS) */
  182065. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  182066. # ifndef PNGAPI
  182067. # define PNGAPI _System
  182068. # endif
  182069. # else
  182070. # if 0 /* ... other platforms, with other meanings */
  182071. # endif
  182072. # endif
  182073. #endif
  182074. #ifndef PNGAPI
  182075. # define PNGAPI
  182076. #endif
  182077. #ifndef PNG_IMPEXP
  182078. # define PNG_IMPEXP
  182079. #endif
  182080. #ifdef PNG_BUILDSYMS
  182081. # ifndef PNG_EXPORT
  182082. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  182083. # endif
  182084. # ifdef PNG_USE_GLOBAL_ARRAYS
  182085. # ifndef PNG_EXPORT_VAR
  182086. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  182087. # endif
  182088. # endif
  182089. #endif
  182090. #ifndef PNG_EXPORT
  182091. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182092. #endif
  182093. #ifdef PNG_USE_GLOBAL_ARRAYS
  182094. # ifndef PNG_EXPORT_VAR
  182095. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  182096. # endif
  182097. #endif
  182098. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  182099. * functions that are passed far data must be model independent.
  182100. */
  182101. #ifndef PNG_ABORT
  182102. # define PNG_ABORT() abort()
  182103. #endif
  182104. #ifdef PNG_SETJMP_SUPPORTED
  182105. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  182106. #else
  182107. # define png_jmpbuf(png_ptr) \
  182108. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  182109. #endif
  182110. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  182111. /* use this to make far-to-near assignments */
  182112. # define CHECK 1
  182113. # define NOCHECK 0
  182114. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182115. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182116. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182117. # define png_strcpy _fstrcpy
  182118. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182119. # define png_strlen _fstrlen
  182120. # define png_memcmp _fmemcmp /* SJT: added */
  182121. # define png_memcpy _fmemcpy
  182122. # define png_memset _fmemset
  182123. #else /* use the usual functions */
  182124. # define CVT_PTR(ptr) (ptr)
  182125. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182126. # ifndef PNG_NO_SNPRINTF
  182127. # ifdef _MSC_VER
  182128. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182129. # define png_snprintf2 _snprintf
  182130. # define png_snprintf6 _snprintf
  182131. # else
  182132. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182133. # define png_snprintf2 snprintf
  182134. # define png_snprintf6 snprintf
  182135. # endif
  182136. # else
  182137. /* You don't have or don't want to use snprintf(). Caution: Using
  182138. * sprintf instead of snprintf exposes your application to accidental
  182139. * or malevolent buffer overflows. If you don't have snprintf()
  182140. * as a general rule you should provide one (you can get one from
  182141. * Portable OpenSSH). */
  182142. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182143. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182144. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182145. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182146. # endif
  182147. # define png_strcpy strcpy
  182148. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182149. # define png_strlen strlen
  182150. # define png_memcmp memcmp /* SJT: added */
  182151. # define png_memcpy memcpy
  182152. # define png_memset memset
  182153. #endif
  182154. /* End of memory model independent support */
  182155. /* Just a little check that someone hasn't tried to define something
  182156. * contradictory.
  182157. */
  182158. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182159. # undef PNG_ZBUF_SIZE
  182160. # define PNG_ZBUF_SIZE 65536L
  182161. #endif
  182162. /* Added at libpng-1.2.8 */
  182163. #endif /* PNG_VERSION_INFO_ONLY */
  182164. #endif /* PNGCONF_H */
  182165. /*** End of inlined file: pngconf.h ***/
  182166. #ifdef _MSC_VER
  182167. #pragma warning (disable: 4996 4100)
  182168. #endif
  182169. /*
  182170. * Added at libpng-1.2.8 */
  182171. /* Ref MSDN: Private as priority over Special
  182172. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182173. * procedures. If this value is given, the StringFileInfo block must
  182174. * contain a PrivateBuild string.
  182175. *
  182176. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182177. * standard release procedures but is a variation of the standard
  182178. * file of the same version number. If this value is given, the
  182179. * StringFileInfo block must contain a SpecialBuild string.
  182180. */
  182181. #if defined(PNG_USER_PRIVATEBUILD)
  182182. # define PNG_LIBPNG_BUILD_TYPE \
  182183. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182184. #else
  182185. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182186. # define PNG_LIBPNG_BUILD_TYPE \
  182187. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182188. # else
  182189. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182190. # endif
  182191. #endif
  182192. #ifndef PNG_VERSION_INFO_ONLY
  182193. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182194. #ifdef __cplusplus
  182195. //extern "C" {
  182196. #endif /* __cplusplus */
  182197. /* This file is arranged in several sections. The first section contains
  182198. * structure and type definitions. The second section contains the external
  182199. * library functions, while the third has the internal library functions,
  182200. * which applications aren't expected to use directly.
  182201. */
  182202. #ifndef PNG_NO_TYPECAST_NULL
  182203. #define int_p_NULL (int *)NULL
  182204. #define png_bytep_NULL (png_bytep)NULL
  182205. #define png_bytepp_NULL (png_bytepp)NULL
  182206. #define png_doublep_NULL (png_doublep)NULL
  182207. #define png_error_ptr_NULL (png_error_ptr)NULL
  182208. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182209. #define png_free_ptr_NULL (png_free_ptr)NULL
  182210. #define png_infopp_NULL (png_infopp)NULL
  182211. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182212. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182213. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182214. #define png_structp_NULL (png_structp)NULL
  182215. #define png_uint_16p_NULL (png_uint_16p)NULL
  182216. #define png_voidp_NULL (png_voidp)NULL
  182217. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182218. #else
  182219. #define int_p_NULL NULL
  182220. #define png_bytep_NULL NULL
  182221. #define png_bytepp_NULL NULL
  182222. #define png_doublep_NULL NULL
  182223. #define png_error_ptr_NULL NULL
  182224. #define png_flush_ptr_NULL NULL
  182225. #define png_free_ptr_NULL NULL
  182226. #define png_infopp_NULL NULL
  182227. #define png_malloc_ptr_NULL NULL
  182228. #define png_read_status_ptr_NULL NULL
  182229. #define png_rw_ptr_NULL NULL
  182230. #define png_structp_NULL NULL
  182231. #define png_uint_16p_NULL NULL
  182232. #define png_voidp_NULL NULL
  182233. #define png_write_status_ptr_NULL NULL
  182234. #endif
  182235. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182236. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182237. /* Version information for C files, stored in png.c. This had better match
  182238. * the version above.
  182239. */
  182240. #ifdef PNG_USE_GLOBAL_ARRAYS
  182241. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182242. /* need room for 99.99.99beta99z */
  182243. #else
  182244. #define png_libpng_ver png_get_header_ver(NULL)
  182245. #endif
  182246. #ifdef PNG_USE_GLOBAL_ARRAYS
  182247. /* This was removed in version 1.0.5c */
  182248. /* Structures to facilitate easy interlacing. See png.c for more details */
  182249. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182250. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182251. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182252. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182253. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182254. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182255. /* This isn't currently used. If you need it, see png.c for more details.
  182256. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182257. */
  182258. #endif
  182259. #endif /* PNG_NO_EXTERN */
  182260. /* Three color definitions. The order of the red, green, and blue, (and the
  182261. * exact size) is not important, although the size of the fields need to
  182262. * be png_byte or png_uint_16 (as defined below).
  182263. */
  182264. typedef struct png_color_struct
  182265. {
  182266. png_byte red;
  182267. png_byte green;
  182268. png_byte blue;
  182269. } png_color;
  182270. typedef png_color FAR * png_colorp;
  182271. typedef png_color FAR * FAR * png_colorpp;
  182272. typedef struct png_color_16_struct
  182273. {
  182274. png_byte index; /* used for palette files */
  182275. png_uint_16 red; /* for use in red green blue files */
  182276. png_uint_16 green;
  182277. png_uint_16 blue;
  182278. png_uint_16 gray; /* for use in grayscale files */
  182279. } png_color_16;
  182280. typedef png_color_16 FAR * png_color_16p;
  182281. typedef png_color_16 FAR * FAR * png_color_16pp;
  182282. typedef struct png_color_8_struct
  182283. {
  182284. png_byte red; /* for use in red green blue files */
  182285. png_byte green;
  182286. png_byte blue;
  182287. png_byte gray; /* for use in grayscale files */
  182288. png_byte alpha; /* for alpha channel files */
  182289. } png_color_8;
  182290. typedef png_color_8 FAR * png_color_8p;
  182291. typedef png_color_8 FAR * FAR * png_color_8pp;
  182292. /*
  182293. * The following two structures are used for the in-core representation
  182294. * of sPLT chunks.
  182295. */
  182296. typedef struct png_sPLT_entry_struct
  182297. {
  182298. png_uint_16 red;
  182299. png_uint_16 green;
  182300. png_uint_16 blue;
  182301. png_uint_16 alpha;
  182302. png_uint_16 frequency;
  182303. } png_sPLT_entry;
  182304. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182305. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182306. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182307. * occupy the LSB of their respective members, and the MSB of each member
  182308. * is zero-filled. The frequency member always occupies the full 16 bits.
  182309. */
  182310. typedef struct png_sPLT_struct
  182311. {
  182312. png_charp name; /* palette name */
  182313. png_byte depth; /* depth of palette samples */
  182314. png_sPLT_entryp entries; /* palette entries */
  182315. png_int_32 nentries; /* number of palette entries */
  182316. } png_sPLT_t;
  182317. typedef png_sPLT_t FAR * png_sPLT_tp;
  182318. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182319. #ifdef PNG_TEXT_SUPPORTED
  182320. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182321. * and whether that contents is compressed or not. The "key" field
  182322. * points to a regular zero-terminated C string. The "text", "lang", and
  182323. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182324. * However, the * structure returned by png_get_text() will always contain
  182325. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182326. * so they can be safely used in printf() and other string-handling functions.
  182327. */
  182328. typedef struct png_text_struct
  182329. {
  182330. int compression; /* compression value:
  182331. -1: tEXt, none
  182332. 0: zTXt, deflate
  182333. 1: iTXt, none
  182334. 2: iTXt, deflate */
  182335. png_charp key; /* keyword, 1-79 character description of "text" */
  182336. png_charp text; /* comment, may be an empty string (ie "")
  182337. or a NULL pointer */
  182338. png_size_t text_length; /* length of the text string */
  182339. #ifdef PNG_iTXt_SUPPORTED
  182340. png_size_t itxt_length; /* length of the itxt string */
  182341. png_charp lang; /* language code, 0-79 characters
  182342. or a NULL pointer */
  182343. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182344. chars or a NULL pointer */
  182345. #endif
  182346. } png_text;
  182347. typedef png_text FAR * png_textp;
  182348. typedef png_text FAR * FAR * png_textpp;
  182349. #endif
  182350. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182351. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182352. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182353. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182354. #define PNG_TEXT_COMPRESSION_NONE -1
  182355. #define PNG_TEXT_COMPRESSION_zTXt 0
  182356. #define PNG_ITXT_COMPRESSION_NONE 1
  182357. #define PNG_ITXT_COMPRESSION_zTXt 2
  182358. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182359. /* png_time is a way to hold the time in an machine independent way.
  182360. * Two conversions are provided, both from time_t and struct tm. There
  182361. * is no portable way to convert to either of these structures, as far
  182362. * as I know. If you know of a portable way, send it to me. As a side
  182363. * note - PNG has always been Year 2000 compliant!
  182364. */
  182365. typedef struct png_time_struct
  182366. {
  182367. png_uint_16 year; /* full year, as in, 1995 */
  182368. png_byte month; /* month of year, 1 - 12 */
  182369. png_byte day; /* day of month, 1 - 31 */
  182370. png_byte hour; /* hour of day, 0 - 23 */
  182371. png_byte minute; /* minute of hour, 0 - 59 */
  182372. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182373. } png_time;
  182374. typedef png_time FAR * png_timep;
  182375. typedef png_time FAR * FAR * png_timepp;
  182376. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182377. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182378. * no specific support. The idea is that we can use this to queue
  182379. * up private chunks for output even though the library doesn't actually
  182380. * know about their semantics.
  182381. */
  182382. typedef struct png_unknown_chunk_t
  182383. {
  182384. png_byte name[5];
  182385. png_byte *data;
  182386. png_size_t size;
  182387. /* libpng-using applications should NOT directly modify this byte. */
  182388. png_byte location; /* mode of operation at read time */
  182389. }
  182390. png_unknown_chunk;
  182391. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182392. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182393. #endif
  182394. /* png_info is a structure that holds the information in a PNG file so
  182395. * that the application can find out the characteristics of the image.
  182396. * If you are reading the file, this structure will tell you what is
  182397. * in the PNG file. If you are writing the file, fill in the information
  182398. * you want to put into the PNG file, then call png_write_info().
  182399. * The names chosen should be very close to the PNG specification, so
  182400. * consult that document for information about the meaning of each field.
  182401. *
  182402. * With libpng < 0.95, it was only possible to directly set and read the
  182403. * the values in the png_info_struct, which meant that the contents and
  182404. * order of the values had to remain fixed. With libpng 0.95 and later,
  182405. * however, there are now functions that abstract the contents of
  182406. * png_info_struct from the application, so this makes it easier to use
  182407. * libpng with dynamic libraries, and even makes it possible to use
  182408. * libraries that don't have all of the libpng ancillary chunk-handing
  182409. * functionality.
  182410. *
  182411. * In any case, the order of the parameters in png_info_struct should NOT
  182412. * be changed for as long as possible to keep compatibility with applications
  182413. * that use the old direct-access method with png_info_struct.
  182414. *
  182415. * The following members may have allocated storage attached that should be
  182416. * cleaned up before the structure is discarded: palette, trans, text,
  182417. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182418. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182419. * are automatically freed when the info structure is deallocated, if they were
  182420. * allocated internally by libpng. This behavior can be changed by means
  182421. * of the png_data_freer() function.
  182422. *
  182423. * More allocation details: all the chunk-reading functions that
  182424. * change these members go through the corresponding png_set_*
  182425. * functions. A function to clear these members is available: see
  182426. * png_free_data(). The png_set_* functions do not depend on being
  182427. * able to point info structure members to any of the storage they are
  182428. * passed (they make their own copies), EXCEPT that the png_set_text
  182429. * functions use the same storage passed to them in the text_ptr or
  182430. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182431. * functions do not make their own copies.
  182432. */
  182433. typedef struct png_info_struct
  182434. {
  182435. /* the following are necessary for every PNG file */
  182436. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182437. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182438. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182439. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182440. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182441. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182442. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182443. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182444. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182445. /* The following three should have been named *_method not *_type */
  182446. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182447. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182448. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182449. /* The following is informational only on read, and not used on writes. */
  182450. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182451. png_byte pixel_depth; /* number of bits per pixel */
  182452. png_byte spare_byte; /* to align the data, and for future use */
  182453. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182454. /* The rest of the data is optional. If you are reading, check the
  182455. * valid field to see if the information in these are valid. If you
  182456. * are writing, set the valid field to those chunks you want written,
  182457. * and initialize the appropriate fields below.
  182458. */
  182459. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182460. /* The gAMA chunk describes the gamma characteristics of the system
  182461. * on which the image was created, normally in the range [1.0, 2.5].
  182462. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182463. */
  182464. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182465. #endif
  182466. #if defined(PNG_sRGB_SUPPORTED)
  182467. /* GR-P, 0.96a */
  182468. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182469. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182470. #endif
  182471. #if defined(PNG_TEXT_SUPPORTED)
  182472. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182473. * uncompressed, compressed, and optionally compressed forms, respectively.
  182474. * The data in "text" is an array of pointers to uncompressed,
  182475. * null-terminated C strings. Each chunk has a keyword that describes the
  182476. * textual data contained in that chunk. Keywords are not required to be
  182477. * unique, and the text string may be empty. Any number of text chunks may
  182478. * be in an image.
  182479. */
  182480. int num_text; /* number of comments read/to write */
  182481. int max_text; /* current size of text array */
  182482. png_textp text; /* array of comments read/to write */
  182483. #endif /* PNG_TEXT_SUPPORTED */
  182484. #if defined(PNG_tIME_SUPPORTED)
  182485. /* The tIME chunk holds the last time the displayed image data was
  182486. * modified. See the png_time struct for the contents of this struct.
  182487. */
  182488. png_time mod_time;
  182489. #endif
  182490. #if defined(PNG_sBIT_SUPPORTED)
  182491. /* The sBIT chunk specifies the number of significant high-order bits
  182492. * in the pixel data. Values are in the range [1, bit_depth], and are
  182493. * only specified for the channels in the pixel data. The contents of
  182494. * the low-order bits is not specified. Data is valid if
  182495. * (valid & PNG_INFO_sBIT) is non-zero.
  182496. */
  182497. png_color_8 sig_bit; /* significant bits in color channels */
  182498. #endif
  182499. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182500. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182501. /* The tRNS chunk supplies transparency data for paletted images and
  182502. * other image types that don't need a full alpha channel. There are
  182503. * "num_trans" transparency values for a paletted image, stored in the
  182504. * same order as the palette colors, starting from index 0. Values
  182505. * for the data are in the range [0, 255], ranging from fully transparent
  182506. * to fully opaque, respectively. For non-paletted images, there is a
  182507. * single color specified that should be treated as fully transparent.
  182508. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182509. */
  182510. png_bytep trans; /* transparent values for paletted image */
  182511. png_color_16 trans_values; /* transparent color for non-palette image */
  182512. #endif
  182513. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182514. /* The bKGD chunk gives the suggested image background color if the
  182515. * display program does not have its own background color and the image
  182516. * is needs to composited onto a background before display. The colors
  182517. * in "background" are normally in the same color space/depth as the
  182518. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182519. */
  182520. png_color_16 background;
  182521. #endif
  182522. #if defined(PNG_oFFs_SUPPORTED)
  182523. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182524. * and downwards from the top-left corner of the display, page, or other
  182525. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182526. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182527. */
  182528. png_int_32 x_offset; /* x offset on page */
  182529. png_int_32 y_offset; /* y offset on page */
  182530. png_byte offset_unit_type; /* offset units type */
  182531. #endif
  182532. #if defined(PNG_pHYs_SUPPORTED)
  182533. /* The pHYs chunk gives the physical pixel density of the image for
  182534. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182535. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182536. */
  182537. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182538. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182539. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182540. #endif
  182541. #if defined(PNG_hIST_SUPPORTED)
  182542. /* The hIST chunk contains the relative frequency or importance of the
  182543. * various palette entries, so that a viewer can intelligently select a
  182544. * reduced-color palette, if required. Data is an array of "num_palette"
  182545. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182546. * is non-zero.
  182547. */
  182548. png_uint_16p hist;
  182549. #endif
  182550. #ifdef PNG_cHRM_SUPPORTED
  182551. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182552. * on which the PNG was created. This data allows the viewer to do gamut
  182553. * mapping of the input image to ensure that the viewer sees the same
  182554. * colors in the image as the creator. Values are in the range
  182555. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182556. */
  182557. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182558. float x_white;
  182559. float y_white;
  182560. float x_red;
  182561. float y_red;
  182562. float x_green;
  182563. float y_green;
  182564. float x_blue;
  182565. float y_blue;
  182566. #endif
  182567. #endif
  182568. #if defined(PNG_pCAL_SUPPORTED)
  182569. /* The pCAL chunk describes a transformation between the stored pixel
  182570. * values and original physical data values used to create the image.
  182571. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182572. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182573. * (possibly non-linear) transformation function given by "pcal_type"
  182574. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182575. * defines below, and the PNG-Group's PNG extensions document for a
  182576. * complete description of the transformations and how they should be
  182577. * implemented, and for a description of the ASCII parameter strings.
  182578. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182579. */
  182580. png_charp pcal_purpose; /* pCAL chunk description string */
  182581. png_int_32 pcal_X0; /* minimum value */
  182582. png_int_32 pcal_X1; /* maximum value */
  182583. png_charp pcal_units; /* Latin-1 string giving physical units */
  182584. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182585. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182586. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182587. #endif
  182588. /* New members added in libpng-1.0.6 */
  182589. #ifdef PNG_FREE_ME_SUPPORTED
  182590. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182591. #endif
  182592. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182593. /* storage for unknown chunks that the library doesn't recognize. */
  182594. png_unknown_chunkp unknown_chunks;
  182595. png_size_t unknown_chunks_num;
  182596. #endif
  182597. #if defined(PNG_iCCP_SUPPORTED)
  182598. /* iCCP chunk data. */
  182599. png_charp iccp_name; /* profile name */
  182600. png_charp iccp_profile; /* International Color Consortium profile data */
  182601. /* Note to maintainer: should be png_bytep */
  182602. png_uint_32 iccp_proflen; /* ICC profile data length */
  182603. png_byte iccp_compression; /* Always zero */
  182604. #endif
  182605. #if defined(PNG_sPLT_SUPPORTED)
  182606. /* data on sPLT chunks (there may be more than one). */
  182607. png_sPLT_tp splt_palettes;
  182608. png_uint_32 splt_palettes_num;
  182609. #endif
  182610. #if defined(PNG_sCAL_SUPPORTED)
  182611. /* The sCAL chunk describes the actual physical dimensions of the
  182612. * subject matter of the graphic. The chunk contains a unit specification
  182613. * a byte value, and two ASCII strings representing floating-point
  182614. * values. The values are width and height corresponsing to one pixel
  182615. * in the image. This external representation is converted to double
  182616. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182617. */
  182618. png_byte scal_unit; /* unit of physical scale */
  182619. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182620. double scal_pixel_width; /* width of one pixel */
  182621. double scal_pixel_height; /* height of one pixel */
  182622. #endif
  182623. #ifdef PNG_FIXED_POINT_SUPPORTED
  182624. png_charp scal_s_width; /* string containing height */
  182625. png_charp scal_s_height; /* string containing width */
  182626. #endif
  182627. #endif
  182628. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182629. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182630. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182631. png_bytepp row_pointers; /* the image bits */
  182632. #endif
  182633. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182634. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182635. #endif
  182636. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182637. png_fixed_point int_x_white;
  182638. png_fixed_point int_y_white;
  182639. png_fixed_point int_x_red;
  182640. png_fixed_point int_y_red;
  182641. png_fixed_point int_x_green;
  182642. png_fixed_point int_y_green;
  182643. png_fixed_point int_x_blue;
  182644. png_fixed_point int_y_blue;
  182645. #endif
  182646. } png_info;
  182647. typedef png_info FAR * png_infop;
  182648. typedef png_info FAR * FAR * png_infopp;
  182649. /* Maximum positive integer used in PNG is (2^31)-1 */
  182650. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182651. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182652. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182653. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182654. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182655. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182656. #endif
  182657. /* These describe the color_type field in png_info. */
  182658. /* color type masks */
  182659. #define PNG_COLOR_MASK_PALETTE 1
  182660. #define PNG_COLOR_MASK_COLOR 2
  182661. #define PNG_COLOR_MASK_ALPHA 4
  182662. /* color types. Note that not all combinations are legal */
  182663. #define PNG_COLOR_TYPE_GRAY 0
  182664. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182665. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182666. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182667. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182668. /* aliases */
  182669. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182670. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182671. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182672. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182673. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182674. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182675. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182676. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182677. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182678. /* These are for the interlacing type. These values should NOT be changed. */
  182679. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182680. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182681. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182682. /* These are for the oFFs chunk. These values should NOT be changed. */
  182683. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182684. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182685. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182686. /* These are for the pCAL chunk. These values should NOT be changed. */
  182687. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182688. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182689. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182690. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182691. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182692. /* These are for the sCAL chunk. These values should NOT be changed. */
  182693. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182694. #define PNG_SCALE_METER 1 /* meters per pixel */
  182695. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182696. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182697. /* These are for the pHYs chunk. These values should NOT be changed. */
  182698. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182699. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182700. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182701. /* These are for the sRGB chunk. These values should NOT be changed. */
  182702. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182703. #define PNG_sRGB_INTENT_RELATIVE 1
  182704. #define PNG_sRGB_INTENT_SATURATION 2
  182705. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182706. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182707. /* This is for text chunks */
  182708. #define PNG_KEYWORD_MAX_LENGTH 79
  182709. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182710. #define PNG_MAX_PALETTE_LENGTH 256
  182711. /* These determine if an ancillary chunk's data has been successfully read
  182712. * from the PNG header, or if the application has filled in the corresponding
  182713. * data in the info_struct to be written into the output file. The values
  182714. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182715. */
  182716. #define PNG_INFO_gAMA 0x0001
  182717. #define PNG_INFO_sBIT 0x0002
  182718. #define PNG_INFO_cHRM 0x0004
  182719. #define PNG_INFO_PLTE 0x0008
  182720. #define PNG_INFO_tRNS 0x0010
  182721. #define PNG_INFO_bKGD 0x0020
  182722. #define PNG_INFO_hIST 0x0040
  182723. #define PNG_INFO_pHYs 0x0080
  182724. #define PNG_INFO_oFFs 0x0100
  182725. #define PNG_INFO_tIME 0x0200
  182726. #define PNG_INFO_pCAL 0x0400
  182727. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182728. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182729. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182730. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182731. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182732. /* This is used for the transformation routines, as some of them
  182733. * change these values for the row. It also should enable using
  182734. * the routines for other purposes.
  182735. */
  182736. typedef struct png_row_info_struct
  182737. {
  182738. png_uint_32 width; /* width of row */
  182739. png_uint_32 rowbytes; /* number of bytes in row */
  182740. png_byte color_type; /* color type of row */
  182741. png_byte bit_depth; /* bit depth of row */
  182742. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182743. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182744. } png_row_info;
  182745. typedef png_row_info FAR * png_row_infop;
  182746. typedef png_row_info FAR * FAR * png_row_infopp;
  182747. /* These are the function types for the I/O functions and for the functions
  182748. * that allow the user to override the default I/O functions with his or her
  182749. * own. The png_error_ptr type should match that of user-supplied warning
  182750. * and error functions, while the png_rw_ptr type should match that of the
  182751. * user read/write data functions.
  182752. */
  182753. typedef struct png_struct_def png_struct;
  182754. typedef png_struct FAR * png_structp;
  182755. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182756. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182757. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182758. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182759. int));
  182760. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182761. int));
  182762. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182763. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182764. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182765. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182766. png_uint_32, int));
  182767. #endif
  182768. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182769. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182770. defined(PNG_LEGACY_SUPPORTED)
  182771. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182772. png_row_infop, png_bytep));
  182773. #endif
  182774. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182775. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182776. #endif
  182777. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182778. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182779. #endif
  182780. /* Transform masks for the high-level interface */
  182781. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182782. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182783. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182784. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182785. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182786. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182787. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182788. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182789. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182790. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182791. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182792. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182793. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182794. /* Flags for MNG supported features */
  182795. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182796. #define PNG_FLAG_MNG_FILTER_64 0x04
  182797. #define PNG_ALL_MNG_FEATURES 0x05
  182798. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182799. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182800. /* The structure that holds the information to read and write PNG files.
  182801. * The only people who need to care about what is inside of this are the
  182802. * people who will be modifying the library for their own special needs.
  182803. * It should NOT be accessed directly by an application, except to store
  182804. * the jmp_buf.
  182805. */
  182806. struct png_struct_def
  182807. {
  182808. #ifdef PNG_SETJMP_SUPPORTED
  182809. jmp_buf jmpbuf; /* used in png_error */
  182810. #endif
  182811. png_error_ptr error_fn; /* function for printing errors and aborting */
  182812. png_error_ptr warning_fn; /* function for printing warnings */
  182813. png_voidp error_ptr; /* user supplied struct for error functions */
  182814. png_rw_ptr write_data_fn; /* function for writing output data */
  182815. png_rw_ptr read_data_fn; /* function for reading input data */
  182816. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182817. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182818. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182819. #endif
  182820. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182821. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182822. #endif
  182823. /* These were added in libpng-1.0.2 */
  182824. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182825. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182826. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182827. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182828. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182829. png_byte user_transform_channels; /* channels in user transformed pixels */
  182830. #endif
  182831. #endif
  182832. png_uint_32 mode; /* tells us where we are in the PNG file */
  182833. png_uint_32 flags; /* flags indicating various things to libpng */
  182834. png_uint_32 transformations; /* which transformations to perform */
  182835. z_stream zstream; /* pointer to decompression structure (below) */
  182836. png_bytep zbuf; /* buffer for zlib */
  182837. png_size_t zbuf_size; /* size of zbuf */
  182838. int zlib_level; /* holds zlib compression level */
  182839. int zlib_method; /* holds zlib compression method */
  182840. int zlib_window_bits; /* holds zlib compression window bits */
  182841. int zlib_mem_level; /* holds zlib compression memory level */
  182842. int zlib_strategy; /* holds zlib compression strategy */
  182843. png_uint_32 width; /* width of image in pixels */
  182844. png_uint_32 height; /* height of image in pixels */
  182845. png_uint_32 num_rows; /* number of rows in current pass */
  182846. png_uint_32 usr_width; /* width of row at start of write */
  182847. png_uint_32 rowbytes; /* size of row in bytes */
  182848. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182849. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182850. png_uint_32 row_number; /* current row in interlace pass */
  182851. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182852. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182853. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182854. png_bytep up_row; /* buffer to save "up" row when filtering */
  182855. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182856. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182857. png_row_info row_info; /* used for transformation routines */
  182858. png_uint_32 idat_size; /* current IDAT size for read */
  182859. png_uint_32 crc; /* current chunk CRC value */
  182860. png_colorp palette; /* palette from the input file */
  182861. png_uint_16 num_palette; /* number of color entries in palette */
  182862. png_uint_16 num_trans; /* number of transparency values */
  182863. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182864. png_byte compression; /* file compression type (always 0) */
  182865. png_byte filter; /* file filter type (always 0) */
  182866. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182867. png_byte pass; /* current interlace pass (0 - 6) */
  182868. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182869. png_byte color_type; /* color type of file */
  182870. png_byte bit_depth; /* bit depth of file */
  182871. png_byte usr_bit_depth; /* bit depth of users row */
  182872. png_byte pixel_depth; /* number of bits per pixel */
  182873. png_byte channels; /* number of channels in file */
  182874. png_byte usr_channels; /* channels at start of write */
  182875. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182876. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182877. #ifdef PNG_LEGACY_SUPPORTED
  182878. png_byte filler; /* filler byte for pixel expansion */
  182879. #else
  182880. png_uint_16 filler; /* filler bytes for pixel expansion */
  182881. #endif
  182882. #endif
  182883. #if defined(PNG_bKGD_SUPPORTED)
  182884. png_byte background_gamma_type;
  182885. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182886. float background_gamma;
  182887. # endif
  182888. png_color_16 background; /* background color in screen gamma space */
  182889. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182890. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182891. #endif
  182892. #endif /* PNG_bKGD_SUPPORTED */
  182893. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182894. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182895. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182896. png_uint_32 flush_rows; /* number of rows written since last flush */
  182897. #endif
  182898. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182899. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182900. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182901. float gamma; /* file gamma value */
  182902. float screen_gamma; /* screen gamma value (display_exponent) */
  182903. #endif
  182904. #endif
  182905. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182906. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182907. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182908. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182909. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182910. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182911. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182912. #endif
  182913. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182914. png_color_8 sig_bit; /* significant bits in each available channel */
  182915. #endif
  182916. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182917. png_color_8 shift; /* shift for significant bit tranformation */
  182918. #endif
  182919. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182920. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182921. png_bytep trans; /* transparency values for paletted files */
  182922. png_color_16 trans_values; /* transparency values for non-paletted files */
  182923. #endif
  182924. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182925. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182926. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182927. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182928. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182929. png_progressive_end_ptr end_fn; /* called after image is complete */
  182930. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182931. png_bytep save_buffer; /* buffer for previously read data */
  182932. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182933. png_bytep current_buffer; /* buffer for recently used data */
  182934. png_uint_32 push_length; /* size of current input chunk */
  182935. png_uint_32 skip_length; /* bytes to skip in input data */
  182936. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182937. png_size_t save_buffer_max; /* total size of save_buffer */
  182938. png_size_t buffer_size; /* total amount of available input data */
  182939. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182940. int process_mode; /* what push library is currently doing */
  182941. int cur_palette; /* current push library palette index */
  182942. # if defined(PNG_TEXT_SUPPORTED)
  182943. png_size_t current_text_size; /* current size of text input data */
  182944. png_size_t current_text_left; /* how much text left to read in input */
  182945. png_charp current_text; /* current text chunk buffer */
  182946. png_charp current_text_ptr; /* current location in current_text */
  182947. # endif /* PNG_TEXT_SUPPORTED */
  182948. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182949. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182950. /* for the Borland special 64K segment handler */
  182951. png_bytepp offset_table_ptr;
  182952. png_bytep offset_table;
  182953. png_uint_16 offset_table_number;
  182954. png_uint_16 offset_table_count;
  182955. png_uint_16 offset_table_count_free;
  182956. #endif
  182957. #if defined(PNG_READ_DITHER_SUPPORTED)
  182958. png_bytep palette_lookup; /* lookup table for dithering */
  182959. png_bytep dither_index; /* index translation for palette files */
  182960. #endif
  182961. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182962. png_uint_16p hist; /* histogram */
  182963. #endif
  182964. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182965. png_byte heuristic_method; /* heuristic for row filter selection */
  182966. png_byte num_prev_filters; /* number of weights for previous rows */
  182967. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182968. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182969. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182970. png_uint_16p filter_costs; /* relative filter calculation cost */
  182971. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182972. #endif
  182973. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182974. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182975. #endif
  182976. /* New members added in libpng-1.0.6 */
  182977. #ifdef PNG_FREE_ME_SUPPORTED
  182978. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182979. #endif
  182980. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182981. png_voidp user_chunk_ptr;
  182982. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182983. #endif
  182984. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182985. int num_chunk_list;
  182986. png_bytep chunk_list;
  182987. #endif
  182988. /* New members added in libpng-1.0.3 */
  182989. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182990. png_byte rgb_to_gray_status;
  182991. /* These were changed from png_byte in libpng-1.0.6 */
  182992. png_uint_16 rgb_to_gray_red_coeff;
  182993. png_uint_16 rgb_to_gray_green_coeff;
  182994. png_uint_16 rgb_to_gray_blue_coeff;
  182995. #endif
  182996. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182997. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182998. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182999. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183000. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  183001. #ifdef PNG_1_0_X
  183002. png_byte mng_features_permitted;
  183003. #else
  183004. png_uint_32 mng_features_permitted;
  183005. #endif /* PNG_1_0_X */
  183006. #endif
  183007. /* New member added in libpng-1.0.7 */
  183008. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183009. png_fixed_point int_gamma;
  183010. #endif
  183011. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  183012. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183013. png_byte filter_type;
  183014. #endif
  183015. #if defined(PNG_1_0_X)
  183016. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  183017. png_uint_32 row_buf_size;
  183018. #endif
  183019. /* New members added in libpng-1.2.0 */
  183020. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183021. # if !defined(PNG_1_0_X)
  183022. # if defined(PNG_MMX_CODE_SUPPORTED)
  183023. png_byte mmx_bitdepth_threshold;
  183024. png_uint_32 mmx_rowbytes_threshold;
  183025. # endif
  183026. png_uint_32 asm_flags;
  183027. # endif
  183028. #endif
  183029. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  183030. #ifdef PNG_USER_MEM_SUPPORTED
  183031. png_voidp mem_ptr; /* user supplied struct for mem functions */
  183032. png_malloc_ptr malloc_fn; /* function for allocating memory */
  183033. png_free_ptr free_fn; /* function for freeing memory */
  183034. #endif
  183035. /* New member added in libpng-1.0.13 and 1.2.0 */
  183036. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  183037. #if defined(PNG_READ_DITHER_SUPPORTED)
  183038. /* The following three members were added at version 1.0.14 and 1.2.4 */
  183039. png_bytep dither_sort; /* working sort array */
  183040. png_bytep index_to_palette; /* where the original index currently is */
  183041. /* in the palette */
  183042. png_bytep palette_to_index; /* which original index points to this */
  183043. /* palette color */
  183044. #endif
  183045. /* New members added in libpng-1.0.16 and 1.2.6 */
  183046. png_byte compression_type;
  183047. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183048. png_uint_32 user_width_max;
  183049. png_uint_32 user_height_max;
  183050. #endif
  183051. /* New member added in libpng-1.0.25 and 1.2.17 */
  183052. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183053. /* storage for unknown chunk that the library doesn't recognize. */
  183054. png_unknown_chunk unknown_chunk;
  183055. #endif
  183056. };
  183057. /* This triggers a compiler error in png.c, if png.c and png.h
  183058. * do not agree upon the version number.
  183059. */
  183060. typedef png_structp version_1_2_21;
  183061. typedef png_struct FAR * FAR * png_structpp;
  183062. /* Here are the function definitions most commonly used. This is not
  183063. * the place to find out how to use libpng. See libpng.txt for the
  183064. * full explanation, see example.c for the summary. This just provides
  183065. * a simple one line description of the use of each function.
  183066. */
  183067. /* Returns the version number of the library */
  183068. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  183069. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  183070. * Handling more than 8 bytes from the beginning of the file is an error.
  183071. */
  183072. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  183073. int num_bytes));
  183074. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  183075. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  183076. * signature, and non-zero otherwise. Having num_to_check == 0 or
  183077. * start > 7 will always fail (ie return non-zero).
  183078. */
  183079. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  183080. png_size_t num_to_check));
  183081. /* Simple signature checking function. This is the same as calling
  183082. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  183083. */
  183084. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  183085. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  183086. extern PNG_EXPORT(png_structp,png_create_read_struct)
  183087. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183088. png_error_ptr error_fn, png_error_ptr warn_fn));
  183089. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  183090. extern PNG_EXPORT(png_structp,png_create_write_struct)
  183091. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183092. png_error_ptr error_fn, png_error_ptr warn_fn));
  183093. #ifdef PNG_WRITE_SUPPORTED
  183094. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  183095. PNGARG((png_structp png_ptr));
  183096. #endif
  183097. #ifdef PNG_WRITE_SUPPORTED
  183098. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  183099. PNGARG((png_structp png_ptr, png_uint_32 size));
  183100. #endif
  183101. /* Reset the compression stream */
  183102. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  183103. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  183104. #ifdef PNG_USER_MEM_SUPPORTED
  183105. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  183106. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183107. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183108. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183109. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  183110. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183111. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183112. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183113. #endif
  183114. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183115. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183116. png_bytep chunk_name, png_bytep data, png_size_t length));
  183117. /* Write the start of a PNG chunk - length and chunk name. */
  183118. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183119. png_bytep chunk_name, png_uint_32 length));
  183120. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183121. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183122. png_bytep data, png_size_t length));
  183123. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183124. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183125. /* Allocate and initialize the info structure */
  183126. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183127. PNGARG((png_structp png_ptr));
  183128. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183129. /* Initialize the info structure (old interface - DEPRECATED) */
  183130. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183131. #undef png_info_init
  183132. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183133. png_sizeof(png_info));
  183134. #endif
  183135. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183136. png_size_t png_info_struct_size));
  183137. /* Writes all the PNG information before the image. */
  183138. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183139. png_infop info_ptr));
  183140. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183141. png_infop info_ptr));
  183142. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183143. /* read the information before the actual image data. */
  183144. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183145. png_infop info_ptr));
  183146. #endif
  183147. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183148. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183149. PNGARG((png_structp png_ptr, png_timep ptime));
  183150. #endif
  183151. #if !defined(_WIN32_WCE)
  183152. /* "time.h" functions are not supported on WindowsCE */
  183153. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183154. /* convert from a struct tm to png_time */
  183155. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183156. struct tm FAR * ttime));
  183157. /* convert from time_t to png_time. Uses gmtime() */
  183158. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183159. time_t ttime));
  183160. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183161. #endif /* _WIN32_WCE */
  183162. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183163. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183164. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183165. #if !defined(PNG_1_0_X)
  183166. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183167. png_ptr));
  183168. #endif
  183169. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183170. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183171. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183172. /* Deprecated */
  183173. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183174. #endif
  183175. #endif
  183176. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183177. /* Use blue, green, red order for pixels. */
  183178. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183179. #endif
  183180. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183181. /* Expand the grayscale to 24-bit RGB if necessary. */
  183182. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183183. #endif
  183184. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183185. /* Reduce RGB to grayscale. */
  183186. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183187. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183188. int error_action, double red, double green ));
  183189. #endif
  183190. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183191. int error_action, png_fixed_point red, png_fixed_point green ));
  183192. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183193. png_ptr));
  183194. #endif
  183195. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183196. png_colorp palette));
  183197. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183198. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183199. #endif
  183200. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183201. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183202. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183203. #endif
  183204. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183205. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183206. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183207. #endif
  183208. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183209. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183210. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183211. png_uint_32 filler, int flags));
  183212. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183213. #define PNG_FILLER_BEFORE 0
  183214. #define PNG_FILLER_AFTER 1
  183215. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183216. #if !defined(PNG_1_0_X)
  183217. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183218. png_uint_32 filler, int flags));
  183219. #endif
  183220. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183221. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183222. /* Swap bytes in 16-bit depth files. */
  183223. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183224. #endif
  183225. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183226. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183227. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183228. #endif
  183229. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183230. /* Swap packing order of pixels in bytes. */
  183231. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183232. #endif
  183233. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183234. /* Converts files to legal bit depths. */
  183235. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183236. png_color_8p true_bits));
  183237. #endif
  183238. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183239. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183240. /* Have the code handle the interlacing. Returns the number of passes. */
  183241. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183242. #endif
  183243. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183244. /* Invert monochrome files */
  183245. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183246. #endif
  183247. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183248. /* Handle alpha and tRNS by replacing with a background color. */
  183249. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183250. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183251. png_color_16p background_color, int background_gamma_code,
  183252. int need_expand, double background_gamma));
  183253. #endif
  183254. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183255. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183256. #define PNG_BACKGROUND_GAMMA_FILE 2
  183257. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183258. #endif
  183259. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183260. /* strip the second byte of information from a 16-bit depth file. */
  183261. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183262. #endif
  183263. #if defined(PNG_READ_DITHER_SUPPORTED)
  183264. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183265. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183266. png_colorp palette, int num_palette, int maximum_colors,
  183267. png_uint_16p histogram, int full_dither));
  183268. #endif
  183269. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183270. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183271. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183272. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183273. double screen_gamma, double default_file_gamma));
  183274. #endif
  183275. #endif
  183276. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183277. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183278. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183279. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183280. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183281. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183282. int empty_plte_permitted));
  183283. #endif
  183284. #endif
  183285. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183286. /* Set how many lines between output flushes - 0 for no flushing */
  183287. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183288. /* Flush the current PNG output buffer */
  183289. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183290. #endif
  183291. /* optional update palette with requested transformations */
  183292. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183293. /* optional call to update the users info structure */
  183294. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183295. png_infop info_ptr));
  183296. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183297. /* read one or more rows of image data. */
  183298. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183299. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183300. #endif
  183301. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183302. /* read a row of data. */
  183303. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183304. png_bytep row,
  183305. png_bytep display_row));
  183306. #endif
  183307. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183308. /* read the whole image into memory at once. */
  183309. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183310. png_bytepp image));
  183311. #endif
  183312. /* write a row of image data */
  183313. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183314. png_bytep row));
  183315. /* write a few rows of image data */
  183316. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183317. png_bytepp row, png_uint_32 num_rows));
  183318. /* write the image data */
  183319. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183320. png_bytepp image));
  183321. /* writes the end of the PNG file. */
  183322. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183323. png_infop info_ptr));
  183324. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183325. /* read the end of the PNG file. */
  183326. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183327. png_infop info_ptr));
  183328. #endif
  183329. /* free any memory associated with the png_info_struct */
  183330. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183331. png_infopp info_ptr_ptr));
  183332. /* free any memory associated with the png_struct and the png_info_structs */
  183333. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183334. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183335. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183336. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183337. png_infop end_info_ptr));
  183338. /* free any memory associated with the png_struct and the png_info_structs */
  183339. extern PNG_EXPORT(void,png_destroy_write_struct)
  183340. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183341. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183342. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183343. /* set the libpng method of handling chunk CRC errors */
  183344. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183345. int crit_action, int ancil_action));
  183346. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183347. * ancillary and critical chunks, and whether to use the data contained
  183348. * therein. Note that it is impossible to "discard" data in a critical
  183349. * chunk. For versions prior to 0.90, the action was always error/quit,
  183350. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183351. * chunks is warn/discard. These values should NOT be changed.
  183352. *
  183353. * value action:critical action:ancillary
  183354. */
  183355. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183356. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183357. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183358. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183359. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183360. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183361. /* These functions give the user control over the scan-line filtering in
  183362. * libpng and the compression methods used by zlib. These functions are
  183363. * mainly useful for testing, as the defaults should work with most users.
  183364. * Those users who are tight on memory or want faster performance at the
  183365. * expense of compression can modify them. See the compression library
  183366. * header file (zlib.h) for an explination of the compression functions.
  183367. */
  183368. /* set the filtering method(s) used by libpng. Currently, the only valid
  183369. * value for "method" is 0.
  183370. */
  183371. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183372. int filters));
  183373. /* Flags for png_set_filter() to say which filters to use. The flags
  183374. * are chosen so that they don't conflict with real filter types
  183375. * below, in case they are supplied instead of the #defined constants.
  183376. * These values should NOT be changed.
  183377. */
  183378. #define PNG_NO_FILTERS 0x00
  183379. #define PNG_FILTER_NONE 0x08
  183380. #define PNG_FILTER_SUB 0x10
  183381. #define PNG_FILTER_UP 0x20
  183382. #define PNG_FILTER_AVG 0x40
  183383. #define PNG_FILTER_PAETH 0x80
  183384. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183385. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183386. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183387. * These defines should NOT be changed.
  183388. */
  183389. #define PNG_FILTER_VALUE_NONE 0
  183390. #define PNG_FILTER_VALUE_SUB 1
  183391. #define PNG_FILTER_VALUE_UP 2
  183392. #define PNG_FILTER_VALUE_AVG 3
  183393. #define PNG_FILTER_VALUE_PAETH 4
  183394. #define PNG_FILTER_VALUE_LAST 5
  183395. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183396. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183397. * defines, either the default (minimum-sum-of-absolute-differences), or
  183398. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183399. *
  183400. * Weights are factors >= 1.0, indicating how important it is to keep the
  183401. * filter type consistent between rows. Larger numbers mean the current
  183402. * filter is that many times as likely to be the same as the "num_weights"
  183403. * previous filters. This is cumulative for each previous row with a weight.
  183404. * There needs to be "num_weights" values in "filter_weights", or it can be
  183405. * NULL if the weights aren't being specified. Weights have no influence on
  183406. * the selection of the first row filter. Well chosen weights can (in theory)
  183407. * improve the compression for a given image.
  183408. *
  183409. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183410. * filter type. Higher costs indicate more decoding expense, and are
  183411. * therefore less likely to be selected over a filter with lower computational
  183412. * costs. There needs to be a value in "filter_costs" for each valid filter
  183413. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183414. * setting the costs. Costs try to improve the speed of decompression without
  183415. * unduly increasing the compressed image size.
  183416. *
  183417. * A negative weight or cost indicates the default value is to be used, and
  183418. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183419. * The default values for both weights and costs are currently 1.0, but may
  183420. * change if good general weighting/cost heuristics can be found. If both
  183421. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183422. * to the UNWEIGHTED method, but with added encoding time/computation.
  183423. */
  183424. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183425. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183426. int heuristic_method, int num_weights, png_doublep filter_weights,
  183427. png_doublep filter_costs));
  183428. #endif
  183429. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183430. /* Heuristic used for row filter selection. These defines should NOT be
  183431. * changed.
  183432. */
  183433. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183434. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183435. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183436. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183437. /* Set the library compression level. Currently, valid values range from
  183438. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183439. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183440. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183441. * for PNG images, and do considerably fewer caclulations. In the future,
  183442. * these values may not correspond directly to the zlib compression levels.
  183443. */
  183444. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183445. int level));
  183446. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183447. PNGARG((png_structp png_ptr, int mem_level));
  183448. extern PNG_EXPORT(void,png_set_compression_strategy)
  183449. PNGARG((png_structp png_ptr, int strategy));
  183450. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183451. PNGARG((png_structp png_ptr, int window_bits));
  183452. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183453. int method));
  183454. /* These next functions are called for input/output, memory, and error
  183455. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183456. * and call standard C I/O routines such as fread(), fwrite(), and
  183457. * fprintf(). These functions can be made to use other I/O routines
  183458. * at run time for those applications that need to handle I/O in a
  183459. * different manner by calling png_set_???_fn(). See libpng.txt for
  183460. * more information.
  183461. */
  183462. #if !defined(PNG_NO_STDIO)
  183463. /* Initialize the input/output for the PNG file to the default functions. */
  183464. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183465. #endif
  183466. /* Replace the (error and abort), and warning functions with user
  183467. * supplied functions. If no messages are to be printed you must still
  183468. * write and use replacement functions. The replacement error_fn should
  183469. * still do a longjmp to the last setjmp location if you are using this
  183470. * method of error handling. If error_fn or warning_fn is NULL, the
  183471. * default function will be used.
  183472. */
  183473. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183474. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183475. /* Return the user pointer associated with the error functions */
  183476. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183477. /* Replace the default data output functions with a user supplied one(s).
  183478. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183479. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183480. * output_flush_fn will be ignored (and thus can be NULL).
  183481. */
  183482. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183483. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183484. /* Replace the default data input function with a user supplied one. */
  183485. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183486. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183487. /* Return the user pointer associated with the I/O functions */
  183488. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183489. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183490. png_read_status_ptr read_row_fn));
  183491. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183492. png_write_status_ptr write_row_fn));
  183493. #ifdef PNG_USER_MEM_SUPPORTED
  183494. /* Replace the default memory allocation functions with user supplied one(s). */
  183495. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183496. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183497. /* Return the user pointer associated with the memory functions */
  183498. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183499. #endif
  183500. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183501. defined(PNG_LEGACY_SUPPORTED)
  183502. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183503. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183504. #endif
  183505. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183506. defined(PNG_LEGACY_SUPPORTED)
  183507. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183508. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183509. #endif
  183510. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183511. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183512. defined(PNG_LEGACY_SUPPORTED)
  183513. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183514. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183515. int user_transform_channels));
  183516. /* Return the user pointer associated with the user transform functions */
  183517. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183518. PNGARG((png_structp png_ptr));
  183519. #endif
  183520. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183521. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183522. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183523. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183524. png_ptr));
  183525. #endif
  183526. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183527. /* Sets the function callbacks for the push reader, and a pointer to a
  183528. * user-defined structure available to the callback functions.
  183529. */
  183530. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183531. png_voidp progressive_ptr,
  183532. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183533. png_progressive_end_ptr end_fn));
  183534. /* returns the user pointer associated with the push read functions */
  183535. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183536. PNGARG((png_structp png_ptr));
  183537. /* function to be called when data becomes available */
  183538. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183539. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183540. /* function that combines rows. Not very much different than the
  183541. * png_combine_row() call. Is this even used?????
  183542. */
  183543. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183544. png_bytep old_row, png_bytep new_row));
  183545. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183546. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183547. png_uint_32 size));
  183548. #if defined(PNG_1_0_X)
  183549. # define png_malloc_warn png_malloc
  183550. #else
  183551. /* Added at libpng version 1.2.4 */
  183552. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183553. png_uint_32 size));
  183554. #endif
  183555. /* frees a pointer allocated by png_malloc() */
  183556. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183557. #if defined(PNG_1_0_X)
  183558. /* Function to allocate memory for zlib. */
  183559. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183560. uInt size));
  183561. /* Function to free memory for zlib */
  183562. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183563. #endif
  183564. /* Free data that was allocated internally */
  183565. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183566. png_infop info_ptr, png_uint_32 free_me, int num));
  183567. #ifdef PNG_FREE_ME_SUPPORTED
  183568. /* Reassign responsibility for freeing existing data, whether allocated
  183569. * by libpng or by the application */
  183570. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183571. png_infop info_ptr, int freer, png_uint_32 mask));
  183572. #endif
  183573. /* assignments for png_data_freer */
  183574. #define PNG_DESTROY_WILL_FREE_DATA 1
  183575. #define PNG_SET_WILL_FREE_DATA 1
  183576. #define PNG_USER_WILL_FREE_DATA 2
  183577. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183578. #define PNG_FREE_HIST 0x0008
  183579. #define PNG_FREE_ICCP 0x0010
  183580. #define PNG_FREE_SPLT 0x0020
  183581. #define PNG_FREE_ROWS 0x0040
  183582. #define PNG_FREE_PCAL 0x0080
  183583. #define PNG_FREE_SCAL 0x0100
  183584. #define PNG_FREE_UNKN 0x0200
  183585. #define PNG_FREE_LIST 0x0400
  183586. #define PNG_FREE_PLTE 0x1000
  183587. #define PNG_FREE_TRNS 0x2000
  183588. #define PNG_FREE_TEXT 0x4000
  183589. #define PNG_FREE_ALL 0x7fff
  183590. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183591. #ifdef PNG_USER_MEM_SUPPORTED
  183592. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183593. png_uint_32 size));
  183594. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183595. png_voidp ptr));
  183596. #endif
  183597. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183598. png_voidp s1, png_voidp s2, png_uint_32 size));
  183599. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183600. png_voidp s1, int value, png_uint_32 size));
  183601. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183602. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183603. int check));
  183604. #endif /* USE_FAR_KEYWORD */
  183605. #ifndef PNG_NO_ERROR_TEXT
  183606. /* Fatal error in PNG image of libpng - can't continue */
  183607. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183608. png_const_charp error_message));
  183609. /* The same, but the chunk name is prepended to the error string. */
  183610. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183611. png_const_charp error_message));
  183612. #else
  183613. /* Fatal error in PNG image of libpng - can't continue */
  183614. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183615. #endif
  183616. #ifndef PNG_NO_WARNINGS
  183617. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183618. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183619. png_const_charp warning_message));
  183620. #ifdef PNG_READ_SUPPORTED
  183621. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183622. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183623. png_const_charp warning_message));
  183624. #endif /* PNG_READ_SUPPORTED */
  183625. #endif /* PNG_NO_WARNINGS */
  183626. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183627. * Similarly, the png_get_<chunk> calls are used to read values from the
  183628. * png_info_struct, either storing the parameters in the passed variables, or
  183629. * setting pointers into the png_info_struct where the data is stored. The
  183630. * png_get_<chunk> functions return a non-zero value if the data was available
  183631. * in info_ptr, or return zero and do not change any of the parameters if the
  183632. * data was not available.
  183633. *
  183634. * These functions should be used instead of directly accessing png_info
  183635. * to avoid problems with future changes in the size and internal layout of
  183636. * png_info_struct.
  183637. */
  183638. /* Returns "flag" if chunk data is valid in info_ptr. */
  183639. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183640. png_infop info_ptr, png_uint_32 flag));
  183641. /* Returns number of bytes needed to hold a transformed row. */
  183642. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183643. png_infop info_ptr));
  183644. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183645. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183646. returned from png_read_png(). */
  183647. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183648. png_infop info_ptr));
  183649. /* Set row_pointers, which is an array of pointers to scanlines for use
  183650. by png_write_png(). */
  183651. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183652. png_infop info_ptr, png_bytepp row_pointers));
  183653. #endif
  183654. /* Returns number of color channels in image. */
  183655. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183656. png_infop info_ptr));
  183657. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183658. /* Returns image width in pixels. */
  183659. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183660. png_ptr, png_infop info_ptr));
  183661. /* Returns image height in pixels. */
  183662. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183663. png_ptr, png_infop info_ptr));
  183664. /* Returns image bit_depth. */
  183665. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183666. png_ptr, png_infop info_ptr));
  183667. /* Returns image color_type. */
  183668. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183669. png_ptr, png_infop info_ptr));
  183670. /* Returns image filter_type. */
  183671. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183672. png_ptr, png_infop info_ptr));
  183673. /* Returns image interlace_type. */
  183674. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183675. png_ptr, png_infop info_ptr));
  183676. /* Returns image compression_type. */
  183677. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183678. png_ptr, png_infop info_ptr));
  183679. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183680. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183681. png_ptr, png_infop info_ptr));
  183682. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183683. png_ptr, png_infop info_ptr));
  183684. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183685. png_ptr, png_infop info_ptr));
  183686. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183687. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183688. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183689. png_ptr, png_infop info_ptr));
  183690. #endif
  183691. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183692. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183693. png_ptr, png_infop info_ptr));
  183694. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183695. png_ptr, png_infop info_ptr));
  183696. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183697. png_ptr, png_infop info_ptr));
  183698. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183699. png_ptr, png_infop info_ptr));
  183700. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183701. /* Returns pointer to signature string read from PNG header */
  183702. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183703. png_infop info_ptr));
  183704. #if defined(PNG_bKGD_SUPPORTED)
  183705. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183706. png_infop info_ptr, png_color_16p *background));
  183707. #endif
  183708. #if defined(PNG_bKGD_SUPPORTED)
  183709. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183710. png_infop info_ptr, png_color_16p background));
  183711. #endif
  183712. #if defined(PNG_cHRM_SUPPORTED)
  183713. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183714. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183715. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183716. double *red_y, double *green_x, double *green_y, double *blue_x,
  183717. double *blue_y));
  183718. #endif
  183719. #ifdef PNG_FIXED_POINT_SUPPORTED
  183720. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183721. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183722. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183723. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183724. *int_blue_x, png_fixed_point *int_blue_y));
  183725. #endif
  183726. #endif
  183727. #if defined(PNG_cHRM_SUPPORTED)
  183728. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183729. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183730. png_infop info_ptr, double white_x, double white_y, double red_x,
  183731. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183732. #endif
  183733. #ifdef PNG_FIXED_POINT_SUPPORTED
  183734. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183735. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183736. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183737. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183738. png_fixed_point int_blue_y));
  183739. #endif
  183740. #endif
  183741. #if defined(PNG_gAMA_SUPPORTED)
  183742. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183743. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183744. png_infop info_ptr, double *file_gamma));
  183745. #endif
  183746. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183747. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183748. #endif
  183749. #if defined(PNG_gAMA_SUPPORTED)
  183750. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183751. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183752. png_infop info_ptr, double file_gamma));
  183753. #endif
  183754. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183755. png_infop info_ptr, png_fixed_point int_file_gamma));
  183756. #endif
  183757. #if defined(PNG_hIST_SUPPORTED)
  183758. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183759. png_infop info_ptr, png_uint_16p *hist));
  183760. #endif
  183761. #if defined(PNG_hIST_SUPPORTED)
  183762. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183763. png_infop info_ptr, png_uint_16p hist));
  183764. #endif
  183765. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183766. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183767. int *bit_depth, int *color_type, int *interlace_method,
  183768. int *compression_method, int *filter_method));
  183769. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183770. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183771. int color_type, int interlace_method, int compression_method,
  183772. int filter_method));
  183773. #if defined(PNG_oFFs_SUPPORTED)
  183774. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183775. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183776. int *unit_type));
  183777. #endif
  183778. #if defined(PNG_oFFs_SUPPORTED)
  183779. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183780. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183781. int unit_type));
  183782. #endif
  183783. #if defined(PNG_pCAL_SUPPORTED)
  183784. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183785. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183786. int *type, int *nparams, png_charp *units, png_charpp *params));
  183787. #endif
  183788. #if defined(PNG_pCAL_SUPPORTED)
  183789. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183790. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183791. int type, int nparams, png_charp units, png_charpp params));
  183792. #endif
  183793. #if defined(PNG_pHYs_SUPPORTED)
  183794. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183795. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183796. #endif
  183797. #if defined(PNG_pHYs_SUPPORTED)
  183798. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183799. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183800. #endif
  183801. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183802. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183803. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183804. png_infop info_ptr, png_colorp palette, int num_palette));
  183805. #if defined(PNG_sBIT_SUPPORTED)
  183806. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183807. png_infop info_ptr, png_color_8p *sig_bit));
  183808. #endif
  183809. #if defined(PNG_sBIT_SUPPORTED)
  183810. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183811. png_infop info_ptr, png_color_8p sig_bit));
  183812. #endif
  183813. #if defined(PNG_sRGB_SUPPORTED)
  183814. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183815. png_infop info_ptr, int *intent));
  183816. #endif
  183817. #if defined(PNG_sRGB_SUPPORTED)
  183818. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183819. png_infop info_ptr, int intent));
  183820. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183821. png_infop info_ptr, int intent));
  183822. #endif
  183823. #if defined(PNG_iCCP_SUPPORTED)
  183824. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183825. png_infop info_ptr, png_charpp name, int *compression_type,
  183826. png_charpp profile, png_uint_32 *proflen));
  183827. /* Note to maintainer: profile should be png_bytepp */
  183828. #endif
  183829. #if defined(PNG_iCCP_SUPPORTED)
  183830. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183831. png_infop info_ptr, png_charp name, int compression_type,
  183832. png_charp profile, png_uint_32 proflen));
  183833. /* Note to maintainer: profile should be png_bytep */
  183834. #endif
  183835. #if defined(PNG_sPLT_SUPPORTED)
  183836. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183837. png_infop info_ptr, png_sPLT_tpp entries));
  183838. #endif
  183839. #if defined(PNG_sPLT_SUPPORTED)
  183840. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183841. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183842. #endif
  183843. #if defined(PNG_TEXT_SUPPORTED)
  183844. /* png_get_text also returns the number of text chunks in *num_text */
  183845. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183846. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183847. #endif
  183848. /*
  183849. * Note while png_set_text() will accept a structure whose text,
  183850. * language, and translated keywords are NULL pointers, the structure
  183851. * returned by png_get_text will always contain regular
  183852. * zero-terminated C strings. They might be empty strings but
  183853. * they will never be NULL pointers.
  183854. */
  183855. #if defined(PNG_TEXT_SUPPORTED)
  183856. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183857. png_infop info_ptr, png_textp text_ptr, int num_text));
  183858. #endif
  183859. #if defined(PNG_tIME_SUPPORTED)
  183860. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183861. png_infop info_ptr, png_timep *mod_time));
  183862. #endif
  183863. #if defined(PNG_tIME_SUPPORTED)
  183864. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183865. png_infop info_ptr, png_timep mod_time));
  183866. #endif
  183867. #if defined(PNG_tRNS_SUPPORTED)
  183868. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183869. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183870. png_color_16p *trans_values));
  183871. #endif
  183872. #if defined(PNG_tRNS_SUPPORTED)
  183873. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183874. png_infop info_ptr, png_bytep trans, int num_trans,
  183875. png_color_16p trans_values));
  183876. #endif
  183877. #if defined(PNG_tRNS_SUPPORTED)
  183878. #endif
  183879. #if defined(PNG_sCAL_SUPPORTED)
  183880. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183881. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183882. png_infop info_ptr, int *unit, double *width, double *height));
  183883. #else
  183884. #ifdef PNG_FIXED_POINT_SUPPORTED
  183885. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183886. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183887. #endif
  183888. #endif
  183889. #endif /* PNG_sCAL_SUPPORTED */
  183890. #if defined(PNG_sCAL_SUPPORTED)
  183891. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183892. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183893. png_infop info_ptr, int unit, double width, double height));
  183894. #else
  183895. #ifdef PNG_FIXED_POINT_SUPPORTED
  183896. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183897. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183898. #endif
  183899. #endif
  183900. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183901. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183902. /* provide a list of chunks and how they are to be handled, if the built-in
  183903. handling or default unknown chunk handling is not desired. Any chunks not
  183904. listed will be handled in the default manner. The IHDR and IEND chunks
  183905. must not be listed.
  183906. keep = 0: follow default behaviour
  183907. = 1: do not keep
  183908. = 2: keep only if safe-to-copy
  183909. = 3: keep even if unsafe-to-copy
  183910. */
  183911. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183912. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183913. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183914. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183915. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183916. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183917. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183918. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183919. #endif
  183920. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183921. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183922. chunk_name));
  183923. #endif
  183924. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183925. If you need to turn it off for a chunk that your application has freed,
  183926. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183927. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183928. png_infop info_ptr, int mask));
  183929. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183930. /* The "params" pointer is currently not used and is for future expansion. */
  183931. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183932. png_infop info_ptr,
  183933. int transforms,
  183934. png_voidp params));
  183935. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183936. png_infop info_ptr,
  183937. int transforms,
  183938. png_voidp params));
  183939. #endif
  183940. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183941. * numbers for PNG_DEBUG mean more debugging information. This has
  183942. * only been added since version 0.95 so it is not implemented throughout
  183943. * libpng yet, but more support will be added as needed.
  183944. */
  183945. #ifdef PNG_DEBUG
  183946. #if (PNG_DEBUG > 0)
  183947. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183948. #include <crtdbg.h>
  183949. #if (PNG_DEBUG > 1)
  183950. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183951. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183952. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183953. #endif
  183954. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183955. #ifndef PNG_DEBUG_FILE
  183956. #define PNG_DEBUG_FILE stderr
  183957. #endif /* PNG_DEBUG_FILE */
  183958. #if (PNG_DEBUG > 1)
  183959. #define png_debug(l,m) \
  183960. { \
  183961. int num_tabs=l; \
  183962. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183963. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183964. }
  183965. #define png_debug1(l,m,p1) \
  183966. { \
  183967. int num_tabs=l; \
  183968. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183969. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183970. }
  183971. #define png_debug2(l,m,p1,p2) \
  183972. { \
  183973. int num_tabs=l; \
  183974. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183975. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183976. }
  183977. #endif /* (PNG_DEBUG > 1) */
  183978. #endif /* _MSC_VER */
  183979. #endif /* (PNG_DEBUG > 0) */
  183980. #endif /* PNG_DEBUG */
  183981. #ifndef png_debug
  183982. #define png_debug(l, m)
  183983. #endif
  183984. #ifndef png_debug1
  183985. #define png_debug1(l, m, p1)
  183986. #endif
  183987. #ifndef png_debug2
  183988. #define png_debug2(l, m, p1, p2)
  183989. #endif
  183990. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183991. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183992. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183993. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183994. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183995. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183996. png_ptr, png_uint_32 mng_features_permitted));
  183997. #endif
  183998. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183999. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  184000. #define PNG_HANDLE_CHUNK_NEVER 1
  184001. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  184002. #define PNG_HANDLE_CHUNK_ALWAYS 3
  184003. /* Added to version 1.2.0 */
  184004. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184005. #if defined(PNG_MMX_CODE_SUPPORTED)
  184006. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  184007. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  184008. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  184009. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  184010. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  184011. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  184012. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  184013. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  184014. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  184015. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  184016. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  184017. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  184018. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  184019. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  184020. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  184021. #define PNG_MMX_WRITE_FLAGS ( 0 )
  184022. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  184023. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  184024. | PNG_MMX_READ_FLAGS \
  184025. | PNG_MMX_WRITE_FLAGS )
  184026. #define PNG_SELECT_READ 1
  184027. #define PNG_SELECT_WRITE 2
  184028. #endif /* PNG_MMX_CODE_SUPPORTED */
  184029. #if !defined(PNG_1_0_X)
  184030. /* pngget.c */
  184031. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  184032. PNGARG((int flag_select, int *compilerID));
  184033. /* pngget.c */
  184034. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  184035. PNGARG((int flag_select));
  184036. /* pngget.c */
  184037. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  184038. PNGARG((png_structp png_ptr));
  184039. /* pngget.c */
  184040. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  184041. PNGARG((png_structp png_ptr));
  184042. /* pngget.c */
  184043. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  184044. PNGARG((png_structp png_ptr));
  184045. /* pngset.c */
  184046. extern PNG_EXPORT(void,png_set_asm_flags)
  184047. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  184048. /* pngset.c */
  184049. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  184050. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  184051. png_uint_32 mmx_rowbytes_threshold));
  184052. #endif /* PNG_1_0_X */
  184053. #if !defined(PNG_1_0_X)
  184054. /* png.c, pnggccrd.c, or pngvcrd.c */
  184055. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  184056. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  184057. /* Strip the prepended error numbers ("#nnn ") from error and warning
  184058. * messages before passing them to the error or warning handler. */
  184059. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184060. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  184061. png_ptr, png_uint_32 strip_mode));
  184062. #endif
  184063. #endif /* PNG_1_0_X */
  184064. /* Added at libpng-1.2.6 */
  184065. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184066. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  184067. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  184068. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  184069. png_ptr));
  184070. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  184071. png_ptr));
  184072. #endif
  184073. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  184074. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  184075. /* With these routines we avoid an integer divide, which will be slower on
  184076. * most machines. However, it does take more operations than the corresponding
  184077. * divide method, so it may be slower on a few RISC systems. There are two
  184078. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  184079. *
  184080. * Note that the rounding factors are NOT supposed to be the same! 128 and
  184081. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  184082. * standard method.
  184083. *
  184084. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  184085. */
  184086. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  184087. # define png_composite(composite, fg, alpha, bg) \
  184088. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  184089. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  184090. (png_uint_16)(alpha)) + (png_uint_16)128); \
  184091. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  184092. # define png_composite_16(composite, fg, alpha, bg) \
  184093. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  184094. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  184095. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  184096. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  184097. #else /* standard method using integer division */
  184098. # define png_composite(composite, fg, alpha, bg) \
  184099. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  184100. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  184101. (png_uint_16)127) / 255)
  184102. # define png_composite_16(composite, fg, alpha, bg) \
  184103. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  184104. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  184105. (png_uint_32)32767) / (png_uint_32)65535L)
  184106. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  184107. /* Inline macros to do direct reads of bytes from the input buffer. These
  184108. * require that you are using an architecture that uses PNG byte ordering
  184109. * (MSB first) and supports unaligned data storage. I think that PowerPC
  184110. * in big-endian mode and 680x0 are the only ones that will support this.
  184111. * The x86 line of processors definitely do not. The png_get_int_32()
  184112. * routine also assumes we are using two's complement format for negative
  184113. * values, which is almost certainly true.
  184114. */
  184115. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184116. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184117. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184118. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184119. #else
  184120. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184121. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184122. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184123. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184124. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184125. PNGARG((png_structp png_ptr, png_bytep buf));
  184126. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184127. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184128. */
  184129. extern PNG_EXPORT(void,png_save_uint_32)
  184130. PNGARG((png_bytep buf, png_uint_32 i));
  184131. extern PNG_EXPORT(void,png_save_int_32)
  184132. PNGARG((png_bytep buf, png_int_32 i));
  184133. /* Place a 16-bit number into a buffer in PNG byte order.
  184134. * The parameter is declared unsigned int, not png_uint_16,
  184135. * just to avoid potential problems on pre-ANSI C compilers.
  184136. */
  184137. extern PNG_EXPORT(void,png_save_uint_16)
  184138. PNGARG((png_bytep buf, unsigned int i));
  184139. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184140. /* ************************************************************************* */
  184141. /* These next functions are used internally in the code. They generally
  184142. * shouldn't be used unless you are writing code to add or replace some
  184143. * functionality in libpng. More information about most functions can
  184144. * be found in the files where the functions are located.
  184145. */
  184146. /* Various modes of operation, that are visible to applications because
  184147. * they are used for unknown chunk location.
  184148. */
  184149. #define PNG_HAVE_IHDR 0x01
  184150. #define PNG_HAVE_PLTE 0x02
  184151. #define PNG_HAVE_IDAT 0x04
  184152. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184153. #define PNG_HAVE_IEND 0x10
  184154. #if defined(PNG_INTERNAL)
  184155. /* More modes of operation. Note that after an init, mode is set to
  184156. * zero automatically when the structure is created.
  184157. */
  184158. #define PNG_HAVE_gAMA 0x20
  184159. #define PNG_HAVE_cHRM 0x40
  184160. #define PNG_HAVE_sRGB 0x80
  184161. #define PNG_HAVE_CHUNK_HEADER 0x100
  184162. #define PNG_WROTE_tIME 0x200
  184163. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184164. #define PNG_BACKGROUND_IS_GRAY 0x800
  184165. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184166. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184167. /* flags for the transformations the PNG library does on the image data */
  184168. #define PNG_BGR 0x0001
  184169. #define PNG_INTERLACE 0x0002
  184170. #define PNG_PACK 0x0004
  184171. #define PNG_SHIFT 0x0008
  184172. #define PNG_SWAP_BYTES 0x0010
  184173. #define PNG_INVERT_MONO 0x0020
  184174. #define PNG_DITHER 0x0040
  184175. #define PNG_BACKGROUND 0x0080
  184176. #define PNG_BACKGROUND_EXPAND 0x0100
  184177. /* 0x0200 unused */
  184178. #define PNG_16_TO_8 0x0400
  184179. #define PNG_RGBA 0x0800
  184180. #define PNG_EXPAND 0x1000
  184181. #define PNG_GAMMA 0x2000
  184182. #define PNG_GRAY_TO_RGB 0x4000
  184183. #define PNG_FILLER 0x8000L
  184184. #define PNG_PACKSWAP 0x10000L
  184185. #define PNG_SWAP_ALPHA 0x20000L
  184186. #define PNG_STRIP_ALPHA 0x40000L
  184187. #define PNG_INVERT_ALPHA 0x80000L
  184188. #define PNG_USER_TRANSFORM 0x100000L
  184189. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184190. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184191. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184192. /* 0x800000L Unused */
  184193. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184194. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184195. /* 0x4000000L unused */
  184196. /* 0x8000000L unused */
  184197. /* 0x10000000L unused */
  184198. /* 0x20000000L unused */
  184199. /* 0x40000000L unused */
  184200. /* flags for png_create_struct */
  184201. #define PNG_STRUCT_PNG 0x0001
  184202. #define PNG_STRUCT_INFO 0x0002
  184203. /* Scaling factor for filter heuristic weighting calculations */
  184204. #define PNG_WEIGHT_SHIFT 8
  184205. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184206. #define PNG_COST_SHIFT 3
  184207. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184208. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184209. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184210. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184211. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184212. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184213. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184214. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184215. #define PNG_FLAG_ROW_INIT 0x0040
  184216. #define PNG_FLAG_FILLER_AFTER 0x0080
  184217. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184218. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184219. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184220. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184221. #define PNG_FLAG_FREE_PLTE 0x1000
  184222. #define PNG_FLAG_FREE_TRNS 0x2000
  184223. #define PNG_FLAG_FREE_HIST 0x4000
  184224. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184225. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184226. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184227. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184228. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184229. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184230. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184231. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184232. /* 0x800000L unused */
  184233. /* 0x1000000L unused */
  184234. /* 0x2000000L unused */
  184235. /* 0x4000000L unused */
  184236. /* 0x8000000L unused */
  184237. /* 0x10000000L unused */
  184238. /* 0x20000000L unused */
  184239. /* 0x40000000L unused */
  184240. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184241. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184242. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184243. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184244. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184245. PNG_FLAG_CRC_CRITICAL_MASK)
  184246. /* save typing and make code easier to understand */
  184247. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184248. abs((int)((c1).green) - (int)((c2).green)) + \
  184249. abs((int)((c1).blue) - (int)((c2).blue)))
  184250. /* Added to libpng-1.2.6 JB */
  184251. #define PNG_ROWBYTES(pixel_bits, width) \
  184252. ((pixel_bits) >= 8 ? \
  184253. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184254. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184255. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184256. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184257. "ideal" and "delta" should be constants, normally simple
  184258. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184259. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184260. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184261. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184262. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184263. /* place to hold the signature string for a PNG file. */
  184264. #ifdef PNG_USE_GLOBAL_ARRAYS
  184265. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184266. #else
  184267. #endif
  184268. #endif /* PNG_NO_EXTERN */
  184269. /* Constant strings for known chunk types. If you need to add a chunk,
  184270. * define the name here, and add an invocation of the macro in png.c and
  184271. * wherever it's needed.
  184272. */
  184273. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184274. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184275. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184276. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184277. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184278. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184279. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184280. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184281. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184282. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184283. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184284. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184285. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184286. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184287. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184288. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184289. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184290. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184291. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184292. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184293. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184294. #ifdef PNG_USE_GLOBAL_ARRAYS
  184295. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184296. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184297. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184298. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184299. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184300. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184301. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184302. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184303. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184304. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184305. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184306. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184307. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184308. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184309. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184310. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184311. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184312. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184313. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184314. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184315. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184316. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184317. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184318. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184319. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184320. */
  184321. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184322. #undef png_read_init
  184323. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184324. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184325. #endif
  184326. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184327. png_const_charp user_png_ver, png_size_t png_struct_size));
  184328. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184329. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184330. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184331. png_info_size));
  184332. #endif
  184333. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184334. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184335. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184336. */
  184337. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184338. #undef png_write_init
  184339. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184340. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184341. #endif
  184342. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184343. png_const_charp user_png_ver, png_size_t png_struct_size));
  184344. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184345. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184346. png_info_size));
  184347. /* Allocate memory for an internal libpng struct */
  184348. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184349. /* Free memory from internal libpng struct */
  184350. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184351. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184352. malloc_fn, png_voidp mem_ptr));
  184353. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184354. png_free_ptr free_fn, png_voidp mem_ptr));
  184355. /* Free any memory that info_ptr points to and reset struct. */
  184356. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184357. png_infop info_ptr));
  184358. #ifndef PNG_1_0_X
  184359. /* Function to allocate memory for zlib. */
  184360. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184361. /* Function to free memory for zlib */
  184362. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184363. #ifdef PNG_SIZE_T
  184364. /* Function to convert a sizeof an item to png_sizeof item */
  184365. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184366. #endif
  184367. /* Next four functions are used internally as callbacks. PNGAPI is required
  184368. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184369. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184370. png_bytep data, png_size_t length));
  184371. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184372. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184373. png_bytep buffer, png_size_t length));
  184374. #endif
  184375. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184376. png_bytep data, png_size_t length));
  184377. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184378. #if !defined(PNG_NO_STDIO)
  184379. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184380. #endif
  184381. #endif
  184382. #else /* PNG_1_0_X */
  184383. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184384. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184385. png_bytep buffer, png_size_t length));
  184386. #endif
  184387. #endif /* PNG_1_0_X */
  184388. /* Reset the CRC variable */
  184389. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184390. /* Write the "data" buffer to whatever output you are using. */
  184391. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184392. png_size_t length));
  184393. /* Read data from whatever input you are using into the "data" buffer */
  184394. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184395. png_size_t length));
  184396. /* Read bytes into buf, and update png_ptr->crc */
  184397. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184398. png_size_t length));
  184399. /* Decompress data in a chunk that uses compression */
  184400. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184401. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184402. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184403. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184404. png_size_t prefix_length, png_size_t *data_length));
  184405. #endif
  184406. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184407. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184408. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184409. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184410. /* Calculate the CRC over a section of data. Note that we are only
  184411. * passing a maximum of 64K on systems that have this as a memory limit,
  184412. * since this is the maximum buffer size we can specify.
  184413. */
  184414. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184415. png_size_t length));
  184416. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184417. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184418. #endif
  184419. /* simple function to write the signature */
  184420. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184421. /* write various chunks */
  184422. /* Write the IHDR chunk, and update the png_struct with the necessary
  184423. * information.
  184424. */
  184425. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184426. png_uint_32 height,
  184427. int bit_depth, int color_type, int compression_method, int filter_method,
  184428. int interlace_method));
  184429. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184430. png_uint_32 num_pal));
  184431. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184432. png_size_t length));
  184433. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184434. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184435. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184436. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184437. #endif
  184438. #ifdef PNG_FIXED_POINT_SUPPORTED
  184439. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184440. file_gamma));
  184441. #endif
  184442. #endif
  184443. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184444. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184445. int color_type));
  184446. #endif
  184447. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184448. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184449. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184450. double white_x, double white_y,
  184451. double red_x, double red_y, double green_x, double green_y,
  184452. double blue_x, double blue_y));
  184453. #endif
  184454. #ifdef PNG_FIXED_POINT_SUPPORTED
  184455. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184456. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184457. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184458. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184459. png_fixed_point int_blue_y));
  184460. #endif
  184461. #endif
  184462. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184463. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184464. int intent));
  184465. #endif
  184466. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184467. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184468. png_charp name, int compression_type,
  184469. png_charp profile, int proflen));
  184470. /* Note to maintainer: profile should be png_bytep */
  184471. #endif
  184472. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184473. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184474. png_sPLT_tp palette));
  184475. #endif
  184476. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184477. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184478. png_color_16p values, int number, int color_type));
  184479. #endif
  184480. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184481. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184482. png_color_16p values, int color_type));
  184483. #endif
  184484. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184485. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184486. int num_hist));
  184487. #endif
  184488. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184489. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184490. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184491. png_charp key, png_charpp new_key));
  184492. #endif
  184493. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184494. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184495. png_charp text, png_size_t text_len));
  184496. #endif
  184497. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184498. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184499. png_charp text, png_size_t text_len, int compression));
  184500. #endif
  184501. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184502. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184503. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184504. png_charp text));
  184505. #endif
  184506. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184507. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184508. png_infop info_ptr, png_textp text_ptr, int num_text));
  184509. #endif
  184510. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184511. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184512. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184513. #endif
  184514. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184515. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184516. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184517. png_charp units, png_charpp params));
  184518. #endif
  184519. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184520. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184521. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184522. int unit_type));
  184523. #endif
  184524. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184525. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184526. png_timep mod_time));
  184527. #endif
  184528. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184529. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184530. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184531. int unit, double width, double height));
  184532. #else
  184533. #ifdef PNG_FIXED_POINT_SUPPORTED
  184534. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184535. int unit, png_charp width, png_charp height));
  184536. #endif
  184537. #endif
  184538. #endif
  184539. /* Called when finished processing a row of data */
  184540. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184541. /* Internal use only. Called before first row of data */
  184542. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184543. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184544. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184545. #endif
  184546. /* combine a row of data, dealing with alpha, etc. if requested */
  184547. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184548. int mask));
  184549. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184550. /* expand an interlaced row */
  184551. /* OLD pre-1.0.9 interface:
  184552. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184553. png_bytep row, int pass, png_uint_32 transformations));
  184554. */
  184555. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184556. #endif
  184557. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184558. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184559. /* grab pixels out of a row for an interlaced pass */
  184560. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184561. png_bytep row, int pass));
  184562. #endif
  184563. /* unfilter a row */
  184564. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184565. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184566. /* Choose the best filter to use and filter the row data */
  184567. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184568. png_row_infop row_info));
  184569. /* Write out the filtered row. */
  184570. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184571. png_bytep filtered_row));
  184572. /* finish a row while reading, dealing with interlacing passes, etc. */
  184573. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184574. /* initialize the row buffers, etc. */
  184575. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184576. /* optional call to update the users info structure */
  184577. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184578. png_infop info_ptr));
  184579. /* these are the functions that do the transformations */
  184580. #if defined(PNG_READ_FILLER_SUPPORTED)
  184581. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184582. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184583. #endif
  184584. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184585. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184586. png_bytep row));
  184587. #endif
  184588. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184589. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184590. png_bytep row));
  184591. #endif
  184592. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184593. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184594. png_bytep row));
  184595. #endif
  184596. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184597. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184598. png_bytep row));
  184599. #endif
  184600. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184601. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184602. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184603. png_bytep row, png_uint_32 flags));
  184604. #endif
  184605. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184606. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184607. #endif
  184608. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184609. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184610. #endif
  184611. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184612. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184613. row_info, png_bytep row));
  184614. #endif
  184615. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184616. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184617. png_bytep row));
  184618. #endif
  184619. #if defined(PNG_READ_PACK_SUPPORTED)
  184620. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184621. #endif
  184622. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184623. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184624. png_color_8p sig_bits));
  184625. #endif
  184626. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184627. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184628. #endif
  184629. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184630. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184631. #endif
  184632. #if defined(PNG_READ_DITHER_SUPPORTED)
  184633. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184634. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184635. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184636. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184637. png_colorp palette, int num_palette));
  184638. # endif
  184639. #endif
  184640. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184641. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184642. #endif
  184643. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184644. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184645. png_bytep row, png_uint_32 bit_depth));
  184646. #endif
  184647. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184648. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184649. png_color_8p bit_depth));
  184650. #endif
  184651. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184652. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184653. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184654. png_color_16p trans_values, png_color_16p background,
  184655. png_color_16p background_1,
  184656. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184657. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184658. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184659. #else
  184660. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184661. png_color_16p trans_values, png_color_16p background));
  184662. #endif
  184663. #endif
  184664. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184665. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184666. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184667. int gamma_shift));
  184668. #endif
  184669. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184670. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184671. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184672. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184673. png_bytep row, png_color_16p trans_value));
  184674. #endif
  184675. /* The following decodes the appropriate chunks, and does error correction,
  184676. * then calls the appropriate callback for the chunk if it is valid.
  184677. */
  184678. /* decode the IHDR chunk */
  184679. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184680. png_uint_32 length));
  184681. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184682. png_uint_32 length));
  184683. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184684. png_uint_32 length));
  184685. #if defined(PNG_READ_bKGD_SUPPORTED)
  184686. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184687. png_uint_32 length));
  184688. #endif
  184689. #if defined(PNG_READ_cHRM_SUPPORTED)
  184690. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184691. png_uint_32 length));
  184692. #endif
  184693. #if defined(PNG_READ_gAMA_SUPPORTED)
  184694. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184695. png_uint_32 length));
  184696. #endif
  184697. #if defined(PNG_READ_hIST_SUPPORTED)
  184698. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184699. png_uint_32 length));
  184700. #endif
  184701. #if defined(PNG_READ_iCCP_SUPPORTED)
  184702. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184703. png_uint_32 length));
  184704. #endif /* PNG_READ_iCCP_SUPPORTED */
  184705. #if defined(PNG_READ_iTXt_SUPPORTED)
  184706. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184707. png_uint_32 length));
  184708. #endif
  184709. #if defined(PNG_READ_oFFs_SUPPORTED)
  184710. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184711. png_uint_32 length));
  184712. #endif
  184713. #if defined(PNG_READ_pCAL_SUPPORTED)
  184714. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184715. png_uint_32 length));
  184716. #endif
  184717. #if defined(PNG_READ_pHYs_SUPPORTED)
  184718. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184719. png_uint_32 length));
  184720. #endif
  184721. #if defined(PNG_READ_sBIT_SUPPORTED)
  184722. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184723. png_uint_32 length));
  184724. #endif
  184725. #if defined(PNG_READ_sCAL_SUPPORTED)
  184726. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184727. png_uint_32 length));
  184728. #endif
  184729. #if defined(PNG_READ_sPLT_SUPPORTED)
  184730. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184731. png_uint_32 length));
  184732. #endif /* PNG_READ_sPLT_SUPPORTED */
  184733. #if defined(PNG_READ_sRGB_SUPPORTED)
  184734. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184735. png_uint_32 length));
  184736. #endif
  184737. #if defined(PNG_READ_tEXt_SUPPORTED)
  184738. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184739. png_uint_32 length));
  184740. #endif
  184741. #if defined(PNG_READ_tIME_SUPPORTED)
  184742. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184743. png_uint_32 length));
  184744. #endif
  184745. #if defined(PNG_READ_tRNS_SUPPORTED)
  184746. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184747. png_uint_32 length));
  184748. #endif
  184749. #if defined(PNG_READ_zTXt_SUPPORTED)
  184750. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184751. png_uint_32 length));
  184752. #endif
  184753. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184754. png_infop info_ptr, png_uint_32 length));
  184755. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184756. png_bytep chunk_name));
  184757. /* handle the transformations for reading and writing */
  184758. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184759. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184760. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184761. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184762. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184763. png_infop info_ptr));
  184764. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184765. png_infop info_ptr));
  184766. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184767. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184768. png_uint_32 length));
  184769. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184770. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184771. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184772. png_bytep buffer, png_size_t buffer_length));
  184773. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184774. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184775. png_bytep buffer, png_size_t buffer_length));
  184776. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184777. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184778. png_infop info_ptr, png_uint_32 length));
  184779. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184780. png_infop info_ptr));
  184781. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184782. png_infop info_ptr));
  184783. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184784. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184785. png_infop info_ptr));
  184786. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184787. png_infop info_ptr));
  184788. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184789. #if defined(PNG_READ_tEXt_SUPPORTED)
  184790. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184791. png_infop info_ptr, png_uint_32 length));
  184792. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184793. png_infop info_ptr));
  184794. #endif
  184795. #if defined(PNG_READ_zTXt_SUPPORTED)
  184796. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184797. png_infop info_ptr, png_uint_32 length));
  184798. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184799. png_infop info_ptr));
  184800. #endif
  184801. #if defined(PNG_READ_iTXt_SUPPORTED)
  184802. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184803. png_infop info_ptr, png_uint_32 length));
  184804. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184805. png_infop info_ptr));
  184806. #endif
  184807. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184808. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184809. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184810. png_bytep row));
  184811. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184812. png_bytep row));
  184813. #endif
  184814. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184815. #if defined(PNG_MMX_CODE_SUPPORTED)
  184816. /* png.c */ /* PRIVATE */
  184817. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184818. #endif
  184819. #endif
  184820. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184821. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184822. png_infop info_ptr));
  184823. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184824. png_infop info_ptr));
  184825. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184826. png_infop info_ptr));
  184827. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184828. png_infop info_ptr));
  184829. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184830. png_infop info_ptr));
  184831. #if defined(PNG_pHYs_SUPPORTED)
  184832. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184833. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184834. #endif /* PNG_pHYs_SUPPORTED */
  184835. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184836. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184837. #endif /* PNG_INTERNAL */
  184838. #ifdef __cplusplus
  184839. //}
  184840. #endif
  184841. #endif /* PNG_VERSION_INFO_ONLY */
  184842. /* do not put anything past this line */
  184843. #endif /* PNG_H */
  184844. /*** End of inlined file: png.h ***/
  184845. #define PNG_NO_EXTERN
  184846. /*** Start of inlined file: png.c ***/
  184847. /* png.c - location for general purpose libpng functions
  184848. *
  184849. * Last changed in libpng 1.2.21 [October 4, 2007]
  184850. * For conditions of distribution and use, see copyright notice in png.h
  184851. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184852. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184853. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184854. */
  184855. #define PNG_INTERNAL
  184856. #define PNG_NO_EXTERN
  184857. /* Generate a compiler error if there is an old png.h in the search path. */
  184858. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184859. /* Version information for C files. This had better match the version
  184860. * string defined in png.h. */
  184861. #ifdef PNG_USE_GLOBAL_ARRAYS
  184862. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184863. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184864. #ifdef PNG_READ_SUPPORTED
  184865. /* png_sig was changed to a function in version 1.0.5c */
  184866. /* Place to hold the signature string for a PNG file. */
  184867. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184868. #endif /* PNG_READ_SUPPORTED */
  184869. /* Invoke global declarations for constant strings for known chunk types */
  184870. PNG_IHDR;
  184871. PNG_IDAT;
  184872. PNG_IEND;
  184873. PNG_PLTE;
  184874. PNG_bKGD;
  184875. PNG_cHRM;
  184876. PNG_gAMA;
  184877. PNG_hIST;
  184878. PNG_iCCP;
  184879. PNG_iTXt;
  184880. PNG_oFFs;
  184881. PNG_pCAL;
  184882. PNG_sCAL;
  184883. PNG_pHYs;
  184884. PNG_sBIT;
  184885. PNG_sPLT;
  184886. PNG_sRGB;
  184887. PNG_tEXt;
  184888. PNG_tIME;
  184889. PNG_tRNS;
  184890. PNG_zTXt;
  184891. #ifdef PNG_READ_SUPPORTED
  184892. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184893. /* start of interlace block */
  184894. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184895. /* offset to next interlace block */
  184896. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184897. /* start of interlace block in the y direction */
  184898. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184899. /* offset to next interlace block in the y direction */
  184900. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184901. /* Height of interlace block. This is not currently used - if you need
  184902. * it, uncomment it here and in png.h
  184903. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184904. */
  184905. /* Mask to determine which pixels are valid in a pass */
  184906. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184907. /* Mask to determine which pixels to overwrite while displaying */
  184908. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184909. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184910. #endif /* PNG_READ_SUPPORTED */
  184911. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184912. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184913. * of the PNG file signature. If the PNG data is embedded into another
  184914. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184915. * or write any of the magic bytes before it starts on the IHDR.
  184916. */
  184917. #ifdef PNG_READ_SUPPORTED
  184918. void PNGAPI
  184919. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184920. {
  184921. if(png_ptr == NULL) return;
  184922. png_debug(1, "in png_set_sig_bytes\n");
  184923. if (num_bytes > 8)
  184924. png_error(png_ptr, "Too many bytes for PNG signature.");
  184925. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184926. }
  184927. /* Checks whether the supplied bytes match the PNG signature. We allow
  184928. * checking less than the full 8-byte signature so that those apps that
  184929. * already read the first few bytes of a file to determine the file type
  184930. * can simply check the remaining bytes for extra assurance. Returns
  184931. * an integer less than, equal to, or greater than zero if sig is found,
  184932. * respectively, to be less than, to match, or be greater than the correct
  184933. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184934. */
  184935. int PNGAPI
  184936. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184937. {
  184938. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184939. if (num_to_check > 8)
  184940. num_to_check = 8;
  184941. else if (num_to_check < 1)
  184942. return (-1);
  184943. if (start > 7)
  184944. return (-1);
  184945. if (start + num_to_check > 8)
  184946. num_to_check = 8 - start;
  184947. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184948. }
  184949. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184950. /* (Obsolete) function to check signature bytes. It does not allow one
  184951. * to check a partial signature. This function might be removed in the
  184952. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184953. */
  184954. int PNGAPI
  184955. png_check_sig(png_bytep sig, int num)
  184956. {
  184957. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184958. }
  184959. #endif
  184960. #endif /* PNG_READ_SUPPORTED */
  184961. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184962. /* Function to allocate memory for zlib and clear it to 0. */
  184963. #ifdef PNG_1_0_X
  184964. voidpf PNGAPI
  184965. #else
  184966. voidpf /* private */
  184967. #endif
  184968. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184969. {
  184970. png_voidp ptr;
  184971. png_structp p=(png_structp)png_ptr;
  184972. png_uint_32 save_flags=p->flags;
  184973. png_uint_32 num_bytes;
  184974. if(png_ptr == NULL) return (NULL);
  184975. if (items > PNG_UINT_32_MAX/size)
  184976. {
  184977. png_warning (p, "Potential overflow in png_zalloc()");
  184978. return (NULL);
  184979. }
  184980. num_bytes = (png_uint_32)items * size;
  184981. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184982. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184983. p->flags=save_flags;
  184984. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184985. if (ptr == NULL)
  184986. return ((voidpf)ptr);
  184987. if (num_bytes > (png_uint_32)0x8000L)
  184988. {
  184989. png_memset(ptr, 0, (png_size_t)0x8000L);
  184990. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184991. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184992. }
  184993. else
  184994. {
  184995. png_memset(ptr, 0, (png_size_t)num_bytes);
  184996. }
  184997. #endif
  184998. return ((voidpf)ptr);
  184999. }
  185000. /* function to free memory for zlib */
  185001. #ifdef PNG_1_0_X
  185002. void PNGAPI
  185003. #else
  185004. void /* private */
  185005. #endif
  185006. png_zfree(voidpf png_ptr, voidpf ptr)
  185007. {
  185008. png_free((png_structp)png_ptr, (png_voidp)ptr);
  185009. }
  185010. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  185011. * in case CRC is > 32 bits to leave the top bits 0.
  185012. */
  185013. void /* PRIVATE */
  185014. png_reset_crc(png_structp png_ptr)
  185015. {
  185016. png_ptr->crc = crc32(0, Z_NULL, 0);
  185017. }
  185018. /* Calculate the CRC over a section of data. We can only pass as
  185019. * much data to this routine as the largest single buffer size. We
  185020. * also check that this data will actually be used before going to the
  185021. * trouble of calculating it.
  185022. */
  185023. void /* PRIVATE */
  185024. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  185025. {
  185026. int need_crc = 1;
  185027. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  185028. {
  185029. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  185030. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  185031. need_crc = 0;
  185032. }
  185033. else /* critical */
  185034. {
  185035. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  185036. need_crc = 0;
  185037. }
  185038. if (need_crc)
  185039. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  185040. }
  185041. /* Allocate the memory for an info_struct for the application. We don't
  185042. * really need the png_ptr, but it could potentially be useful in the
  185043. * future. This should be used in favour of malloc(png_sizeof(png_info))
  185044. * and png_info_init() so that applications that want to use a shared
  185045. * libpng don't have to be recompiled if png_info changes size.
  185046. */
  185047. png_infop PNGAPI
  185048. png_create_info_struct(png_structp png_ptr)
  185049. {
  185050. png_infop info_ptr;
  185051. png_debug(1, "in png_create_info_struct\n");
  185052. if(png_ptr == NULL) return (NULL);
  185053. #ifdef PNG_USER_MEM_SUPPORTED
  185054. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  185055. png_ptr->malloc_fn, png_ptr->mem_ptr);
  185056. #else
  185057. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185058. #endif
  185059. if (info_ptr != NULL)
  185060. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185061. return (info_ptr);
  185062. }
  185063. /* This function frees the memory associated with a single info struct.
  185064. * Normally, one would use either png_destroy_read_struct() or
  185065. * png_destroy_write_struct() to free an info struct, but this may be
  185066. * useful for some applications.
  185067. */
  185068. void PNGAPI
  185069. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  185070. {
  185071. png_infop info_ptr = NULL;
  185072. if(png_ptr == NULL) return;
  185073. png_debug(1, "in png_destroy_info_struct\n");
  185074. if (info_ptr_ptr != NULL)
  185075. info_ptr = *info_ptr_ptr;
  185076. if (info_ptr != NULL)
  185077. {
  185078. png_info_destroy(png_ptr, info_ptr);
  185079. #ifdef PNG_USER_MEM_SUPPORTED
  185080. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  185081. png_ptr->mem_ptr);
  185082. #else
  185083. png_destroy_struct((png_voidp)info_ptr);
  185084. #endif
  185085. *info_ptr_ptr = NULL;
  185086. }
  185087. }
  185088. /* Initialize the info structure. This is now an internal function (0.89)
  185089. * and applications using it are urged to use png_create_info_struct()
  185090. * instead.
  185091. */
  185092. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185093. #undef png_info_init
  185094. void PNGAPI
  185095. png_info_init(png_infop info_ptr)
  185096. {
  185097. /* We only come here via pre-1.0.12-compiled applications */
  185098. png_info_init_3(&info_ptr, 0);
  185099. }
  185100. #endif
  185101. void PNGAPI
  185102. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  185103. {
  185104. png_infop info_ptr = *ptr_ptr;
  185105. if(info_ptr == NULL) return;
  185106. png_debug(1, "in png_info_init_3\n");
  185107. if(png_sizeof(png_info) > png_info_struct_size)
  185108. {
  185109. png_destroy_struct(info_ptr);
  185110. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185111. *ptr_ptr = info_ptr;
  185112. }
  185113. /* set everything to 0 */
  185114. png_memset(info_ptr, 0, png_sizeof (png_info));
  185115. }
  185116. #ifdef PNG_FREE_ME_SUPPORTED
  185117. void PNGAPI
  185118. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185119. int freer, png_uint_32 mask)
  185120. {
  185121. png_debug(1, "in png_data_freer\n");
  185122. if (png_ptr == NULL || info_ptr == NULL)
  185123. return;
  185124. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185125. info_ptr->free_me |= mask;
  185126. else if(freer == PNG_USER_WILL_FREE_DATA)
  185127. info_ptr->free_me &= ~mask;
  185128. else
  185129. png_warning(png_ptr,
  185130. "Unknown freer parameter in png_data_freer.");
  185131. }
  185132. #endif
  185133. void PNGAPI
  185134. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185135. int num)
  185136. {
  185137. png_debug(1, "in png_free_data\n");
  185138. if (png_ptr == NULL || info_ptr == NULL)
  185139. return;
  185140. #if defined(PNG_TEXT_SUPPORTED)
  185141. /* free text item num or (if num == -1) all text items */
  185142. #ifdef PNG_FREE_ME_SUPPORTED
  185143. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185144. #else
  185145. if (mask & PNG_FREE_TEXT)
  185146. #endif
  185147. {
  185148. if (num != -1)
  185149. {
  185150. if (info_ptr->text && info_ptr->text[num].key)
  185151. {
  185152. png_free(png_ptr, info_ptr->text[num].key);
  185153. info_ptr->text[num].key = NULL;
  185154. }
  185155. }
  185156. else
  185157. {
  185158. int i;
  185159. for (i = 0; i < info_ptr->num_text; i++)
  185160. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185161. png_free(png_ptr, info_ptr->text);
  185162. info_ptr->text = NULL;
  185163. info_ptr->num_text=0;
  185164. }
  185165. }
  185166. #endif
  185167. #if defined(PNG_tRNS_SUPPORTED)
  185168. /* free any tRNS entry */
  185169. #ifdef PNG_FREE_ME_SUPPORTED
  185170. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185171. #else
  185172. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185173. #endif
  185174. {
  185175. png_free(png_ptr, info_ptr->trans);
  185176. info_ptr->valid &= ~PNG_INFO_tRNS;
  185177. #ifndef PNG_FREE_ME_SUPPORTED
  185178. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185179. #endif
  185180. info_ptr->trans = NULL;
  185181. }
  185182. #endif
  185183. #if defined(PNG_sCAL_SUPPORTED)
  185184. /* free any sCAL entry */
  185185. #ifdef PNG_FREE_ME_SUPPORTED
  185186. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185187. #else
  185188. if (mask & PNG_FREE_SCAL)
  185189. #endif
  185190. {
  185191. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185192. png_free(png_ptr, info_ptr->scal_s_width);
  185193. png_free(png_ptr, info_ptr->scal_s_height);
  185194. info_ptr->scal_s_width = NULL;
  185195. info_ptr->scal_s_height = NULL;
  185196. #endif
  185197. info_ptr->valid &= ~PNG_INFO_sCAL;
  185198. }
  185199. #endif
  185200. #if defined(PNG_pCAL_SUPPORTED)
  185201. /* free any pCAL entry */
  185202. #ifdef PNG_FREE_ME_SUPPORTED
  185203. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185204. #else
  185205. if (mask & PNG_FREE_PCAL)
  185206. #endif
  185207. {
  185208. png_free(png_ptr, info_ptr->pcal_purpose);
  185209. png_free(png_ptr, info_ptr->pcal_units);
  185210. info_ptr->pcal_purpose = NULL;
  185211. info_ptr->pcal_units = NULL;
  185212. if (info_ptr->pcal_params != NULL)
  185213. {
  185214. int i;
  185215. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185216. {
  185217. png_free(png_ptr, info_ptr->pcal_params[i]);
  185218. info_ptr->pcal_params[i]=NULL;
  185219. }
  185220. png_free(png_ptr, info_ptr->pcal_params);
  185221. info_ptr->pcal_params = NULL;
  185222. }
  185223. info_ptr->valid &= ~PNG_INFO_pCAL;
  185224. }
  185225. #endif
  185226. #if defined(PNG_iCCP_SUPPORTED)
  185227. /* free any iCCP entry */
  185228. #ifdef PNG_FREE_ME_SUPPORTED
  185229. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185230. #else
  185231. if (mask & PNG_FREE_ICCP)
  185232. #endif
  185233. {
  185234. png_free(png_ptr, info_ptr->iccp_name);
  185235. png_free(png_ptr, info_ptr->iccp_profile);
  185236. info_ptr->iccp_name = NULL;
  185237. info_ptr->iccp_profile = NULL;
  185238. info_ptr->valid &= ~PNG_INFO_iCCP;
  185239. }
  185240. #endif
  185241. #if defined(PNG_sPLT_SUPPORTED)
  185242. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185243. #ifdef PNG_FREE_ME_SUPPORTED
  185244. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185245. #else
  185246. if (mask & PNG_FREE_SPLT)
  185247. #endif
  185248. {
  185249. if (num != -1)
  185250. {
  185251. if(info_ptr->splt_palettes)
  185252. {
  185253. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185254. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185255. info_ptr->splt_palettes[num].name = NULL;
  185256. info_ptr->splt_palettes[num].entries = NULL;
  185257. }
  185258. }
  185259. else
  185260. {
  185261. if(info_ptr->splt_palettes_num)
  185262. {
  185263. int i;
  185264. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185265. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185266. png_free(png_ptr, info_ptr->splt_palettes);
  185267. info_ptr->splt_palettes = NULL;
  185268. info_ptr->splt_palettes_num = 0;
  185269. }
  185270. info_ptr->valid &= ~PNG_INFO_sPLT;
  185271. }
  185272. }
  185273. #endif
  185274. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185275. if(png_ptr->unknown_chunk.data)
  185276. {
  185277. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185278. png_ptr->unknown_chunk.data = NULL;
  185279. }
  185280. #ifdef PNG_FREE_ME_SUPPORTED
  185281. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185282. #else
  185283. if (mask & PNG_FREE_UNKN)
  185284. #endif
  185285. {
  185286. if (num != -1)
  185287. {
  185288. if(info_ptr->unknown_chunks)
  185289. {
  185290. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185291. info_ptr->unknown_chunks[num].data = NULL;
  185292. }
  185293. }
  185294. else
  185295. {
  185296. int i;
  185297. if(info_ptr->unknown_chunks_num)
  185298. {
  185299. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185300. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185301. png_free(png_ptr, info_ptr->unknown_chunks);
  185302. info_ptr->unknown_chunks = NULL;
  185303. info_ptr->unknown_chunks_num = 0;
  185304. }
  185305. }
  185306. }
  185307. #endif
  185308. #if defined(PNG_hIST_SUPPORTED)
  185309. /* free any hIST entry */
  185310. #ifdef PNG_FREE_ME_SUPPORTED
  185311. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185312. #else
  185313. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185314. #endif
  185315. {
  185316. png_free(png_ptr, info_ptr->hist);
  185317. info_ptr->hist = NULL;
  185318. info_ptr->valid &= ~PNG_INFO_hIST;
  185319. #ifndef PNG_FREE_ME_SUPPORTED
  185320. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185321. #endif
  185322. }
  185323. #endif
  185324. /* free any PLTE entry that was internally allocated */
  185325. #ifdef PNG_FREE_ME_SUPPORTED
  185326. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185327. #else
  185328. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185329. #endif
  185330. {
  185331. png_zfree(png_ptr, info_ptr->palette);
  185332. info_ptr->palette = NULL;
  185333. info_ptr->valid &= ~PNG_INFO_PLTE;
  185334. #ifndef PNG_FREE_ME_SUPPORTED
  185335. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185336. #endif
  185337. info_ptr->num_palette = 0;
  185338. }
  185339. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185340. /* free any image bits attached to the info structure */
  185341. #ifdef PNG_FREE_ME_SUPPORTED
  185342. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185343. #else
  185344. if (mask & PNG_FREE_ROWS)
  185345. #endif
  185346. {
  185347. if(info_ptr->row_pointers)
  185348. {
  185349. int row;
  185350. for (row = 0; row < (int)info_ptr->height; row++)
  185351. {
  185352. png_free(png_ptr, info_ptr->row_pointers[row]);
  185353. info_ptr->row_pointers[row]=NULL;
  185354. }
  185355. png_free(png_ptr, info_ptr->row_pointers);
  185356. info_ptr->row_pointers=NULL;
  185357. }
  185358. info_ptr->valid &= ~PNG_INFO_IDAT;
  185359. }
  185360. #endif
  185361. #ifdef PNG_FREE_ME_SUPPORTED
  185362. if(num == -1)
  185363. info_ptr->free_me &= ~mask;
  185364. else
  185365. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185366. #endif
  185367. }
  185368. /* This is an internal routine to free any memory that the info struct is
  185369. * pointing to before re-using it or freeing the struct itself. Recall
  185370. * that png_free() checks for NULL pointers for us.
  185371. */
  185372. void /* PRIVATE */
  185373. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185374. {
  185375. png_debug(1, "in png_info_destroy\n");
  185376. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185377. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185378. if (png_ptr->num_chunk_list)
  185379. {
  185380. png_free(png_ptr, png_ptr->chunk_list);
  185381. png_ptr->chunk_list=NULL;
  185382. png_ptr->num_chunk_list=0;
  185383. }
  185384. #endif
  185385. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185386. }
  185387. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185388. /* This function returns a pointer to the io_ptr associated with the user
  185389. * functions. The application should free any memory associated with this
  185390. * pointer before png_write_destroy() or png_read_destroy() are called.
  185391. */
  185392. png_voidp PNGAPI
  185393. png_get_io_ptr(png_structp png_ptr)
  185394. {
  185395. if(png_ptr == NULL) return (NULL);
  185396. return (png_ptr->io_ptr);
  185397. }
  185398. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185399. #if !defined(PNG_NO_STDIO)
  185400. /* Initialize the default input/output functions for the PNG file. If you
  185401. * use your own read or write routines, you can call either png_set_read_fn()
  185402. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185403. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185404. * necessarily available.
  185405. */
  185406. void PNGAPI
  185407. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185408. {
  185409. png_debug(1, "in png_init_io\n");
  185410. if(png_ptr == NULL) return;
  185411. png_ptr->io_ptr = (png_voidp)fp;
  185412. }
  185413. #endif
  185414. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185415. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185416. * a "Creation Time" or other text-based time string.
  185417. */
  185418. png_charp PNGAPI
  185419. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185420. {
  185421. static PNG_CONST char short_months[12][4] =
  185422. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185423. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185424. if(png_ptr == NULL) return (NULL);
  185425. if (png_ptr->time_buffer == NULL)
  185426. {
  185427. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185428. png_sizeof(char)));
  185429. }
  185430. #if defined(_WIN32_WCE)
  185431. {
  185432. wchar_t time_buf[29];
  185433. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185434. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185435. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185436. ptime->second % 61);
  185437. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185438. NULL, NULL);
  185439. }
  185440. #else
  185441. #ifdef USE_FAR_KEYWORD
  185442. {
  185443. char near_time_buf[29];
  185444. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185445. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185446. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185447. ptime->second % 61);
  185448. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185449. 29*png_sizeof(char));
  185450. }
  185451. #else
  185452. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185453. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185454. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185455. ptime->second % 61);
  185456. #endif
  185457. #endif /* _WIN32_WCE */
  185458. return ((png_charp)png_ptr->time_buffer);
  185459. }
  185460. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185461. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185462. png_charp PNGAPI
  185463. png_get_copyright(png_structp png_ptr)
  185464. {
  185465. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185466. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185467. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185468. Copyright (c) 1996-1997 Andreas Dilger\n\
  185469. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185470. }
  185471. /* The following return the library version as a short string in the
  185472. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185473. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185474. * is defined in png.h.
  185475. * Note: now there is no difference between png_get_libpng_ver() and
  185476. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185477. * it is guaranteed that png.c uses the correct version of png.h.
  185478. */
  185479. png_charp PNGAPI
  185480. png_get_libpng_ver(png_structp png_ptr)
  185481. {
  185482. /* Version of *.c files used when building libpng */
  185483. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185484. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185485. }
  185486. png_charp PNGAPI
  185487. png_get_header_ver(png_structp png_ptr)
  185488. {
  185489. /* Version of *.h files used when building libpng */
  185490. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185491. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185492. }
  185493. png_charp PNGAPI
  185494. png_get_header_version(png_structp png_ptr)
  185495. {
  185496. /* Returns longer string containing both version and date */
  185497. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185498. return ((png_charp) PNG_HEADER_VERSION_STRING
  185499. #ifndef PNG_READ_SUPPORTED
  185500. " (NO READ SUPPORT)"
  185501. #endif
  185502. "\n");
  185503. }
  185504. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185505. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185506. int PNGAPI
  185507. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185508. {
  185509. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185510. int i;
  185511. png_bytep p;
  185512. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185513. return 0;
  185514. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185515. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185516. if (!png_memcmp(chunk_name, p, 4))
  185517. return ((int)*(p+4));
  185518. return 0;
  185519. }
  185520. #endif
  185521. /* This function, added to libpng-1.0.6g, is untested. */
  185522. int PNGAPI
  185523. png_reset_zstream(png_structp png_ptr)
  185524. {
  185525. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185526. return (inflateReset(&png_ptr->zstream));
  185527. }
  185528. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185529. /* This function was added to libpng-1.0.7 */
  185530. png_uint_32 PNGAPI
  185531. png_access_version_number(void)
  185532. {
  185533. /* Version of *.c files used when building libpng */
  185534. return((png_uint_32) PNG_LIBPNG_VER);
  185535. }
  185536. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185537. #if !defined(PNG_1_0_X)
  185538. /* this function was added to libpng 1.2.0 */
  185539. int PNGAPI
  185540. png_mmx_support(void)
  185541. {
  185542. /* obsolete, to be removed from libpng-1.4.0 */
  185543. return -1;
  185544. }
  185545. #endif /* PNG_1_0_X */
  185546. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185547. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185548. #ifdef PNG_SIZE_T
  185549. /* Added at libpng version 1.2.6 */
  185550. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185551. png_size_t PNGAPI
  185552. png_convert_size(size_t size)
  185553. {
  185554. if (size > (png_size_t)-1)
  185555. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185556. return ((png_size_t)size);
  185557. }
  185558. #endif /* PNG_SIZE_T */
  185559. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185560. /*** End of inlined file: png.c ***/
  185561. /*** Start of inlined file: pngerror.c ***/
  185562. /* pngerror.c - stub functions for i/o and memory allocation
  185563. *
  185564. * Last changed in libpng 1.2.20 October 4, 2007
  185565. * For conditions of distribution and use, see copyright notice in png.h
  185566. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185567. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185568. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185569. *
  185570. * This file provides a location for all error handling. Users who
  185571. * need special error handling are expected to write replacement functions
  185572. * and use png_set_error_fn() to use those functions. See the instructions
  185573. * at each function.
  185574. */
  185575. #define PNG_INTERNAL
  185576. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185577. static void /* PRIVATE */
  185578. png_default_error PNGARG((png_structp png_ptr,
  185579. png_const_charp error_message));
  185580. #ifndef PNG_NO_WARNINGS
  185581. static void /* PRIVATE */
  185582. png_default_warning PNGARG((png_structp png_ptr,
  185583. png_const_charp warning_message));
  185584. #endif /* PNG_NO_WARNINGS */
  185585. /* This function is called whenever there is a fatal error. This function
  185586. * should not be changed. If there is a need to handle errors differently,
  185587. * you should supply a replacement error function and use png_set_error_fn()
  185588. * to replace the error function at run-time.
  185589. */
  185590. #ifndef PNG_NO_ERROR_TEXT
  185591. void PNGAPI
  185592. png_error(png_structp png_ptr, png_const_charp error_message)
  185593. {
  185594. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185595. char msg[16];
  185596. if (png_ptr != NULL)
  185597. {
  185598. if (png_ptr->flags&
  185599. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185600. {
  185601. if (*error_message == '#')
  185602. {
  185603. int offset;
  185604. for (offset=1; offset<15; offset++)
  185605. if (*(error_message+offset) == ' ')
  185606. break;
  185607. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185608. {
  185609. int i;
  185610. for (i=0; i<offset-1; i++)
  185611. msg[i]=error_message[i+1];
  185612. msg[i]='\0';
  185613. error_message=msg;
  185614. }
  185615. else
  185616. error_message+=offset;
  185617. }
  185618. else
  185619. {
  185620. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185621. {
  185622. msg[0]='0';
  185623. msg[1]='\0';
  185624. error_message=msg;
  185625. }
  185626. }
  185627. }
  185628. }
  185629. #endif
  185630. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185631. (*(png_ptr->error_fn))(png_ptr, error_message);
  185632. /* If the custom handler doesn't exist, or if it returns,
  185633. use the default handler, which will not return. */
  185634. png_default_error(png_ptr, error_message);
  185635. }
  185636. #else
  185637. void PNGAPI
  185638. png_err(png_structp png_ptr)
  185639. {
  185640. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185641. (*(png_ptr->error_fn))(png_ptr, '\0');
  185642. /* If the custom handler doesn't exist, or if it returns,
  185643. use the default handler, which will not return. */
  185644. png_default_error(png_ptr, '\0');
  185645. }
  185646. #endif /* PNG_NO_ERROR_TEXT */
  185647. #ifndef PNG_NO_WARNINGS
  185648. /* This function is called whenever there is a non-fatal error. This function
  185649. * should not be changed. If there is a need to handle warnings differently,
  185650. * you should supply a replacement warning function and use
  185651. * png_set_error_fn() to replace the warning function at run-time.
  185652. */
  185653. void PNGAPI
  185654. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185655. {
  185656. int offset = 0;
  185657. if (png_ptr != NULL)
  185658. {
  185659. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185660. if (png_ptr->flags&
  185661. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185662. #endif
  185663. {
  185664. if (*warning_message == '#')
  185665. {
  185666. for (offset=1; offset<15; offset++)
  185667. if (*(warning_message+offset) == ' ')
  185668. break;
  185669. }
  185670. }
  185671. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185672. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185673. }
  185674. else
  185675. png_default_warning(png_ptr, warning_message+offset);
  185676. }
  185677. #endif /* PNG_NO_WARNINGS */
  185678. /* These utilities are used internally to build an error message that relates
  185679. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185680. * this is used to prefix the message. The message is limited in length
  185681. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185682. * if the character is invalid.
  185683. */
  185684. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185685. /*static PNG_CONST char png_digit[16] = {
  185686. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185687. 'A', 'B', 'C', 'D', 'E', 'F'
  185688. };*/
  185689. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185690. static void /* PRIVATE */
  185691. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185692. error_message)
  185693. {
  185694. int iout = 0, iin = 0;
  185695. while (iin < 4)
  185696. {
  185697. int c = png_ptr->chunk_name[iin++];
  185698. if (isnonalpha(c))
  185699. {
  185700. buffer[iout++] = '[';
  185701. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185702. buffer[iout++] = png_digit[c & 0x0f];
  185703. buffer[iout++] = ']';
  185704. }
  185705. else
  185706. {
  185707. buffer[iout++] = (png_byte)c;
  185708. }
  185709. }
  185710. if (error_message == NULL)
  185711. buffer[iout] = 0;
  185712. else
  185713. {
  185714. buffer[iout++] = ':';
  185715. buffer[iout++] = ' ';
  185716. png_strncpy(buffer+iout, error_message, 63);
  185717. buffer[iout+63] = 0;
  185718. }
  185719. }
  185720. #ifdef PNG_READ_SUPPORTED
  185721. void PNGAPI
  185722. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185723. {
  185724. char msg[18+64];
  185725. if (png_ptr == NULL)
  185726. png_error(png_ptr, error_message);
  185727. else
  185728. {
  185729. png_format_buffer(png_ptr, msg, error_message);
  185730. png_error(png_ptr, msg);
  185731. }
  185732. }
  185733. #endif /* PNG_READ_SUPPORTED */
  185734. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185735. #ifndef PNG_NO_WARNINGS
  185736. void PNGAPI
  185737. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185738. {
  185739. char msg[18+64];
  185740. if (png_ptr == NULL)
  185741. png_warning(png_ptr, warning_message);
  185742. else
  185743. {
  185744. png_format_buffer(png_ptr, msg, warning_message);
  185745. png_warning(png_ptr, msg);
  185746. }
  185747. }
  185748. #endif /* PNG_NO_WARNINGS */
  185749. /* This is the default error handling function. Note that replacements for
  185750. * this function MUST NOT RETURN, or the program will likely crash. This
  185751. * function is used by default, or if the program supplies NULL for the
  185752. * error function pointer in png_set_error_fn().
  185753. */
  185754. static void /* PRIVATE */
  185755. png_default_error(png_structp, png_const_charp error_message)
  185756. {
  185757. #ifndef PNG_NO_CONSOLE_IO
  185758. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185759. if (*error_message == '#')
  185760. {
  185761. int offset;
  185762. char error_number[16];
  185763. for (offset=0; offset<15; offset++)
  185764. {
  185765. error_number[offset] = *(error_message+offset+1);
  185766. if (*(error_message+offset) == ' ')
  185767. break;
  185768. }
  185769. if((offset > 1) && (offset < 15))
  185770. {
  185771. error_number[offset-1]='\0';
  185772. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185773. error_message+offset);
  185774. }
  185775. else
  185776. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185777. }
  185778. else
  185779. #endif
  185780. fprintf(stderr, "libpng error: %s\n", error_message);
  185781. #endif
  185782. #ifdef PNG_SETJMP_SUPPORTED
  185783. if (png_ptr)
  185784. {
  185785. # ifdef USE_FAR_KEYWORD
  185786. {
  185787. jmp_buf jmpbuf;
  185788. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185789. longjmp(jmpbuf, 1);
  185790. }
  185791. # else
  185792. longjmp(png_ptr->jmpbuf, 1);
  185793. # endif
  185794. }
  185795. #else
  185796. PNG_ABORT();
  185797. #endif
  185798. #ifdef PNG_NO_CONSOLE_IO
  185799. error_message = error_message; /* make compiler happy */
  185800. #endif
  185801. }
  185802. #ifndef PNG_NO_WARNINGS
  185803. /* This function is called when there is a warning, but the library thinks
  185804. * it can continue anyway. Replacement functions don't have to do anything
  185805. * here if you don't want them to. In the default configuration, png_ptr is
  185806. * not used, but it is passed in case it may be useful.
  185807. */
  185808. static void /* PRIVATE */
  185809. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185810. {
  185811. #ifndef PNG_NO_CONSOLE_IO
  185812. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185813. if (*warning_message == '#')
  185814. {
  185815. int offset;
  185816. char warning_number[16];
  185817. for (offset=0; offset<15; offset++)
  185818. {
  185819. warning_number[offset]=*(warning_message+offset+1);
  185820. if (*(warning_message+offset) == ' ')
  185821. break;
  185822. }
  185823. if((offset > 1) && (offset < 15))
  185824. {
  185825. warning_number[offset-1]='\0';
  185826. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185827. warning_message+offset);
  185828. }
  185829. else
  185830. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185831. }
  185832. else
  185833. # endif
  185834. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185835. #else
  185836. warning_message = warning_message; /* make compiler happy */
  185837. #endif
  185838. png_ptr = png_ptr; /* make compiler happy */
  185839. }
  185840. #endif /* PNG_NO_WARNINGS */
  185841. /* This function is called when the application wants to use another method
  185842. * of handling errors and warnings. Note that the error function MUST NOT
  185843. * return to the calling routine or serious problems will occur. The return
  185844. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185845. */
  185846. void PNGAPI
  185847. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185848. png_error_ptr error_fn, png_error_ptr warning_fn)
  185849. {
  185850. if (png_ptr == NULL)
  185851. return;
  185852. png_ptr->error_ptr = error_ptr;
  185853. png_ptr->error_fn = error_fn;
  185854. png_ptr->warning_fn = warning_fn;
  185855. }
  185856. /* This function returns a pointer to the error_ptr associated with the user
  185857. * functions. The application should free any memory associated with this
  185858. * pointer before png_write_destroy and png_read_destroy are called.
  185859. */
  185860. png_voidp PNGAPI
  185861. png_get_error_ptr(png_structp png_ptr)
  185862. {
  185863. if (png_ptr == NULL)
  185864. return NULL;
  185865. return ((png_voidp)png_ptr->error_ptr);
  185866. }
  185867. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185868. void PNGAPI
  185869. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185870. {
  185871. if(png_ptr != NULL)
  185872. {
  185873. png_ptr->flags &=
  185874. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185875. }
  185876. }
  185877. #endif
  185878. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185879. /*** End of inlined file: pngerror.c ***/
  185880. /*** Start of inlined file: pngget.c ***/
  185881. /* pngget.c - retrieval of values from info struct
  185882. *
  185883. * Last changed in libpng 1.2.15 January 5, 2007
  185884. * For conditions of distribution and use, see copyright notice in png.h
  185885. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185886. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185887. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185888. */
  185889. #define PNG_INTERNAL
  185890. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185891. png_uint_32 PNGAPI
  185892. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185893. {
  185894. if (png_ptr != NULL && info_ptr != NULL)
  185895. return(info_ptr->valid & flag);
  185896. else
  185897. return(0);
  185898. }
  185899. png_uint_32 PNGAPI
  185900. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185901. {
  185902. if (png_ptr != NULL && info_ptr != NULL)
  185903. return(info_ptr->rowbytes);
  185904. else
  185905. return(0);
  185906. }
  185907. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185908. png_bytepp PNGAPI
  185909. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185910. {
  185911. if (png_ptr != NULL && info_ptr != NULL)
  185912. return(info_ptr->row_pointers);
  185913. else
  185914. return(0);
  185915. }
  185916. #endif
  185917. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185918. /* easy access to info, added in libpng-0.99 */
  185919. png_uint_32 PNGAPI
  185920. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185921. {
  185922. if (png_ptr != NULL && info_ptr != NULL)
  185923. {
  185924. return info_ptr->width;
  185925. }
  185926. return (0);
  185927. }
  185928. png_uint_32 PNGAPI
  185929. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185930. {
  185931. if (png_ptr != NULL && info_ptr != NULL)
  185932. {
  185933. return info_ptr->height;
  185934. }
  185935. return (0);
  185936. }
  185937. png_byte PNGAPI
  185938. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185939. {
  185940. if (png_ptr != NULL && info_ptr != NULL)
  185941. {
  185942. return info_ptr->bit_depth;
  185943. }
  185944. return (0);
  185945. }
  185946. png_byte PNGAPI
  185947. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185948. {
  185949. if (png_ptr != NULL && info_ptr != NULL)
  185950. {
  185951. return info_ptr->color_type;
  185952. }
  185953. return (0);
  185954. }
  185955. png_byte PNGAPI
  185956. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185957. {
  185958. if (png_ptr != NULL && info_ptr != NULL)
  185959. {
  185960. return info_ptr->filter_type;
  185961. }
  185962. return (0);
  185963. }
  185964. png_byte PNGAPI
  185965. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185966. {
  185967. if (png_ptr != NULL && info_ptr != NULL)
  185968. {
  185969. return info_ptr->interlace_type;
  185970. }
  185971. return (0);
  185972. }
  185973. png_byte PNGAPI
  185974. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185975. {
  185976. if (png_ptr != NULL && info_ptr != NULL)
  185977. {
  185978. return info_ptr->compression_type;
  185979. }
  185980. return (0);
  185981. }
  185982. png_uint_32 PNGAPI
  185983. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185984. {
  185985. if (png_ptr != NULL && info_ptr != NULL)
  185986. #if defined(PNG_pHYs_SUPPORTED)
  185987. if (info_ptr->valid & PNG_INFO_pHYs)
  185988. {
  185989. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185990. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185991. return (0);
  185992. else return (info_ptr->x_pixels_per_unit);
  185993. }
  185994. #else
  185995. return (0);
  185996. #endif
  185997. return (0);
  185998. }
  185999. png_uint_32 PNGAPI
  186000. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186001. {
  186002. if (png_ptr != NULL && info_ptr != NULL)
  186003. #if defined(PNG_pHYs_SUPPORTED)
  186004. if (info_ptr->valid & PNG_INFO_pHYs)
  186005. {
  186006. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  186007. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186008. return (0);
  186009. else return (info_ptr->y_pixels_per_unit);
  186010. }
  186011. #else
  186012. return (0);
  186013. #endif
  186014. return (0);
  186015. }
  186016. png_uint_32 PNGAPI
  186017. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186018. {
  186019. if (png_ptr != NULL && info_ptr != NULL)
  186020. #if defined(PNG_pHYs_SUPPORTED)
  186021. if (info_ptr->valid & PNG_INFO_pHYs)
  186022. {
  186023. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  186024. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  186025. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  186026. return (0);
  186027. else return (info_ptr->x_pixels_per_unit);
  186028. }
  186029. #else
  186030. return (0);
  186031. #endif
  186032. return (0);
  186033. }
  186034. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186035. float PNGAPI
  186036. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  186037. {
  186038. if (png_ptr != NULL && info_ptr != NULL)
  186039. #if defined(PNG_pHYs_SUPPORTED)
  186040. if (info_ptr->valid & PNG_INFO_pHYs)
  186041. {
  186042. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  186043. if (info_ptr->x_pixels_per_unit == 0)
  186044. return ((float)0.0);
  186045. else
  186046. return ((float)((float)info_ptr->y_pixels_per_unit
  186047. /(float)info_ptr->x_pixels_per_unit));
  186048. }
  186049. #else
  186050. return (0.0);
  186051. #endif
  186052. return ((float)0.0);
  186053. }
  186054. #endif
  186055. png_int_32 PNGAPI
  186056. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186057. {
  186058. if (png_ptr != NULL && info_ptr != NULL)
  186059. #if defined(PNG_oFFs_SUPPORTED)
  186060. if (info_ptr->valid & PNG_INFO_oFFs)
  186061. {
  186062. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186063. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186064. return (0);
  186065. else return (info_ptr->x_offset);
  186066. }
  186067. #else
  186068. return (0);
  186069. #endif
  186070. return (0);
  186071. }
  186072. png_int_32 PNGAPI
  186073. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186074. {
  186075. if (png_ptr != NULL && info_ptr != NULL)
  186076. #if defined(PNG_oFFs_SUPPORTED)
  186077. if (info_ptr->valid & PNG_INFO_oFFs)
  186078. {
  186079. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186080. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186081. return (0);
  186082. else return (info_ptr->y_offset);
  186083. }
  186084. #else
  186085. return (0);
  186086. #endif
  186087. return (0);
  186088. }
  186089. png_int_32 PNGAPI
  186090. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186091. {
  186092. if (png_ptr != NULL && info_ptr != NULL)
  186093. #if defined(PNG_oFFs_SUPPORTED)
  186094. if (info_ptr->valid & PNG_INFO_oFFs)
  186095. {
  186096. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186097. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186098. return (0);
  186099. else return (info_ptr->x_offset);
  186100. }
  186101. #else
  186102. return (0);
  186103. #endif
  186104. return (0);
  186105. }
  186106. png_int_32 PNGAPI
  186107. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186108. {
  186109. if (png_ptr != NULL && info_ptr != NULL)
  186110. #if defined(PNG_oFFs_SUPPORTED)
  186111. if (info_ptr->valid & PNG_INFO_oFFs)
  186112. {
  186113. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186114. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186115. return (0);
  186116. else return (info_ptr->y_offset);
  186117. }
  186118. #else
  186119. return (0);
  186120. #endif
  186121. return (0);
  186122. }
  186123. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186124. png_uint_32 PNGAPI
  186125. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186126. {
  186127. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186128. *.0254 +.5));
  186129. }
  186130. png_uint_32 PNGAPI
  186131. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186132. {
  186133. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186134. *.0254 +.5));
  186135. }
  186136. png_uint_32 PNGAPI
  186137. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186138. {
  186139. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186140. *.0254 +.5));
  186141. }
  186142. float PNGAPI
  186143. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186144. {
  186145. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186146. *.00003937);
  186147. }
  186148. float PNGAPI
  186149. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186150. {
  186151. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186152. *.00003937);
  186153. }
  186154. #if defined(PNG_pHYs_SUPPORTED)
  186155. png_uint_32 PNGAPI
  186156. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186157. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186158. {
  186159. png_uint_32 retval = 0;
  186160. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186161. {
  186162. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186163. if (res_x != NULL)
  186164. {
  186165. *res_x = info_ptr->x_pixels_per_unit;
  186166. retval |= PNG_INFO_pHYs;
  186167. }
  186168. if (res_y != NULL)
  186169. {
  186170. *res_y = info_ptr->y_pixels_per_unit;
  186171. retval |= PNG_INFO_pHYs;
  186172. }
  186173. if (unit_type != NULL)
  186174. {
  186175. *unit_type = (int)info_ptr->phys_unit_type;
  186176. retval |= PNG_INFO_pHYs;
  186177. if(*unit_type == 1)
  186178. {
  186179. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186180. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186181. }
  186182. }
  186183. }
  186184. return (retval);
  186185. }
  186186. #endif /* PNG_pHYs_SUPPORTED */
  186187. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186188. /* png_get_channels really belongs in here, too, but it's been around longer */
  186189. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186190. png_byte PNGAPI
  186191. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186192. {
  186193. if (png_ptr != NULL && info_ptr != NULL)
  186194. return(info_ptr->channels);
  186195. else
  186196. return (0);
  186197. }
  186198. png_bytep PNGAPI
  186199. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186200. {
  186201. if (png_ptr != NULL && info_ptr != NULL)
  186202. return(info_ptr->signature);
  186203. else
  186204. return (NULL);
  186205. }
  186206. #if defined(PNG_bKGD_SUPPORTED)
  186207. png_uint_32 PNGAPI
  186208. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186209. png_color_16p *background)
  186210. {
  186211. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186212. && background != NULL)
  186213. {
  186214. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186215. *background = &(info_ptr->background);
  186216. return (PNG_INFO_bKGD);
  186217. }
  186218. return (0);
  186219. }
  186220. #endif
  186221. #if defined(PNG_cHRM_SUPPORTED)
  186222. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186223. png_uint_32 PNGAPI
  186224. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186225. double *white_x, double *white_y, double *red_x, double *red_y,
  186226. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186227. {
  186228. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186229. {
  186230. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186231. if (white_x != NULL)
  186232. *white_x = (double)info_ptr->x_white;
  186233. if (white_y != NULL)
  186234. *white_y = (double)info_ptr->y_white;
  186235. if (red_x != NULL)
  186236. *red_x = (double)info_ptr->x_red;
  186237. if (red_y != NULL)
  186238. *red_y = (double)info_ptr->y_red;
  186239. if (green_x != NULL)
  186240. *green_x = (double)info_ptr->x_green;
  186241. if (green_y != NULL)
  186242. *green_y = (double)info_ptr->y_green;
  186243. if (blue_x != NULL)
  186244. *blue_x = (double)info_ptr->x_blue;
  186245. if (blue_y != NULL)
  186246. *blue_y = (double)info_ptr->y_blue;
  186247. return (PNG_INFO_cHRM);
  186248. }
  186249. return (0);
  186250. }
  186251. #endif
  186252. #ifdef PNG_FIXED_POINT_SUPPORTED
  186253. png_uint_32 PNGAPI
  186254. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186255. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186256. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186257. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186258. {
  186259. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186260. {
  186261. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186262. if (white_x != NULL)
  186263. *white_x = info_ptr->int_x_white;
  186264. if (white_y != NULL)
  186265. *white_y = info_ptr->int_y_white;
  186266. if (red_x != NULL)
  186267. *red_x = info_ptr->int_x_red;
  186268. if (red_y != NULL)
  186269. *red_y = info_ptr->int_y_red;
  186270. if (green_x != NULL)
  186271. *green_x = info_ptr->int_x_green;
  186272. if (green_y != NULL)
  186273. *green_y = info_ptr->int_y_green;
  186274. if (blue_x != NULL)
  186275. *blue_x = info_ptr->int_x_blue;
  186276. if (blue_y != NULL)
  186277. *blue_y = info_ptr->int_y_blue;
  186278. return (PNG_INFO_cHRM);
  186279. }
  186280. return (0);
  186281. }
  186282. #endif
  186283. #endif
  186284. #if defined(PNG_gAMA_SUPPORTED)
  186285. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186286. png_uint_32 PNGAPI
  186287. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186288. {
  186289. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186290. && file_gamma != NULL)
  186291. {
  186292. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186293. *file_gamma = (double)info_ptr->gamma;
  186294. return (PNG_INFO_gAMA);
  186295. }
  186296. return (0);
  186297. }
  186298. #endif
  186299. #ifdef PNG_FIXED_POINT_SUPPORTED
  186300. png_uint_32 PNGAPI
  186301. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186302. png_fixed_point *int_file_gamma)
  186303. {
  186304. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186305. && int_file_gamma != NULL)
  186306. {
  186307. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186308. *int_file_gamma = info_ptr->int_gamma;
  186309. return (PNG_INFO_gAMA);
  186310. }
  186311. return (0);
  186312. }
  186313. #endif
  186314. #endif
  186315. #if defined(PNG_sRGB_SUPPORTED)
  186316. png_uint_32 PNGAPI
  186317. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186318. {
  186319. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186320. && file_srgb_intent != NULL)
  186321. {
  186322. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186323. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186324. return (PNG_INFO_sRGB);
  186325. }
  186326. return (0);
  186327. }
  186328. #endif
  186329. #if defined(PNG_iCCP_SUPPORTED)
  186330. png_uint_32 PNGAPI
  186331. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186332. png_charpp name, int *compression_type,
  186333. png_charpp profile, png_uint_32 *proflen)
  186334. {
  186335. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186336. && name != NULL && profile != NULL && proflen != NULL)
  186337. {
  186338. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186339. *name = info_ptr->iccp_name;
  186340. *profile = info_ptr->iccp_profile;
  186341. /* compression_type is a dummy so the API won't have to change
  186342. if we introduce multiple compression types later. */
  186343. *proflen = (int)info_ptr->iccp_proflen;
  186344. *compression_type = (int)info_ptr->iccp_compression;
  186345. return (PNG_INFO_iCCP);
  186346. }
  186347. return (0);
  186348. }
  186349. #endif
  186350. #if defined(PNG_sPLT_SUPPORTED)
  186351. png_uint_32 PNGAPI
  186352. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186353. png_sPLT_tpp spalettes)
  186354. {
  186355. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186356. {
  186357. *spalettes = info_ptr->splt_palettes;
  186358. return ((png_uint_32)info_ptr->splt_palettes_num);
  186359. }
  186360. return (0);
  186361. }
  186362. #endif
  186363. #if defined(PNG_hIST_SUPPORTED)
  186364. png_uint_32 PNGAPI
  186365. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186366. {
  186367. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186368. && hist != NULL)
  186369. {
  186370. png_debug1(1, "in %s retrieval function\n", "hIST");
  186371. *hist = info_ptr->hist;
  186372. return (PNG_INFO_hIST);
  186373. }
  186374. return (0);
  186375. }
  186376. #endif
  186377. png_uint_32 PNGAPI
  186378. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186379. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186380. int *color_type, int *interlace_type, int *compression_type,
  186381. int *filter_type)
  186382. {
  186383. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186384. bit_depth != NULL && color_type != NULL)
  186385. {
  186386. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186387. *width = info_ptr->width;
  186388. *height = info_ptr->height;
  186389. *bit_depth = info_ptr->bit_depth;
  186390. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186391. png_error(png_ptr, "Invalid bit depth");
  186392. *color_type = info_ptr->color_type;
  186393. if (info_ptr->color_type > 6)
  186394. png_error(png_ptr, "Invalid color type");
  186395. if (compression_type != NULL)
  186396. *compression_type = info_ptr->compression_type;
  186397. if (filter_type != NULL)
  186398. *filter_type = info_ptr->filter_type;
  186399. if (interlace_type != NULL)
  186400. *interlace_type = info_ptr->interlace_type;
  186401. /* check for potential overflow of rowbytes */
  186402. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186403. png_error(png_ptr, "Invalid image width");
  186404. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186405. png_error(png_ptr, "Invalid image height");
  186406. if (info_ptr->width > (PNG_UINT_32_MAX
  186407. >> 3) /* 8-byte RGBA pixels */
  186408. - 64 /* bigrowbuf hack */
  186409. - 1 /* filter byte */
  186410. - 7*8 /* rounding of width to multiple of 8 pixels */
  186411. - 8) /* extra max_pixel_depth pad */
  186412. {
  186413. png_warning(png_ptr,
  186414. "Width too large for libpng to process image data.");
  186415. }
  186416. return (1);
  186417. }
  186418. return (0);
  186419. }
  186420. #if defined(PNG_oFFs_SUPPORTED)
  186421. png_uint_32 PNGAPI
  186422. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186423. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186424. {
  186425. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186426. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186427. {
  186428. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186429. *offset_x = info_ptr->x_offset;
  186430. *offset_y = info_ptr->y_offset;
  186431. *unit_type = (int)info_ptr->offset_unit_type;
  186432. return (PNG_INFO_oFFs);
  186433. }
  186434. return (0);
  186435. }
  186436. #endif
  186437. #if defined(PNG_pCAL_SUPPORTED)
  186438. png_uint_32 PNGAPI
  186439. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186440. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186441. png_charp *units, png_charpp *params)
  186442. {
  186443. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186444. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186445. nparams != NULL && units != NULL && params != NULL)
  186446. {
  186447. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186448. *purpose = info_ptr->pcal_purpose;
  186449. *X0 = info_ptr->pcal_X0;
  186450. *X1 = info_ptr->pcal_X1;
  186451. *type = (int)info_ptr->pcal_type;
  186452. *nparams = (int)info_ptr->pcal_nparams;
  186453. *units = info_ptr->pcal_units;
  186454. *params = info_ptr->pcal_params;
  186455. return (PNG_INFO_pCAL);
  186456. }
  186457. return (0);
  186458. }
  186459. #endif
  186460. #if defined(PNG_sCAL_SUPPORTED)
  186461. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186462. png_uint_32 PNGAPI
  186463. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186464. int *unit, double *width, double *height)
  186465. {
  186466. if (png_ptr != NULL && info_ptr != NULL &&
  186467. (info_ptr->valid & PNG_INFO_sCAL))
  186468. {
  186469. *unit = info_ptr->scal_unit;
  186470. *width = info_ptr->scal_pixel_width;
  186471. *height = info_ptr->scal_pixel_height;
  186472. return (PNG_INFO_sCAL);
  186473. }
  186474. return(0);
  186475. }
  186476. #else
  186477. #ifdef PNG_FIXED_POINT_SUPPORTED
  186478. png_uint_32 PNGAPI
  186479. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186480. int *unit, png_charpp width, png_charpp height)
  186481. {
  186482. if (png_ptr != NULL && info_ptr != NULL &&
  186483. (info_ptr->valid & PNG_INFO_sCAL))
  186484. {
  186485. *unit = info_ptr->scal_unit;
  186486. *width = info_ptr->scal_s_width;
  186487. *height = info_ptr->scal_s_height;
  186488. return (PNG_INFO_sCAL);
  186489. }
  186490. return(0);
  186491. }
  186492. #endif
  186493. #endif
  186494. #endif
  186495. #if defined(PNG_pHYs_SUPPORTED)
  186496. png_uint_32 PNGAPI
  186497. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186498. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186499. {
  186500. png_uint_32 retval = 0;
  186501. if (png_ptr != NULL && info_ptr != NULL &&
  186502. (info_ptr->valid & PNG_INFO_pHYs))
  186503. {
  186504. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186505. if (res_x != NULL)
  186506. {
  186507. *res_x = info_ptr->x_pixels_per_unit;
  186508. retval |= PNG_INFO_pHYs;
  186509. }
  186510. if (res_y != NULL)
  186511. {
  186512. *res_y = info_ptr->y_pixels_per_unit;
  186513. retval |= PNG_INFO_pHYs;
  186514. }
  186515. if (unit_type != NULL)
  186516. {
  186517. *unit_type = (int)info_ptr->phys_unit_type;
  186518. retval |= PNG_INFO_pHYs;
  186519. }
  186520. }
  186521. return (retval);
  186522. }
  186523. #endif
  186524. png_uint_32 PNGAPI
  186525. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186526. int *num_palette)
  186527. {
  186528. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186529. && palette != NULL)
  186530. {
  186531. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186532. *palette = info_ptr->palette;
  186533. *num_palette = info_ptr->num_palette;
  186534. png_debug1(3, "num_palette = %d\n", *num_palette);
  186535. return (PNG_INFO_PLTE);
  186536. }
  186537. return (0);
  186538. }
  186539. #if defined(PNG_sBIT_SUPPORTED)
  186540. png_uint_32 PNGAPI
  186541. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186542. {
  186543. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186544. && sig_bit != NULL)
  186545. {
  186546. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186547. *sig_bit = &(info_ptr->sig_bit);
  186548. return (PNG_INFO_sBIT);
  186549. }
  186550. return (0);
  186551. }
  186552. #endif
  186553. #if defined(PNG_TEXT_SUPPORTED)
  186554. png_uint_32 PNGAPI
  186555. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186556. int *num_text)
  186557. {
  186558. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186559. {
  186560. png_debug1(1, "in %s retrieval function\n",
  186561. (png_ptr->chunk_name[0] == '\0' ? "text"
  186562. : (png_const_charp)png_ptr->chunk_name));
  186563. if (text_ptr != NULL)
  186564. *text_ptr = info_ptr->text;
  186565. if (num_text != NULL)
  186566. *num_text = info_ptr->num_text;
  186567. return ((png_uint_32)info_ptr->num_text);
  186568. }
  186569. if (num_text != NULL)
  186570. *num_text = 0;
  186571. return(0);
  186572. }
  186573. #endif
  186574. #if defined(PNG_tIME_SUPPORTED)
  186575. png_uint_32 PNGAPI
  186576. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186577. {
  186578. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186579. && mod_time != NULL)
  186580. {
  186581. png_debug1(1, "in %s retrieval function\n", "tIME");
  186582. *mod_time = &(info_ptr->mod_time);
  186583. return (PNG_INFO_tIME);
  186584. }
  186585. return (0);
  186586. }
  186587. #endif
  186588. #if defined(PNG_tRNS_SUPPORTED)
  186589. png_uint_32 PNGAPI
  186590. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186591. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186592. {
  186593. png_uint_32 retval = 0;
  186594. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186595. {
  186596. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186597. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186598. {
  186599. if (trans != NULL)
  186600. {
  186601. *trans = info_ptr->trans;
  186602. retval |= PNG_INFO_tRNS;
  186603. }
  186604. if (trans_values != NULL)
  186605. *trans_values = &(info_ptr->trans_values);
  186606. }
  186607. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186608. {
  186609. if (trans_values != NULL)
  186610. {
  186611. *trans_values = &(info_ptr->trans_values);
  186612. retval |= PNG_INFO_tRNS;
  186613. }
  186614. if(trans != NULL)
  186615. *trans = NULL;
  186616. }
  186617. if(num_trans != NULL)
  186618. {
  186619. *num_trans = info_ptr->num_trans;
  186620. retval |= PNG_INFO_tRNS;
  186621. }
  186622. }
  186623. return (retval);
  186624. }
  186625. #endif
  186626. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186627. png_uint_32 PNGAPI
  186628. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186629. png_unknown_chunkpp unknowns)
  186630. {
  186631. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186632. {
  186633. *unknowns = info_ptr->unknown_chunks;
  186634. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186635. }
  186636. return (0);
  186637. }
  186638. #endif
  186639. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186640. png_byte PNGAPI
  186641. png_get_rgb_to_gray_status (png_structp png_ptr)
  186642. {
  186643. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186644. }
  186645. #endif
  186646. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186647. png_voidp PNGAPI
  186648. png_get_user_chunk_ptr(png_structp png_ptr)
  186649. {
  186650. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186651. }
  186652. #endif
  186653. #ifdef PNG_WRITE_SUPPORTED
  186654. png_uint_32 PNGAPI
  186655. png_get_compression_buffer_size(png_structp png_ptr)
  186656. {
  186657. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186658. }
  186659. #endif
  186660. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186661. #ifndef PNG_1_0_X
  186662. /* this function was added to libpng 1.2.0 and should exist by default */
  186663. png_uint_32 PNGAPI
  186664. png_get_asm_flags (png_structp png_ptr)
  186665. {
  186666. /* obsolete, to be removed from libpng-1.4.0 */
  186667. return (png_ptr? 0L: 0L);
  186668. }
  186669. /* this function was added to libpng 1.2.0 and should exist by default */
  186670. png_uint_32 PNGAPI
  186671. png_get_asm_flagmask (int flag_select)
  186672. {
  186673. /* obsolete, to be removed from libpng-1.4.0 */
  186674. flag_select=flag_select;
  186675. return 0L;
  186676. }
  186677. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186678. /* this function was added to libpng 1.2.0 */
  186679. png_uint_32 PNGAPI
  186680. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186681. {
  186682. /* obsolete, to be removed from libpng-1.4.0 */
  186683. flag_select=flag_select;
  186684. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186685. return 0L;
  186686. }
  186687. /* this function was added to libpng 1.2.0 */
  186688. png_byte PNGAPI
  186689. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186690. {
  186691. /* obsolete, to be removed from libpng-1.4.0 */
  186692. return (png_ptr? 0: 0);
  186693. }
  186694. /* this function was added to libpng 1.2.0 */
  186695. png_uint_32 PNGAPI
  186696. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186697. {
  186698. /* obsolete, to be removed from libpng-1.4.0 */
  186699. return (png_ptr? 0L: 0L);
  186700. }
  186701. #endif /* ?PNG_1_0_X */
  186702. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186703. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186704. /* these functions were added to libpng 1.2.6 */
  186705. png_uint_32 PNGAPI
  186706. png_get_user_width_max (png_structp png_ptr)
  186707. {
  186708. return (png_ptr? png_ptr->user_width_max : 0);
  186709. }
  186710. png_uint_32 PNGAPI
  186711. png_get_user_height_max (png_structp png_ptr)
  186712. {
  186713. return (png_ptr? png_ptr->user_height_max : 0);
  186714. }
  186715. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186716. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186717. /*** End of inlined file: pngget.c ***/
  186718. /*** Start of inlined file: pngmem.c ***/
  186719. /* pngmem.c - stub functions for memory allocation
  186720. *
  186721. * Last changed in libpng 1.2.13 November 13, 2006
  186722. * For conditions of distribution and use, see copyright notice in png.h
  186723. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186724. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186725. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186726. *
  186727. * This file provides a location for all memory allocation. Users who
  186728. * need special memory handling are expected to supply replacement
  186729. * functions for png_malloc() and png_free(), and to use
  186730. * png_create_read_struct_2() and png_create_write_struct_2() to
  186731. * identify the replacement functions.
  186732. */
  186733. #define PNG_INTERNAL
  186734. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186735. /* Borland DOS special memory handler */
  186736. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186737. /* if you change this, be sure to change the one in png.h also */
  186738. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186739. by a single call to calloc() if this is thought to improve performance. */
  186740. png_voidp /* PRIVATE */
  186741. png_create_struct(int type)
  186742. {
  186743. #ifdef PNG_USER_MEM_SUPPORTED
  186744. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186745. }
  186746. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  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 (png_get_copyright(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, (png_uint_32)size);
  186766. }
  186767. else
  186768. #endif /* PNG_USER_MEM_SUPPORTED */
  186769. struct_ptr = (png_voidp)farmalloc(size);
  186770. if (struct_ptr != NULL)
  186771. png_memset(struct_ptr, 0, size);
  186772. return (struct_ptr);
  186773. }
  186774. /* Free memory allocated by a png_create_struct() call */
  186775. void /* PRIVATE */
  186776. png_destroy_struct(png_voidp struct_ptr)
  186777. {
  186778. #ifdef PNG_USER_MEM_SUPPORTED
  186779. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186780. }
  186781. /* Free memory allocated by a png_create_struct() call */
  186782. void /* PRIVATE */
  186783. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186784. png_voidp mem_ptr)
  186785. {
  186786. #endif
  186787. if (struct_ptr != NULL)
  186788. {
  186789. #ifdef PNG_USER_MEM_SUPPORTED
  186790. if(free_fn != NULL)
  186791. {
  186792. png_struct dummy_struct;
  186793. png_structp png_ptr = &dummy_struct;
  186794. png_ptr->mem_ptr=mem_ptr;
  186795. (*(free_fn))(png_ptr, struct_ptr);
  186796. return;
  186797. }
  186798. #endif /* PNG_USER_MEM_SUPPORTED */
  186799. farfree (struct_ptr);
  186800. }
  186801. }
  186802. /* Allocate memory. For reasonable files, size should never exceed
  186803. * 64K. However, zlib may allocate more then 64K if you don't tell
  186804. * it not to. See zconf.h and png.h for more information. zlib does
  186805. * need to allocate exactly 64K, so whatever you call here must
  186806. * have the ability to do that.
  186807. *
  186808. * Borland seems to have a problem in DOS mode for exactly 64K.
  186809. * It gives you a segment with an offset of 8 (perhaps to store its
  186810. * memory stuff). zlib doesn't like this at all, so we have to
  186811. * detect and deal with it. This code should not be needed in
  186812. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186813. * been updated by Alexander Lehmann for version 0.89 to waste less
  186814. * memory.
  186815. *
  186816. * Note that we can't use png_size_t for the "size" declaration,
  186817. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186818. * result, we would be truncating potentially larger memory requests
  186819. * (which should cause a fatal error) and introducing major problems.
  186820. */
  186821. png_voidp PNGAPI
  186822. png_malloc(png_structp png_ptr, png_uint_32 size)
  186823. {
  186824. png_voidp ret;
  186825. if (png_ptr == NULL || size == 0)
  186826. return (NULL);
  186827. #ifdef PNG_USER_MEM_SUPPORTED
  186828. if(png_ptr->malloc_fn != NULL)
  186829. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186830. else
  186831. ret = (png_malloc_default(png_ptr, size));
  186832. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186833. png_error(png_ptr, "Out of memory!");
  186834. return (ret);
  186835. }
  186836. png_voidp PNGAPI
  186837. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186838. {
  186839. png_voidp ret;
  186840. #endif /* PNG_USER_MEM_SUPPORTED */
  186841. if (png_ptr == NULL || size == 0)
  186842. return (NULL);
  186843. #ifdef PNG_MAX_MALLOC_64K
  186844. if (size > (png_uint_32)65536L)
  186845. {
  186846. png_warning(png_ptr, "Cannot Allocate > 64K");
  186847. ret = NULL;
  186848. }
  186849. else
  186850. #endif
  186851. if (size != (size_t)size)
  186852. ret = NULL;
  186853. else if (size == (png_uint_32)65536L)
  186854. {
  186855. if (png_ptr->offset_table == NULL)
  186856. {
  186857. /* try to see if we need to do any of this fancy stuff */
  186858. ret = farmalloc(size);
  186859. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186860. {
  186861. int num_blocks;
  186862. png_uint_32 total_size;
  186863. png_bytep table;
  186864. int i;
  186865. png_byte huge * hptr;
  186866. if (ret != NULL)
  186867. {
  186868. farfree(ret);
  186869. ret = NULL;
  186870. }
  186871. if(png_ptr->zlib_window_bits > 14)
  186872. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186873. else
  186874. num_blocks = 1;
  186875. if (png_ptr->zlib_mem_level >= 7)
  186876. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186877. else
  186878. num_blocks++;
  186879. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186880. table = farmalloc(total_size);
  186881. if (table == NULL)
  186882. {
  186883. #ifndef PNG_USER_MEM_SUPPORTED
  186884. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186885. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186886. else
  186887. png_warning(png_ptr, "Out Of Memory.");
  186888. #endif
  186889. return (NULL);
  186890. }
  186891. if ((png_size_t)table & 0xfff0)
  186892. {
  186893. #ifndef PNG_USER_MEM_SUPPORTED
  186894. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186895. png_error(png_ptr,
  186896. "Farmalloc didn't return normalized pointer");
  186897. else
  186898. png_warning(png_ptr,
  186899. "Farmalloc didn't return normalized pointer");
  186900. #endif
  186901. return (NULL);
  186902. }
  186903. png_ptr->offset_table = table;
  186904. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186905. png_sizeof (png_bytep));
  186906. if (png_ptr->offset_table_ptr == NULL)
  186907. {
  186908. #ifndef PNG_USER_MEM_SUPPORTED
  186909. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186910. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186911. else
  186912. png_warning(png_ptr, "Out Of memory.");
  186913. #endif
  186914. return (NULL);
  186915. }
  186916. hptr = (png_byte huge *)table;
  186917. if ((png_size_t)hptr & 0xf)
  186918. {
  186919. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186920. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186921. }
  186922. for (i = 0; i < num_blocks; i++)
  186923. {
  186924. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186925. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186926. }
  186927. png_ptr->offset_table_number = num_blocks;
  186928. png_ptr->offset_table_count = 0;
  186929. png_ptr->offset_table_count_free = 0;
  186930. }
  186931. }
  186932. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186933. {
  186934. #ifndef PNG_USER_MEM_SUPPORTED
  186935. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186936. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186937. else
  186938. png_warning(png_ptr, "Out of Memory.");
  186939. #endif
  186940. return (NULL);
  186941. }
  186942. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186943. }
  186944. else
  186945. ret = farmalloc(size);
  186946. #ifndef PNG_USER_MEM_SUPPORTED
  186947. if (ret == NULL)
  186948. {
  186949. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186950. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186951. else
  186952. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186953. }
  186954. #endif
  186955. return (ret);
  186956. }
  186957. /* free a pointer allocated by png_malloc(). In the default
  186958. configuration, png_ptr is not used, but is passed in case it
  186959. is needed. If ptr is NULL, return without taking any action. */
  186960. void PNGAPI
  186961. png_free(png_structp png_ptr, png_voidp ptr)
  186962. {
  186963. if (png_ptr == NULL || ptr == NULL)
  186964. return;
  186965. #ifdef PNG_USER_MEM_SUPPORTED
  186966. if (png_ptr->free_fn != NULL)
  186967. {
  186968. (*(png_ptr->free_fn))(png_ptr, ptr);
  186969. return;
  186970. }
  186971. else png_free_default(png_ptr, ptr);
  186972. }
  186973. void PNGAPI
  186974. png_free_default(png_structp png_ptr, png_voidp ptr)
  186975. {
  186976. #endif /* PNG_USER_MEM_SUPPORTED */
  186977. if(png_ptr == NULL) return;
  186978. if (png_ptr->offset_table != NULL)
  186979. {
  186980. int i;
  186981. for (i = 0; i < png_ptr->offset_table_count; i++)
  186982. {
  186983. if (ptr == png_ptr->offset_table_ptr[i])
  186984. {
  186985. ptr = NULL;
  186986. png_ptr->offset_table_count_free++;
  186987. break;
  186988. }
  186989. }
  186990. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186991. {
  186992. farfree(png_ptr->offset_table);
  186993. farfree(png_ptr->offset_table_ptr);
  186994. png_ptr->offset_table = NULL;
  186995. png_ptr->offset_table_ptr = NULL;
  186996. }
  186997. }
  186998. if (ptr != NULL)
  186999. {
  187000. farfree(ptr);
  187001. }
  187002. }
  187003. #else /* Not the Borland DOS special memory handler */
  187004. /* Allocate memory for a png_struct or a png_info. The malloc and
  187005. memset can be replaced by a single call to calloc() if this is thought
  187006. to improve performance noticably. */
  187007. png_voidp /* PRIVATE */
  187008. png_create_struct(int type)
  187009. {
  187010. #ifdef PNG_USER_MEM_SUPPORTED
  187011. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  187012. }
  187013. /* Allocate memory for a png_struct or a png_info. The malloc and
  187014. memset can be replaced by a single call to calloc() if this is thought
  187015. to improve performance noticably. */
  187016. png_voidp /* PRIVATE */
  187017. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  187018. {
  187019. #endif /* PNG_USER_MEM_SUPPORTED */
  187020. png_size_t size;
  187021. png_voidp struct_ptr;
  187022. if (type == PNG_STRUCT_INFO)
  187023. size = png_sizeof(png_info);
  187024. else if (type == PNG_STRUCT_PNG)
  187025. size = png_sizeof(png_struct);
  187026. else
  187027. return (NULL);
  187028. #ifdef PNG_USER_MEM_SUPPORTED
  187029. if(malloc_fn != NULL)
  187030. {
  187031. png_struct dummy_struct;
  187032. png_structp png_ptr = &dummy_struct;
  187033. png_ptr->mem_ptr=mem_ptr;
  187034. struct_ptr = (*(malloc_fn))(png_ptr, size);
  187035. if (struct_ptr != NULL)
  187036. png_memset(struct_ptr, 0, size);
  187037. return (struct_ptr);
  187038. }
  187039. #endif /* PNG_USER_MEM_SUPPORTED */
  187040. #if defined(__TURBOC__) && !defined(__FLAT__)
  187041. struct_ptr = (png_voidp)farmalloc(size);
  187042. #else
  187043. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187044. struct_ptr = (png_voidp)halloc(size,1);
  187045. # else
  187046. struct_ptr = (png_voidp)malloc(size);
  187047. # endif
  187048. #endif
  187049. if (struct_ptr != NULL)
  187050. png_memset(struct_ptr, 0, size);
  187051. return (struct_ptr);
  187052. }
  187053. /* Free memory allocated by a png_create_struct() call */
  187054. void /* PRIVATE */
  187055. png_destroy_struct(png_voidp struct_ptr)
  187056. {
  187057. #ifdef PNG_USER_MEM_SUPPORTED
  187058. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187059. }
  187060. /* Free memory allocated by a png_create_struct() call */
  187061. void /* PRIVATE */
  187062. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187063. png_voidp mem_ptr)
  187064. {
  187065. #endif /* PNG_USER_MEM_SUPPORTED */
  187066. if (struct_ptr != NULL)
  187067. {
  187068. #ifdef PNG_USER_MEM_SUPPORTED
  187069. if(free_fn != NULL)
  187070. {
  187071. png_struct dummy_struct;
  187072. png_structp png_ptr = &dummy_struct;
  187073. png_ptr->mem_ptr=mem_ptr;
  187074. (*(free_fn))(png_ptr, struct_ptr);
  187075. return;
  187076. }
  187077. #endif /* PNG_USER_MEM_SUPPORTED */
  187078. #if defined(__TURBOC__) && !defined(__FLAT__)
  187079. farfree(struct_ptr);
  187080. #else
  187081. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187082. hfree(struct_ptr);
  187083. # else
  187084. free(struct_ptr);
  187085. # endif
  187086. #endif
  187087. }
  187088. }
  187089. /* Allocate memory. For reasonable files, size should never exceed
  187090. 64K. However, zlib may allocate more then 64K if you don't tell
  187091. it not to. See zconf.h and png.h for more information. zlib does
  187092. need to allocate exactly 64K, so whatever you call here must
  187093. have the ability to do that. */
  187094. png_voidp PNGAPI
  187095. png_malloc(png_structp png_ptr, png_uint_32 size)
  187096. {
  187097. png_voidp ret;
  187098. #ifdef PNG_USER_MEM_SUPPORTED
  187099. if (png_ptr == NULL || size == 0)
  187100. return (NULL);
  187101. if(png_ptr->malloc_fn != NULL)
  187102. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187103. else
  187104. ret = (png_malloc_default(png_ptr, size));
  187105. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187106. png_error(png_ptr, "Out of Memory!");
  187107. return (ret);
  187108. }
  187109. png_voidp PNGAPI
  187110. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187111. {
  187112. png_voidp ret;
  187113. #endif /* PNG_USER_MEM_SUPPORTED */
  187114. if (png_ptr == NULL || size == 0)
  187115. return (NULL);
  187116. #ifdef PNG_MAX_MALLOC_64K
  187117. if (size > (png_uint_32)65536L)
  187118. {
  187119. #ifndef PNG_USER_MEM_SUPPORTED
  187120. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187121. png_error(png_ptr, "Cannot Allocate > 64K");
  187122. else
  187123. #endif
  187124. return NULL;
  187125. }
  187126. #endif
  187127. /* Check for overflow */
  187128. #if defined(__TURBOC__) && !defined(__FLAT__)
  187129. if (size != (unsigned long)size)
  187130. ret = NULL;
  187131. else
  187132. ret = farmalloc(size);
  187133. #else
  187134. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187135. if (size != (unsigned long)size)
  187136. ret = NULL;
  187137. else
  187138. ret = halloc(size, 1);
  187139. # else
  187140. if (size != (size_t)size)
  187141. ret = NULL;
  187142. else
  187143. ret = malloc((size_t)size);
  187144. # endif
  187145. #endif
  187146. #ifndef PNG_USER_MEM_SUPPORTED
  187147. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187148. png_error(png_ptr, "Out of Memory");
  187149. #endif
  187150. return (ret);
  187151. }
  187152. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187153. without taking any action. */
  187154. void PNGAPI
  187155. png_free(png_structp png_ptr, png_voidp ptr)
  187156. {
  187157. if (png_ptr == NULL || ptr == NULL)
  187158. return;
  187159. #ifdef PNG_USER_MEM_SUPPORTED
  187160. if (png_ptr->free_fn != NULL)
  187161. {
  187162. (*(png_ptr->free_fn))(png_ptr, ptr);
  187163. return;
  187164. }
  187165. else png_free_default(png_ptr, ptr);
  187166. }
  187167. void PNGAPI
  187168. png_free_default(png_structp png_ptr, png_voidp ptr)
  187169. {
  187170. if (png_ptr == NULL || ptr == NULL)
  187171. return;
  187172. #endif /* PNG_USER_MEM_SUPPORTED */
  187173. #if defined(__TURBOC__) && !defined(__FLAT__)
  187174. farfree(ptr);
  187175. #else
  187176. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187177. hfree(ptr);
  187178. # else
  187179. free(ptr);
  187180. # endif
  187181. #endif
  187182. }
  187183. #endif /* Not Borland DOS special memory handler */
  187184. #if defined(PNG_1_0_X)
  187185. # define png_malloc_warn png_malloc
  187186. #else
  187187. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187188. * function will set up png_malloc() to issue a png_warning and return NULL
  187189. * instead of issuing a png_error, if it fails to allocate the requested
  187190. * memory.
  187191. */
  187192. png_voidp PNGAPI
  187193. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187194. {
  187195. png_voidp ptr;
  187196. png_uint_32 save_flags;
  187197. if(png_ptr == NULL) return (NULL);
  187198. save_flags=png_ptr->flags;
  187199. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187200. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187201. png_ptr->flags=save_flags;
  187202. return(ptr);
  187203. }
  187204. #endif
  187205. png_voidp PNGAPI
  187206. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187207. png_uint_32 length)
  187208. {
  187209. png_size_t size;
  187210. size = (png_size_t)length;
  187211. if ((png_uint_32)size != length)
  187212. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187213. return(png_memcpy (s1, s2, size));
  187214. }
  187215. png_voidp PNGAPI
  187216. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187217. png_uint_32 length)
  187218. {
  187219. png_size_t size;
  187220. size = (png_size_t)length;
  187221. if ((png_uint_32)size != length)
  187222. png_error(png_ptr,"Overflow in png_memset_check.");
  187223. return (png_memset (s1, value, size));
  187224. }
  187225. #ifdef PNG_USER_MEM_SUPPORTED
  187226. /* This function is called when the application wants to use another method
  187227. * of allocating and freeing memory.
  187228. */
  187229. void PNGAPI
  187230. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187231. malloc_fn, png_free_ptr free_fn)
  187232. {
  187233. if(png_ptr != NULL) {
  187234. png_ptr->mem_ptr = mem_ptr;
  187235. png_ptr->malloc_fn = malloc_fn;
  187236. png_ptr->free_fn = free_fn;
  187237. }
  187238. }
  187239. /* This function returns a pointer to the mem_ptr associated with the user
  187240. * functions. The application should free any memory associated with this
  187241. * pointer before png_write_destroy and png_read_destroy are called.
  187242. */
  187243. png_voidp PNGAPI
  187244. png_get_mem_ptr(png_structp png_ptr)
  187245. {
  187246. if(png_ptr == NULL) return (NULL);
  187247. return ((png_voidp)png_ptr->mem_ptr);
  187248. }
  187249. #endif /* PNG_USER_MEM_SUPPORTED */
  187250. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187251. /*** End of inlined file: pngmem.c ***/
  187252. /*** Start of inlined file: pngread.c ***/
  187253. /* pngread.c - read a PNG file
  187254. *
  187255. * Last changed in libpng 1.2.20 September 7, 2007
  187256. * For conditions of distribution and use, see copyright notice in png.h
  187257. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187258. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187259. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187260. *
  187261. * This file contains routines that an application calls directly to
  187262. * read a PNG file or stream.
  187263. */
  187264. #define PNG_INTERNAL
  187265. #if defined(PNG_READ_SUPPORTED)
  187266. /* Create a PNG structure for reading, and allocate any memory needed. */
  187267. png_structp PNGAPI
  187268. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187269. png_error_ptr error_fn, png_error_ptr warn_fn)
  187270. {
  187271. #ifdef PNG_USER_MEM_SUPPORTED
  187272. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187273. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187274. }
  187275. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187276. png_structp PNGAPI
  187277. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187278. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187279. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187280. {
  187281. #endif /* PNG_USER_MEM_SUPPORTED */
  187282. png_structp png_ptr;
  187283. #ifdef PNG_SETJMP_SUPPORTED
  187284. #ifdef USE_FAR_KEYWORD
  187285. jmp_buf jmpbuf;
  187286. #endif
  187287. #endif
  187288. int i;
  187289. png_debug(1, "in png_create_read_struct\n");
  187290. #ifdef PNG_USER_MEM_SUPPORTED
  187291. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187292. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187293. #else
  187294. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187295. #endif
  187296. if (png_ptr == NULL)
  187297. return (NULL);
  187298. /* added at libpng-1.2.6 */
  187299. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187300. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187301. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187302. #endif
  187303. #ifdef PNG_SETJMP_SUPPORTED
  187304. #ifdef USE_FAR_KEYWORD
  187305. if (setjmp(jmpbuf))
  187306. #else
  187307. if (setjmp(png_ptr->jmpbuf))
  187308. #endif
  187309. {
  187310. png_free(png_ptr, png_ptr->zbuf);
  187311. png_ptr->zbuf=NULL;
  187312. #ifdef PNG_USER_MEM_SUPPORTED
  187313. png_destroy_struct_2((png_voidp)png_ptr,
  187314. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187315. #else
  187316. png_destroy_struct((png_voidp)png_ptr);
  187317. #endif
  187318. return (NULL);
  187319. }
  187320. #ifdef USE_FAR_KEYWORD
  187321. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187322. #endif
  187323. #endif
  187324. #ifdef PNG_USER_MEM_SUPPORTED
  187325. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187326. #endif
  187327. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187328. i=0;
  187329. do
  187330. {
  187331. if(user_png_ver[i] != png_libpng_ver[i])
  187332. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187333. } while (png_libpng_ver[i++]);
  187334. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187335. {
  187336. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187337. * we must recompile any applications that use any older library version.
  187338. * For versions after libpng 1.0, we will be compatible, so we need
  187339. * only check the first digit.
  187340. */
  187341. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187342. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187343. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187344. {
  187345. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187346. char msg[80];
  187347. if (user_png_ver)
  187348. {
  187349. png_snprintf(msg, 80,
  187350. "Application was compiled with png.h from libpng-%.20s",
  187351. user_png_ver);
  187352. png_warning(png_ptr, msg);
  187353. }
  187354. png_snprintf(msg, 80,
  187355. "Application is running with png.c from libpng-%.20s",
  187356. png_libpng_ver);
  187357. png_warning(png_ptr, msg);
  187358. #endif
  187359. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187360. png_ptr->flags=0;
  187361. #endif
  187362. png_error(png_ptr,
  187363. "Incompatible libpng version in application and library");
  187364. }
  187365. }
  187366. /* initialize zbuf - compression buffer */
  187367. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187368. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187369. (png_uint_32)png_ptr->zbuf_size);
  187370. png_ptr->zstream.zalloc = png_zalloc;
  187371. png_ptr->zstream.zfree = png_zfree;
  187372. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187373. switch (inflateInit(&png_ptr->zstream))
  187374. {
  187375. case Z_OK: /* Do nothing */ break;
  187376. case Z_MEM_ERROR:
  187377. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187378. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187379. default: png_error(png_ptr, "Unknown zlib error");
  187380. }
  187381. png_ptr->zstream.next_out = png_ptr->zbuf;
  187382. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187383. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187384. #ifdef PNG_SETJMP_SUPPORTED
  187385. /* Applications that neglect to set up their own setjmp() and then encounter
  187386. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187387. abort instead of returning. */
  187388. #ifdef USE_FAR_KEYWORD
  187389. if (setjmp(jmpbuf))
  187390. PNG_ABORT();
  187391. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187392. #else
  187393. if (setjmp(png_ptr->jmpbuf))
  187394. PNG_ABORT();
  187395. #endif
  187396. #endif
  187397. return (png_ptr);
  187398. }
  187399. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187400. /* Initialize PNG structure for reading, and allocate any memory needed.
  187401. This interface is deprecated in favour of the png_create_read_struct(),
  187402. and it will disappear as of libpng-1.3.0. */
  187403. #undef png_read_init
  187404. void PNGAPI
  187405. png_read_init(png_structp png_ptr)
  187406. {
  187407. /* We only come here via pre-1.0.7-compiled applications */
  187408. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187409. }
  187410. void PNGAPI
  187411. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187412. png_size_t png_struct_size, png_size_t png_info_size)
  187413. {
  187414. /* We only come here via pre-1.0.12-compiled applications */
  187415. if(png_ptr == NULL) return;
  187416. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187417. if(png_sizeof(png_struct) > png_struct_size ||
  187418. png_sizeof(png_info) > png_info_size)
  187419. {
  187420. char msg[80];
  187421. png_ptr->warning_fn=NULL;
  187422. if (user_png_ver)
  187423. {
  187424. png_snprintf(msg, 80,
  187425. "Application was compiled with png.h from libpng-%.20s",
  187426. user_png_ver);
  187427. png_warning(png_ptr, msg);
  187428. }
  187429. png_snprintf(msg, 80,
  187430. "Application is running with png.c from libpng-%.20s",
  187431. png_libpng_ver);
  187432. png_warning(png_ptr, msg);
  187433. }
  187434. #endif
  187435. if(png_sizeof(png_struct) > png_struct_size)
  187436. {
  187437. png_ptr->error_fn=NULL;
  187438. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187439. png_ptr->flags=0;
  187440. #endif
  187441. png_error(png_ptr,
  187442. "The png struct allocated by the application for reading is too small.");
  187443. }
  187444. if(png_sizeof(png_info) > png_info_size)
  187445. {
  187446. png_ptr->error_fn=NULL;
  187447. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187448. png_ptr->flags=0;
  187449. #endif
  187450. png_error(png_ptr,
  187451. "The info struct allocated by application for reading is too small.");
  187452. }
  187453. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187454. }
  187455. #endif /* PNG_1_0_X || PNG_1_2_X */
  187456. void PNGAPI
  187457. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187458. png_size_t png_struct_size)
  187459. {
  187460. #ifdef PNG_SETJMP_SUPPORTED
  187461. jmp_buf tmp_jmp; /* to save current jump buffer */
  187462. #endif
  187463. int i=0;
  187464. png_structp png_ptr=*ptr_ptr;
  187465. if(png_ptr == NULL) return;
  187466. do
  187467. {
  187468. if(user_png_ver[i] != png_libpng_ver[i])
  187469. {
  187470. #ifdef PNG_LEGACY_SUPPORTED
  187471. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187472. #else
  187473. png_ptr->warning_fn=NULL;
  187474. png_warning(png_ptr,
  187475. "Application uses deprecated png_read_init() and should be recompiled.");
  187476. break;
  187477. #endif
  187478. }
  187479. } while (png_libpng_ver[i++]);
  187480. png_debug(1, "in png_read_init_3\n");
  187481. #ifdef PNG_SETJMP_SUPPORTED
  187482. /* save jump buffer and error functions */
  187483. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187484. #endif
  187485. if(png_sizeof(png_struct) > png_struct_size)
  187486. {
  187487. png_destroy_struct(png_ptr);
  187488. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187489. png_ptr = *ptr_ptr;
  187490. }
  187491. /* reset all variables to 0 */
  187492. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187493. #ifdef PNG_SETJMP_SUPPORTED
  187494. /* restore jump buffer */
  187495. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187496. #endif
  187497. /* added at libpng-1.2.6 */
  187498. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187499. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187500. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187501. #endif
  187502. /* initialize zbuf - compression buffer */
  187503. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187504. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187505. (png_uint_32)png_ptr->zbuf_size);
  187506. png_ptr->zstream.zalloc = png_zalloc;
  187507. png_ptr->zstream.zfree = png_zfree;
  187508. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187509. switch (inflateInit(&png_ptr->zstream))
  187510. {
  187511. case Z_OK: /* Do nothing */ break;
  187512. case Z_MEM_ERROR:
  187513. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187514. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187515. default: png_error(png_ptr, "Unknown zlib error");
  187516. }
  187517. png_ptr->zstream.next_out = png_ptr->zbuf;
  187518. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187519. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187520. }
  187521. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187522. /* Read the information before the actual image data. This has been
  187523. * changed in v0.90 to allow reading a file that already has the magic
  187524. * bytes read from the stream. You can tell libpng how many bytes have
  187525. * been read from the beginning of the stream (up to the maximum of 8)
  187526. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187527. * here. The application can then have access to the signature bytes we
  187528. * read if it is determined that this isn't a valid PNG file.
  187529. */
  187530. void PNGAPI
  187531. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187532. {
  187533. if(png_ptr == NULL) return;
  187534. png_debug(1, "in png_read_info\n");
  187535. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187536. if (png_ptr->sig_bytes < 8)
  187537. {
  187538. png_size_t num_checked = png_ptr->sig_bytes,
  187539. num_to_check = 8 - num_checked;
  187540. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187541. png_ptr->sig_bytes = 8;
  187542. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187543. {
  187544. if (num_checked < 4 &&
  187545. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187546. png_error(png_ptr, "Not a PNG file");
  187547. else
  187548. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187549. }
  187550. if (num_checked < 3)
  187551. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187552. }
  187553. for(;;)
  187554. {
  187555. #ifdef PNG_USE_LOCAL_ARRAYS
  187556. PNG_CONST PNG_IHDR;
  187557. PNG_CONST PNG_IDAT;
  187558. PNG_CONST PNG_IEND;
  187559. PNG_CONST PNG_PLTE;
  187560. #if defined(PNG_READ_bKGD_SUPPORTED)
  187561. PNG_CONST PNG_bKGD;
  187562. #endif
  187563. #if defined(PNG_READ_cHRM_SUPPORTED)
  187564. PNG_CONST PNG_cHRM;
  187565. #endif
  187566. #if defined(PNG_READ_gAMA_SUPPORTED)
  187567. PNG_CONST PNG_gAMA;
  187568. #endif
  187569. #if defined(PNG_READ_hIST_SUPPORTED)
  187570. PNG_CONST PNG_hIST;
  187571. #endif
  187572. #if defined(PNG_READ_iCCP_SUPPORTED)
  187573. PNG_CONST PNG_iCCP;
  187574. #endif
  187575. #if defined(PNG_READ_iTXt_SUPPORTED)
  187576. PNG_CONST PNG_iTXt;
  187577. #endif
  187578. #if defined(PNG_READ_oFFs_SUPPORTED)
  187579. PNG_CONST PNG_oFFs;
  187580. #endif
  187581. #if defined(PNG_READ_pCAL_SUPPORTED)
  187582. PNG_CONST PNG_pCAL;
  187583. #endif
  187584. #if defined(PNG_READ_pHYs_SUPPORTED)
  187585. PNG_CONST PNG_pHYs;
  187586. #endif
  187587. #if defined(PNG_READ_sBIT_SUPPORTED)
  187588. PNG_CONST PNG_sBIT;
  187589. #endif
  187590. #if defined(PNG_READ_sCAL_SUPPORTED)
  187591. PNG_CONST PNG_sCAL;
  187592. #endif
  187593. #if defined(PNG_READ_sPLT_SUPPORTED)
  187594. PNG_CONST PNG_sPLT;
  187595. #endif
  187596. #if defined(PNG_READ_sRGB_SUPPORTED)
  187597. PNG_CONST PNG_sRGB;
  187598. #endif
  187599. #if defined(PNG_READ_tEXt_SUPPORTED)
  187600. PNG_CONST PNG_tEXt;
  187601. #endif
  187602. #if defined(PNG_READ_tIME_SUPPORTED)
  187603. PNG_CONST PNG_tIME;
  187604. #endif
  187605. #if defined(PNG_READ_tRNS_SUPPORTED)
  187606. PNG_CONST PNG_tRNS;
  187607. #endif
  187608. #if defined(PNG_READ_zTXt_SUPPORTED)
  187609. PNG_CONST PNG_zTXt;
  187610. #endif
  187611. #endif /* PNG_USE_LOCAL_ARRAYS */
  187612. png_byte chunk_length[4];
  187613. png_uint_32 length;
  187614. png_read_data(png_ptr, chunk_length, 4);
  187615. length = png_get_uint_31(png_ptr,chunk_length);
  187616. png_reset_crc(png_ptr);
  187617. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187618. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187619. length);
  187620. /* This should be a binary subdivision search or a hash for
  187621. * matching the chunk name rather than a linear search.
  187622. */
  187623. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187624. if(png_ptr->mode & PNG_AFTER_IDAT)
  187625. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187626. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187627. png_handle_IHDR(png_ptr, info_ptr, length);
  187628. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187629. png_handle_IEND(png_ptr, info_ptr, length);
  187630. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187631. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187632. {
  187633. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187634. png_ptr->mode |= PNG_HAVE_IDAT;
  187635. png_handle_unknown(png_ptr, info_ptr, length);
  187636. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187637. png_ptr->mode |= PNG_HAVE_PLTE;
  187638. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187639. {
  187640. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187641. png_error(png_ptr, "Missing IHDR before IDAT");
  187642. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187643. !(png_ptr->mode & PNG_HAVE_PLTE))
  187644. png_error(png_ptr, "Missing PLTE before IDAT");
  187645. break;
  187646. }
  187647. }
  187648. #endif
  187649. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187650. png_handle_PLTE(png_ptr, info_ptr, length);
  187651. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187652. {
  187653. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187654. png_error(png_ptr, "Missing IHDR before IDAT");
  187655. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187656. !(png_ptr->mode & PNG_HAVE_PLTE))
  187657. png_error(png_ptr, "Missing PLTE before IDAT");
  187658. png_ptr->idat_size = length;
  187659. png_ptr->mode |= PNG_HAVE_IDAT;
  187660. break;
  187661. }
  187662. #if defined(PNG_READ_bKGD_SUPPORTED)
  187663. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187664. png_handle_bKGD(png_ptr, info_ptr, length);
  187665. #endif
  187666. #if defined(PNG_READ_cHRM_SUPPORTED)
  187667. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187668. png_handle_cHRM(png_ptr, info_ptr, length);
  187669. #endif
  187670. #if defined(PNG_READ_gAMA_SUPPORTED)
  187671. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187672. png_handle_gAMA(png_ptr, info_ptr, length);
  187673. #endif
  187674. #if defined(PNG_READ_hIST_SUPPORTED)
  187675. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187676. png_handle_hIST(png_ptr, info_ptr, length);
  187677. #endif
  187678. #if defined(PNG_READ_oFFs_SUPPORTED)
  187679. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187680. png_handle_oFFs(png_ptr, info_ptr, length);
  187681. #endif
  187682. #if defined(PNG_READ_pCAL_SUPPORTED)
  187683. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187684. png_handle_pCAL(png_ptr, info_ptr, length);
  187685. #endif
  187686. #if defined(PNG_READ_sCAL_SUPPORTED)
  187687. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187688. png_handle_sCAL(png_ptr, info_ptr, length);
  187689. #endif
  187690. #if defined(PNG_READ_pHYs_SUPPORTED)
  187691. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187692. png_handle_pHYs(png_ptr, info_ptr, length);
  187693. #endif
  187694. #if defined(PNG_READ_sBIT_SUPPORTED)
  187695. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187696. png_handle_sBIT(png_ptr, info_ptr, length);
  187697. #endif
  187698. #if defined(PNG_READ_sRGB_SUPPORTED)
  187699. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187700. png_handle_sRGB(png_ptr, info_ptr, length);
  187701. #endif
  187702. #if defined(PNG_READ_iCCP_SUPPORTED)
  187703. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187704. png_handle_iCCP(png_ptr, info_ptr, length);
  187705. #endif
  187706. #if defined(PNG_READ_sPLT_SUPPORTED)
  187707. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187708. png_handle_sPLT(png_ptr, info_ptr, length);
  187709. #endif
  187710. #if defined(PNG_READ_tEXt_SUPPORTED)
  187711. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187712. png_handle_tEXt(png_ptr, info_ptr, length);
  187713. #endif
  187714. #if defined(PNG_READ_tIME_SUPPORTED)
  187715. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187716. png_handle_tIME(png_ptr, info_ptr, length);
  187717. #endif
  187718. #if defined(PNG_READ_tRNS_SUPPORTED)
  187719. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187720. png_handle_tRNS(png_ptr, info_ptr, length);
  187721. #endif
  187722. #if defined(PNG_READ_zTXt_SUPPORTED)
  187723. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187724. png_handle_zTXt(png_ptr, info_ptr, length);
  187725. #endif
  187726. #if defined(PNG_READ_iTXt_SUPPORTED)
  187727. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187728. png_handle_iTXt(png_ptr, info_ptr, length);
  187729. #endif
  187730. else
  187731. png_handle_unknown(png_ptr, info_ptr, length);
  187732. }
  187733. }
  187734. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187735. /* optional call to update the users info_ptr structure */
  187736. void PNGAPI
  187737. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187738. {
  187739. png_debug(1, "in png_read_update_info\n");
  187740. if(png_ptr == NULL) return;
  187741. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187742. png_read_start_row(png_ptr);
  187743. else
  187744. png_warning(png_ptr,
  187745. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187746. png_read_transform_info(png_ptr, info_ptr);
  187747. }
  187748. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187749. /* Initialize palette, background, etc, after transformations
  187750. * are set, but before any reading takes place. This allows
  187751. * the user to obtain a gamma-corrected palette, for example.
  187752. * If the user doesn't call this, we will do it ourselves.
  187753. */
  187754. void PNGAPI
  187755. png_start_read_image(png_structp png_ptr)
  187756. {
  187757. png_debug(1, "in png_start_read_image\n");
  187758. if(png_ptr == NULL) return;
  187759. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187760. png_read_start_row(png_ptr);
  187761. }
  187762. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187763. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187764. void PNGAPI
  187765. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187766. {
  187767. #ifdef PNG_USE_LOCAL_ARRAYS
  187768. PNG_CONST PNG_IDAT;
  187769. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187770. 0xff};
  187771. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187772. #endif
  187773. int ret;
  187774. if(png_ptr == NULL) return;
  187775. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187776. png_ptr->row_number, png_ptr->pass);
  187777. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187778. png_read_start_row(png_ptr);
  187779. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187780. {
  187781. /* check for transforms that have been set but were defined out */
  187782. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187783. if (png_ptr->transformations & PNG_INVERT_MONO)
  187784. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187785. #endif
  187786. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187787. if (png_ptr->transformations & PNG_FILLER)
  187788. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187789. #endif
  187790. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187791. if (png_ptr->transformations & PNG_PACKSWAP)
  187792. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187793. #endif
  187794. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187795. if (png_ptr->transformations & PNG_PACK)
  187796. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187797. #endif
  187798. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187799. if (png_ptr->transformations & PNG_SHIFT)
  187800. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187801. #endif
  187802. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187803. if (png_ptr->transformations & PNG_BGR)
  187804. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187805. #endif
  187806. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187807. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187808. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187809. #endif
  187810. }
  187811. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187812. /* if interlaced and we do not need a new row, combine row and return */
  187813. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187814. {
  187815. switch (png_ptr->pass)
  187816. {
  187817. case 0:
  187818. if (png_ptr->row_number & 0x07)
  187819. {
  187820. if (dsp_row != NULL)
  187821. png_combine_row(png_ptr, dsp_row,
  187822. png_pass_dsp_mask[png_ptr->pass]);
  187823. png_read_finish_row(png_ptr);
  187824. return;
  187825. }
  187826. break;
  187827. case 1:
  187828. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187829. {
  187830. if (dsp_row != NULL)
  187831. png_combine_row(png_ptr, dsp_row,
  187832. png_pass_dsp_mask[png_ptr->pass]);
  187833. png_read_finish_row(png_ptr);
  187834. return;
  187835. }
  187836. break;
  187837. case 2:
  187838. if ((png_ptr->row_number & 0x07) != 4)
  187839. {
  187840. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187841. png_combine_row(png_ptr, dsp_row,
  187842. png_pass_dsp_mask[png_ptr->pass]);
  187843. png_read_finish_row(png_ptr);
  187844. return;
  187845. }
  187846. break;
  187847. case 3:
  187848. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187849. {
  187850. if (dsp_row != NULL)
  187851. png_combine_row(png_ptr, dsp_row,
  187852. png_pass_dsp_mask[png_ptr->pass]);
  187853. png_read_finish_row(png_ptr);
  187854. return;
  187855. }
  187856. break;
  187857. case 4:
  187858. if ((png_ptr->row_number & 3) != 2)
  187859. {
  187860. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187861. png_combine_row(png_ptr, dsp_row,
  187862. png_pass_dsp_mask[png_ptr->pass]);
  187863. png_read_finish_row(png_ptr);
  187864. return;
  187865. }
  187866. break;
  187867. case 5:
  187868. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187869. {
  187870. if (dsp_row != NULL)
  187871. png_combine_row(png_ptr, dsp_row,
  187872. png_pass_dsp_mask[png_ptr->pass]);
  187873. png_read_finish_row(png_ptr);
  187874. return;
  187875. }
  187876. break;
  187877. case 6:
  187878. if (!(png_ptr->row_number & 1))
  187879. {
  187880. png_read_finish_row(png_ptr);
  187881. return;
  187882. }
  187883. break;
  187884. }
  187885. }
  187886. #endif
  187887. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187888. png_error(png_ptr, "Invalid attempt to read row data");
  187889. png_ptr->zstream.next_out = png_ptr->row_buf;
  187890. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187891. do
  187892. {
  187893. if (!(png_ptr->zstream.avail_in))
  187894. {
  187895. while (!png_ptr->idat_size)
  187896. {
  187897. png_byte chunk_length[4];
  187898. png_crc_finish(png_ptr, 0);
  187899. png_read_data(png_ptr, chunk_length, 4);
  187900. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187901. png_reset_crc(png_ptr);
  187902. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187903. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187904. png_error(png_ptr, "Not enough image data");
  187905. }
  187906. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187907. png_ptr->zstream.next_in = png_ptr->zbuf;
  187908. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187909. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187910. png_crc_read(png_ptr, png_ptr->zbuf,
  187911. (png_size_t)png_ptr->zstream.avail_in);
  187912. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187913. }
  187914. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187915. if (ret == Z_STREAM_END)
  187916. {
  187917. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187918. png_ptr->idat_size)
  187919. png_error(png_ptr, "Extra compressed data");
  187920. png_ptr->mode |= PNG_AFTER_IDAT;
  187921. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187922. break;
  187923. }
  187924. if (ret != Z_OK)
  187925. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187926. "Decompression error");
  187927. } while (png_ptr->zstream.avail_out);
  187928. png_ptr->row_info.color_type = png_ptr->color_type;
  187929. png_ptr->row_info.width = png_ptr->iwidth;
  187930. png_ptr->row_info.channels = png_ptr->channels;
  187931. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187932. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187933. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187934. png_ptr->row_info.width);
  187935. if(png_ptr->row_buf[0])
  187936. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187937. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187938. (int)(png_ptr->row_buf[0]));
  187939. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187940. png_ptr->rowbytes + 1);
  187941. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187942. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187943. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187944. {
  187945. /* Intrapixel differencing */
  187946. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187947. }
  187948. #endif
  187949. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187950. png_do_read_transformations(png_ptr);
  187951. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187952. /* blow up interlaced rows to full size */
  187953. if (png_ptr->interlaced &&
  187954. (png_ptr->transformations & PNG_INTERLACE))
  187955. {
  187956. if (png_ptr->pass < 6)
  187957. /* old interface (pre-1.0.9):
  187958. png_do_read_interlace(&(png_ptr->row_info),
  187959. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187960. */
  187961. png_do_read_interlace(png_ptr);
  187962. if (dsp_row != NULL)
  187963. png_combine_row(png_ptr, dsp_row,
  187964. png_pass_dsp_mask[png_ptr->pass]);
  187965. if (row != NULL)
  187966. png_combine_row(png_ptr, row,
  187967. png_pass_mask[png_ptr->pass]);
  187968. }
  187969. else
  187970. #endif
  187971. {
  187972. if (row != NULL)
  187973. png_combine_row(png_ptr, row, 0xff);
  187974. if (dsp_row != NULL)
  187975. png_combine_row(png_ptr, dsp_row, 0xff);
  187976. }
  187977. png_read_finish_row(png_ptr);
  187978. if (png_ptr->read_row_fn != NULL)
  187979. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187980. }
  187981. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187982. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187983. /* Read one or more rows of image data. If the image is interlaced,
  187984. * and png_set_interlace_handling() has been called, the rows need to
  187985. * contain the contents of the rows from the previous pass. If the
  187986. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187987. * called, the rows contents must be initialized to the contents of the
  187988. * screen.
  187989. *
  187990. * "row" holds the actual image, and pixels are placed in it
  187991. * as they arrive. If the image is displayed after each pass, it will
  187992. * appear to "sparkle" in. "display_row" can be used to display a
  187993. * "chunky" progressive image, with finer detail added as it becomes
  187994. * available. If you do not want this "chunky" display, you may pass
  187995. * NULL for display_row. If you do not want the sparkle display, and
  187996. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187997. * If you have called png_handle_alpha(), and the image has either an
  187998. * alpha channel or a transparency chunk, you must provide a buffer for
  187999. * rows. In this case, you do not have to provide a display_row buffer
  188000. * also, but you may. If the image is not interlaced, or if you have
  188001. * not called png_set_interlace_handling(), the display_row buffer will
  188002. * be ignored, so pass NULL to it.
  188003. *
  188004. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188005. */
  188006. void PNGAPI
  188007. png_read_rows(png_structp png_ptr, png_bytepp row,
  188008. png_bytepp display_row, png_uint_32 num_rows)
  188009. {
  188010. png_uint_32 i;
  188011. png_bytepp rp;
  188012. png_bytepp dp;
  188013. png_debug(1, "in png_read_rows\n");
  188014. if(png_ptr == NULL) return;
  188015. rp = row;
  188016. dp = display_row;
  188017. if (rp != NULL && dp != NULL)
  188018. for (i = 0; i < num_rows; i++)
  188019. {
  188020. png_bytep rptr = *rp++;
  188021. png_bytep dptr = *dp++;
  188022. png_read_row(png_ptr, rptr, dptr);
  188023. }
  188024. else if(rp != NULL)
  188025. for (i = 0; i < num_rows; i++)
  188026. {
  188027. png_bytep rptr = *rp;
  188028. png_read_row(png_ptr, rptr, png_bytep_NULL);
  188029. rp++;
  188030. }
  188031. else if(dp != NULL)
  188032. for (i = 0; i < num_rows; i++)
  188033. {
  188034. png_bytep dptr = *dp;
  188035. png_read_row(png_ptr, png_bytep_NULL, dptr);
  188036. dp++;
  188037. }
  188038. }
  188039. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188040. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188041. /* Read the entire image. If the image has an alpha channel or a tRNS
  188042. * chunk, and you have called png_handle_alpha()[*], you will need to
  188043. * initialize the image to the current image that PNG will be overlaying.
  188044. * We set the num_rows again here, in case it was incorrectly set in
  188045. * png_read_start_row() by a call to png_read_update_info() or
  188046. * png_start_read_image() if png_set_interlace_handling() wasn't called
  188047. * prior to either of these functions like it should have been. You can
  188048. * only call this function once. If you desire to have an image for
  188049. * each pass of a interlaced image, use png_read_rows() instead.
  188050. *
  188051. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188052. */
  188053. void PNGAPI
  188054. png_read_image(png_structp png_ptr, png_bytepp image)
  188055. {
  188056. png_uint_32 i,image_height;
  188057. int pass, j;
  188058. png_bytepp rp;
  188059. png_debug(1, "in png_read_image\n");
  188060. if(png_ptr == NULL) return;
  188061. #ifdef PNG_READ_INTERLACING_SUPPORTED
  188062. pass = png_set_interlace_handling(png_ptr);
  188063. #else
  188064. if (png_ptr->interlaced)
  188065. png_error(png_ptr,
  188066. "Cannot read interlaced image -- interlace handler disabled.");
  188067. pass = 1;
  188068. #endif
  188069. image_height=png_ptr->height;
  188070. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  188071. for (j = 0; j < pass; j++)
  188072. {
  188073. rp = image;
  188074. for (i = 0; i < image_height; i++)
  188075. {
  188076. png_read_row(png_ptr, *rp, png_bytep_NULL);
  188077. rp++;
  188078. }
  188079. }
  188080. }
  188081. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188082. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188083. /* Read the end of the PNG file. Will not read past the end of the
  188084. * file, will verify the end is accurate, and will read any comments
  188085. * or time information at the end of the file, if info is not NULL.
  188086. */
  188087. void PNGAPI
  188088. png_read_end(png_structp png_ptr, png_infop info_ptr)
  188089. {
  188090. png_byte chunk_length[4];
  188091. png_uint_32 length;
  188092. png_debug(1, "in png_read_end\n");
  188093. if(png_ptr == NULL) return;
  188094. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  188095. do
  188096. {
  188097. #ifdef PNG_USE_LOCAL_ARRAYS
  188098. PNG_CONST PNG_IHDR;
  188099. PNG_CONST PNG_IDAT;
  188100. PNG_CONST PNG_IEND;
  188101. PNG_CONST PNG_PLTE;
  188102. #if defined(PNG_READ_bKGD_SUPPORTED)
  188103. PNG_CONST PNG_bKGD;
  188104. #endif
  188105. #if defined(PNG_READ_cHRM_SUPPORTED)
  188106. PNG_CONST PNG_cHRM;
  188107. #endif
  188108. #if defined(PNG_READ_gAMA_SUPPORTED)
  188109. PNG_CONST PNG_gAMA;
  188110. #endif
  188111. #if defined(PNG_READ_hIST_SUPPORTED)
  188112. PNG_CONST PNG_hIST;
  188113. #endif
  188114. #if defined(PNG_READ_iCCP_SUPPORTED)
  188115. PNG_CONST PNG_iCCP;
  188116. #endif
  188117. #if defined(PNG_READ_iTXt_SUPPORTED)
  188118. PNG_CONST PNG_iTXt;
  188119. #endif
  188120. #if defined(PNG_READ_oFFs_SUPPORTED)
  188121. PNG_CONST PNG_oFFs;
  188122. #endif
  188123. #if defined(PNG_READ_pCAL_SUPPORTED)
  188124. PNG_CONST PNG_pCAL;
  188125. #endif
  188126. #if defined(PNG_READ_pHYs_SUPPORTED)
  188127. PNG_CONST PNG_pHYs;
  188128. #endif
  188129. #if defined(PNG_READ_sBIT_SUPPORTED)
  188130. PNG_CONST PNG_sBIT;
  188131. #endif
  188132. #if defined(PNG_READ_sCAL_SUPPORTED)
  188133. PNG_CONST PNG_sCAL;
  188134. #endif
  188135. #if defined(PNG_READ_sPLT_SUPPORTED)
  188136. PNG_CONST PNG_sPLT;
  188137. #endif
  188138. #if defined(PNG_READ_sRGB_SUPPORTED)
  188139. PNG_CONST PNG_sRGB;
  188140. #endif
  188141. #if defined(PNG_READ_tEXt_SUPPORTED)
  188142. PNG_CONST PNG_tEXt;
  188143. #endif
  188144. #if defined(PNG_READ_tIME_SUPPORTED)
  188145. PNG_CONST PNG_tIME;
  188146. #endif
  188147. #if defined(PNG_READ_tRNS_SUPPORTED)
  188148. PNG_CONST PNG_tRNS;
  188149. #endif
  188150. #if defined(PNG_READ_zTXt_SUPPORTED)
  188151. PNG_CONST PNG_zTXt;
  188152. #endif
  188153. #endif /* PNG_USE_LOCAL_ARRAYS */
  188154. png_read_data(png_ptr, chunk_length, 4);
  188155. length = png_get_uint_31(png_ptr,chunk_length);
  188156. png_reset_crc(png_ptr);
  188157. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188158. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188159. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188160. png_handle_IHDR(png_ptr, info_ptr, length);
  188161. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188162. png_handle_IEND(png_ptr, info_ptr, length);
  188163. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188164. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188165. {
  188166. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188167. {
  188168. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188169. png_error(png_ptr, "Too many IDAT's found");
  188170. }
  188171. png_handle_unknown(png_ptr, info_ptr, length);
  188172. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188173. png_ptr->mode |= PNG_HAVE_PLTE;
  188174. }
  188175. #endif
  188176. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188177. {
  188178. /* Zero length IDATs are legal after the last IDAT has been
  188179. * read, but not after other chunks have been read.
  188180. */
  188181. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188182. png_error(png_ptr, "Too many IDAT's found");
  188183. png_crc_finish(png_ptr, length);
  188184. }
  188185. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188186. png_handle_PLTE(png_ptr, info_ptr, length);
  188187. #if defined(PNG_READ_bKGD_SUPPORTED)
  188188. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188189. png_handle_bKGD(png_ptr, info_ptr, length);
  188190. #endif
  188191. #if defined(PNG_READ_cHRM_SUPPORTED)
  188192. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188193. png_handle_cHRM(png_ptr, info_ptr, length);
  188194. #endif
  188195. #if defined(PNG_READ_gAMA_SUPPORTED)
  188196. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188197. png_handle_gAMA(png_ptr, info_ptr, length);
  188198. #endif
  188199. #if defined(PNG_READ_hIST_SUPPORTED)
  188200. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188201. png_handle_hIST(png_ptr, info_ptr, length);
  188202. #endif
  188203. #if defined(PNG_READ_oFFs_SUPPORTED)
  188204. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188205. png_handle_oFFs(png_ptr, info_ptr, length);
  188206. #endif
  188207. #if defined(PNG_READ_pCAL_SUPPORTED)
  188208. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188209. png_handle_pCAL(png_ptr, info_ptr, length);
  188210. #endif
  188211. #if defined(PNG_READ_sCAL_SUPPORTED)
  188212. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188213. png_handle_sCAL(png_ptr, info_ptr, length);
  188214. #endif
  188215. #if defined(PNG_READ_pHYs_SUPPORTED)
  188216. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188217. png_handle_pHYs(png_ptr, info_ptr, length);
  188218. #endif
  188219. #if defined(PNG_READ_sBIT_SUPPORTED)
  188220. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188221. png_handle_sBIT(png_ptr, info_ptr, length);
  188222. #endif
  188223. #if defined(PNG_READ_sRGB_SUPPORTED)
  188224. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188225. png_handle_sRGB(png_ptr, info_ptr, length);
  188226. #endif
  188227. #if defined(PNG_READ_iCCP_SUPPORTED)
  188228. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188229. png_handle_iCCP(png_ptr, info_ptr, length);
  188230. #endif
  188231. #if defined(PNG_READ_sPLT_SUPPORTED)
  188232. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188233. png_handle_sPLT(png_ptr, info_ptr, length);
  188234. #endif
  188235. #if defined(PNG_READ_tEXt_SUPPORTED)
  188236. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188237. png_handle_tEXt(png_ptr, info_ptr, length);
  188238. #endif
  188239. #if defined(PNG_READ_tIME_SUPPORTED)
  188240. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188241. png_handle_tIME(png_ptr, info_ptr, length);
  188242. #endif
  188243. #if defined(PNG_READ_tRNS_SUPPORTED)
  188244. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188245. png_handle_tRNS(png_ptr, info_ptr, length);
  188246. #endif
  188247. #if defined(PNG_READ_zTXt_SUPPORTED)
  188248. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188249. png_handle_zTXt(png_ptr, info_ptr, length);
  188250. #endif
  188251. #if defined(PNG_READ_iTXt_SUPPORTED)
  188252. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188253. png_handle_iTXt(png_ptr, info_ptr, length);
  188254. #endif
  188255. else
  188256. png_handle_unknown(png_ptr, info_ptr, length);
  188257. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188258. }
  188259. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188260. /* free all memory used by the read */
  188261. void PNGAPI
  188262. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188263. png_infopp end_info_ptr_ptr)
  188264. {
  188265. png_structp png_ptr = NULL;
  188266. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188267. #ifdef PNG_USER_MEM_SUPPORTED
  188268. png_free_ptr free_fn;
  188269. png_voidp mem_ptr;
  188270. #endif
  188271. png_debug(1, "in png_destroy_read_struct\n");
  188272. if (png_ptr_ptr != NULL)
  188273. png_ptr = *png_ptr_ptr;
  188274. if (info_ptr_ptr != NULL)
  188275. info_ptr = *info_ptr_ptr;
  188276. if (end_info_ptr_ptr != NULL)
  188277. end_info_ptr = *end_info_ptr_ptr;
  188278. #ifdef PNG_USER_MEM_SUPPORTED
  188279. free_fn = png_ptr->free_fn;
  188280. mem_ptr = png_ptr->mem_ptr;
  188281. #endif
  188282. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188283. if (info_ptr != NULL)
  188284. {
  188285. #if defined(PNG_TEXT_SUPPORTED)
  188286. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188287. #endif
  188288. #ifdef PNG_USER_MEM_SUPPORTED
  188289. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188290. (png_voidp)mem_ptr);
  188291. #else
  188292. png_destroy_struct((png_voidp)info_ptr);
  188293. #endif
  188294. *info_ptr_ptr = NULL;
  188295. }
  188296. if (end_info_ptr != NULL)
  188297. {
  188298. #if defined(PNG_READ_TEXT_SUPPORTED)
  188299. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188300. #endif
  188301. #ifdef PNG_USER_MEM_SUPPORTED
  188302. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188303. (png_voidp)mem_ptr);
  188304. #else
  188305. png_destroy_struct((png_voidp)end_info_ptr);
  188306. #endif
  188307. *end_info_ptr_ptr = NULL;
  188308. }
  188309. if (png_ptr != NULL)
  188310. {
  188311. #ifdef PNG_USER_MEM_SUPPORTED
  188312. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188313. (png_voidp)mem_ptr);
  188314. #else
  188315. png_destroy_struct((png_voidp)png_ptr);
  188316. #endif
  188317. *png_ptr_ptr = NULL;
  188318. }
  188319. }
  188320. /* free all memory used by the read (old method) */
  188321. void /* PRIVATE */
  188322. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188323. {
  188324. #ifdef PNG_SETJMP_SUPPORTED
  188325. jmp_buf tmp_jmp;
  188326. #endif
  188327. png_error_ptr error_fn;
  188328. png_error_ptr warning_fn;
  188329. png_voidp error_ptr;
  188330. #ifdef PNG_USER_MEM_SUPPORTED
  188331. png_free_ptr free_fn;
  188332. #endif
  188333. png_debug(1, "in png_read_destroy\n");
  188334. if (info_ptr != NULL)
  188335. png_info_destroy(png_ptr, info_ptr);
  188336. if (end_info_ptr != NULL)
  188337. png_info_destroy(png_ptr, end_info_ptr);
  188338. png_free(png_ptr, png_ptr->zbuf);
  188339. png_free(png_ptr, png_ptr->big_row_buf);
  188340. png_free(png_ptr, png_ptr->prev_row);
  188341. #if defined(PNG_READ_DITHER_SUPPORTED)
  188342. png_free(png_ptr, png_ptr->palette_lookup);
  188343. png_free(png_ptr, png_ptr->dither_index);
  188344. #endif
  188345. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188346. png_free(png_ptr, png_ptr->gamma_table);
  188347. #endif
  188348. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188349. png_free(png_ptr, png_ptr->gamma_from_1);
  188350. png_free(png_ptr, png_ptr->gamma_to_1);
  188351. #endif
  188352. #ifdef PNG_FREE_ME_SUPPORTED
  188353. if (png_ptr->free_me & PNG_FREE_PLTE)
  188354. png_zfree(png_ptr, png_ptr->palette);
  188355. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188356. #else
  188357. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188358. png_zfree(png_ptr, png_ptr->palette);
  188359. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188360. #endif
  188361. #if defined(PNG_tRNS_SUPPORTED) || \
  188362. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188363. #ifdef PNG_FREE_ME_SUPPORTED
  188364. if (png_ptr->free_me & PNG_FREE_TRNS)
  188365. png_free(png_ptr, png_ptr->trans);
  188366. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188367. #else
  188368. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188369. png_free(png_ptr, png_ptr->trans);
  188370. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188371. #endif
  188372. #endif
  188373. #if defined(PNG_READ_hIST_SUPPORTED)
  188374. #ifdef PNG_FREE_ME_SUPPORTED
  188375. if (png_ptr->free_me & PNG_FREE_HIST)
  188376. png_free(png_ptr, png_ptr->hist);
  188377. png_ptr->free_me &= ~PNG_FREE_HIST;
  188378. #else
  188379. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188380. png_free(png_ptr, png_ptr->hist);
  188381. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188382. #endif
  188383. #endif
  188384. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188385. if (png_ptr->gamma_16_table != NULL)
  188386. {
  188387. int i;
  188388. int istop = (1 << (8 - png_ptr->gamma_shift));
  188389. for (i = 0; i < istop; i++)
  188390. {
  188391. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188392. }
  188393. png_free(png_ptr, png_ptr->gamma_16_table);
  188394. }
  188395. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188396. if (png_ptr->gamma_16_from_1 != NULL)
  188397. {
  188398. int i;
  188399. int istop = (1 << (8 - png_ptr->gamma_shift));
  188400. for (i = 0; i < istop; i++)
  188401. {
  188402. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188403. }
  188404. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188405. }
  188406. if (png_ptr->gamma_16_to_1 != NULL)
  188407. {
  188408. int i;
  188409. int istop = (1 << (8 - png_ptr->gamma_shift));
  188410. for (i = 0; i < istop; i++)
  188411. {
  188412. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188413. }
  188414. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188415. }
  188416. #endif
  188417. #endif
  188418. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188419. png_free(png_ptr, png_ptr->time_buffer);
  188420. #endif
  188421. inflateEnd(&png_ptr->zstream);
  188422. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188423. png_free(png_ptr, png_ptr->save_buffer);
  188424. #endif
  188425. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188426. #ifdef PNG_TEXT_SUPPORTED
  188427. png_free(png_ptr, png_ptr->current_text);
  188428. #endif /* PNG_TEXT_SUPPORTED */
  188429. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188430. /* Save the important info out of the png_struct, in case it is
  188431. * being used again.
  188432. */
  188433. #ifdef PNG_SETJMP_SUPPORTED
  188434. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188435. #endif
  188436. error_fn = png_ptr->error_fn;
  188437. warning_fn = png_ptr->warning_fn;
  188438. error_ptr = png_ptr->error_ptr;
  188439. #ifdef PNG_USER_MEM_SUPPORTED
  188440. free_fn = png_ptr->free_fn;
  188441. #endif
  188442. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188443. png_ptr->error_fn = error_fn;
  188444. png_ptr->warning_fn = warning_fn;
  188445. png_ptr->error_ptr = error_ptr;
  188446. #ifdef PNG_USER_MEM_SUPPORTED
  188447. png_ptr->free_fn = free_fn;
  188448. #endif
  188449. #ifdef PNG_SETJMP_SUPPORTED
  188450. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188451. #endif
  188452. }
  188453. void PNGAPI
  188454. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188455. {
  188456. if(png_ptr == NULL) return;
  188457. png_ptr->read_row_fn = read_row_fn;
  188458. }
  188459. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188460. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188461. void PNGAPI
  188462. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188463. int transforms,
  188464. voidp params)
  188465. {
  188466. int row;
  188467. if(png_ptr == NULL) return;
  188468. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188469. /* invert the alpha channel from opacity to transparency
  188470. */
  188471. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188472. png_set_invert_alpha(png_ptr);
  188473. #endif
  188474. /* png_read_info() gives us all of the information from the
  188475. * PNG file before the first IDAT (image data chunk).
  188476. */
  188477. png_read_info(png_ptr, info_ptr);
  188478. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188479. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188480. /* -------------- image transformations start here ------------------- */
  188481. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188482. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188483. */
  188484. if (transforms & PNG_TRANSFORM_STRIP_16)
  188485. png_set_strip_16(png_ptr);
  188486. #endif
  188487. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188488. /* Strip alpha bytes from the input data without combining with
  188489. * the background (not recommended).
  188490. */
  188491. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188492. png_set_strip_alpha(png_ptr);
  188493. #endif
  188494. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188495. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188496. * byte into separate bytes (useful for paletted and grayscale images).
  188497. */
  188498. if (transforms & PNG_TRANSFORM_PACKING)
  188499. png_set_packing(png_ptr);
  188500. #endif
  188501. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188502. /* Change the order of packed pixels to least significant bit first
  188503. * (not useful if you are using png_set_packing).
  188504. */
  188505. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188506. png_set_packswap(png_ptr);
  188507. #endif
  188508. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188509. /* Expand paletted colors into true RGB triplets
  188510. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188511. * Expand paletted or RGB images with transparency to full alpha
  188512. * channels so the data will be available as RGBA quartets.
  188513. */
  188514. if (transforms & PNG_TRANSFORM_EXPAND)
  188515. if ((png_ptr->bit_depth < 8) ||
  188516. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188517. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188518. png_set_expand(png_ptr);
  188519. #endif
  188520. /* We don't handle background color or gamma transformation or dithering.
  188521. */
  188522. #if defined(PNG_READ_INVERT_SUPPORTED)
  188523. /* invert monochrome files to have 0 as white and 1 as black
  188524. */
  188525. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188526. png_set_invert_mono(png_ptr);
  188527. #endif
  188528. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188529. /* If you want to shift the pixel values from the range [0,255] or
  188530. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188531. * colors were originally in:
  188532. */
  188533. if ((transforms & PNG_TRANSFORM_SHIFT)
  188534. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188535. {
  188536. png_color_8p sig_bit;
  188537. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188538. png_set_shift(png_ptr, sig_bit);
  188539. }
  188540. #endif
  188541. #if defined(PNG_READ_BGR_SUPPORTED)
  188542. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188543. */
  188544. if (transforms & PNG_TRANSFORM_BGR)
  188545. png_set_bgr(png_ptr);
  188546. #endif
  188547. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188548. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188549. */
  188550. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188551. png_set_swap_alpha(png_ptr);
  188552. #endif
  188553. #if defined(PNG_READ_SWAP_SUPPORTED)
  188554. /* swap bytes of 16 bit files to least significant byte first
  188555. */
  188556. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188557. png_set_swap(png_ptr);
  188558. #endif
  188559. /* We don't handle adding filler bytes */
  188560. /* Optional call to gamma correct and add the background to the palette
  188561. * and update info structure. REQUIRED if you are expecting libpng to
  188562. * update the palette for you (i.e., you selected such a transform above).
  188563. */
  188564. png_read_update_info(png_ptr, info_ptr);
  188565. /* -------------- image transformations end here ------------------- */
  188566. #ifdef PNG_FREE_ME_SUPPORTED
  188567. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188568. #endif
  188569. if(info_ptr->row_pointers == NULL)
  188570. {
  188571. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188572. info_ptr->height * png_sizeof(png_bytep));
  188573. #ifdef PNG_FREE_ME_SUPPORTED
  188574. info_ptr->free_me |= PNG_FREE_ROWS;
  188575. #endif
  188576. for (row = 0; row < (int)info_ptr->height; row++)
  188577. {
  188578. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188579. png_get_rowbytes(png_ptr, info_ptr));
  188580. }
  188581. }
  188582. png_read_image(png_ptr, info_ptr->row_pointers);
  188583. info_ptr->valid |= PNG_INFO_IDAT;
  188584. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188585. png_read_end(png_ptr, info_ptr);
  188586. transforms = transforms; /* quiet compiler warnings */
  188587. params = params;
  188588. }
  188589. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188590. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188591. #endif /* PNG_READ_SUPPORTED */
  188592. /*** End of inlined file: pngread.c ***/
  188593. /*** Start of inlined file: pngpread.c ***/
  188594. /* pngpread.c - read a png file in push mode
  188595. *
  188596. * Last changed in libpng 1.2.21 October 4, 2007
  188597. * For conditions of distribution and use, see copyright notice in png.h
  188598. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188599. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188600. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188601. */
  188602. #define PNG_INTERNAL
  188603. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188604. /* push model modes */
  188605. #define PNG_READ_SIG_MODE 0
  188606. #define PNG_READ_CHUNK_MODE 1
  188607. #define PNG_READ_IDAT_MODE 2
  188608. #define PNG_SKIP_MODE 3
  188609. #define PNG_READ_tEXt_MODE 4
  188610. #define PNG_READ_zTXt_MODE 5
  188611. #define PNG_READ_DONE_MODE 6
  188612. #define PNG_READ_iTXt_MODE 7
  188613. #define PNG_ERROR_MODE 8
  188614. void PNGAPI
  188615. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188616. png_bytep buffer, png_size_t buffer_size)
  188617. {
  188618. if(png_ptr == NULL) return;
  188619. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188620. while (png_ptr->buffer_size)
  188621. {
  188622. png_process_some_data(png_ptr, info_ptr);
  188623. }
  188624. }
  188625. /* What we do with the incoming data depends on what we were previously
  188626. * doing before we ran out of data...
  188627. */
  188628. void /* PRIVATE */
  188629. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188630. {
  188631. if(png_ptr == NULL) return;
  188632. switch (png_ptr->process_mode)
  188633. {
  188634. case PNG_READ_SIG_MODE:
  188635. {
  188636. png_push_read_sig(png_ptr, info_ptr);
  188637. break;
  188638. }
  188639. case PNG_READ_CHUNK_MODE:
  188640. {
  188641. png_push_read_chunk(png_ptr, info_ptr);
  188642. break;
  188643. }
  188644. case PNG_READ_IDAT_MODE:
  188645. {
  188646. png_push_read_IDAT(png_ptr);
  188647. break;
  188648. }
  188649. #if defined(PNG_READ_tEXt_SUPPORTED)
  188650. case PNG_READ_tEXt_MODE:
  188651. {
  188652. png_push_read_tEXt(png_ptr, info_ptr);
  188653. break;
  188654. }
  188655. #endif
  188656. #if defined(PNG_READ_zTXt_SUPPORTED)
  188657. case PNG_READ_zTXt_MODE:
  188658. {
  188659. png_push_read_zTXt(png_ptr, info_ptr);
  188660. break;
  188661. }
  188662. #endif
  188663. #if defined(PNG_READ_iTXt_SUPPORTED)
  188664. case PNG_READ_iTXt_MODE:
  188665. {
  188666. png_push_read_iTXt(png_ptr, info_ptr);
  188667. break;
  188668. }
  188669. #endif
  188670. case PNG_SKIP_MODE:
  188671. {
  188672. png_push_crc_finish(png_ptr);
  188673. break;
  188674. }
  188675. default:
  188676. {
  188677. png_ptr->buffer_size = 0;
  188678. break;
  188679. }
  188680. }
  188681. }
  188682. /* Read any remaining signature bytes from the stream and compare them with
  188683. * the correct PNG signature. It is possible that this routine is called
  188684. * with bytes already read from the signature, either because they have been
  188685. * checked by the calling application, or because of multiple calls to this
  188686. * routine.
  188687. */
  188688. void /* PRIVATE */
  188689. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188690. {
  188691. png_size_t num_checked = png_ptr->sig_bytes,
  188692. num_to_check = 8 - num_checked;
  188693. if (png_ptr->buffer_size < num_to_check)
  188694. {
  188695. num_to_check = png_ptr->buffer_size;
  188696. }
  188697. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188698. num_to_check);
  188699. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188700. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188701. {
  188702. if (num_checked < 4 &&
  188703. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188704. png_error(png_ptr, "Not a PNG file");
  188705. else
  188706. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188707. }
  188708. else
  188709. {
  188710. if (png_ptr->sig_bytes >= 8)
  188711. {
  188712. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188713. }
  188714. }
  188715. }
  188716. void /* PRIVATE */
  188717. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188718. {
  188719. #ifdef PNG_USE_LOCAL_ARRAYS
  188720. PNG_CONST PNG_IHDR;
  188721. PNG_CONST PNG_IDAT;
  188722. PNG_CONST PNG_IEND;
  188723. PNG_CONST PNG_PLTE;
  188724. #if defined(PNG_READ_bKGD_SUPPORTED)
  188725. PNG_CONST PNG_bKGD;
  188726. #endif
  188727. #if defined(PNG_READ_cHRM_SUPPORTED)
  188728. PNG_CONST PNG_cHRM;
  188729. #endif
  188730. #if defined(PNG_READ_gAMA_SUPPORTED)
  188731. PNG_CONST PNG_gAMA;
  188732. #endif
  188733. #if defined(PNG_READ_hIST_SUPPORTED)
  188734. PNG_CONST PNG_hIST;
  188735. #endif
  188736. #if defined(PNG_READ_iCCP_SUPPORTED)
  188737. PNG_CONST PNG_iCCP;
  188738. #endif
  188739. #if defined(PNG_READ_iTXt_SUPPORTED)
  188740. PNG_CONST PNG_iTXt;
  188741. #endif
  188742. #if defined(PNG_READ_oFFs_SUPPORTED)
  188743. PNG_CONST PNG_oFFs;
  188744. #endif
  188745. #if defined(PNG_READ_pCAL_SUPPORTED)
  188746. PNG_CONST PNG_pCAL;
  188747. #endif
  188748. #if defined(PNG_READ_pHYs_SUPPORTED)
  188749. PNG_CONST PNG_pHYs;
  188750. #endif
  188751. #if defined(PNG_READ_sBIT_SUPPORTED)
  188752. PNG_CONST PNG_sBIT;
  188753. #endif
  188754. #if defined(PNG_READ_sCAL_SUPPORTED)
  188755. PNG_CONST PNG_sCAL;
  188756. #endif
  188757. #if defined(PNG_READ_sRGB_SUPPORTED)
  188758. PNG_CONST PNG_sRGB;
  188759. #endif
  188760. #if defined(PNG_READ_sPLT_SUPPORTED)
  188761. PNG_CONST PNG_sPLT;
  188762. #endif
  188763. #if defined(PNG_READ_tEXt_SUPPORTED)
  188764. PNG_CONST PNG_tEXt;
  188765. #endif
  188766. #if defined(PNG_READ_tIME_SUPPORTED)
  188767. PNG_CONST PNG_tIME;
  188768. #endif
  188769. #if defined(PNG_READ_tRNS_SUPPORTED)
  188770. PNG_CONST PNG_tRNS;
  188771. #endif
  188772. #if defined(PNG_READ_zTXt_SUPPORTED)
  188773. PNG_CONST PNG_zTXt;
  188774. #endif
  188775. #endif /* PNG_USE_LOCAL_ARRAYS */
  188776. /* First we make sure we have enough data for the 4 byte chunk name
  188777. * and the 4 byte chunk length before proceeding with decoding the
  188778. * chunk data. To fully decode each of these chunks, we also make
  188779. * sure we have enough data in the buffer for the 4 byte CRC at the
  188780. * end of every chunk (except IDAT, which is handled separately).
  188781. */
  188782. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188783. {
  188784. png_byte chunk_length[4];
  188785. if (png_ptr->buffer_size < 8)
  188786. {
  188787. png_push_save_buffer(png_ptr);
  188788. return;
  188789. }
  188790. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188791. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188792. png_reset_crc(png_ptr);
  188793. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188794. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188795. }
  188796. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188797. if(png_ptr->mode & PNG_AFTER_IDAT)
  188798. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188799. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188800. {
  188801. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188802. {
  188803. png_push_save_buffer(png_ptr);
  188804. return;
  188805. }
  188806. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188807. }
  188808. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188809. {
  188810. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188811. {
  188812. png_push_save_buffer(png_ptr);
  188813. return;
  188814. }
  188815. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188816. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188817. png_push_have_end(png_ptr, info_ptr);
  188818. }
  188819. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188820. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188821. {
  188822. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188823. {
  188824. png_push_save_buffer(png_ptr);
  188825. return;
  188826. }
  188827. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188828. png_ptr->mode |= PNG_HAVE_IDAT;
  188829. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188830. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188831. png_ptr->mode |= PNG_HAVE_PLTE;
  188832. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188833. {
  188834. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188835. png_error(png_ptr, "Missing IHDR before IDAT");
  188836. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188837. !(png_ptr->mode & PNG_HAVE_PLTE))
  188838. png_error(png_ptr, "Missing PLTE before IDAT");
  188839. }
  188840. }
  188841. #endif
  188842. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188843. {
  188844. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188845. {
  188846. png_push_save_buffer(png_ptr);
  188847. return;
  188848. }
  188849. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188850. }
  188851. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188852. {
  188853. /* If we reach an IDAT chunk, this means we have read all of the
  188854. * header chunks, and we can start reading the image (or if this
  188855. * is called after the image has been read - we have an error).
  188856. */
  188857. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188858. png_error(png_ptr, "Missing IHDR before IDAT");
  188859. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188860. !(png_ptr->mode & PNG_HAVE_PLTE))
  188861. png_error(png_ptr, "Missing PLTE before IDAT");
  188862. if (png_ptr->mode & PNG_HAVE_IDAT)
  188863. {
  188864. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188865. if (png_ptr->push_length == 0)
  188866. return;
  188867. if (png_ptr->mode & PNG_AFTER_IDAT)
  188868. png_error(png_ptr, "Too many IDAT's found");
  188869. }
  188870. png_ptr->idat_size = png_ptr->push_length;
  188871. png_ptr->mode |= PNG_HAVE_IDAT;
  188872. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188873. png_push_have_info(png_ptr, info_ptr);
  188874. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188875. png_ptr->zstream.next_out = png_ptr->row_buf;
  188876. return;
  188877. }
  188878. #if defined(PNG_READ_gAMA_SUPPORTED)
  188879. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188880. {
  188881. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188882. {
  188883. png_push_save_buffer(png_ptr);
  188884. return;
  188885. }
  188886. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188887. }
  188888. #endif
  188889. #if defined(PNG_READ_sBIT_SUPPORTED)
  188890. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188891. {
  188892. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188893. {
  188894. png_push_save_buffer(png_ptr);
  188895. return;
  188896. }
  188897. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188898. }
  188899. #endif
  188900. #if defined(PNG_READ_cHRM_SUPPORTED)
  188901. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188902. {
  188903. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188904. {
  188905. png_push_save_buffer(png_ptr);
  188906. return;
  188907. }
  188908. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188909. }
  188910. #endif
  188911. #if defined(PNG_READ_sRGB_SUPPORTED)
  188912. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188913. {
  188914. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188915. {
  188916. png_push_save_buffer(png_ptr);
  188917. return;
  188918. }
  188919. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188920. }
  188921. #endif
  188922. #if defined(PNG_READ_iCCP_SUPPORTED)
  188923. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188924. {
  188925. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188926. {
  188927. png_push_save_buffer(png_ptr);
  188928. return;
  188929. }
  188930. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188931. }
  188932. #endif
  188933. #if defined(PNG_READ_sPLT_SUPPORTED)
  188934. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188935. {
  188936. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188937. {
  188938. png_push_save_buffer(png_ptr);
  188939. return;
  188940. }
  188941. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188942. }
  188943. #endif
  188944. #if defined(PNG_READ_tRNS_SUPPORTED)
  188945. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188946. {
  188947. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188948. {
  188949. png_push_save_buffer(png_ptr);
  188950. return;
  188951. }
  188952. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188953. }
  188954. #endif
  188955. #if defined(PNG_READ_bKGD_SUPPORTED)
  188956. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188957. {
  188958. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188959. {
  188960. png_push_save_buffer(png_ptr);
  188961. return;
  188962. }
  188963. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188964. }
  188965. #endif
  188966. #if defined(PNG_READ_hIST_SUPPORTED)
  188967. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188968. {
  188969. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188970. {
  188971. png_push_save_buffer(png_ptr);
  188972. return;
  188973. }
  188974. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188975. }
  188976. #endif
  188977. #if defined(PNG_READ_pHYs_SUPPORTED)
  188978. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188979. {
  188980. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188981. {
  188982. png_push_save_buffer(png_ptr);
  188983. return;
  188984. }
  188985. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188986. }
  188987. #endif
  188988. #if defined(PNG_READ_oFFs_SUPPORTED)
  188989. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188990. {
  188991. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188992. {
  188993. png_push_save_buffer(png_ptr);
  188994. return;
  188995. }
  188996. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188997. }
  188998. #endif
  188999. #if defined(PNG_READ_pCAL_SUPPORTED)
  189000. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  189001. {
  189002. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189003. {
  189004. png_push_save_buffer(png_ptr);
  189005. return;
  189006. }
  189007. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  189008. }
  189009. #endif
  189010. #if defined(PNG_READ_sCAL_SUPPORTED)
  189011. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  189012. {
  189013. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189014. {
  189015. png_push_save_buffer(png_ptr);
  189016. return;
  189017. }
  189018. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  189019. }
  189020. #endif
  189021. #if defined(PNG_READ_tIME_SUPPORTED)
  189022. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  189023. {
  189024. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189025. {
  189026. png_push_save_buffer(png_ptr);
  189027. return;
  189028. }
  189029. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  189030. }
  189031. #endif
  189032. #if defined(PNG_READ_tEXt_SUPPORTED)
  189033. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  189034. {
  189035. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189036. {
  189037. png_push_save_buffer(png_ptr);
  189038. return;
  189039. }
  189040. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  189041. }
  189042. #endif
  189043. #if defined(PNG_READ_zTXt_SUPPORTED)
  189044. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  189045. {
  189046. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189047. {
  189048. png_push_save_buffer(png_ptr);
  189049. return;
  189050. }
  189051. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  189052. }
  189053. #endif
  189054. #if defined(PNG_READ_iTXt_SUPPORTED)
  189055. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189056. {
  189057. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189058. {
  189059. png_push_save_buffer(png_ptr);
  189060. return;
  189061. }
  189062. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  189063. }
  189064. #endif
  189065. else
  189066. {
  189067. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189068. {
  189069. png_push_save_buffer(png_ptr);
  189070. return;
  189071. }
  189072. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189073. }
  189074. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189075. }
  189076. void /* PRIVATE */
  189077. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  189078. {
  189079. png_ptr->process_mode = PNG_SKIP_MODE;
  189080. png_ptr->skip_length = skip;
  189081. }
  189082. void /* PRIVATE */
  189083. png_push_crc_finish(png_structp png_ptr)
  189084. {
  189085. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  189086. {
  189087. png_size_t save_size;
  189088. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  189089. save_size = (png_size_t)png_ptr->skip_length;
  189090. else
  189091. save_size = png_ptr->save_buffer_size;
  189092. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189093. png_ptr->skip_length -= save_size;
  189094. png_ptr->buffer_size -= save_size;
  189095. png_ptr->save_buffer_size -= save_size;
  189096. png_ptr->save_buffer_ptr += save_size;
  189097. }
  189098. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  189099. {
  189100. png_size_t save_size;
  189101. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  189102. save_size = (png_size_t)png_ptr->skip_length;
  189103. else
  189104. save_size = png_ptr->current_buffer_size;
  189105. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189106. png_ptr->skip_length -= save_size;
  189107. png_ptr->buffer_size -= save_size;
  189108. png_ptr->current_buffer_size -= save_size;
  189109. png_ptr->current_buffer_ptr += save_size;
  189110. }
  189111. if (!png_ptr->skip_length)
  189112. {
  189113. if (png_ptr->buffer_size < 4)
  189114. {
  189115. png_push_save_buffer(png_ptr);
  189116. return;
  189117. }
  189118. png_crc_finish(png_ptr, 0);
  189119. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189120. }
  189121. }
  189122. void PNGAPI
  189123. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189124. {
  189125. png_bytep ptr;
  189126. if(png_ptr == NULL) return;
  189127. ptr = buffer;
  189128. if (png_ptr->save_buffer_size)
  189129. {
  189130. png_size_t save_size;
  189131. if (length < png_ptr->save_buffer_size)
  189132. save_size = length;
  189133. else
  189134. save_size = png_ptr->save_buffer_size;
  189135. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189136. length -= save_size;
  189137. ptr += save_size;
  189138. png_ptr->buffer_size -= save_size;
  189139. png_ptr->save_buffer_size -= save_size;
  189140. png_ptr->save_buffer_ptr += save_size;
  189141. }
  189142. if (length && png_ptr->current_buffer_size)
  189143. {
  189144. png_size_t save_size;
  189145. if (length < png_ptr->current_buffer_size)
  189146. save_size = length;
  189147. else
  189148. save_size = png_ptr->current_buffer_size;
  189149. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189150. png_ptr->buffer_size -= save_size;
  189151. png_ptr->current_buffer_size -= save_size;
  189152. png_ptr->current_buffer_ptr += save_size;
  189153. }
  189154. }
  189155. void /* PRIVATE */
  189156. png_push_save_buffer(png_structp png_ptr)
  189157. {
  189158. if (png_ptr->save_buffer_size)
  189159. {
  189160. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189161. {
  189162. png_size_t i,istop;
  189163. png_bytep sp;
  189164. png_bytep dp;
  189165. istop = png_ptr->save_buffer_size;
  189166. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189167. i < istop; i++, sp++, dp++)
  189168. {
  189169. *dp = *sp;
  189170. }
  189171. }
  189172. }
  189173. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189174. png_ptr->save_buffer_max)
  189175. {
  189176. png_size_t new_max;
  189177. png_bytep old_buffer;
  189178. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189179. (png_ptr->current_buffer_size + 256))
  189180. {
  189181. png_error(png_ptr, "Potential overflow of save_buffer");
  189182. }
  189183. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189184. old_buffer = png_ptr->save_buffer;
  189185. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189186. (png_uint_32)new_max);
  189187. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189188. png_free(png_ptr, old_buffer);
  189189. png_ptr->save_buffer_max = new_max;
  189190. }
  189191. if (png_ptr->current_buffer_size)
  189192. {
  189193. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189194. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189195. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189196. png_ptr->current_buffer_size = 0;
  189197. }
  189198. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189199. png_ptr->buffer_size = 0;
  189200. }
  189201. void /* PRIVATE */
  189202. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189203. png_size_t buffer_length)
  189204. {
  189205. png_ptr->current_buffer = buffer;
  189206. png_ptr->current_buffer_size = buffer_length;
  189207. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189208. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189209. }
  189210. void /* PRIVATE */
  189211. png_push_read_IDAT(png_structp png_ptr)
  189212. {
  189213. #ifdef PNG_USE_LOCAL_ARRAYS
  189214. PNG_CONST PNG_IDAT;
  189215. #endif
  189216. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189217. {
  189218. png_byte chunk_length[4];
  189219. if (png_ptr->buffer_size < 8)
  189220. {
  189221. png_push_save_buffer(png_ptr);
  189222. return;
  189223. }
  189224. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189225. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189226. png_reset_crc(png_ptr);
  189227. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189228. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189229. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189230. {
  189231. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189232. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189233. png_error(png_ptr, "Not enough compressed data");
  189234. return;
  189235. }
  189236. png_ptr->idat_size = png_ptr->push_length;
  189237. }
  189238. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189239. {
  189240. png_size_t save_size;
  189241. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189242. {
  189243. save_size = (png_size_t)png_ptr->idat_size;
  189244. /* check for overflow */
  189245. if((png_uint_32)save_size != png_ptr->idat_size)
  189246. png_error(png_ptr, "save_size overflowed in pngpread");
  189247. }
  189248. else
  189249. save_size = png_ptr->save_buffer_size;
  189250. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189251. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189252. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189253. png_ptr->idat_size -= save_size;
  189254. png_ptr->buffer_size -= save_size;
  189255. png_ptr->save_buffer_size -= save_size;
  189256. png_ptr->save_buffer_ptr += save_size;
  189257. }
  189258. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189259. {
  189260. png_size_t save_size;
  189261. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189262. {
  189263. save_size = (png_size_t)png_ptr->idat_size;
  189264. /* check for overflow */
  189265. if((png_uint_32)save_size != png_ptr->idat_size)
  189266. png_error(png_ptr, "save_size overflowed in pngpread");
  189267. }
  189268. else
  189269. save_size = png_ptr->current_buffer_size;
  189270. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189271. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189272. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189273. png_ptr->idat_size -= save_size;
  189274. png_ptr->buffer_size -= save_size;
  189275. png_ptr->current_buffer_size -= save_size;
  189276. png_ptr->current_buffer_ptr += save_size;
  189277. }
  189278. if (!png_ptr->idat_size)
  189279. {
  189280. if (png_ptr->buffer_size < 4)
  189281. {
  189282. png_push_save_buffer(png_ptr);
  189283. return;
  189284. }
  189285. png_crc_finish(png_ptr, 0);
  189286. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189287. png_ptr->mode |= PNG_AFTER_IDAT;
  189288. }
  189289. }
  189290. void /* PRIVATE */
  189291. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189292. png_size_t buffer_length)
  189293. {
  189294. int ret;
  189295. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189296. png_error(png_ptr, "Extra compression data");
  189297. png_ptr->zstream.next_in = buffer;
  189298. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189299. for(;;)
  189300. {
  189301. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189302. if (ret != Z_OK)
  189303. {
  189304. if (ret == Z_STREAM_END)
  189305. {
  189306. if (png_ptr->zstream.avail_in)
  189307. png_error(png_ptr, "Extra compressed data");
  189308. if (!(png_ptr->zstream.avail_out))
  189309. {
  189310. png_push_process_row(png_ptr);
  189311. }
  189312. png_ptr->mode |= PNG_AFTER_IDAT;
  189313. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189314. break;
  189315. }
  189316. else if (ret == Z_BUF_ERROR)
  189317. break;
  189318. else
  189319. png_error(png_ptr, "Decompression Error");
  189320. }
  189321. if (!(png_ptr->zstream.avail_out))
  189322. {
  189323. if ((
  189324. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189325. png_ptr->interlaced && png_ptr->pass > 6) ||
  189326. (!png_ptr->interlaced &&
  189327. #endif
  189328. png_ptr->row_number == png_ptr->num_rows))
  189329. {
  189330. if (png_ptr->zstream.avail_in)
  189331. {
  189332. png_warning(png_ptr, "Too much data in IDAT chunks");
  189333. }
  189334. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189335. break;
  189336. }
  189337. png_push_process_row(png_ptr);
  189338. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189339. png_ptr->zstream.next_out = png_ptr->row_buf;
  189340. }
  189341. else
  189342. break;
  189343. }
  189344. }
  189345. void /* PRIVATE */
  189346. png_push_process_row(png_structp png_ptr)
  189347. {
  189348. png_ptr->row_info.color_type = png_ptr->color_type;
  189349. png_ptr->row_info.width = png_ptr->iwidth;
  189350. png_ptr->row_info.channels = png_ptr->channels;
  189351. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189352. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189353. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189354. png_ptr->row_info.width);
  189355. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189356. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189357. (int)(png_ptr->row_buf[0]));
  189358. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189359. png_ptr->rowbytes + 1);
  189360. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189361. png_do_read_transformations(png_ptr);
  189362. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189363. /* blow up interlaced rows to full size */
  189364. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189365. {
  189366. if (png_ptr->pass < 6)
  189367. /* old interface (pre-1.0.9):
  189368. png_do_read_interlace(&(png_ptr->row_info),
  189369. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189370. */
  189371. png_do_read_interlace(png_ptr);
  189372. switch (png_ptr->pass)
  189373. {
  189374. case 0:
  189375. {
  189376. int i;
  189377. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189378. {
  189379. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189380. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189381. }
  189382. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189383. {
  189384. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189385. {
  189386. png_push_have_row(png_ptr, png_bytep_NULL);
  189387. png_read_push_finish_row(png_ptr);
  189388. }
  189389. }
  189390. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189391. {
  189392. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189393. {
  189394. png_push_have_row(png_ptr, png_bytep_NULL);
  189395. png_read_push_finish_row(png_ptr);
  189396. }
  189397. }
  189398. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189399. {
  189400. png_push_have_row(png_ptr, png_bytep_NULL);
  189401. png_read_push_finish_row(png_ptr);
  189402. }
  189403. break;
  189404. }
  189405. case 1:
  189406. {
  189407. int i;
  189408. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189409. {
  189410. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189411. png_read_push_finish_row(png_ptr);
  189412. }
  189413. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189414. {
  189415. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189416. {
  189417. png_push_have_row(png_ptr, png_bytep_NULL);
  189418. png_read_push_finish_row(png_ptr);
  189419. }
  189420. }
  189421. break;
  189422. }
  189423. case 2:
  189424. {
  189425. int i;
  189426. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189427. {
  189428. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189429. png_read_push_finish_row(png_ptr);
  189430. }
  189431. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189432. {
  189433. png_push_have_row(png_ptr, png_bytep_NULL);
  189434. png_read_push_finish_row(png_ptr);
  189435. }
  189436. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189437. {
  189438. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189439. {
  189440. png_push_have_row(png_ptr, png_bytep_NULL);
  189441. png_read_push_finish_row(png_ptr);
  189442. }
  189443. }
  189444. break;
  189445. }
  189446. case 3:
  189447. {
  189448. int i;
  189449. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189450. {
  189451. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189452. png_read_push_finish_row(png_ptr);
  189453. }
  189454. if (png_ptr->pass == 4) /* skip top two generated rows */
  189455. {
  189456. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189457. {
  189458. png_push_have_row(png_ptr, png_bytep_NULL);
  189459. png_read_push_finish_row(png_ptr);
  189460. }
  189461. }
  189462. break;
  189463. }
  189464. case 4:
  189465. {
  189466. int i;
  189467. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189468. {
  189469. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189470. png_read_push_finish_row(png_ptr);
  189471. }
  189472. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189473. {
  189474. png_push_have_row(png_ptr, png_bytep_NULL);
  189475. png_read_push_finish_row(png_ptr);
  189476. }
  189477. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189478. {
  189479. png_push_have_row(png_ptr, png_bytep_NULL);
  189480. png_read_push_finish_row(png_ptr);
  189481. }
  189482. break;
  189483. }
  189484. case 5:
  189485. {
  189486. int i;
  189487. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189488. {
  189489. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189490. png_read_push_finish_row(png_ptr);
  189491. }
  189492. if (png_ptr->pass == 6) /* skip top generated row */
  189493. {
  189494. png_push_have_row(png_ptr, png_bytep_NULL);
  189495. png_read_push_finish_row(png_ptr);
  189496. }
  189497. break;
  189498. }
  189499. case 6:
  189500. {
  189501. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189502. png_read_push_finish_row(png_ptr);
  189503. if (png_ptr->pass != 6)
  189504. break;
  189505. png_push_have_row(png_ptr, png_bytep_NULL);
  189506. png_read_push_finish_row(png_ptr);
  189507. }
  189508. }
  189509. }
  189510. else
  189511. #endif
  189512. {
  189513. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189514. png_read_push_finish_row(png_ptr);
  189515. }
  189516. }
  189517. void /* PRIVATE */
  189518. png_read_push_finish_row(png_structp png_ptr)
  189519. {
  189520. #ifdef PNG_USE_LOCAL_ARRAYS
  189521. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189522. /* start of interlace block */
  189523. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189524. /* offset to next interlace block */
  189525. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189526. /* start of interlace block in the y direction */
  189527. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189528. /* offset to next interlace block in the y direction */
  189529. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189530. /* Height of interlace block. This is not currently used - if you need
  189531. * it, uncomment it here and in png.h
  189532. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189533. */
  189534. #endif
  189535. png_ptr->row_number++;
  189536. if (png_ptr->row_number < png_ptr->num_rows)
  189537. return;
  189538. if (png_ptr->interlaced)
  189539. {
  189540. png_ptr->row_number = 0;
  189541. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189542. png_ptr->rowbytes + 1);
  189543. do
  189544. {
  189545. png_ptr->pass++;
  189546. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189547. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189548. (png_ptr->pass == 5 && png_ptr->width < 2))
  189549. png_ptr->pass++;
  189550. if (png_ptr->pass > 7)
  189551. png_ptr->pass--;
  189552. if (png_ptr->pass >= 7)
  189553. break;
  189554. png_ptr->iwidth = (png_ptr->width +
  189555. png_pass_inc[png_ptr->pass] - 1 -
  189556. png_pass_start[png_ptr->pass]) /
  189557. png_pass_inc[png_ptr->pass];
  189558. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189559. png_ptr->iwidth) + 1;
  189560. if (png_ptr->transformations & PNG_INTERLACE)
  189561. break;
  189562. png_ptr->num_rows = (png_ptr->height +
  189563. png_pass_yinc[png_ptr->pass] - 1 -
  189564. png_pass_ystart[png_ptr->pass]) /
  189565. png_pass_yinc[png_ptr->pass];
  189566. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189567. }
  189568. }
  189569. #if defined(PNG_READ_tEXt_SUPPORTED)
  189570. void /* PRIVATE */
  189571. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189572. length)
  189573. {
  189574. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189575. {
  189576. png_error(png_ptr, "Out of place tEXt");
  189577. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189578. }
  189579. #ifdef PNG_MAX_MALLOC_64K
  189580. png_ptr->skip_length = 0; /* This may not be necessary */
  189581. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189582. {
  189583. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189584. png_ptr->skip_length = length - (png_uint_32)65535L;
  189585. length = (png_uint_32)65535L;
  189586. }
  189587. #endif
  189588. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189589. (png_uint_32)(length+1));
  189590. png_ptr->current_text[length] = '\0';
  189591. png_ptr->current_text_ptr = png_ptr->current_text;
  189592. png_ptr->current_text_size = (png_size_t)length;
  189593. png_ptr->current_text_left = (png_size_t)length;
  189594. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189595. }
  189596. void /* PRIVATE */
  189597. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189598. {
  189599. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189600. {
  189601. png_size_t text_size;
  189602. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189603. text_size = png_ptr->buffer_size;
  189604. else
  189605. text_size = png_ptr->current_text_left;
  189606. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189607. png_ptr->current_text_left -= text_size;
  189608. png_ptr->current_text_ptr += text_size;
  189609. }
  189610. if (!(png_ptr->current_text_left))
  189611. {
  189612. png_textp text_ptr;
  189613. png_charp text;
  189614. png_charp key;
  189615. int ret;
  189616. if (png_ptr->buffer_size < 4)
  189617. {
  189618. png_push_save_buffer(png_ptr);
  189619. return;
  189620. }
  189621. png_push_crc_finish(png_ptr);
  189622. #if defined(PNG_MAX_MALLOC_64K)
  189623. if (png_ptr->skip_length)
  189624. return;
  189625. #endif
  189626. key = png_ptr->current_text;
  189627. for (text = key; *text; text++)
  189628. /* empty loop */ ;
  189629. if (text < key + png_ptr->current_text_size)
  189630. text++;
  189631. text_ptr = (png_textp)png_malloc(png_ptr,
  189632. (png_uint_32)png_sizeof(png_text));
  189633. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189634. text_ptr->key = key;
  189635. #ifdef PNG_iTXt_SUPPORTED
  189636. text_ptr->lang = NULL;
  189637. text_ptr->lang_key = NULL;
  189638. #endif
  189639. text_ptr->text = text;
  189640. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189641. png_free(png_ptr, key);
  189642. png_free(png_ptr, text_ptr);
  189643. png_ptr->current_text = NULL;
  189644. if (ret)
  189645. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189646. }
  189647. }
  189648. #endif
  189649. #if defined(PNG_READ_zTXt_SUPPORTED)
  189650. void /* PRIVATE */
  189651. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189652. length)
  189653. {
  189654. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189655. {
  189656. png_error(png_ptr, "Out of place zTXt");
  189657. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189658. }
  189659. #ifdef PNG_MAX_MALLOC_64K
  189660. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189661. * to be able to store the uncompressed data. Actually, the threshold
  189662. * is probably around 32K, but it isn't as definite as 64K is.
  189663. */
  189664. if (length > (png_uint_32)65535L)
  189665. {
  189666. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189667. png_push_crc_skip(png_ptr, length);
  189668. return;
  189669. }
  189670. #endif
  189671. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189672. (png_uint_32)(length+1));
  189673. png_ptr->current_text[length] = '\0';
  189674. png_ptr->current_text_ptr = png_ptr->current_text;
  189675. png_ptr->current_text_size = (png_size_t)length;
  189676. png_ptr->current_text_left = (png_size_t)length;
  189677. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189678. }
  189679. void /* PRIVATE */
  189680. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189681. {
  189682. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189683. {
  189684. png_size_t text_size;
  189685. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189686. text_size = png_ptr->buffer_size;
  189687. else
  189688. text_size = png_ptr->current_text_left;
  189689. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189690. png_ptr->current_text_left -= text_size;
  189691. png_ptr->current_text_ptr += text_size;
  189692. }
  189693. if (!(png_ptr->current_text_left))
  189694. {
  189695. png_textp text_ptr;
  189696. png_charp text;
  189697. png_charp key;
  189698. int ret;
  189699. png_size_t text_size, key_size;
  189700. if (png_ptr->buffer_size < 4)
  189701. {
  189702. png_push_save_buffer(png_ptr);
  189703. return;
  189704. }
  189705. png_push_crc_finish(png_ptr);
  189706. key = png_ptr->current_text;
  189707. for (text = key; *text; text++)
  189708. /* empty loop */ ;
  189709. /* zTXt can't have zero text */
  189710. if (text >= key + png_ptr->current_text_size)
  189711. {
  189712. png_ptr->current_text = NULL;
  189713. png_free(png_ptr, key);
  189714. return;
  189715. }
  189716. text++;
  189717. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189718. {
  189719. png_ptr->current_text = NULL;
  189720. png_free(png_ptr, key);
  189721. return;
  189722. }
  189723. text++;
  189724. png_ptr->zstream.next_in = (png_bytep )text;
  189725. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189726. (text - key));
  189727. png_ptr->zstream.next_out = png_ptr->zbuf;
  189728. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189729. key_size = text - key;
  189730. text_size = 0;
  189731. text = NULL;
  189732. ret = Z_STREAM_END;
  189733. while (png_ptr->zstream.avail_in)
  189734. {
  189735. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189736. if (ret != Z_OK && ret != Z_STREAM_END)
  189737. {
  189738. inflateReset(&png_ptr->zstream);
  189739. png_ptr->zstream.avail_in = 0;
  189740. png_ptr->current_text = NULL;
  189741. png_free(png_ptr, key);
  189742. png_free(png_ptr, text);
  189743. return;
  189744. }
  189745. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189746. {
  189747. if (text == NULL)
  189748. {
  189749. text = (png_charp)png_malloc(png_ptr,
  189750. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189751. + key_size + 1));
  189752. png_memcpy(text + key_size, png_ptr->zbuf,
  189753. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189754. png_memcpy(text, key, key_size);
  189755. text_size = key_size + png_ptr->zbuf_size -
  189756. png_ptr->zstream.avail_out;
  189757. *(text + text_size) = '\0';
  189758. }
  189759. else
  189760. {
  189761. png_charp tmp;
  189762. tmp = text;
  189763. text = (png_charp)png_malloc(png_ptr, text_size +
  189764. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189765. + 1));
  189766. png_memcpy(text, tmp, text_size);
  189767. png_free(png_ptr, tmp);
  189768. png_memcpy(text + text_size, png_ptr->zbuf,
  189769. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189770. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189771. *(text + text_size) = '\0';
  189772. }
  189773. if (ret != Z_STREAM_END)
  189774. {
  189775. png_ptr->zstream.next_out = png_ptr->zbuf;
  189776. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189777. }
  189778. }
  189779. else
  189780. {
  189781. break;
  189782. }
  189783. if (ret == Z_STREAM_END)
  189784. break;
  189785. }
  189786. inflateReset(&png_ptr->zstream);
  189787. png_ptr->zstream.avail_in = 0;
  189788. if (ret != Z_STREAM_END)
  189789. {
  189790. png_ptr->current_text = NULL;
  189791. png_free(png_ptr, key);
  189792. png_free(png_ptr, text);
  189793. return;
  189794. }
  189795. png_ptr->current_text = NULL;
  189796. png_free(png_ptr, key);
  189797. key = text;
  189798. text += key_size;
  189799. text_ptr = (png_textp)png_malloc(png_ptr,
  189800. (png_uint_32)png_sizeof(png_text));
  189801. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189802. text_ptr->key = key;
  189803. #ifdef PNG_iTXt_SUPPORTED
  189804. text_ptr->lang = NULL;
  189805. text_ptr->lang_key = NULL;
  189806. #endif
  189807. text_ptr->text = text;
  189808. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189809. png_free(png_ptr, key);
  189810. png_free(png_ptr, text_ptr);
  189811. if (ret)
  189812. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189813. }
  189814. }
  189815. #endif
  189816. #if defined(PNG_READ_iTXt_SUPPORTED)
  189817. void /* PRIVATE */
  189818. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189819. length)
  189820. {
  189821. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189822. {
  189823. png_error(png_ptr, "Out of place iTXt");
  189824. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189825. }
  189826. #ifdef PNG_MAX_MALLOC_64K
  189827. png_ptr->skip_length = 0; /* This may not be necessary */
  189828. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189829. {
  189830. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189831. png_ptr->skip_length = length - (png_uint_32)65535L;
  189832. length = (png_uint_32)65535L;
  189833. }
  189834. #endif
  189835. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189836. (png_uint_32)(length+1));
  189837. png_ptr->current_text[length] = '\0';
  189838. png_ptr->current_text_ptr = png_ptr->current_text;
  189839. png_ptr->current_text_size = (png_size_t)length;
  189840. png_ptr->current_text_left = (png_size_t)length;
  189841. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189842. }
  189843. void /* PRIVATE */
  189844. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189845. {
  189846. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189847. {
  189848. png_size_t text_size;
  189849. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189850. text_size = png_ptr->buffer_size;
  189851. else
  189852. text_size = png_ptr->current_text_left;
  189853. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189854. png_ptr->current_text_left -= text_size;
  189855. png_ptr->current_text_ptr += text_size;
  189856. }
  189857. if (!(png_ptr->current_text_left))
  189858. {
  189859. png_textp text_ptr;
  189860. png_charp key;
  189861. int comp_flag;
  189862. png_charp lang;
  189863. png_charp lang_key;
  189864. png_charp text;
  189865. int ret;
  189866. if (png_ptr->buffer_size < 4)
  189867. {
  189868. png_push_save_buffer(png_ptr);
  189869. return;
  189870. }
  189871. png_push_crc_finish(png_ptr);
  189872. #if defined(PNG_MAX_MALLOC_64K)
  189873. if (png_ptr->skip_length)
  189874. return;
  189875. #endif
  189876. key = png_ptr->current_text;
  189877. for (lang = key; *lang; lang++)
  189878. /* empty loop */ ;
  189879. if (lang < key + png_ptr->current_text_size - 3)
  189880. lang++;
  189881. comp_flag = *lang++;
  189882. lang++; /* skip comp_type, always zero */
  189883. for (lang_key = lang; *lang_key; lang_key++)
  189884. /* empty loop */ ;
  189885. lang_key++; /* skip NUL separator */
  189886. text=lang_key;
  189887. if (lang_key < key + png_ptr->current_text_size - 1)
  189888. {
  189889. for (; *text; text++)
  189890. /* empty loop */ ;
  189891. }
  189892. if (text < key + png_ptr->current_text_size)
  189893. text++;
  189894. text_ptr = (png_textp)png_malloc(png_ptr,
  189895. (png_uint_32)png_sizeof(png_text));
  189896. text_ptr->compression = comp_flag + 2;
  189897. text_ptr->key = key;
  189898. text_ptr->lang = lang;
  189899. text_ptr->lang_key = lang_key;
  189900. text_ptr->text = text;
  189901. text_ptr->text_length = 0;
  189902. text_ptr->itxt_length = png_strlen(text);
  189903. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189904. png_ptr->current_text = NULL;
  189905. png_free(png_ptr, text_ptr);
  189906. if (ret)
  189907. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189908. }
  189909. }
  189910. #endif
  189911. /* This function is called when we haven't found a handler for this
  189912. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189913. * name or a critical chunk), the chunk is (currently) silently ignored.
  189914. */
  189915. void /* PRIVATE */
  189916. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189917. length)
  189918. {
  189919. png_uint_32 skip=0;
  189920. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189921. if (!(png_ptr->chunk_name[0] & 0x20))
  189922. {
  189923. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189924. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189925. PNG_HANDLE_CHUNK_ALWAYS
  189926. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189927. && png_ptr->read_user_chunk_fn == NULL
  189928. #endif
  189929. )
  189930. #endif
  189931. png_chunk_error(png_ptr, "unknown critical chunk");
  189932. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189933. }
  189934. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189935. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189936. {
  189937. #ifdef PNG_MAX_MALLOC_64K
  189938. if (length > (png_uint_32)65535L)
  189939. {
  189940. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189941. skip = length - (png_uint_32)65535L;
  189942. length = (png_uint_32)65535L;
  189943. }
  189944. #endif
  189945. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189946. (png_charp)png_ptr->chunk_name, 5);
  189947. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189948. png_ptr->unknown_chunk.size = (png_size_t)length;
  189949. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189950. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189951. if(png_ptr->read_user_chunk_fn != NULL)
  189952. {
  189953. /* callback to user unknown chunk handler */
  189954. int ret;
  189955. ret = (*(png_ptr->read_user_chunk_fn))
  189956. (png_ptr, &png_ptr->unknown_chunk);
  189957. if (ret < 0)
  189958. png_chunk_error(png_ptr, "error in user chunk");
  189959. if (ret == 0)
  189960. {
  189961. if (!(png_ptr->chunk_name[0] & 0x20))
  189962. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189963. PNG_HANDLE_CHUNK_ALWAYS)
  189964. png_chunk_error(png_ptr, "unknown critical chunk");
  189965. png_set_unknown_chunks(png_ptr, info_ptr,
  189966. &png_ptr->unknown_chunk, 1);
  189967. }
  189968. }
  189969. #else
  189970. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189971. #endif
  189972. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189973. png_ptr->unknown_chunk.data = NULL;
  189974. }
  189975. else
  189976. #endif
  189977. skip=length;
  189978. png_push_crc_skip(png_ptr, skip);
  189979. }
  189980. void /* PRIVATE */
  189981. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189982. {
  189983. if (png_ptr->info_fn != NULL)
  189984. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189985. }
  189986. void /* PRIVATE */
  189987. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189988. {
  189989. if (png_ptr->end_fn != NULL)
  189990. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189991. }
  189992. void /* PRIVATE */
  189993. png_push_have_row(png_structp png_ptr, png_bytep row)
  189994. {
  189995. if (png_ptr->row_fn != NULL)
  189996. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189997. (int)png_ptr->pass);
  189998. }
  189999. void PNGAPI
  190000. png_progressive_combine_row (png_structp png_ptr,
  190001. png_bytep old_row, png_bytep new_row)
  190002. {
  190003. #ifdef PNG_USE_LOCAL_ARRAYS
  190004. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  190005. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  190006. #endif
  190007. if(png_ptr == NULL) return;
  190008. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  190009. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  190010. }
  190011. void PNGAPI
  190012. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  190013. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  190014. png_progressive_end_ptr end_fn)
  190015. {
  190016. if(png_ptr == NULL) return;
  190017. png_ptr->info_fn = info_fn;
  190018. png_ptr->row_fn = row_fn;
  190019. png_ptr->end_fn = end_fn;
  190020. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  190021. }
  190022. png_voidp PNGAPI
  190023. png_get_progressive_ptr(png_structp png_ptr)
  190024. {
  190025. if(png_ptr == NULL) return (NULL);
  190026. return png_ptr->io_ptr;
  190027. }
  190028. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  190029. /*** End of inlined file: pngpread.c ***/
  190030. /*** Start of inlined file: pngrio.c ***/
  190031. /* pngrio.c - functions for data input
  190032. *
  190033. * Last changed in libpng 1.2.13 November 13, 2006
  190034. * For conditions of distribution and use, see copyright notice in png.h
  190035. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  190036. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190037. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190038. *
  190039. * This file provides a location for all input. Users who need
  190040. * special handling are expected to write a function that has the same
  190041. * arguments as this and performs a similar function, but that possibly
  190042. * has a different input method. Note that you shouldn't change this
  190043. * function, but rather write a replacement function and then make
  190044. * libpng use it at run time with png_set_read_fn(...).
  190045. */
  190046. #define PNG_INTERNAL
  190047. #if defined(PNG_READ_SUPPORTED)
  190048. /* Read the data from whatever input you are using. The default routine
  190049. reads from a file pointer. Note that this routine sometimes gets called
  190050. with very small lengths, so you should implement some kind of simple
  190051. buffering if you are using unbuffered reads. This should never be asked
  190052. to read more then 64K on a 16 bit machine. */
  190053. void /* PRIVATE */
  190054. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190055. {
  190056. png_debug1(4,"reading %d bytes\n", (int)length);
  190057. if (png_ptr->read_data_fn != NULL)
  190058. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  190059. else
  190060. png_error(png_ptr, "Call to NULL read function");
  190061. }
  190062. #if !defined(PNG_NO_STDIO)
  190063. /* This is the function that does the actual reading of data. If you are
  190064. not reading from a standard C stream, you should create a replacement
  190065. read_data function and use it at run time with png_set_read_fn(), rather
  190066. than changing the library. */
  190067. #ifndef USE_FAR_KEYWORD
  190068. void PNGAPI
  190069. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190070. {
  190071. png_size_t check;
  190072. if(png_ptr == NULL) return;
  190073. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  190074. * instead of an int, which is what fread() actually returns.
  190075. */
  190076. #if defined(_WIN32_WCE)
  190077. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190078. check = 0;
  190079. #else
  190080. check = (png_size_t)fread(data, (png_size_t)1, length,
  190081. (png_FILE_p)png_ptr->io_ptr);
  190082. #endif
  190083. if (check != length)
  190084. png_error(png_ptr, "Read Error");
  190085. }
  190086. #else
  190087. /* this is the model-independent version. Since the standard I/O library
  190088. can't handle far buffers in the medium and small models, we have to copy
  190089. the data.
  190090. */
  190091. #define NEAR_BUF_SIZE 1024
  190092. #define MIN(a,b) (a <= b ? a : b)
  190093. static void PNGAPI
  190094. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190095. {
  190096. int check;
  190097. png_byte *n_data;
  190098. png_FILE_p io_ptr;
  190099. if(png_ptr == NULL) return;
  190100. /* Check if data really is near. If so, use usual code. */
  190101. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  190102. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  190103. if ((png_bytep)n_data == data)
  190104. {
  190105. #if defined(_WIN32_WCE)
  190106. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190107. check = 0;
  190108. #else
  190109. check = fread(n_data, 1, length, io_ptr);
  190110. #endif
  190111. }
  190112. else
  190113. {
  190114. png_byte buf[NEAR_BUF_SIZE];
  190115. png_size_t read, remaining, err;
  190116. check = 0;
  190117. remaining = length;
  190118. do
  190119. {
  190120. read = MIN(NEAR_BUF_SIZE, remaining);
  190121. #if defined(_WIN32_WCE)
  190122. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190123. err = 0;
  190124. #else
  190125. err = fread(buf, (png_size_t)1, read, io_ptr);
  190126. #endif
  190127. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190128. if(err != read)
  190129. break;
  190130. else
  190131. check += err;
  190132. data += read;
  190133. remaining -= read;
  190134. }
  190135. while (remaining != 0);
  190136. }
  190137. if ((png_uint_32)check != (png_uint_32)length)
  190138. png_error(png_ptr, "read Error");
  190139. }
  190140. #endif
  190141. #endif
  190142. /* This function allows the application to supply a new input function
  190143. for libpng if standard C streams aren't being used.
  190144. This function takes as its arguments:
  190145. png_ptr - pointer to a png input data structure
  190146. io_ptr - pointer to user supplied structure containing info about
  190147. the input functions. May be NULL.
  190148. read_data_fn - pointer to a new input function that takes as its
  190149. arguments a pointer to a png_struct, a pointer to
  190150. a location where input data can be stored, and a 32-bit
  190151. unsigned int that is the number of bytes to be read.
  190152. To exit and output any fatal error messages the new write
  190153. function should call png_error(png_ptr, "Error msg"). */
  190154. void PNGAPI
  190155. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190156. png_rw_ptr read_data_fn)
  190157. {
  190158. if(png_ptr == NULL) return;
  190159. png_ptr->io_ptr = io_ptr;
  190160. #if !defined(PNG_NO_STDIO)
  190161. if (read_data_fn != NULL)
  190162. png_ptr->read_data_fn = read_data_fn;
  190163. else
  190164. png_ptr->read_data_fn = png_default_read_data;
  190165. #else
  190166. png_ptr->read_data_fn = read_data_fn;
  190167. #endif
  190168. /* It is an error to write to a read device */
  190169. if (png_ptr->write_data_fn != NULL)
  190170. {
  190171. png_ptr->write_data_fn = NULL;
  190172. png_warning(png_ptr,
  190173. "It's an error to set both read_data_fn and write_data_fn in the ");
  190174. png_warning(png_ptr,
  190175. "same structure. Resetting write_data_fn to NULL.");
  190176. }
  190177. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190178. png_ptr->output_flush_fn = NULL;
  190179. #endif
  190180. }
  190181. #endif /* PNG_READ_SUPPORTED */
  190182. /*** End of inlined file: pngrio.c ***/
  190183. /*** Start of inlined file: pngrtran.c ***/
  190184. /* pngrtran.c - transforms the data in a row for PNG readers
  190185. *
  190186. * Last changed in libpng 1.2.21 [October 4, 2007]
  190187. * For conditions of distribution and use, see copyright notice in png.h
  190188. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190189. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190190. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190191. *
  190192. * This file contains functions optionally called by an application
  190193. * in order to tell libpng how to handle data when reading a PNG.
  190194. * Transformations that are used in both reading and writing are
  190195. * in pngtrans.c.
  190196. */
  190197. #define PNG_INTERNAL
  190198. #if defined(PNG_READ_SUPPORTED)
  190199. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190200. void PNGAPI
  190201. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190202. {
  190203. png_debug(1, "in png_set_crc_action\n");
  190204. /* Tell libpng how we react to CRC errors in critical chunks */
  190205. if(png_ptr == NULL) return;
  190206. switch (crit_action)
  190207. {
  190208. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190209. break;
  190210. case PNG_CRC_WARN_USE: /* warn/use data */
  190211. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190212. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190213. break;
  190214. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190215. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190216. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190217. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190218. break;
  190219. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190220. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190221. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190222. case PNG_CRC_DEFAULT:
  190223. default:
  190224. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190225. break;
  190226. }
  190227. switch (ancil_action)
  190228. {
  190229. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190230. break;
  190231. case PNG_CRC_WARN_USE: /* warn/use data */
  190232. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190233. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190234. break;
  190235. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190236. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190237. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190238. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190239. break;
  190240. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190241. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190242. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190243. break;
  190244. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190245. case PNG_CRC_DEFAULT:
  190246. default:
  190247. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190248. break;
  190249. }
  190250. }
  190251. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190252. defined(PNG_FLOATING_POINT_SUPPORTED)
  190253. /* handle alpha and tRNS via a background color */
  190254. void PNGAPI
  190255. png_set_background(png_structp png_ptr,
  190256. png_color_16p background_color, int background_gamma_code,
  190257. int need_expand, double background_gamma)
  190258. {
  190259. png_debug(1, "in png_set_background\n");
  190260. if(png_ptr == NULL) return;
  190261. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190262. {
  190263. png_warning(png_ptr, "Application must supply a known background gamma");
  190264. return;
  190265. }
  190266. png_ptr->transformations |= PNG_BACKGROUND;
  190267. png_memcpy(&(png_ptr->background), background_color,
  190268. png_sizeof(png_color_16));
  190269. png_ptr->background_gamma = (float)background_gamma;
  190270. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190271. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190272. }
  190273. #endif
  190274. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190275. /* strip 16 bit depth files to 8 bit depth */
  190276. void PNGAPI
  190277. png_set_strip_16(png_structp png_ptr)
  190278. {
  190279. png_debug(1, "in png_set_strip_16\n");
  190280. if(png_ptr == NULL) return;
  190281. png_ptr->transformations |= PNG_16_TO_8;
  190282. }
  190283. #endif
  190284. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190285. void PNGAPI
  190286. png_set_strip_alpha(png_structp png_ptr)
  190287. {
  190288. png_debug(1, "in png_set_strip_alpha\n");
  190289. if(png_ptr == NULL) return;
  190290. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190291. }
  190292. #endif
  190293. #if defined(PNG_READ_DITHER_SUPPORTED)
  190294. /* Dither file to 8 bit. Supply a palette, the current number
  190295. * of elements in the palette, the maximum number of elements
  190296. * allowed, and a histogram if possible. If the current number
  190297. * of colors is greater then the maximum number, the palette will be
  190298. * modified to fit in the maximum number. "full_dither" indicates
  190299. * whether we need a dithering cube set up for RGB images, or if we
  190300. * simply are reducing the number of colors in a paletted image.
  190301. */
  190302. typedef struct png_dsort_struct
  190303. {
  190304. struct png_dsort_struct FAR * next;
  190305. png_byte left;
  190306. png_byte right;
  190307. } png_dsort;
  190308. typedef png_dsort FAR * png_dsortp;
  190309. typedef png_dsort FAR * FAR * png_dsortpp;
  190310. void PNGAPI
  190311. png_set_dither(png_structp png_ptr, png_colorp palette,
  190312. int num_palette, int maximum_colors, png_uint_16p histogram,
  190313. int full_dither)
  190314. {
  190315. png_debug(1, "in png_set_dither\n");
  190316. if(png_ptr == NULL) return;
  190317. png_ptr->transformations |= PNG_DITHER;
  190318. if (!full_dither)
  190319. {
  190320. int i;
  190321. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190322. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190323. for (i = 0; i < num_palette; i++)
  190324. png_ptr->dither_index[i] = (png_byte)i;
  190325. }
  190326. if (num_palette > maximum_colors)
  190327. {
  190328. if (histogram != NULL)
  190329. {
  190330. /* This is easy enough, just throw out the least used colors.
  190331. Perhaps not the best solution, but good enough. */
  190332. int i;
  190333. /* initialize an array to sort colors */
  190334. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190335. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190336. /* initialize the dither_sort array */
  190337. for (i = 0; i < num_palette; i++)
  190338. png_ptr->dither_sort[i] = (png_byte)i;
  190339. /* Find the least used palette entries by starting a
  190340. bubble sort, and running it until we have sorted
  190341. out enough colors. Note that we don't care about
  190342. sorting all the colors, just finding which are
  190343. least used. */
  190344. for (i = num_palette - 1; i >= maximum_colors; i--)
  190345. {
  190346. int done; /* to stop early if the list is pre-sorted */
  190347. int j;
  190348. done = 1;
  190349. for (j = 0; j < i; j++)
  190350. {
  190351. if (histogram[png_ptr->dither_sort[j]]
  190352. < histogram[png_ptr->dither_sort[j + 1]])
  190353. {
  190354. png_byte t;
  190355. t = png_ptr->dither_sort[j];
  190356. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190357. png_ptr->dither_sort[j + 1] = t;
  190358. done = 0;
  190359. }
  190360. }
  190361. if (done)
  190362. break;
  190363. }
  190364. /* swap the palette around, and set up a table, if necessary */
  190365. if (full_dither)
  190366. {
  190367. int j = num_palette;
  190368. /* put all the useful colors within the max, but don't
  190369. move the others */
  190370. for (i = 0; i < maximum_colors; i++)
  190371. {
  190372. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190373. {
  190374. do
  190375. j--;
  190376. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190377. palette[i] = palette[j];
  190378. }
  190379. }
  190380. }
  190381. else
  190382. {
  190383. int j = num_palette;
  190384. /* move all the used colors inside the max limit, and
  190385. develop a translation table */
  190386. for (i = 0; i < maximum_colors; i++)
  190387. {
  190388. /* only move the colors we need to */
  190389. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190390. {
  190391. png_color tmp_color;
  190392. do
  190393. j--;
  190394. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190395. tmp_color = palette[j];
  190396. palette[j] = palette[i];
  190397. palette[i] = tmp_color;
  190398. /* indicate where the color went */
  190399. png_ptr->dither_index[j] = (png_byte)i;
  190400. png_ptr->dither_index[i] = (png_byte)j;
  190401. }
  190402. }
  190403. /* find closest color for those colors we are not using */
  190404. for (i = 0; i < num_palette; i++)
  190405. {
  190406. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190407. {
  190408. int min_d, k, min_k, d_index;
  190409. /* find the closest color to one we threw out */
  190410. d_index = png_ptr->dither_index[i];
  190411. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190412. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190413. {
  190414. int d;
  190415. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190416. if (d < min_d)
  190417. {
  190418. min_d = d;
  190419. min_k = k;
  190420. }
  190421. }
  190422. /* point to closest color */
  190423. png_ptr->dither_index[i] = (png_byte)min_k;
  190424. }
  190425. }
  190426. }
  190427. png_free(png_ptr, png_ptr->dither_sort);
  190428. png_ptr->dither_sort=NULL;
  190429. }
  190430. else
  190431. {
  190432. /* This is much harder to do simply (and quickly). Perhaps
  190433. we need to go through a median cut routine, but those
  190434. don't always behave themselves with only a few colors
  190435. as input. So we will just find the closest two colors,
  190436. and throw out one of them (chosen somewhat randomly).
  190437. [We don't understand this at all, so if someone wants to
  190438. work on improving it, be our guest - AED, GRP]
  190439. */
  190440. int i;
  190441. int max_d;
  190442. int num_new_palette;
  190443. png_dsortp t;
  190444. png_dsortpp hash;
  190445. t=NULL;
  190446. /* initialize palette index arrays */
  190447. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190448. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190449. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190450. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190451. /* initialize the sort array */
  190452. for (i = 0; i < num_palette; i++)
  190453. {
  190454. png_ptr->index_to_palette[i] = (png_byte)i;
  190455. png_ptr->palette_to_index[i] = (png_byte)i;
  190456. }
  190457. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190458. png_sizeof (png_dsortp)));
  190459. for (i = 0; i < 769; i++)
  190460. hash[i] = NULL;
  190461. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190462. num_new_palette = num_palette;
  190463. /* initial wild guess at how far apart the farthest pixel
  190464. pair we will be eliminating will be. Larger
  190465. numbers mean more areas will be allocated, Smaller
  190466. numbers run the risk of not saving enough data, and
  190467. having to do this all over again.
  190468. I have not done extensive checking on this number.
  190469. */
  190470. max_d = 96;
  190471. while (num_new_palette > maximum_colors)
  190472. {
  190473. for (i = 0; i < num_new_palette - 1; i++)
  190474. {
  190475. int j;
  190476. for (j = i + 1; j < num_new_palette; j++)
  190477. {
  190478. int d;
  190479. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190480. if (d <= max_d)
  190481. {
  190482. t = (png_dsortp)png_malloc_warn(png_ptr,
  190483. (png_uint_32)(png_sizeof(png_dsort)));
  190484. if (t == NULL)
  190485. break;
  190486. t->next = hash[d];
  190487. t->left = (png_byte)i;
  190488. t->right = (png_byte)j;
  190489. hash[d] = t;
  190490. }
  190491. }
  190492. if (t == NULL)
  190493. break;
  190494. }
  190495. if (t != NULL)
  190496. for (i = 0; i <= max_d; i++)
  190497. {
  190498. if (hash[i] != NULL)
  190499. {
  190500. png_dsortp p;
  190501. for (p = hash[i]; p; p = p->next)
  190502. {
  190503. if ((int)png_ptr->index_to_palette[p->left]
  190504. < num_new_palette &&
  190505. (int)png_ptr->index_to_palette[p->right]
  190506. < num_new_palette)
  190507. {
  190508. int j, next_j;
  190509. if (num_new_palette & 0x01)
  190510. {
  190511. j = p->left;
  190512. next_j = p->right;
  190513. }
  190514. else
  190515. {
  190516. j = p->right;
  190517. next_j = p->left;
  190518. }
  190519. num_new_palette--;
  190520. palette[png_ptr->index_to_palette[j]]
  190521. = palette[num_new_palette];
  190522. if (!full_dither)
  190523. {
  190524. int k;
  190525. for (k = 0; k < num_palette; k++)
  190526. {
  190527. if (png_ptr->dither_index[k] ==
  190528. png_ptr->index_to_palette[j])
  190529. png_ptr->dither_index[k] =
  190530. png_ptr->index_to_palette[next_j];
  190531. if ((int)png_ptr->dither_index[k] ==
  190532. num_new_palette)
  190533. png_ptr->dither_index[k] =
  190534. png_ptr->index_to_palette[j];
  190535. }
  190536. }
  190537. png_ptr->index_to_palette[png_ptr->palette_to_index
  190538. [num_new_palette]] = png_ptr->index_to_palette[j];
  190539. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190540. = png_ptr->palette_to_index[num_new_palette];
  190541. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190542. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190543. }
  190544. if (num_new_palette <= maximum_colors)
  190545. break;
  190546. }
  190547. if (num_new_palette <= maximum_colors)
  190548. break;
  190549. }
  190550. }
  190551. for (i = 0; i < 769; i++)
  190552. {
  190553. if (hash[i] != NULL)
  190554. {
  190555. png_dsortp p = hash[i];
  190556. while (p)
  190557. {
  190558. t = p->next;
  190559. png_free(png_ptr, p);
  190560. p = t;
  190561. }
  190562. }
  190563. hash[i] = 0;
  190564. }
  190565. max_d += 96;
  190566. }
  190567. png_free(png_ptr, hash);
  190568. png_free(png_ptr, png_ptr->palette_to_index);
  190569. png_free(png_ptr, png_ptr->index_to_palette);
  190570. png_ptr->palette_to_index=NULL;
  190571. png_ptr->index_to_palette=NULL;
  190572. }
  190573. num_palette = maximum_colors;
  190574. }
  190575. if (png_ptr->palette == NULL)
  190576. {
  190577. png_ptr->palette = palette;
  190578. }
  190579. png_ptr->num_palette = (png_uint_16)num_palette;
  190580. if (full_dither)
  190581. {
  190582. int i;
  190583. png_bytep distance;
  190584. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190585. PNG_DITHER_BLUE_BITS;
  190586. int num_red = (1 << PNG_DITHER_RED_BITS);
  190587. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190588. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190589. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190590. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190591. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190592. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190593. png_sizeof (png_byte));
  190594. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190595. png_sizeof(png_byte)));
  190596. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190597. for (i = 0; i < num_palette; i++)
  190598. {
  190599. int ir, ig, ib;
  190600. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190601. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190602. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190603. for (ir = 0; ir < num_red; ir++)
  190604. {
  190605. /* int dr = abs(ir - r); */
  190606. int dr = ((ir > r) ? ir - r : r - ir);
  190607. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190608. for (ig = 0; ig < num_green; ig++)
  190609. {
  190610. /* int dg = abs(ig - g); */
  190611. int dg = ((ig > g) ? ig - g : g - ig);
  190612. int dt = dr + dg;
  190613. int dm = ((dr > dg) ? dr : dg);
  190614. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190615. for (ib = 0; ib < num_blue; ib++)
  190616. {
  190617. int d_index = index_g | ib;
  190618. /* int db = abs(ib - b); */
  190619. int db = ((ib > b) ? ib - b : b - ib);
  190620. int dmax = ((dm > db) ? dm : db);
  190621. int d = dmax + dt + db;
  190622. if (d < (int)distance[d_index])
  190623. {
  190624. distance[d_index] = (png_byte)d;
  190625. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190626. }
  190627. }
  190628. }
  190629. }
  190630. }
  190631. png_free(png_ptr, distance);
  190632. }
  190633. }
  190634. #endif
  190635. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190636. /* Transform the image from the file_gamma to the screen_gamma. We
  190637. * only do transformations on images where the file_gamma and screen_gamma
  190638. * are not close reciprocals, otherwise it slows things down slightly, and
  190639. * also needlessly introduces small errors.
  190640. *
  190641. * We will turn off gamma transformation later if no semitransparent entries
  190642. * are present in the tRNS array for palette images. We can't do it here
  190643. * because we don't necessarily have the tRNS chunk yet.
  190644. */
  190645. void PNGAPI
  190646. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190647. {
  190648. png_debug(1, "in png_set_gamma\n");
  190649. if(png_ptr == NULL) return;
  190650. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190651. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190652. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190653. png_ptr->transformations |= PNG_GAMMA;
  190654. png_ptr->gamma = (float)file_gamma;
  190655. png_ptr->screen_gamma = (float)scrn_gamma;
  190656. }
  190657. #endif
  190658. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190659. /* Expand paletted images to RGB, expand grayscale images of
  190660. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190661. * to alpha channels.
  190662. */
  190663. void PNGAPI
  190664. png_set_expand(png_structp png_ptr)
  190665. {
  190666. png_debug(1, "in png_set_expand\n");
  190667. if(png_ptr == NULL) return;
  190668. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190669. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190670. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190671. #endif
  190672. }
  190673. /* GRR 19990627: the following three functions currently are identical
  190674. * to png_set_expand(). However, it is entirely reasonable that someone
  190675. * might wish to expand an indexed image to RGB but *not* expand a single,
  190676. * fully transparent palette entry to a full alpha channel--perhaps instead
  190677. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190678. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190679. * IOW, a future version of the library may make the transformations flag
  190680. * a bit more fine-grained, with separate bits for each of these three
  190681. * functions.
  190682. *
  190683. * More to the point, these functions make it obvious what libpng will be
  190684. * doing, whereas "expand" can (and does) mean any number of things.
  190685. *
  190686. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190687. * to expand only the sample depth but not to expand the tRNS to alpha.
  190688. */
  190689. /* Expand paletted images to RGB. */
  190690. void PNGAPI
  190691. png_set_palette_to_rgb(png_structp png_ptr)
  190692. {
  190693. png_debug(1, "in png_set_palette_to_rgb\n");
  190694. if(png_ptr == NULL) return;
  190695. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190696. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190697. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190698. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190699. #endif
  190700. }
  190701. #if !defined(PNG_1_0_X)
  190702. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190703. void PNGAPI
  190704. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190705. {
  190706. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190707. if(png_ptr == NULL) return;
  190708. png_ptr->transformations |= PNG_EXPAND;
  190709. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190710. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190711. #endif
  190712. }
  190713. #endif
  190714. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190715. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190716. /* Deprecated as of libpng-1.2.9 */
  190717. void PNGAPI
  190718. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190719. {
  190720. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190721. if(png_ptr == NULL) return;
  190722. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190723. }
  190724. #endif
  190725. /* Expand tRNS chunks to alpha channels. */
  190726. void PNGAPI
  190727. png_set_tRNS_to_alpha(png_structp png_ptr)
  190728. {
  190729. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190730. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190731. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190732. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190733. #endif
  190734. }
  190735. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190736. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190737. void PNGAPI
  190738. png_set_gray_to_rgb(png_structp png_ptr)
  190739. {
  190740. png_debug(1, "in png_set_gray_to_rgb\n");
  190741. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190742. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190743. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190744. #endif
  190745. }
  190746. #endif
  190747. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190748. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190749. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190750. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190751. */
  190752. void PNGAPI
  190753. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190754. double green)
  190755. {
  190756. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190757. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190758. if(png_ptr == NULL) return;
  190759. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190760. }
  190761. #endif
  190762. void PNGAPI
  190763. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190764. png_fixed_point red, png_fixed_point green)
  190765. {
  190766. png_debug(1, "in png_set_rgb_to_gray\n");
  190767. if(png_ptr == NULL) return;
  190768. switch(error_action)
  190769. {
  190770. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190771. break;
  190772. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190773. break;
  190774. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190775. }
  190776. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190777. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190778. png_ptr->transformations |= PNG_EXPAND;
  190779. #else
  190780. {
  190781. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190782. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190783. }
  190784. #endif
  190785. {
  190786. png_uint_16 red_int, green_int;
  190787. if(red < 0 || green < 0)
  190788. {
  190789. red_int = 6968; /* .212671 * 32768 + .5 */
  190790. green_int = 23434; /* .715160 * 32768 + .5 */
  190791. }
  190792. else if(red + green < 100000L)
  190793. {
  190794. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190795. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190796. }
  190797. else
  190798. {
  190799. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190800. red_int = 6968;
  190801. green_int = 23434;
  190802. }
  190803. png_ptr->rgb_to_gray_red_coeff = red_int;
  190804. png_ptr->rgb_to_gray_green_coeff = green_int;
  190805. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190806. }
  190807. }
  190808. #endif
  190809. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190810. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190811. defined(PNG_LEGACY_SUPPORTED)
  190812. void PNGAPI
  190813. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190814. read_user_transform_fn)
  190815. {
  190816. png_debug(1, "in png_set_read_user_transform_fn\n");
  190817. if(png_ptr == NULL) return;
  190818. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190819. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190820. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190821. #endif
  190822. #ifdef PNG_LEGACY_SUPPORTED
  190823. if(read_user_transform_fn)
  190824. png_warning(png_ptr,
  190825. "This version of libpng does not support user transforms");
  190826. #endif
  190827. }
  190828. #endif
  190829. /* Initialize everything needed for the read. This includes modifying
  190830. * the palette.
  190831. */
  190832. void /* PRIVATE */
  190833. png_init_read_transformations(png_structp png_ptr)
  190834. {
  190835. png_debug(1, "in png_init_read_transformations\n");
  190836. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190837. if(png_ptr != NULL)
  190838. #endif
  190839. {
  190840. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190841. || defined(PNG_READ_GAMMA_SUPPORTED)
  190842. int color_type = png_ptr->color_type;
  190843. #endif
  190844. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190845. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190846. /* Detect gray background and attempt to enable optimization
  190847. * for gray --> RGB case */
  190848. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190849. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190850. * background color might actually be gray yet not be flagged as such.
  190851. * This is not a problem for the current code, which uses
  190852. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190853. * png_do_gray_to_rgb() transformation.
  190854. */
  190855. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190856. !(color_type & PNG_COLOR_MASK_COLOR))
  190857. {
  190858. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190859. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190860. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190861. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190862. png_ptr->background.red == png_ptr->background.green &&
  190863. png_ptr->background.red == png_ptr->background.blue)
  190864. {
  190865. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190866. png_ptr->background.gray = png_ptr->background.red;
  190867. }
  190868. #endif
  190869. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190870. (png_ptr->transformations & PNG_EXPAND))
  190871. {
  190872. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190873. {
  190874. /* expand background and tRNS chunks */
  190875. switch (png_ptr->bit_depth)
  190876. {
  190877. case 1:
  190878. png_ptr->background.gray *= (png_uint_16)0xff;
  190879. png_ptr->background.red = png_ptr->background.green
  190880. = png_ptr->background.blue = png_ptr->background.gray;
  190881. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190882. {
  190883. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190884. png_ptr->trans_values.red = png_ptr->trans_values.green
  190885. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190886. }
  190887. break;
  190888. case 2:
  190889. png_ptr->background.gray *= (png_uint_16)0x55;
  190890. png_ptr->background.red = png_ptr->background.green
  190891. = png_ptr->background.blue = png_ptr->background.gray;
  190892. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190893. {
  190894. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190895. png_ptr->trans_values.red = png_ptr->trans_values.green
  190896. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190897. }
  190898. break;
  190899. case 4:
  190900. png_ptr->background.gray *= (png_uint_16)0x11;
  190901. png_ptr->background.red = png_ptr->background.green
  190902. = png_ptr->background.blue = png_ptr->background.gray;
  190903. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190904. {
  190905. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190906. png_ptr->trans_values.red = png_ptr->trans_values.green
  190907. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190908. }
  190909. break;
  190910. case 8:
  190911. case 16:
  190912. png_ptr->background.red = png_ptr->background.green
  190913. = png_ptr->background.blue = png_ptr->background.gray;
  190914. break;
  190915. }
  190916. }
  190917. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190918. {
  190919. png_ptr->background.red =
  190920. png_ptr->palette[png_ptr->background.index].red;
  190921. png_ptr->background.green =
  190922. png_ptr->palette[png_ptr->background.index].green;
  190923. png_ptr->background.blue =
  190924. png_ptr->palette[png_ptr->background.index].blue;
  190925. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190926. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190927. {
  190928. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190929. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190930. #endif
  190931. {
  190932. /* invert the alpha channel (in tRNS) unless the pixels are
  190933. going to be expanded, in which case leave it for later */
  190934. int i,istop;
  190935. istop=(int)png_ptr->num_trans;
  190936. for (i=0; i<istop; i++)
  190937. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190938. }
  190939. }
  190940. #endif
  190941. }
  190942. }
  190943. #endif
  190944. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190945. png_ptr->background_1 = png_ptr->background;
  190946. #endif
  190947. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190948. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190949. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190950. < PNG_GAMMA_THRESHOLD))
  190951. {
  190952. int i,k;
  190953. k=0;
  190954. for (i=0; i<png_ptr->num_trans; i++)
  190955. {
  190956. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190957. k=1; /* partial transparency is present */
  190958. }
  190959. if (k == 0)
  190960. png_ptr->transformations &= (~PNG_GAMMA);
  190961. }
  190962. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190963. png_ptr->gamma != 0.0)
  190964. {
  190965. png_build_gamma_table(png_ptr);
  190966. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190967. if (png_ptr->transformations & PNG_BACKGROUND)
  190968. {
  190969. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190970. {
  190971. /* could skip if no transparency and
  190972. */
  190973. png_color back, back_1;
  190974. png_colorp palette = png_ptr->palette;
  190975. int num_palette = png_ptr->num_palette;
  190976. int i;
  190977. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190978. {
  190979. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190980. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190981. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190982. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190983. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190984. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190985. }
  190986. else
  190987. {
  190988. double g, gs;
  190989. switch (png_ptr->background_gamma_type)
  190990. {
  190991. case PNG_BACKGROUND_GAMMA_SCREEN:
  190992. g = (png_ptr->screen_gamma);
  190993. gs = 1.0;
  190994. break;
  190995. case PNG_BACKGROUND_GAMMA_FILE:
  190996. g = 1.0 / (png_ptr->gamma);
  190997. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190998. break;
  190999. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191000. g = 1.0 / (png_ptr->background_gamma);
  191001. gs = 1.0 / (png_ptr->background_gamma *
  191002. png_ptr->screen_gamma);
  191003. break;
  191004. default:
  191005. g = 1.0; /* back_1 */
  191006. gs = 1.0; /* back */
  191007. }
  191008. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  191009. {
  191010. back.red = (png_byte)png_ptr->background.red;
  191011. back.green = (png_byte)png_ptr->background.green;
  191012. back.blue = (png_byte)png_ptr->background.blue;
  191013. }
  191014. else
  191015. {
  191016. back.red = (png_byte)(pow(
  191017. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  191018. back.green = (png_byte)(pow(
  191019. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  191020. back.blue = (png_byte)(pow(
  191021. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  191022. }
  191023. back_1.red = (png_byte)(pow(
  191024. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  191025. back_1.green = (png_byte)(pow(
  191026. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  191027. back_1.blue = (png_byte)(pow(
  191028. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  191029. }
  191030. for (i = 0; i < num_palette; i++)
  191031. {
  191032. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191033. {
  191034. if (png_ptr->trans[i] == 0)
  191035. {
  191036. palette[i] = back;
  191037. }
  191038. else /* if (png_ptr->trans[i] != 0xff) */
  191039. {
  191040. png_byte v, w;
  191041. v = png_ptr->gamma_to_1[palette[i].red];
  191042. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191043. palette[i].red = png_ptr->gamma_from_1[w];
  191044. v = png_ptr->gamma_to_1[palette[i].green];
  191045. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191046. palette[i].green = png_ptr->gamma_from_1[w];
  191047. v = png_ptr->gamma_to_1[palette[i].blue];
  191048. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191049. palette[i].blue = png_ptr->gamma_from_1[w];
  191050. }
  191051. }
  191052. else
  191053. {
  191054. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191055. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191056. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191057. }
  191058. }
  191059. }
  191060. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  191061. else
  191062. /* color_type != PNG_COLOR_TYPE_PALETTE */
  191063. {
  191064. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  191065. double g = 1.0;
  191066. double gs = 1.0;
  191067. switch (png_ptr->background_gamma_type)
  191068. {
  191069. case PNG_BACKGROUND_GAMMA_SCREEN:
  191070. g = (png_ptr->screen_gamma);
  191071. gs = 1.0;
  191072. break;
  191073. case PNG_BACKGROUND_GAMMA_FILE:
  191074. g = 1.0 / (png_ptr->gamma);
  191075. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191076. break;
  191077. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191078. g = 1.0 / (png_ptr->background_gamma);
  191079. gs = 1.0 / (png_ptr->background_gamma *
  191080. png_ptr->screen_gamma);
  191081. break;
  191082. }
  191083. png_ptr->background_1.gray = (png_uint_16)(pow(
  191084. (double)png_ptr->background.gray / m, g) * m + .5);
  191085. png_ptr->background.gray = (png_uint_16)(pow(
  191086. (double)png_ptr->background.gray / m, gs) * m + .5);
  191087. if ((png_ptr->background.red != png_ptr->background.green) ||
  191088. (png_ptr->background.red != png_ptr->background.blue) ||
  191089. (png_ptr->background.red != png_ptr->background.gray))
  191090. {
  191091. /* RGB or RGBA with color background */
  191092. png_ptr->background_1.red = (png_uint_16)(pow(
  191093. (double)png_ptr->background.red / m, g) * m + .5);
  191094. png_ptr->background_1.green = (png_uint_16)(pow(
  191095. (double)png_ptr->background.green / m, g) * m + .5);
  191096. png_ptr->background_1.blue = (png_uint_16)(pow(
  191097. (double)png_ptr->background.blue / m, g) * m + .5);
  191098. png_ptr->background.red = (png_uint_16)(pow(
  191099. (double)png_ptr->background.red / m, gs) * m + .5);
  191100. png_ptr->background.green = (png_uint_16)(pow(
  191101. (double)png_ptr->background.green / m, gs) * m + .5);
  191102. png_ptr->background.blue = (png_uint_16)(pow(
  191103. (double)png_ptr->background.blue / m, gs) * m + .5);
  191104. }
  191105. else
  191106. {
  191107. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  191108. png_ptr->background_1.red = png_ptr->background_1.green
  191109. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  191110. png_ptr->background.red = png_ptr->background.green
  191111. = png_ptr->background.blue = png_ptr->background.gray;
  191112. }
  191113. }
  191114. }
  191115. else
  191116. /* transformation does not include PNG_BACKGROUND */
  191117. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191118. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191119. {
  191120. png_colorp palette = png_ptr->palette;
  191121. int num_palette = png_ptr->num_palette;
  191122. int i;
  191123. for (i = 0; i < num_palette; i++)
  191124. {
  191125. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191126. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191127. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191128. }
  191129. }
  191130. }
  191131. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191132. else
  191133. #endif
  191134. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191135. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191136. /* No GAMMA transformation */
  191137. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191138. (color_type == PNG_COLOR_TYPE_PALETTE))
  191139. {
  191140. int i;
  191141. int istop = (int)png_ptr->num_trans;
  191142. png_color back;
  191143. png_colorp palette = png_ptr->palette;
  191144. back.red = (png_byte)png_ptr->background.red;
  191145. back.green = (png_byte)png_ptr->background.green;
  191146. back.blue = (png_byte)png_ptr->background.blue;
  191147. for (i = 0; i < istop; i++)
  191148. {
  191149. if (png_ptr->trans[i] == 0)
  191150. {
  191151. palette[i] = back;
  191152. }
  191153. else if (png_ptr->trans[i] != 0xff)
  191154. {
  191155. /* The png_composite() macro is defined in png.h */
  191156. png_composite(palette[i].red, palette[i].red,
  191157. png_ptr->trans[i], back.red);
  191158. png_composite(palette[i].green, palette[i].green,
  191159. png_ptr->trans[i], back.green);
  191160. png_composite(palette[i].blue, palette[i].blue,
  191161. png_ptr->trans[i], back.blue);
  191162. }
  191163. }
  191164. }
  191165. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191166. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191167. if ((png_ptr->transformations & PNG_SHIFT) &&
  191168. (color_type == PNG_COLOR_TYPE_PALETTE))
  191169. {
  191170. png_uint_16 i;
  191171. png_uint_16 istop = png_ptr->num_palette;
  191172. int sr = 8 - png_ptr->sig_bit.red;
  191173. int sg = 8 - png_ptr->sig_bit.green;
  191174. int sb = 8 - png_ptr->sig_bit.blue;
  191175. if (sr < 0 || sr > 8)
  191176. sr = 0;
  191177. if (sg < 0 || sg > 8)
  191178. sg = 0;
  191179. if (sb < 0 || sb > 8)
  191180. sb = 0;
  191181. for (i = 0; i < istop; i++)
  191182. {
  191183. png_ptr->palette[i].red >>= sr;
  191184. png_ptr->palette[i].green >>= sg;
  191185. png_ptr->palette[i].blue >>= sb;
  191186. }
  191187. }
  191188. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191189. }
  191190. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191191. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191192. if(png_ptr)
  191193. return;
  191194. #endif
  191195. }
  191196. /* Modify the info structure to reflect the transformations. The
  191197. * info should be updated so a PNG file could be written with it,
  191198. * assuming the transformations result in valid PNG data.
  191199. */
  191200. void /* PRIVATE */
  191201. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191202. {
  191203. png_debug(1, "in png_read_transform_info\n");
  191204. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191205. if (png_ptr->transformations & PNG_EXPAND)
  191206. {
  191207. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191208. {
  191209. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191210. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191211. else
  191212. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191213. info_ptr->bit_depth = 8;
  191214. info_ptr->num_trans = 0;
  191215. }
  191216. else
  191217. {
  191218. if (png_ptr->num_trans)
  191219. {
  191220. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191221. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191222. else
  191223. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191224. }
  191225. if (info_ptr->bit_depth < 8)
  191226. info_ptr->bit_depth = 8;
  191227. info_ptr->num_trans = 0;
  191228. }
  191229. }
  191230. #endif
  191231. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191232. if (png_ptr->transformations & PNG_BACKGROUND)
  191233. {
  191234. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191235. info_ptr->num_trans = 0;
  191236. info_ptr->background = png_ptr->background;
  191237. }
  191238. #endif
  191239. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191240. if (png_ptr->transformations & PNG_GAMMA)
  191241. {
  191242. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191243. info_ptr->gamma = png_ptr->gamma;
  191244. #endif
  191245. #ifdef PNG_FIXED_POINT_SUPPORTED
  191246. info_ptr->int_gamma = png_ptr->int_gamma;
  191247. #endif
  191248. }
  191249. #endif
  191250. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191251. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191252. info_ptr->bit_depth = 8;
  191253. #endif
  191254. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191255. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191256. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191257. #endif
  191258. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191259. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191260. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191261. #endif
  191262. #if defined(PNG_READ_DITHER_SUPPORTED)
  191263. if (png_ptr->transformations & PNG_DITHER)
  191264. {
  191265. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191266. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191267. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191268. {
  191269. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191270. }
  191271. }
  191272. #endif
  191273. #if defined(PNG_READ_PACK_SUPPORTED)
  191274. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191275. info_ptr->bit_depth = 8;
  191276. #endif
  191277. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191278. info_ptr->channels = 1;
  191279. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191280. info_ptr->channels = 3;
  191281. else
  191282. info_ptr->channels = 1;
  191283. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191284. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191285. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191286. #endif
  191287. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191288. info_ptr->channels++;
  191289. #if defined(PNG_READ_FILLER_SUPPORTED)
  191290. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191291. if ((png_ptr->transformations & PNG_FILLER) &&
  191292. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191293. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191294. {
  191295. info_ptr->channels++;
  191296. /* if adding a true alpha channel not just filler */
  191297. #if !defined(PNG_1_0_X)
  191298. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191299. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191300. #endif
  191301. }
  191302. #endif
  191303. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191304. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191305. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191306. {
  191307. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191308. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191309. if(info_ptr->channels < png_ptr->user_transform_channels)
  191310. info_ptr->channels = png_ptr->user_transform_channels;
  191311. }
  191312. #endif
  191313. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191314. info_ptr->bit_depth);
  191315. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191316. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191317. if(png_ptr)
  191318. return;
  191319. #endif
  191320. }
  191321. /* Transform the row. The order of transformations is significant,
  191322. * and is very touchy. If you add a transformation, take care to
  191323. * decide how it fits in with the other transformations here.
  191324. */
  191325. void /* PRIVATE */
  191326. png_do_read_transformations(png_structp png_ptr)
  191327. {
  191328. png_debug(1, "in png_do_read_transformations\n");
  191329. if (png_ptr->row_buf == NULL)
  191330. {
  191331. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191332. char msg[50];
  191333. png_snprintf2(msg, 50,
  191334. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191335. png_ptr->pass);
  191336. png_error(png_ptr, msg);
  191337. #else
  191338. png_error(png_ptr, "NULL row buffer");
  191339. #endif
  191340. }
  191341. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191342. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191343. /* Application has failed to call either png_read_start_image()
  191344. * or png_read_update_info() after setting transforms that expand
  191345. * pixels. This check added to libpng-1.2.19 */
  191346. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191347. png_error(png_ptr, "Uninitialized row");
  191348. #else
  191349. png_warning(png_ptr, "Uninitialized row");
  191350. #endif
  191351. #endif
  191352. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191353. if (png_ptr->transformations & PNG_EXPAND)
  191354. {
  191355. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191356. {
  191357. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191358. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191359. }
  191360. else
  191361. {
  191362. if (png_ptr->num_trans &&
  191363. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191364. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191365. &(png_ptr->trans_values));
  191366. else
  191367. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191368. NULL);
  191369. }
  191370. }
  191371. #endif
  191372. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191373. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191374. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191375. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191376. #endif
  191377. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191378. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191379. {
  191380. int rgb_error =
  191381. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191382. if(rgb_error)
  191383. {
  191384. png_ptr->rgb_to_gray_status=1;
  191385. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191386. PNG_RGB_TO_GRAY_WARN)
  191387. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191388. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191389. PNG_RGB_TO_GRAY_ERR)
  191390. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191391. }
  191392. }
  191393. #endif
  191394. /*
  191395. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191396. In most cases, the "simple transparency" should be done prior to doing
  191397. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191398. pixel is transparent. You would also need to make sure that the
  191399. transparency information is upgraded to RGB.
  191400. To summarize, the current flow is:
  191401. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191402. with background "in place" if transparent,
  191403. convert to RGB if necessary
  191404. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191405. convert to RGB if necessary
  191406. To support RGB backgrounds for gray images we need:
  191407. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191408. 3 or 6 bytes and composite with background
  191409. "in place" if transparent (3x compare/pixel
  191410. compared to doing composite with gray bkgrnd)
  191411. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191412. remove alpha bytes (3x float operations/pixel
  191413. compared with composite on gray background)
  191414. Greg's change will do this. The reason it wasn't done before is for
  191415. performance, as this increases the per-pixel operations. If we would check
  191416. in advance if the background was gray or RGB, and position the gray-to-RGB
  191417. transform appropriately, then it would save a lot of work/time.
  191418. */
  191419. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191420. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191421. * for performance reasons */
  191422. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191423. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191424. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191425. #endif
  191426. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191427. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191428. ((png_ptr->num_trans != 0 ) ||
  191429. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191430. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191431. &(png_ptr->trans_values), &(png_ptr->background)
  191432. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191433. , &(png_ptr->background_1),
  191434. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191435. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191436. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191437. png_ptr->gamma_shift
  191438. #endif
  191439. );
  191440. #endif
  191441. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191442. if ((png_ptr->transformations & PNG_GAMMA) &&
  191443. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191444. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191445. ((png_ptr->num_trans != 0) ||
  191446. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191447. #endif
  191448. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191449. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191450. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191451. png_ptr->gamma_shift);
  191452. #endif
  191453. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191454. if (png_ptr->transformations & PNG_16_TO_8)
  191455. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191456. #endif
  191457. #if defined(PNG_READ_DITHER_SUPPORTED)
  191458. if (png_ptr->transformations & PNG_DITHER)
  191459. {
  191460. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191461. png_ptr->palette_lookup, png_ptr->dither_index);
  191462. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191463. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191464. }
  191465. #endif
  191466. #if defined(PNG_READ_INVERT_SUPPORTED)
  191467. if (png_ptr->transformations & PNG_INVERT_MONO)
  191468. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191469. #endif
  191470. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191471. if (png_ptr->transformations & PNG_SHIFT)
  191472. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191473. &(png_ptr->shift));
  191474. #endif
  191475. #if defined(PNG_READ_PACK_SUPPORTED)
  191476. if (png_ptr->transformations & PNG_PACK)
  191477. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191478. #endif
  191479. #if defined(PNG_READ_BGR_SUPPORTED)
  191480. if (png_ptr->transformations & PNG_BGR)
  191481. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191482. #endif
  191483. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191484. if (png_ptr->transformations & PNG_PACKSWAP)
  191485. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191486. #endif
  191487. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191488. /* if gray -> RGB, do so now only if we did not do so above */
  191489. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191490. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191491. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191492. #endif
  191493. #if defined(PNG_READ_FILLER_SUPPORTED)
  191494. if (png_ptr->transformations & PNG_FILLER)
  191495. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191496. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191497. #endif
  191498. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191499. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191500. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191501. #endif
  191502. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191503. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191504. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191505. #endif
  191506. #if defined(PNG_READ_SWAP_SUPPORTED)
  191507. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191508. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191509. #endif
  191510. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191511. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191512. {
  191513. if(png_ptr->read_user_transform_fn != NULL)
  191514. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191515. (png_ptr, /* png_ptr */
  191516. &(png_ptr->row_info), /* row_info: */
  191517. /* png_uint_32 width; width of row */
  191518. /* png_uint_32 rowbytes; number of bytes in row */
  191519. /* png_byte color_type; color type of pixels */
  191520. /* png_byte bit_depth; bit depth of samples */
  191521. /* png_byte channels; number of channels (1-4) */
  191522. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191523. png_ptr->row_buf + 1); /* start of pixel data for row */
  191524. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191525. if(png_ptr->user_transform_depth)
  191526. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191527. if(png_ptr->user_transform_channels)
  191528. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191529. #endif
  191530. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191531. png_ptr->row_info.channels);
  191532. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191533. png_ptr->row_info.width);
  191534. }
  191535. #endif
  191536. }
  191537. #if defined(PNG_READ_PACK_SUPPORTED)
  191538. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191539. * without changing the actual values. Thus, if you had a row with
  191540. * a bit depth of 1, you would end up with bytes that only contained
  191541. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191542. * png_do_shift() after this.
  191543. */
  191544. void /* PRIVATE */
  191545. png_do_unpack(png_row_infop row_info, png_bytep row)
  191546. {
  191547. png_debug(1, "in png_do_unpack\n");
  191548. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191549. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191550. #else
  191551. if (row_info->bit_depth < 8)
  191552. #endif
  191553. {
  191554. png_uint_32 i;
  191555. png_uint_32 row_width=row_info->width;
  191556. switch (row_info->bit_depth)
  191557. {
  191558. case 1:
  191559. {
  191560. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191561. png_bytep dp = row + (png_size_t)row_width - 1;
  191562. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191563. for (i = 0; i < row_width; i++)
  191564. {
  191565. *dp = (png_byte)((*sp >> shift) & 0x01);
  191566. if (shift == 7)
  191567. {
  191568. shift = 0;
  191569. sp--;
  191570. }
  191571. else
  191572. shift++;
  191573. dp--;
  191574. }
  191575. break;
  191576. }
  191577. case 2:
  191578. {
  191579. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191580. png_bytep dp = row + (png_size_t)row_width - 1;
  191581. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191582. for (i = 0; i < row_width; i++)
  191583. {
  191584. *dp = (png_byte)((*sp >> shift) & 0x03);
  191585. if (shift == 6)
  191586. {
  191587. shift = 0;
  191588. sp--;
  191589. }
  191590. else
  191591. shift += 2;
  191592. dp--;
  191593. }
  191594. break;
  191595. }
  191596. case 4:
  191597. {
  191598. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191599. png_bytep dp = row + (png_size_t)row_width - 1;
  191600. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191601. for (i = 0; i < row_width; i++)
  191602. {
  191603. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191604. if (shift == 4)
  191605. {
  191606. shift = 0;
  191607. sp--;
  191608. }
  191609. else
  191610. shift = 4;
  191611. dp--;
  191612. }
  191613. break;
  191614. }
  191615. }
  191616. row_info->bit_depth = 8;
  191617. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191618. row_info->rowbytes = row_width * row_info->channels;
  191619. }
  191620. }
  191621. #endif
  191622. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191623. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191624. * pixels back to their significant bits values. Thus, if you have
  191625. * a row of bit depth 8, but only 5 are significant, this will shift
  191626. * the values back to 0 through 31.
  191627. */
  191628. void /* PRIVATE */
  191629. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191630. {
  191631. png_debug(1, "in png_do_unshift\n");
  191632. if (
  191633. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191634. row != NULL && row_info != NULL && sig_bits != NULL &&
  191635. #endif
  191636. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191637. {
  191638. int shift[4];
  191639. int channels = 0;
  191640. int c;
  191641. png_uint_16 value = 0;
  191642. png_uint_32 row_width = row_info->width;
  191643. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191644. {
  191645. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191646. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191647. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191648. }
  191649. else
  191650. {
  191651. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191652. }
  191653. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191654. {
  191655. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191656. }
  191657. for (c = 0; c < channels; c++)
  191658. {
  191659. if (shift[c] <= 0)
  191660. shift[c] = 0;
  191661. else
  191662. value = 1;
  191663. }
  191664. if (!value)
  191665. return;
  191666. switch (row_info->bit_depth)
  191667. {
  191668. case 2:
  191669. {
  191670. png_bytep bp;
  191671. png_uint_32 i;
  191672. png_uint_32 istop = row_info->rowbytes;
  191673. for (bp = row, i = 0; i < istop; i++)
  191674. {
  191675. *bp >>= 1;
  191676. *bp++ &= 0x55;
  191677. }
  191678. break;
  191679. }
  191680. case 4:
  191681. {
  191682. png_bytep bp = row;
  191683. png_uint_32 i;
  191684. png_uint_32 istop = row_info->rowbytes;
  191685. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191686. (png_byte)((int)0xf >> shift[0]));
  191687. for (i = 0; i < istop; i++)
  191688. {
  191689. *bp >>= shift[0];
  191690. *bp++ &= mask;
  191691. }
  191692. break;
  191693. }
  191694. case 8:
  191695. {
  191696. png_bytep bp = row;
  191697. png_uint_32 i;
  191698. png_uint_32 istop = row_width * channels;
  191699. for (i = 0; i < istop; i++)
  191700. {
  191701. *bp++ >>= shift[i%channels];
  191702. }
  191703. break;
  191704. }
  191705. case 16:
  191706. {
  191707. png_bytep bp = row;
  191708. png_uint_32 i;
  191709. png_uint_32 istop = channels * row_width;
  191710. for (i = 0; i < istop; i++)
  191711. {
  191712. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191713. value >>= shift[i%channels];
  191714. *bp++ = (png_byte)(value >> 8);
  191715. *bp++ = (png_byte)(value & 0xff);
  191716. }
  191717. break;
  191718. }
  191719. }
  191720. }
  191721. }
  191722. #endif
  191723. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191724. /* chop rows of bit depth 16 down to 8 */
  191725. void /* PRIVATE */
  191726. png_do_chop(png_row_infop row_info, png_bytep row)
  191727. {
  191728. png_debug(1, "in png_do_chop\n");
  191729. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191730. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191731. #else
  191732. if (row_info->bit_depth == 16)
  191733. #endif
  191734. {
  191735. png_bytep sp = row;
  191736. png_bytep dp = row;
  191737. png_uint_32 i;
  191738. png_uint_32 istop = row_info->width * row_info->channels;
  191739. for (i = 0; i<istop; i++, sp += 2, dp++)
  191740. {
  191741. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191742. /* This does a more accurate scaling of the 16-bit color
  191743. * value, rather than a simple low-byte truncation.
  191744. *
  191745. * What the ideal calculation should be:
  191746. * *dp = (((((png_uint_32)(*sp) << 8) |
  191747. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191748. *
  191749. * GRR: no, I think this is what it really should be:
  191750. * *dp = (((((png_uint_32)(*sp) << 8) |
  191751. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191752. *
  191753. * GRR: here's the exact calculation with shifts:
  191754. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191755. * *dp = (temp - (temp >> 8)) >> 8;
  191756. *
  191757. * Approximate calculation with shift/add instead of multiply/divide:
  191758. * *dp = ((((png_uint_32)(*sp) << 8) |
  191759. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191760. *
  191761. * What we actually do to avoid extra shifting and conversion:
  191762. */
  191763. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191764. #else
  191765. /* Simply discard the low order byte */
  191766. *dp = *sp;
  191767. #endif
  191768. }
  191769. row_info->bit_depth = 8;
  191770. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191771. row_info->rowbytes = row_info->width * row_info->channels;
  191772. }
  191773. }
  191774. #endif
  191775. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191776. void /* PRIVATE */
  191777. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191778. {
  191779. png_debug(1, "in png_do_read_swap_alpha\n");
  191780. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191781. if (row != NULL && row_info != NULL)
  191782. #endif
  191783. {
  191784. png_uint_32 row_width = row_info->width;
  191785. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191786. {
  191787. /* This converts from RGBA to ARGB */
  191788. if (row_info->bit_depth == 8)
  191789. {
  191790. png_bytep sp = row + row_info->rowbytes;
  191791. png_bytep dp = sp;
  191792. png_byte save;
  191793. png_uint_32 i;
  191794. for (i = 0; i < row_width; i++)
  191795. {
  191796. save = *(--sp);
  191797. *(--dp) = *(--sp);
  191798. *(--dp) = *(--sp);
  191799. *(--dp) = *(--sp);
  191800. *(--dp) = save;
  191801. }
  191802. }
  191803. /* This converts from RRGGBBAA to AARRGGBB */
  191804. else
  191805. {
  191806. png_bytep sp = row + row_info->rowbytes;
  191807. png_bytep dp = sp;
  191808. png_byte save[2];
  191809. png_uint_32 i;
  191810. for (i = 0; i < row_width; i++)
  191811. {
  191812. save[0] = *(--sp);
  191813. save[1] = *(--sp);
  191814. *(--dp) = *(--sp);
  191815. *(--dp) = *(--sp);
  191816. *(--dp) = *(--sp);
  191817. *(--dp) = *(--sp);
  191818. *(--dp) = *(--sp);
  191819. *(--dp) = *(--sp);
  191820. *(--dp) = save[0];
  191821. *(--dp) = save[1];
  191822. }
  191823. }
  191824. }
  191825. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191826. {
  191827. /* This converts from GA to AG */
  191828. if (row_info->bit_depth == 8)
  191829. {
  191830. png_bytep sp = row + row_info->rowbytes;
  191831. png_bytep dp = sp;
  191832. png_byte save;
  191833. png_uint_32 i;
  191834. for (i = 0; i < row_width; i++)
  191835. {
  191836. save = *(--sp);
  191837. *(--dp) = *(--sp);
  191838. *(--dp) = save;
  191839. }
  191840. }
  191841. /* This converts from GGAA to AAGG */
  191842. else
  191843. {
  191844. png_bytep sp = row + row_info->rowbytes;
  191845. png_bytep dp = sp;
  191846. png_byte save[2];
  191847. png_uint_32 i;
  191848. for (i = 0; i < row_width; i++)
  191849. {
  191850. save[0] = *(--sp);
  191851. save[1] = *(--sp);
  191852. *(--dp) = *(--sp);
  191853. *(--dp) = *(--sp);
  191854. *(--dp) = save[0];
  191855. *(--dp) = save[1];
  191856. }
  191857. }
  191858. }
  191859. }
  191860. }
  191861. #endif
  191862. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191863. void /* PRIVATE */
  191864. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191865. {
  191866. png_debug(1, "in png_do_read_invert_alpha\n");
  191867. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191868. if (row != NULL && row_info != NULL)
  191869. #endif
  191870. {
  191871. png_uint_32 row_width = row_info->width;
  191872. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191873. {
  191874. /* This inverts the alpha channel in RGBA */
  191875. if (row_info->bit_depth == 8)
  191876. {
  191877. png_bytep sp = row + row_info->rowbytes;
  191878. png_bytep dp = sp;
  191879. png_uint_32 i;
  191880. for (i = 0; i < row_width; i++)
  191881. {
  191882. *(--dp) = (png_byte)(255 - *(--sp));
  191883. /* This does nothing:
  191884. *(--dp) = *(--sp);
  191885. *(--dp) = *(--sp);
  191886. *(--dp) = *(--sp);
  191887. We can replace it with:
  191888. */
  191889. sp-=3;
  191890. dp=sp;
  191891. }
  191892. }
  191893. /* This inverts the alpha channel in RRGGBBAA */
  191894. else
  191895. {
  191896. png_bytep sp = row + row_info->rowbytes;
  191897. png_bytep dp = sp;
  191898. png_uint_32 i;
  191899. for (i = 0; i < row_width; i++)
  191900. {
  191901. *(--dp) = (png_byte)(255 - *(--sp));
  191902. *(--dp) = (png_byte)(255 - *(--sp));
  191903. /* This does nothing:
  191904. *(--dp) = *(--sp);
  191905. *(--dp) = *(--sp);
  191906. *(--dp) = *(--sp);
  191907. *(--dp) = *(--sp);
  191908. *(--dp) = *(--sp);
  191909. *(--dp) = *(--sp);
  191910. We can replace it with:
  191911. */
  191912. sp-=6;
  191913. dp=sp;
  191914. }
  191915. }
  191916. }
  191917. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191918. {
  191919. /* This inverts the alpha channel in GA */
  191920. if (row_info->bit_depth == 8)
  191921. {
  191922. png_bytep sp = row + row_info->rowbytes;
  191923. png_bytep dp = sp;
  191924. png_uint_32 i;
  191925. for (i = 0; i < row_width; i++)
  191926. {
  191927. *(--dp) = (png_byte)(255 - *(--sp));
  191928. *(--dp) = *(--sp);
  191929. }
  191930. }
  191931. /* This inverts the alpha channel in GGAA */
  191932. else
  191933. {
  191934. png_bytep sp = row + row_info->rowbytes;
  191935. png_bytep dp = sp;
  191936. png_uint_32 i;
  191937. for (i = 0; i < row_width; i++)
  191938. {
  191939. *(--dp) = (png_byte)(255 - *(--sp));
  191940. *(--dp) = (png_byte)(255 - *(--sp));
  191941. /*
  191942. *(--dp) = *(--sp);
  191943. *(--dp) = *(--sp);
  191944. */
  191945. sp-=2;
  191946. dp=sp;
  191947. }
  191948. }
  191949. }
  191950. }
  191951. }
  191952. #endif
  191953. #if defined(PNG_READ_FILLER_SUPPORTED)
  191954. /* Add filler channel if we have RGB color */
  191955. void /* PRIVATE */
  191956. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191957. png_uint_32 filler, png_uint_32 flags)
  191958. {
  191959. png_uint_32 i;
  191960. png_uint_32 row_width = row_info->width;
  191961. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191962. png_byte lo_filler = (png_byte)(filler & 0xff);
  191963. png_debug(1, "in png_do_read_filler\n");
  191964. if (
  191965. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191966. row != NULL && row_info != NULL &&
  191967. #endif
  191968. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191969. {
  191970. if(row_info->bit_depth == 8)
  191971. {
  191972. /* This changes the data from G to GX */
  191973. if (flags & PNG_FLAG_FILLER_AFTER)
  191974. {
  191975. png_bytep sp = row + (png_size_t)row_width;
  191976. png_bytep dp = sp + (png_size_t)row_width;
  191977. for (i = 1; i < row_width; i++)
  191978. {
  191979. *(--dp) = lo_filler;
  191980. *(--dp) = *(--sp);
  191981. }
  191982. *(--dp) = lo_filler;
  191983. row_info->channels = 2;
  191984. row_info->pixel_depth = 16;
  191985. row_info->rowbytes = row_width * 2;
  191986. }
  191987. /* This changes the data from G to XG */
  191988. else
  191989. {
  191990. png_bytep sp = row + (png_size_t)row_width;
  191991. png_bytep dp = sp + (png_size_t)row_width;
  191992. for (i = 0; i < row_width; i++)
  191993. {
  191994. *(--dp) = *(--sp);
  191995. *(--dp) = lo_filler;
  191996. }
  191997. row_info->channels = 2;
  191998. row_info->pixel_depth = 16;
  191999. row_info->rowbytes = row_width * 2;
  192000. }
  192001. }
  192002. else if(row_info->bit_depth == 16)
  192003. {
  192004. /* This changes the data from GG to GGXX */
  192005. if (flags & PNG_FLAG_FILLER_AFTER)
  192006. {
  192007. png_bytep sp = row + (png_size_t)row_width * 2;
  192008. png_bytep dp = sp + (png_size_t)row_width * 2;
  192009. for (i = 1; i < row_width; i++)
  192010. {
  192011. *(--dp) = hi_filler;
  192012. *(--dp) = lo_filler;
  192013. *(--dp) = *(--sp);
  192014. *(--dp) = *(--sp);
  192015. }
  192016. *(--dp) = hi_filler;
  192017. *(--dp) = lo_filler;
  192018. row_info->channels = 2;
  192019. row_info->pixel_depth = 32;
  192020. row_info->rowbytes = row_width * 4;
  192021. }
  192022. /* This changes the data from GG to XXGG */
  192023. else
  192024. {
  192025. png_bytep sp = row + (png_size_t)row_width * 2;
  192026. png_bytep dp = sp + (png_size_t)row_width * 2;
  192027. for (i = 0; i < row_width; i++)
  192028. {
  192029. *(--dp) = *(--sp);
  192030. *(--dp) = *(--sp);
  192031. *(--dp) = hi_filler;
  192032. *(--dp) = lo_filler;
  192033. }
  192034. row_info->channels = 2;
  192035. row_info->pixel_depth = 32;
  192036. row_info->rowbytes = row_width * 4;
  192037. }
  192038. }
  192039. } /* COLOR_TYPE == GRAY */
  192040. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192041. {
  192042. if(row_info->bit_depth == 8)
  192043. {
  192044. /* This changes the data from RGB to RGBX */
  192045. if (flags & PNG_FLAG_FILLER_AFTER)
  192046. {
  192047. png_bytep sp = row + (png_size_t)row_width * 3;
  192048. png_bytep dp = sp + (png_size_t)row_width;
  192049. for (i = 1; i < row_width; i++)
  192050. {
  192051. *(--dp) = lo_filler;
  192052. *(--dp) = *(--sp);
  192053. *(--dp) = *(--sp);
  192054. *(--dp) = *(--sp);
  192055. }
  192056. *(--dp) = lo_filler;
  192057. row_info->channels = 4;
  192058. row_info->pixel_depth = 32;
  192059. row_info->rowbytes = row_width * 4;
  192060. }
  192061. /* This changes the data from RGB to XRGB */
  192062. else
  192063. {
  192064. png_bytep sp = row + (png_size_t)row_width * 3;
  192065. png_bytep dp = sp + (png_size_t)row_width;
  192066. for (i = 0; i < row_width; i++)
  192067. {
  192068. *(--dp) = *(--sp);
  192069. *(--dp) = *(--sp);
  192070. *(--dp) = *(--sp);
  192071. *(--dp) = lo_filler;
  192072. }
  192073. row_info->channels = 4;
  192074. row_info->pixel_depth = 32;
  192075. row_info->rowbytes = row_width * 4;
  192076. }
  192077. }
  192078. else if(row_info->bit_depth == 16)
  192079. {
  192080. /* This changes the data from RRGGBB to RRGGBBXX */
  192081. if (flags & PNG_FLAG_FILLER_AFTER)
  192082. {
  192083. png_bytep sp = row + (png_size_t)row_width * 6;
  192084. png_bytep dp = sp + (png_size_t)row_width * 2;
  192085. for (i = 1; i < row_width; i++)
  192086. {
  192087. *(--dp) = hi_filler;
  192088. *(--dp) = lo_filler;
  192089. *(--dp) = *(--sp);
  192090. *(--dp) = *(--sp);
  192091. *(--dp) = *(--sp);
  192092. *(--dp) = *(--sp);
  192093. *(--dp) = *(--sp);
  192094. *(--dp) = *(--sp);
  192095. }
  192096. *(--dp) = hi_filler;
  192097. *(--dp) = lo_filler;
  192098. row_info->channels = 4;
  192099. row_info->pixel_depth = 64;
  192100. row_info->rowbytes = row_width * 8;
  192101. }
  192102. /* This changes the data from RRGGBB to XXRRGGBB */
  192103. else
  192104. {
  192105. png_bytep sp = row + (png_size_t)row_width * 6;
  192106. png_bytep dp = sp + (png_size_t)row_width * 2;
  192107. for (i = 0; i < row_width; i++)
  192108. {
  192109. *(--dp) = *(--sp);
  192110. *(--dp) = *(--sp);
  192111. *(--dp) = *(--sp);
  192112. *(--dp) = *(--sp);
  192113. *(--dp) = *(--sp);
  192114. *(--dp) = *(--sp);
  192115. *(--dp) = hi_filler;
  192116. *(--dp) = lo_filler;
  192117. }
  192118. row_info->channels = 4;
  192119. row_info->pixel_depth = 64;
  192120. row_info->rowbytes = row_width * 8;
  192121. }
  192122. }
  192123. } /* COLOR_TYPE == RGB */
  192124. }
  192125. #endif
  192126. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192127. /* expand grayscale files to RGB, with or without alpha */
  192128. void /* PRIVATE */
  192129. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192130. {
  192131. png_uint_32 i;
  192132. png_uint_32 row_width = row_info->width;
  192133. png_debug(1, "in png_do_gray_to_rgb\n");
  192134. if (row_info->bit_depth >= 8 &&
  192135. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192136. row != NULL && row_info != NULL &&
  192137. #endif
  192138. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192139. {
  192140. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192141. {
  192142. if (row_info->bit_depth == 8)
  192143. {
  192144. png_bytep sp = row + (png_size_t)row_width - 1;
  192145. png_bytep dp = sp + (png_size_t)row_width * 2;
  192146. for (i = 0; i < row_width; i++)
  192147. {
  192148. *(dp--) = *sp;
  192149. *(dp--) = *sp;
  192150. *(dp--) = *(sp--);
  192151. }
  192152. }
  192153. else
  192154. {
  192155. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192156. png_bytep dp = sp + (png_size_t)row_width * 4;
  192157. for (i = 0; i < row_width; i++)
  192158. {
  192159. *(dp--) = *sp;
  192160. *(dp--) = *(sp - 1);
  192161. *(dp--) = *sp;
  192162. *(dp--) = *(sp - 1);
  192163. *(dp--) = *(sp--);
  192164. *(dp--) = *(sp--);
  192165. }
  192166. }
  192167. }
  192168. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192169. {
  192170. if (row_info->bit_depth == 8)
  192171. {
  192172. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192173. png_bytep dp = sp + (png_size_t)row_width * 2;
  192174. for (i = 0; i < row_width; i++)
  192175. {
  192176. *(dp--) = *(sp--);
  192177. *(dp--) = *sp;
  192178. *(dp--) = *sp;
  192179. *(dp--) = *(sp--);
  192180. }
  192181. }
  192182. else
  192183. {
  192184. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192185. png_bytep dp = sp + (png_size_t)row_width * 4;
  192186. for (i = 0; i < row_width; i++)
  192187. {
  192188. *(dp--) = *(sp--);
  192189. *(dp--) = *(sp--);
  192190. *(dp--) = *sp;
  192191. *(dp--) = *(sp - 1);
  192192. *(dp--) = *sp;
  192193. *(dp--) = *(sp - 1);
  192194. *(dp--) = *(sp--);
  192195. *(dp--) = *(sp--);
  192196. }
  192197. }
  192198. }
  192199. row_info->channels += (png_byte)2;
  192200. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192201. row_info->pixel_depth = (png_byte)(row_info->channels *
  192202. row_info->bit_depth);
  192203. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192204. }
  192205. }
  192206. #endif
  192207. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192208. /* reduce RGB files to grayscale, with or without alpha
  192209. * using the equation given in Poynton's ColorFAQ at
  192210. * <http://www.inforamp.net/~poynton/>
  192211. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192212. *
  192213. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192214. *
  192215. * We approximate this with
  192216. *
  192217. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192218. *
  192219. * which can be expressed with integers as
  192220. *
  192221. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192222. *
  192223. * The calculation is to be done in a linear colorspace.
  192224. *
  192225. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192226. */
  192227. int /* PRIVATE */
  192228. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192229. {
  192230. png_uint_32 i;
  192231. png_uint_32 row_width = row_info->width;
  192232. int rgb_error = 0;
  192233. png_debug(1, "in png_do_rgb_to_gray\n");
  192234. if (
  192235. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192236. row != NULL && row_info != NULL &&
  192237. #endif
  192238. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192239. {
  192240. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192241. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192242. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192243. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192244. {
  192245. if (row_info->bit_depth == 8)
  192246. {
  192247. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192248. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192249. {
  192250. png_bytep sp = row;
  192251. png_bytep dp = row;
  192252. for (i = 0; i < row_width; i++)
  192253. {
  192254. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192255. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192256. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192257. if(red != green || red != blue)
  192258. {
  192259. rgb_error |= 1;
  192260. *(dp++) = png_ptr->gamma_from_1[
  192261. (rc*red+gc*green+bc*blue)>>15];
  192262. }
  192263. else
  192264. *(dp++) = *(sp-1);
  192265. }
  192266. }
  192267. else
  192268. #endif
  192269. {
  192270. png_bytep sp = row;
  192271. png_bytep dp = row;
  192272. for (i = 0; i < row_width; i++)
  192273. {
  192274. png_byte red = *(sp++);
  192275. png_byte green = *(sp++);
  192276. png_byte blue = *(sp++);
  192277. if(red != green || red != blue)
  192278. {
  192279. rgb_error |= 1;
  192280. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192281. }
  192282. else
  192283. *(dp++) = *(sp-1);
  192284. }
  192285. }
  192286. }
  192287. else /* RGB bit_depth == 16 */
  192288. {
  192289. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192290. if (png_ptr->gamma_16_to_1 != NULL &&
  192291. png_ptr->gamma_16_from_1 != NULL)
  192292. {
  192293. png_bytep sp = row;
  192294. png_bytep dp = row;
  192295. for (i = 0; i < row_width; i++)
  192296. {
  192297. png_uint_16 red, green, blue, w;
  192298. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192299. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192300. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192301. if(red == green && red == blue)
  192302. w = red;
  192303. else
  192304. {
  192305. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192306. png_ptr->gamma_shift][red>>8];
  192307. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192308. png_ptr->gamma_shift][green>>8];
  192309. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192310. png_ptr->gamma_shift][blue>>8];
  192311. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192312. + bc*blue_1)>>15);
  192313. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192314. png_ptr->gamma_shift][gray16 >> 8];
  192315. rgb_error |= 1;
  192316. }
  192317. *(dp++) = (png_byte)((w>>8) & 0xff);
  192318. *(dp++) = (png_byte)(w & 0xff);
  192319. }
  192320. }
  192321. else
  192322. #endif
  192323. {
  192324. png_bytep sp = row;
  192325. png_bytep dp = row;
  192326. for (i = 0; i < row_width; i++)
  192327. {
  192328. png_uint_16 red, green, blue, gray16;
  192329. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192330. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192331. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192332. if(red != green || red != blue)
  192333. rgb_error |= 1;
  192334. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192335. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192336. *(dp++) = (png_byte)(gray16 & 0xff);
  192337. }
  192338. }
  192339. }
  192340. }
  192341. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192342. {
  192343. if (row_info->bit_depth == 8)
  192344. {
  192345. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192346. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192347. {
  192348. png_bytep sp = row;
  192349. png_bytep dp = row;
  192350. for (i = 0; i < row_width; i++)
  192351. {
  192352. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192353. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192354. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192355. if(red != green || red != blue)
  192356. rgb_error |= 1;
  192357. *(dp++) = png_ptr->gamma_from_1
  192358. [(rc*red + gc*green + bc*blue)>>15];
  192359. *(dp++) = *(sp++); /* alpha */
  192360. }
  192361. }
  192362. else
  192363. #endif
  192364. {
  192365. png_bytep sp = row;
  192366. png_bytep dp = row;
  192367. for (i = 0; i < row_width; i++)
  192368. {
  192369. png_byte red = *(sp++);
  192370. png_byte green = *(sp++);
  192371. png_byte blue = *(sp++);
  192372. if(red != green || red != blue)
  192373. rgb_error |= 1;
  192374. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192375. *(dp++) = *(sp++); /* alpha */
  192376. }
  192377. }
  192378. }
  192379. else /* RGBA bit_depth == 16 */
  192380. {
  192381. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192382. if (png_ptr->gamma_16_to_1 != NULL &&
  192383. png_ptr->gamma_16_from_1 != NULL)
  192384. {
  192385. png_bytep sp = row;
  192386. png_bytep dp = row;
  192387. for (i = 0; i < row_width; i++)
  192388. {
  192389. png_uint_16 red, green, blue, w;
  192390. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192391. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192392. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192393. if(red == green && red == blue)
  192394. w = red;
  192395. else
  192396. {
  192397. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192398. png_ptr->gamma_shift][red>>8];
  192399. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192400. png_ptr->gamma_shift][green>>8];
  192401. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192402. png_ptr->gamma_shift][blue>>8];
  192403. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192404. + gc * green_1 + bc * blue_1)>>15);
  192405. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192406. png_ptr->gamma_shift][gray16 >> 8];
  192407. rgb_error |= 1;
  192408. }
  192409. *(dp++) = (png_byte)((w>>8) & 0xff);
  192410. *(dp++) = (png_byte)(w & 0xff);
  192411. *(dp++) = *(sp++); /* alpha */
  192412. *(dp++) = *(sp++);
  192413. }
  192414. }
  192415. else
  192416. #endif
  192417. {
  192418. png_bytep sp = row;
  192419. png_bytep dp = row;
  192420. for (i = 0; i < row_width; i++)
  192421. {
  192422. png_uint_16 red, green, blue, gray16;
  192423. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192424. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192425. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192426. if(red != green || red != blue)
  192427. rgb_error |= 1;
  192428. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192429. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192430. *(dp++) = (png_byte)(gray16 & 0xff);
  192431. *(dp++) = *(sp++); /* alpha */
  192432. *(dp++) = *(sp++);
  192433. }
  192434. }
  192435. }
  192436. }
  192437. row_info->channels -= (png_byte)2;
  192438. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192439. row_info->pixel_depth = (png_byte)(row_info->channels *
  192440. row_info->bit_depth);
  192441. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192442. }
  192443. return rgb_error;
  192444. }
  192445. #endif
  192446. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192447. * large of png_color. This lets grayscale images be treated as
  192448. * paletted. Most useful for gamma correction and simplification
  192449. * of code.
  192450. */
  192451. void PNGAPI
  192452. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192453. {
  192454. int num_palette;
  192455. int color_inc;
  192456. int i;
  192457. int v;
  192458. png_debug(1, "in png_do_build_grayscale_palette\n");
  192459. if (palette == NULL)
  192460. return;
  192461. switch (bit_depth)
  192462. {
  192463. case 1:
  192464. num_palette = 2;
  192465. color_inc = 0xff;
  192466. break;
  192467. case 2:
  192468. num_palette = 4;
  192469. color_inc = 0x55;
  192470. break;
  192471. case 4:
  192472. num_palette = 16;
  192473. color_inc = 0x11;
  192474. break;
  192475. case 8:
  192476. num_palette = 256;
  192477. color_inc = 1;
  192478. break;
  192479. default:
  192480. num_palette = 0;
  192481. color_inc = 0;
  192482. break;
  192483. }
  192484. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192485. {
  192486. palette[i].red = (png_byte)v;
  192487. palette[i].green = (png_byte)v;
  192488. palette[i].blue = (png_byte)v;
  192489. }
  192490. }
  192491. /* This function is currently unused. Do we really need it? */
  192492. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192493. void /* PRIVATE */
  192494. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192495. int num_palette)
  192496. {
  192497. png_debug(1, "in png_correct_palette\n");
  192498. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192499. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192500. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192501. {
  192502. png_color back, back_1;
  192503. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192504. {
  192505. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192506. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192507. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192508. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192509. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192510. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192511. }
  192512. else
  192513. {
  192514. double g;
  192515. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192516. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192517. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192518. {
  192519. back.red = png_ptr->background.red;
  192520. back.green = png_ptr->background.green;
  192521. back.blue = png_ptr->background.blue;
  192522. }
  192523. else
  192524. {
  192525. back.red =
  192526. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192527. 255.0 + 0.5);
  192528. back.green =
  192529. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192530. 255.0 + 0.5);
  192531. back.blue =
  192532. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192533. 255.0 + 0.5);
  192534. }
  192535. g = 1.0 / png_ptr->background_gamma;
  192536. back_1.red =
  192537. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192538. 255.0 + 0.5);
  192539. back_1.green =
  192540. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192541. 255.0 + 0.5);
  192542. back_1.blue =
  192543. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192544. 255.0 + 0.5);
  192545. }
  192546. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192547. {
  192548. png_uint_32 i;
  192549. for (i = 0; i < (png_uint_32)num_palette; i++)
  192550. {
  192551. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192552. {
  192553. palette[i] = back;
  192554. }
  192555. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192556. {
  192557. png_byte v, w;
  192558. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192559. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192560. palette[i].red = png_ptr->gamma_from_1[w];
  192561. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192562. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192563. palette[i].green = png_ptr->gamma_from_1[w];
  192564. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192565. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192566. palette[i].blue = png_ptr->gamma_from_1[w];
  192567. }
  192568. else
  192569. {
  192570. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192571. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192572. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192573. }
  192574. }
  192575. }
  192576. else
  192577. {
  192578. int i;
  192579. for (i = 0; i < num_palette; i++)
  192580. {
  192581. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192582. {
  192583. palette[i] = back;
  192584. }
  192585. else
  192586. {
  192587. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192588. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192589. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192590. }
  192591. }
  192592. }
  192593. }
  192594. else
  192595. #endif
  192596. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192597. if (png_ptr->transformations & PNG_GAMMA)
  192598. {
  192599. int i;
  192600. for (i = 0; i < num_palette; i++)
  192601. {
  192602. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192603. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192604. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192605. }
  192606. }
  192607. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192608. else
  192609. #endif
  192610. #endif
  192611. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192612. if (png_ptr->transformations & PNG_BACKGROUND)
  192613. {
  192614. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192615. {
  192616. png_color back;
  192617. back.red = (png_byte)png_ptr->background.red;
  192618. back.green = (png_byte)png_ptr->background.green;
  192619. back.blue = (png_byte)png_ptr->background.blue;
  192620. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192621. {
  192622. if (png_ptr->trans[i] == 0)
  192623. {
  192624. palette[i].red = back.red;
  192625. palette[i].green = back.green;
  192626. palette[i].blue = back.blue;
  192627. }
  192628. else if (png_ptr->trans[i] != 0xff)
  192629. {
  192630. png_composite(palette[i].red, png_ptr->palette[i].red,
  192631. png_ptr->trans[i], back.red);
  192632. png_composite(palette[i].green, png_ptr->palette[i].green,
  192633. png_ptr->trans[i], back.green);
  192634. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192635. png_ptr->trans[i], back.blue);
  192636. }
  192637. }
  192638. }
  192639. else /* assume grayscale palette (what else could it be?) */
  192640. {
  192641. int i;
  192642. for (i = 0; i < num_palette; i++)
  192643. {
  192644. if (i == (png_byte)png_ptr->trans_values.gray)
  192645. {
  192646. palette[i].red = (png_byte)png_ptr->background.red;
  192647. palette[i].green = (png_byte)png_ptr->background.green;
  192648. palette[i].blue = (png_byte)png_ptr->background.blue;
  192649. }
  192650. }
  192651. }
  192652. }
  192653. #endif
  192654. }
  192655. #endif
  192656. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192657. /* Replace any alpha or transparency with the supplied background color.
  192658. * "background" is already in the screen gamma, while "background_1" is
  192659. * at a gamma of 1.0. Paletted files have already been taken care of.
  192660. */
  192661. void /* PRIVATE */
  192662. png_do_background(png_row_infop row_info, png_bytep row,
  192663. png_color_16p trans_values, png_color_16p background
  192664. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192665. , png_color_16p background_1,
  192666. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192667. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192668. png_uint_16pp gamma_16_to_1, int gamma_shift
  192669. #endif
  192670. )
  192671. {
  192672. png_bytep sp, dp;
  192673. png_uint_32 i;
  192674. png_uint_32 row_width=row_info->width;
  192675. int shift;
  192676. png_debug(1, "in png_do_background\n");
  192677. if (background != NULL &&
  192678. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192679. row != NULL && row_info != NULL &&
  192680. #endif
  192681. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192682. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192683. {
  192684. switch (row_info->color_type)
  192685. {
  192686. case PNG_COLOR_TYPE_GRAY:
  192687. {
  192688. switch (row_info->bit_depth)
  192689. {
  192690. case 1:
  192691. {
  192692. sp = row;
  192693. shift = 7;
  192694. for (i = 0; i < row_width; i++)
  192695. {
  192696. if ((png_uint_16)((*sp >> shift) & 0x01)
  192697. == trans_values->gray)
  192698. {
  192699. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192700. *sp |= (png_byte)(background->gray << shift);
  192701. }
  192702. if (!shift)
  192703. {
  192704. shift = 7;
  192705. sp++;
  192706. }
  192707. else
  192708. shift--;
  192709. }
  192710. break;
  192711. }
  192712. case 2:
  192713. {
  192714. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192715. if (gamma_table != NULL)
  192716. {
  192717. sp = row;
  192718. shift = 6;
  192719. for (i = 0; i < row_width; i++)
  192720. {
  192721. if ((png_uint_16)((*sp >> shift) & 0x03)
  192722. == trans_values->gray)
  192723. {
  192724. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192725. *sp |= (png_byte)(background->gray << shift);
  192726. }
  192727. else
  192728. {
  192729. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192730. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192731. (p << 4) | (p << 6)] >> 6) & 0x03);
  192732. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192733. *sp |= (png_byte)(g << shift);
  192734. }
  192735. if (!shift)
  192736. {
  192737. shift = 6;
  192738. sp++;
  192739. }
  192740. else
  192741. shift -= 2;
  192742. }
  192743. }
  192744. else
  192745. #endif
  192746. {
  192747. sp = row;
  192748. shift = 6;
  192749. for (i = 0; i < row_width; i++)
  192750. {
  192751. if ((png_uint_16)((*sp >> shift) & 0x03)
  192752. == trans_values->gray)
  192753. {
  192754. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192755. *sp |= (png_byte)(background->gray << shift);
  192756. }
  192757. if (!shift)
  192758. {
  192759. shift = 6;
  192760. sp++;
  192761. }
  192762. else
  192763. shift -= 2;
  192764. }
  192765. }
  192766. break;
  192767. }
  192768. case 4:
  192769. {
  192770. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192771. if (gamma_table != NULL)
  192772. {
  192773. sp = row;
  192774. shift = 4;
  192775. for (i = 0; i < row_width; i++)
  192776. {
  192777. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192778. == trans_values->gray)
  192779. {
  192780. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192781. *sp |= (png_byte)(background->gray << shift);
  192782. }
  192783. else
  192784. {
  192785. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192786. png_byte g = (png_byte)((gamma_table[p |
  192787. (p << 4)] >> 4) & 0x0f);
  192788. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192789. *sp |= (png_byte)(g << shift);
  192790. }
  192791. if (!shift)
  192792. {
  192793. shift = 4;
  192794. sp++;
  192795. }
  192796. else
  192797. shift -= 4;
  192798. }
  192799. }
  192800. else
  192801. #endif
  192802. {
  192803. sp = row;
  192804. shift = 4;
  192805. for (i = 0; i < row_width; i++)
  192806. {
  192807. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192808. == trans_values->gray)
  192809. {
  192810. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192811. *sp |= (png_byte)(background->gray << shift);
  192812. }
  192813. if (!shift)
  192814. {
  192815. shift = 4;
  192816. sp++;
  192817. }
  192818. else
  192819. shift -= 4;
  192820. }
  192821. }
  192822. break;
  192823. }
  192824. case 8:
  192825. {
  192826. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192827. if (gamma_table != NULL)
  192828. {
  192829. sp = row;
  192830. for (i = 0; i < row_width; i++, sp++)
  192831. {
  192832. if (*sp == trans_values->gray)
  192833. {
  192834. *sp = (png_byte)background->gray;
  192835. }
  192836. else
  192837. {
  192838. *sp = gamma_table[*sp];
  192839. }
  192840. }
  192841. }
  192842. else
  192843. #endif
  192844. {
  192845. sp = row;
  192846. for (i = 0; i < row_width; i++, sp++)
  192847. {
  192848. if (*sp == trans_values->gray)
  192849. {
  192850. *sp = (png_byte)background->gray;
  192851. }
  192852. }
  192853. }
  192854. break;
  192855. }
  192856. case 16:
  192857. {
  192858. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192859. if (gamma_16 != NULL)
  192860. {
  192861. sp = row;
  192862. for (i = 0; i < row_width; i++, sp += 2)
  192863. {
  192864. png_uint_16 v;
  192865. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192866. if (v == trans_values->gray)
  192867. {
  192868. /* background is already in screen gamma */
  192869. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192870. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192871. }
  192872. else
  192873. {
  192874. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192875. *sp = (png_byte)((v >> 8) & 0xff);
  192876. *(sp + 1) = (png_byte)(v & 0xff);
  192877. }
  192878. }
  192879. }
  192880. else
  192881. #endif
  192882. {
  192883. sp = row;
  192884. for (i = 0; i < row_width; i++, sp += 2)
  192885. {
  192886. png_uint_16 v;
  192887. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192888. if (v == trans_values->gray)
  192889. {
  192890. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192891. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192892. }
  192893. }
  192894. }
  192895. break;
  192896. }
  192897. }
  192898. break;
  192899. }
  192900. case PNG_COLOR_TYPE_RGB:
  192901. {
  192902. if (row_info->bit_depth == 8)
  192903. {
  192904. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192905. if (gamma_table != NULL)
  192906. {
  192907. sp = row;
  192908. for (i = 0; i < row_width; i++, sp += 3)
  192909. {
  192910. if (*sp == trans_values->red &&
  192911. *(sp + 1) == trans_values->green &&
  192912. *(sp + 2) == trans_values->blue)
  192913. {
  192914. *sp = (png_byte)background->red;
  192915. *(sp + 1) = (png_byte)background->green;
  192916. *(sp + 2) = (png_byte)background->blue;
  192917. }
  192918. else
  192919. {
  192920. *sp = gamma_table[*sp];
  192921. *(sp + 1) = gamma_table[*(sp + 1)];
  192922. *(sp + 2) = gamma_table[*(sp + 2)];
  192923. }
  192924. }
  192925. }
  192926. else
  192927. #endif
  192928. {
  192929. sp = row;
  192930. for (i = 0; i < row_width; i++, sp += 3)
  192931. {
  192932. if (*sp == trans_values->red &&
  192933. *(sp + 1) == trans_values->green &&
  192934. *(sp + 2) == trans_values->blue)
  192935. {
  192936. *sp = (png_byte)background->red;
  192937. *(sp + 1) = (png_byte)background->green;
  192938. *(sp + 2) = (png_byte)background->blue;
  192939. }
  192940. }
  192941. }
  192942. }
  192943. else /* if (row_info->bit_depth == 16) */
  192944. {
  192945. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192946. if (gamma_16 != NULL)
  192947. {
  192948. sp = row;
  192949. for (i = 0; i < row_width; i++, sp += 6)
  192950. {
  192951. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192952. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192953. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192954. if (r == trans_values->red && g == trans_values->green &&
  192955. b == trans_values->blue)
  192956. {
  192957. /* background is already in screen gamma */
  192958. *sp = (png_byte)((background->red >> 8) & 0xff);
  192959. *(sp + 1) = (png_byte)(background->red & 0xff);
  192960. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192961. *(sp + 3) = (png_byte)(background->green & 0xff);
  192962. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192963. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192964. }
  192965. else
  192966. {
  192967. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192968. *sp = (png_byte)((v >> 8) & 0xff);
  192969. *(sp + 1) = (png_byte)(v & 0xff);
  192970. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192971. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192972. *(sp + 3) = (png_byte)(v & 0xff);
  192973. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192974. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192975. *(sp + 5) = (png_byte)(v & 0xff);
  192976. }
  192977. }
  192978. }
  192979. else
  192980. #endif
  192981. {
  192982. sp = row;
  192983. for (i = 0; i < row_width; i++, sp += 6)
  192984. {
  192985. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192986. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192987. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192988. if (r == trans_values->red && g == trans_values->green &&
  192989. b == trans_values->blue)
  192990. {
  192991. *sp = (png_byte)((background->red >> 8) & 0xff);
  192992. *(sp + 1) = (png_byte)(background->red & 0xff);
  192993. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192994. *(sp + 3) = (png_byte)(background->green & 0xff);
  192995. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192996. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192997. }
  192998. }
  192999. }
  193000. }
  193001. break;
  193002. }
  193003. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193004. {
  193005. if (row_info->bit_depth == 8)
  193006. {
  193007. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193008. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193009. gamma_table != NULL)
  193010. {
  193011. sp = row;
  193012. dp = row;
  193013. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193014. {
  193015. png_uint_16 a = *(sp + 1);
  193016. if (a == 0xff)
  193017. {
  193018. *dp = gamma_table[*sp];
  193019. }
  193020. else if (a == 0)
  193021. {
  193022. /* background is already in screen gamma */
  193023. *dp = (png_byte)background->gray;
  193024. }
  193025. else
  193026. {
  193027. png_byte v, w;
  193028. v = gamma_to_1[*sp];
  193029. png_composite(w, v, a, background_1->gray);
  193030. *dp = gamma_from_1[w];
  193031. }
  193032. }
  193033. }
  193034. else
  193035. #endif
  193036. {
  193037. sp = row;
  193038. dp = row;
  193039. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193040. {
  193041. png_byte a = *(sp + 1);
  193042. if (a == 0xff)
  193043. {
  193044. *dp = *sp;
  193045. }
  193046. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193047. else if (a == 0)
  193048. {
  193049. *dp = (png_byte)background->gray;
  193050. }
  193051. else
  193052. {
  193053. png_composite(*dp, *sp, a, background_1->gray);
  193054. }
  193055. #else
  193056. *dp = (png_byte)background->gray;
  193057. #endif
  193058. }
  193059. }
  193060. }
  193061. else /* if (png_ptr->bit_depth == 16) */
  193062. {
  193063. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193064. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193065. gamma_16_to_1 != NULL)
  193066. {
  193067. sp = row;
  193068. dp = row;
  193069. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193070. {
  193071. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193072. if (a == (png_uint_16)0xffff)
  193073. {
  193074. png_uint_16 v;
  193075. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193076. *dp = (png_byte)((v >> 8) & 0xff);
  193077. *(dp + 1) = (png_byte)(v & 0xff);
  193078. }
  193079. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193080. else if (a == 0)
  193081. #else
  193082. else
  193083. #endif
  193084. {
  193085. /* background is already in screen gamma */
  193086. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193087. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193088. }
  193089. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193090. else
  193091. {
  193092. png_uint_16 g, v, w;
  193093. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193094. png_composite_16(v, g, a, background_1->gray);
  193095. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  193096. *dp = (png_byte)((w >> 8) & 0xff);
  193097. *(dp + 1) = (png_byte)(w & 0xff);
  193098. }
  193099. #endif
  193100. }
  193101. }
  193102. else
  193103. #endif
  193104. {
  193105. sp = row;
  193106. dp = row;
  193107. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193108. {
  193109. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193110. if (a == (png_uint_16)0xffff)
  193111. {
  193112. png_memcpy(dp, sp, 2);
  193113. }
  193114. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193115. else if (a == 0)
  193116. #else
  193117. else
  193118. #endif
  193119. {
  193120. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193121. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193122. }
  193123. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193124. else
  193125. {
  193126. png_uint_16 g, v;
  193127. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193128. png_composite_16(v, g, a, background_1->gray);
  193129. *dp = (png_byte)((v >> 8) & 0xff);
  193130. *(dp + 1) = (png_byte)(v & 0xff);
  193131. }
  193132. #endif
  193133. }
  193134. }
  193135. }
  193136. break;
  193137. }
  193138. case PNG_COLOR_TYPE_RGB_ALPHA:
  193139. {
  193140. if (row_info->bit_depth == 8)
  193141. {
  193142. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193143. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193144. gamma_table != NULL)
  193145. {
  193146. sp = row;
  193147. dp = row;
  193148. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193149. {
  193150. png_byte a = *(sp + 3);
  193151. if (a == 0xff)
  193152. {
  193153. *dp = gamma_table[*sp];
  193154. *(dp + 1) = gamma_table[*(sp + 1)];
  193155. *(dp + 2) = gamma_table[*(sp + 2)];
  193156. }
  193157. else if (a == 0)
  193158. {
  193159. /* background is already in screen gamma */
  193160. *dp = (png_byte)background->red;
  193161. *(dp + 1) = (png_byte)background->green;
  193162. *(dp + 2) = (png_byte)background->blue;
  193163. }
  193164. else
  193165. {
  193166. png_byte v, w;
  193167. v = gamma_to_1[*sp];
  193168. png_composite(w, v, a, background_1->red);
  193169. *dp = gamma_from_1[w];
  193170. v = gamma_to_1[*(sp + 1)];
  193171. png_composite(w, v, a, background_1->green);
  193172. *(dp + 1) = gamma_from_1[w];
  193173. v = gamma_to_1[*(sp + 2)];
  193174. png_composite(w, v, a, background_1->blue);
  193175. *(dp + 2) = gamma_from_1[w];
  193176. }
  193177. }
  193178. }
  193179. else
  193180. #endif
  193181. {
  193182. sp = row;
  193183. dp = row;
  193184. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193185. {
  193186. png_byte a = *(sp + 3);
  193187. if (a == 0xff)
  193188. {
  193189. *dp = *sp;
  193190. *(dp + 1) = *(sp + 1);
  193191. *(dp + 2) = *(sp + 2);
  193192. }
  193193. else if (a == 0)
  193194. {
  193195. *dp = (png_byte)background->red;
  193196. *(dp + 1) = (png_byte)background->green;
  193197. *(dp + 2) = (png_byte)background->blue;
  193198. }
  193199. else
  193200. {
  193201. png_composite(*dp, *sp, a, background->red);
  193202. png_composite(*(dp + 1), *(sp + 1), a,
  193203. background->green);
  193204. png_composite(*(dp + 2), *(sp + 2), a,
  193205. background->blue);
  193206. }
  193207. }
  193208. }
  193209. }
  193210. else /* if (row_info->bit_depth == 16) */
  193211. {
  193212. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193213. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193214. gamma_16_to_1 != NULL)
  193215. {
  193216. sp = row;
  193217. dp = row;
  193218. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193219. {
  193220. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193221. << 8) + (png_uint_16)(*(sp + 7)));
  193222. if (a == (png_uint_16)0xffff)
  193223. {
  193224. png_uint_16 v;
  193225. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193226. *dp = (png_byte)((v >> 8) & 0xff);
  193227. *(dp + 1) = (png_byte)(v & 0xff);
  193228. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193229. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193230. *(dp + 3) = (png_byte)(v & 0xff);
  193231. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193232. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193233. *(dp + 5) = (png_byte)(v & 0xff);
  193234. }
  193235. else if (a == 0)
  193236. {
  193237. /* background is already in screen gamma */
  193238. *dp = (png_byte)((background->red >> 8) & 0xff);
  193239. *(dp + 1) = (png_byte)(background->red & 0xff);
  193240. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193241. *(dp + 3) = (png_byte)(background->green & 0xff);
  193242. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193243. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193244. }
  193245. else
  193246. {
  193247. png_uint_16 v, w, x;
  193248. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193249. png_composite_16(w, v, a, background_1->red);
  193250. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193251. *dp = (png_byte)((x >> 8) & 0xff);
  193252. *(dp + 1) = (png_byte)(x & 0xff);
  193253. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193254. png_composite_16(w, v, a, background_1->green);
  193255. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193256. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193257. *(dp + 3) = (png_byte)(x & 0xff);
  193258. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193259. png_composite_16(w, v, a, background_1->blue);
  193260. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193261. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193262. *(dp + 5) = (png_byte)(x & 0xff);
  193263. }
  193264. }
  193265. }
  193266. else
  193267. #endif
  193268. {
  193269. sp = row;
  193270. dp = row;
  193271. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193272. {
  193273. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193274. << 8) + (png_uint_16)(*(sp + 7)));
  193275. if (a == (png_uint_16)0xffff)
  193276. {
  193277. png_memcpy(dp, sp, 6);
  193278. }
  193279. else if (a == 0)
  193280. {
  193281. *dp = (png_byte)((background->red >> 8) & 0xff);
  193282. *(dp + 1) = (png_byte)(background->red & 0xff);
  193283. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193284. *(dp + 3) = (png_byte)(background->green & 0xff);
  193285. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193286. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193287. }
  193288. else
  193289. {
  193290. png_uint_16 v;
  193291. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193292. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193293. + *(sp + 3));
  193294. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193295. + *(sp + 5));
  193296. png_composite_16(v, r, a, background->red);
  193297. *dp = (png_byte)((v >> 8) & 0xff);
  193298. *(dp + 1) = (png_byte)(v & 0xff);
  193299. png_composite_16(v, g, a, background->green);
  193300. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193301. *(dp + 3) = (png_byte)(v & 0xff);
  193302. png_composite_16(v, b, a, background->blue);
  193303. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193304. *(dp + 5) = (png_byte)(v & 0xff);
  193305. }
  193306. }
  193307. }
  193308. }
  193309. break;
  193310. }
  193311. }
  193312. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193313. {
  193314. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193315. row_info->channels--;
  193316. row_info->pixel_depth = (png_byte)(row_info->channels *
  193317. row_info->bit_depth);
  193318. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193319. }
  193320. }
  193321. }
  193322. #endif
  193323. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193324. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193325. * you do this after you deal with the transparency issue on grayscale
  193326. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193327. * is 16, use gamma_16_table and gamma_shift. Build these with
  193328. * build_gamma_table().
  193329. */
  193330. void /* PRIVATE */
  193331. png_do_gamma(png_row_infop row_info, png_bytep row,
  193332. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193333. int gamma_shift)
  193334. {
  193335. png_bytep sp;
  193336. png_uint_32 i;
  193337. png_uint_32 row_width=row_info->width;
  193338. png_debug(1, "in png_do_gamma\n");
  193339. if (
  193340. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193341. row != NULL && row_info != NULL &&
  193342. #endif
  193343. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193344. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193345. {
  193346. switch (row_info->color_type)
  193347. {
  193348. case PNG_COLOR_TYPE_RGB:
  193349. {
  193350. if (row_info->bit_depth == 8)
  193351. {
  193352. sp = row;
  193353. for (i = 0; i < row_width; i++)
  193354. {
  193355. *sp = gamma_table[*sp];
  193356. sp++;
  193357. *sp = gamma_table[*sp];
  193358. sp++;
  193359. *sp = gamma_table[*sp];
  193360. sp++;
  193361. }
  193362. }
  193363. else /* if (row_info->bit_depth == 16) */
  193364. {
  193365. sp = row;
  193366. for (i = 0; i < row_width; i++)
  193367. {
  193368. png_uint_16 v;
  193369. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193370. *sp = (png_byte)((v >> 8) & 0xff);
  193371. *(sp + 1) = (png_byte)(v & 0xff);
  193372. sp += 2;
  193373. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193374. *sp = (png_byte)((v >> 8) & 0xff);
  193375. *(sp + 1) = (png_byte)(v & 0xff);
  193376. sp += 2;
  193377. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193378. *sp = (png_byte)((v >> 8) & 0xff);
  193379. *(sp + 1) = (png_byte)(v & 0xff);
  193380. sp += 2;
  193381. }
  193382. }
  193383. break;
  193384. }
  193385. case PNG_COLOR_TYPE_RGB_ALPHA:
  193386. {
  193387. if (row_info->bit_depth == 8)
  193388. {
  193389. sp = row;
  193390. for (i = 0; i < row_width; i++)
  193391. {
  193392. *sp = gamma_table[*sp];
  193393. sp++;
  193394. *sp = gamma_table[*sp];
  193395. sp++;
  193396. *sp = gamma_table[*sp];
  193397. sp++;
  193398. sp++;
  193399. }
  193400. }
  193401. else /* if (row_info->bit_depth == 16) */
  193402. {
  193403. sp = row;
  193404. for (i = 0; i < row_width; i++)
  193405. {
  193406. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193407. *sp = (png_byte)((v >> 8) & 0xff);
  193408. *(sp + 1) = (png_byte)(v & 0xff);
  193409. sp += 2;
  193410. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193411. *sp = (png_byte)((v >> 8) & 0xff);
  193412. *(sp + 1) = (png_byte)(v & 0xff);
  193413. sp += 2;
  193414. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193415. *sp = (png_byte)((v >> 8) & 0xff);
  193416. *(sp + 1) = (png_byte)(v & 0xff);
  193417. sp += 4;
  193418. }
  193419. }
  193420. break;
  193421. }
  193422. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193423. {
  193424. if (row_info->bit_depth == 8)
  193425. {
  193426. sp = row;
  193427. for (i = 0; i < row_width; i++)
  193428. {
  193429. *sp = gamma_table[*sp];
  193430. sp += 2;
  193431. }
  193432. }
  193433. else /* if (row_info->bit_depth == 16) */
  193434. {
  193435. sp = row;
  193436. for (i = 0; i < row_width; i++)
  193437. {
  193438. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193439. *sp = (png_byte)((v >> 8) & 0xff);
  193440. *(sp + 1) = (png_byte)(v & 0xff);
  193441. sp += 4;
  193442. }
  193443. }
  193444. break;
  193445. }
  193446. case PNG_COLOR_TYPE_GRAY:
  193447. {
  193448. if (row_info->bit_depth == 2)
  193449. {
  193450. sp = row;
  193451. for (i = 0; i < row_width; i += 4)
  193452. {
  193453. int a = *sp & 0xc0;
  193454. int b = *sp & 0x30;
  193455. int c = *sp & 0x0c;
  193456. int d = *sp & 0x03;
  193457. *sp = (png_byte)(
  193458. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193459. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193460. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193461. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193462. sp++;
  193463. }
  193464. }
  193465. if (row_info->bit_depth == 4)
  193466. {
  193467. sp = row;
  193468. for (i = 0; i < row_width; i += 2)
  193469. {
  193470. int msb = *sp & 0xf0;
  193471. int lsb = *sp & 0x0f;
  193472. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193473. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193474. sp++;
  193475. }
  193476. }
  193477. else if (row_info->bit_depth == 8)
  193478. {
  193479. sp = row;
  193480. for (i = 0; i < row_width; i++)
  193481. {
  193482. *sp = gamma_table[*sp];
  193483. sp++;
  193484. }
  193485. }
  193486. else if (row_info->bit_depth == 16)
  193487. {
  193488. sp = row;
  193489. for (i = 0; i < row_width; i++)
  193490. {
  193491. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193492. *sp = (png_byte)((v >> 8) & 0xff);
  193493. *(sp + 1) = (png_byte)(v & 0xff);
  193494. sp += 2;
  193495. }
  193496. }
  193497. break;
  193498. }
  193499. }
  193500. }
  193501. }
  193502. #endif
  193503. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193504. /* Expands a palette row to an RGB or RGBA row depending
  193505. * upon whether you supply trans and num_trans.
  193506. */
  193507. void /* PRIVATE */
  193508. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193509. png_colorp palette, png_bytep trans, int num_trans)
  193510. {
  193511. int shift, value;
  193512. png_bytep sp, dp;
  193513. png_uint_32 i;
  193514. png_uint_32 row_width=row_info->width;
  193515. png_debug(1, "in png_do_expand_palette\n");
  193516. if (
  193517. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193518. row != NULL && row_info != NULL &&
  193519. #endif
  193520. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193521. {
  193522. if (row_info->bit_depth < 8)
  193523. {
  193524. switch (row_info->bit_depth)
  193525. {
  193526. case 1:
  193527. {
  193528. sp = row + (png_size_t)((row_width - 1) >> 3);
  193529. dp = row + (png_size_t)row_width - 1;
  193530. shift = 7 - (int)((row_width + 7) & 0x07);
  193531. for (i = 0; i < row_width; i++)
  193532. {
  193533. if ((*sp >> shift) & 0x01)
  193534. *dp = 1;
  193535. else
  193536. *dp = 0;
  193537. if (shift == 7)
  193538. {
  193539. shift = 0;
  193540. sp--;
  193541. }
  193542. else
  193543. shift++;
  193544. dp--;
  193545. }
  193546. break;
  193547. }
  193548. case 2:
  193549. {
  193550. sp = row + (png_size_t)((row_width - 1) >> 2);
  193551. dp = row + (png_size_t)row_width - 1;
  193552. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193553. for (i = 0; i < row_width; i++)
  193554. {
  193555. value = (*sp >> shift) & 0x03;
  193556. *dp = (png_byte)value;
  193557. if (shift == 6)
  193558. {
  193559. shift = 0;
  193560. sp--;
  193561. }
  193562. else
  193563. shift += 2;
  193564. dp--;
  193565. }
  193566. break;
  193567. }
  193568. case 4:
  193569. {
  193570. sp = row + (png_size_t)((row_width - 1) >> 1);
  193571. dp = row + (png_size_t)row_width - 1;
  193572. shift = (int)((row_width & 0x01) << 2);
  193573. for (i = 0; i < row_width; i++)
  193574. {
  193575. value = (*sp >> shift) & 0x0f;
  193576. *dp = (png_byte)value;
  193577. if (shift == 4)
  193578. {
  193579. shift = 0;
  193580. sp--;
  193581. }
  193582. else
  193583. shift += 4;
  193584. dp--;
  193585. }
  193586. break;
  193587. }
  193588. }
  193589. row_info->bit_depth = 8;
  193590. row_info->pixel_depth = 8;
  193591. row_info->rowbytes = row_width;
  193592. }
  193593. switch (row_info->bit_depth)
  193594. {
  193595. case 8:
  193596. {
  193597. if (trans != NULL)
  193598. {
  193599. sp = row + (png_size_t)row_width - 1;
  193600. dp = row + (png_size_t)(row_width << 2) - 1;
  193601. for (i = 0; i < row_width; i++)
  193602. {
  193603. if ((int)(*sp) >= num_trans)
  193604. *dp-- = 0xff;
  193605. else
  193606. *dp-- = trans[*sp];
  193607. *dp-- = palette[*sp].blue;
  193608. *dp-- = palette[*sp].green;
  193609. *dp-- = palette[*sp].red;
  193610. sp--;
  193611. }
  193612. row_info->bit_depth = 8;
  193613. row_info->pixel_depth = 32;
  193614. row_info->rowbytes = row_width * 4;
  193615. row_info->color_type = 6;
  193616. row_info->channels = 4;
  193617. }
  193618. else
  193619. {
  193620. sp = row + (png_size_t)row_width - 1;
  193621. dp = row + (png_size_t)(row_width * 3) - 1;
  193622. for (i = 0; i < row_width; i++)
  193623. {
  193624. *dp-- = palette[*sp].blue;
  193625. *dp-- = palette[*sp].green;
  193626. *dp-- = palette[*sp].red;
  193627. sp--;
  193628. }
  193629. row_info->bit_depth = 8;
  193630. row_info->pixel_depth = 24;
  193631. row_info->rowbytes = row_width * 3;
  193632. row_info->color_type = 2;
  193633. row_info->channels = 3;
  193634. }
  193635. break;
  193636. }
  193637. }
  193638. }
  193639. }
  193640. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193641. * expanded transparency value is supplied, an alpha channel is built.
  193642. */
  193643. void /* PRIVATE */
  193644. png_do_expand(png_row_infop row_info, png_bytep row,
  193645. png_color_16p trans_value)
  193646. {
  193647. int shift, value;
  193648. png_bytep sp, dp;
  193649. png_uint_32 i;
  193650. png_uint_32 row_width=row_info->width;
  193651. png_debug(1, "in png_do_expand\n");
  193652. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193653. if (row != NULL && row_info != NULL)
  193654. #endif
  193655. {
  193656. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193657. {
  193658. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193659. if (row_info->bit_depth < 8)
  193660. {
  193661. switch (row_info->bit_depth)
  193662. {
  193663. case 1:
  193664. {
  193665. gray = (png_uint_16)((gray&0x01)*0xff);
  193666. sp = row + (png_size_t)((row_width - 1) >> 3);
  193667. dp = row + (png_size_t)row_width - 1;
  193668. shift = 7 - (int)((row_width + 7) & 0x07);
  193669. for (i = 0; i < row_width; i++)
  193670. {
  193671. if ((*sp >> shift) & 0x01)
  193672. *dp = 0xff;
  193673. else
  193674. *dp = 0;
  193675. if (shift == 7)
  193676. {
  193677. shift = 0;
  193678. sp--;
  193679. }
  193680. else
  193681. shift++;
  193682. dp--;
  193683. }
  193684. break;
  193685. }
  193686. case 2:
  193687. {
  193688. gray = (png_uint_16)((gray&0x03)*0x55);
  193689. sp = row + (png_size_t)((row_width - 1) >> 2);
  193690. dp = row + (png_size_t)row_width - 1;
  193691. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193692. for (i = 0; i < row_width; i++)
  193693. {
  193694. value = (*sp >> shift) & 0x03;
  193695. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193696. (value << 6));
  193697. if (shift == 6)
  193698. {
  193699. shift = 0;
  193700. sp--;
  193701. }
  193702. else
  193703. shift += 2;
  193704. dp--;
  193705. }
  193706. break;
  193707. }
  193708. case 4:
  193709. {
  193710. gray = (png_uint_16)((gray&0x0f)*0x11);
  193711. sp = row + (png_size_t)((row_width - 1) >> 1);
  193712. dp = row + (png_size_t)row_width - 1;
  193713. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193714. for (i = 0; i < row_width; i++)
  193715. {
  193716. value = (*sp >> shift) & 0x0f;
  193717. *dp = (png_byte)(value | (value << 4));
  193718. if (shift == 4)
  193719. {
  193720. shift = 0;
  193721. sp--;
  193722. }
  193723. else
  193724. shift = 4;
  193725. dp--;
  193726. }
  193727. break;
  193728. }
  193729. }
  193730. row_info->bit_depth = 8;
  193731. row_info->pixel_depth = 8;
  193732. row_info->rowbytes = row_width;
  193733. }
  193734. if (trans_value != NULL)
  193735. {
  193736. if (row_info->bit_depth == 8)
  193737. {
  193738. gray = gray & 0xff;
  193739. sp = row + (png_size_t)row_width - 1;
  193740. dp = row + (png_size_t)(row_width << 1) - 1;
  193741. for (i = 0; i < row_width; i++)
  193742. {
  193743. if (*sp == gray)
  193744. *dp-- = 0;
  193745. else
  193746. *dp-- = 0xff;
  193747. *dp-- = *sp--;
  193748. }
  193749. }
  193750. else if (row_info->bit_depth == 16)
  193751. {
  193752. png_byte gray_high = (gray >> 8) & 0xff;
  193753. png_byte gray_low = gray & 0xff;
  193754. sp = row + row_info->rowbytes - 1;
  193755. dp = row + (row_info->rowbytes << 1) - 1;
  193756. for (i = 0; i < row_width; i++)
  193757. {
  193758. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193759. {
  193760. *dp-- = 0;
  193761. *dp-- = 0;
  193762. }
  193763. else
  193764. {
  193765. *dp-- = 0xff;
  193766. *dp-- = 0xff;
  193767. }
  193768. *dp-- = *sp--;
  193769. *dp-- = *sp--;
  193770. }
  193771. }
  193772. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193773. row_info->channels = 2;
  193774. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193775. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193776. row_width);
  193777. }
  193778. }
  193779. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193780. {
  193781. if (row_info->bit_depth == 8)
  193782. {
  193783. png_byte red = trans_value->red & 0xff;
  193784. png_byte green = trans_value->green & 0xff;
  193785. png_byte blue = trans_value->blue & 0xff;
  193786. sp = row + (png_size_t)row_info->rowbytes - 1;
  193787. dp = row + (png_size_t)(row_width << 2) - 1;
  193788. for (i = 0; i < row_width; i++)
  193789. {
  193790. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193791. *dp-- = 0;
  193792. else
  193793. *dp-- = 0xff;
  193794. *dp-- = *sp--;
  193795. *dp-- = *sp--;
  193796. *dp-- = *sp--;
  193797. }
  193798. }
  193799. else if (row_info->bit_depth == 16)
  193800. {
  193801. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193802. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193803. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193804. png_byte red_low = trans_value->red & 0xff;
  193805. png_byte green_low = trans_value->green & 0xff;
  193806. png_byte blue_low = trans_value->blue & 0xff;
  193807. sp = row + row_info->rowbytes - 1;
  193808. dp = row + (png_size_t)(row_width << 3) - 1;
  193809. for (i = 0; i < row_width; i++)
  193810. {
  193811. if (*(sp - 5) == red_high &&
  193812. *(sp - 4) == red_low &&
  193813. *(sp - 3) == green_high &&
  193814. *(sp - 2) == green_low &&
  193815. *(sp - 1) == blue_high &&
  193816. *(sp ) == blue_low)
  193817. {
  193818. *dp-- = 0;
  193819. *dp-- = 0;
  193820. }
  193821. else
  193822. {
  193823. *dp-- = 0xff;
  193824. *dp-- = 0xff;
  193825. }
  193826. *dp-- = *sp--;
  193827. *dp-- = *sp--;
  193828. *dp-- = *sp--;
  193829. *dp-- = *sp--;
  193830. *dp-- = *sp--;
  193831. *dp-- = *sp--;
  193832. }
  193833. }
  193834. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193835. row_info->channels = 4;
  193836. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193837. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193838. }
  193839. }
  193840. }
  193841. #endif
  193842. #if defined(PNG_READ_DITHER_SUPPORTED)
  193843. void /* PRIVATE */
  193844. png_do_dither(png_row_infop row_info, png_bytep row,
  193845. png_bytep palette_lookup, png_bytep dither_lookup)
  193846. {
  193847. png_bytep sp, dp;
  193848. png_uint_32 i;
  193849. png_uint_32 row_width=row_info->width;
  193850. png_debug(1, "in png_do_dither\n");
  193851. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193852. if (row != NULL && row_info != NULL)
  193853. #endif
  193854. {
  193855. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193856. palette_lookup && row_info->bit_depth == 8)
  193857. {
  193858. int r, g, b, p;
  193859. sp = row;
  193860. dp = row;
  193861. for (i = 0; i < row_width; i++)
  193862. {
  193863. r = *sp++;
  193864. g = *sp++;
  193865. b = *sp++;
  193866. /* this looks real messy, but the compiler will reduce
  193867. it down to a reasonable formula. For example, with
  193868. 5 bits per color, we get:
  193869. p = (((r >> 3) & 0x1f) << 10) |
  193870. (((g >> 3) & 0x1f) << 5) |
  193871. ((b >> 3) & 0x1f);
  193872. */
  193873. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193874. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193875. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193876. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193877. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193878. (PNG_DITHER_BLUE_BITS)) |
  193879. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193880. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193881. *dp++ = palette_lookup[p];
  193882. }
  193883. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193884. row_info->channels = 1;
  193885. row_info->pixel_depth = row_info->bit_depth;
  193886. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193887. }
  193888. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193889. palette_lookup != NULL && row_info->bit_depth == 8)
  193890. {
  193891. int r, g, b, p;
  193892. sp = row;
  193893. dp = row;
  193894. for (i = 0; i < row_width; i++)
  193895. {
  193896. r = *sp++;
  193897. g = *sp++;
  193898. b = *sp++;
  193899. sp++;
  193900. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193901. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193902. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193903. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193904. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193905. (PNG_DITHER_BLUE_BITS)) |
  193906. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193907. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193908. *dp++ = palette_lookup[p];
  193909. }
  193910. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193911. row_info->channels = 1;
  193912. row_info->pixel_depth = row_info->bit_depth;
  193913. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193914. }
  193915. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193916. dither_lookup && row_info->bit_depth == 8)
  193917. {
  193918. sp = row;
  193919. for (i = 0; i < row_width; i++, sp++)
  193920. {
  193921. *sp = dither_lookup[*sp];
  193922. }
  193923. }
  193924. }
  193925. }
  193926. #endif
  193927. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193928. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193929. static PNG_CONST int png_gamma_shift[] =
  193930. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193931. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193932. * tables, we don't make a full table if we are reducing to 8-bit in
  193933. * the future. Note also how the gamma_16 tables are segmented so that
  193934. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193935. */
  193936. void /* PRIVATE */
  193937. png_build_gamma_table(png_structp png_ptr)
  193938. {
  193939. png_debug(1, "in png_build_gamma_table\n");
  193940. if (png_ptr->bit_depth <= 8)
  193941. {
  193942. int i;
  193943. double g;
  193944. if (png_ptr->screen_gamma > .000001)
  193945. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193946. else
  193947. g = 1.0;
  193948. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193949. (png_uint_32)256);
  193950. for (i = 0; i < 256; i++)
  193951. {
  193952. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193953. g) * 255.0 + .5);
  193954. }
  193955. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193956. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193957. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193958. {
  193959. g = 1.0 / (png_ptr->gamma);
  193960. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193961. (png_uint_32)256);
  193962. for (i = 0; i < 256; i++)
  193963. {
  193964. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193965. g) * 255.0 + .5);
  193966. }
  193967. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193968. (png_uint_32)256);
  193969. if(png_ptr->screen_gamma > 0.000001)
  193970. g = 1.0 / png_ptr->screen_gamma;
  193971. else
  193972. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193973. for (i = 0; i < 256; i++)
  193974. {
  193975. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193976. g) * 255.0 + .5);
  193977. }
  193978. }
  193979. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193980. }
  193981. else
  193982. {
  193983. double g;
  193984. int i, j, shift, num;
  193985. int sig_bit;
  193986. png_uint_32 ig;
  193987. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193988. {
  193989. sig_bit = (int)png_ptr->sig_bit.red;
  193990. if ((int)png_ptr->sig_bit.green > sig_bit)
  193991. sig_bit = png_ptr->sig_bit.green;
  193992. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193993. sig_bit = png_ptr->sig_bit.blue;
  193994. }
  193995. else
  193996. {
  193997. sig_bit = (int)png_ptr->sig_bit.gray;
  193998. }
  193999. if (sig_bit > 0)
  194000. shift = 16 - sig_bit;
  194001. else
  194002. shift = 0;
  194003. if (png_ptr->transformations & PNG_16_TO_8)
  194004. {
  194005. if (shift < (16 - PNG_MAX_GAMMA_8))
  194006. shift = (16 - PNG_MAX_GAMMA_8);
  194007. }
  194008. if (shift > 8)
  194009. shift = 8;
  194010. if (shift < 0)
  194011. shift = 0;
  194012. png_ptr->gamma_shift = (png_byte)shift;
  194013. num = (1 << (8 - shift));
  194014. if (png_ptr->screen_gamma > .000001)
  194015. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194016. else
  194017. g = 1.0;
  194018. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  194019. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194020. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  194021. {
  194022. double fin, fout;
  194023. png_uint_32 last, max;
  194024. for (i = 0; i < num; i++)
  194025. {
  194026. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194027. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194028. }
  194029. g = 1.0 / g;
  194030. last = 0;
  194031. for (i = 0; i < 256; i++)
  194032. {
  194033. fout = ((double)i + 0.5) / 256.0;
  194034. fin = pow(fout, g);
  194035. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  194036. while (last <= max)
  194037. {
  194038. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194039. [(int)(last >> (8 - shift))] = (png_uint_16)(
  194040. (png_uint_16)i | ((png_uint_16)i << 8));
  194041. last++;
  194042. }
  194043. }
  194044. while (last < ((png_uint_32)num << 8))
  194045. {
  194046. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194047. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  194048. last++;
  194049. }
  194050. }
  194051. else
  194052. {
  194053. for (i = 0; i < num; i++)
  194054. {
  194055. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194056. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194057. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  194058. for (j = 0; j < 256; j++)
  194059. {
  194060. png_ptr->gamma_16_table[i][j] =
  194061. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194062. 65535.0, g) * 65535.0 + .5);
  194063. }
  194064. }
  194065. }
  194066. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194067. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194068. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  194069. {
  194070. g = 1.0 / (png_ptr->gamma);
  194071. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  194072. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  194073. for (i = 0; i < num; i++)
  194074. {
  194075. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194076. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194077. ig = (((png_uint_32)i *
  194078. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194079. for (j = 0; j < 256; j++)
  194080. {
  194081. png_ptr->gamma_16_to_1[i][j] =
  194082. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194083. 65535.0, g) * 65535.0 + .5);
  194084. }
  194085. }
  194086. if(png_ptr->screen_gamma > 0.000001)
  194087. g = 1.0 / png_ptr->screen_gamma;
  194088. else
  194089. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194090. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  194091. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194092. for (i = 0; i < num; i++)
  194093. {
  194094. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194095. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194096. ig = (((png_uint_32)i *
  194097. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194098. for (j = 0; j < 256; j++)
  194099. {
  194100. png_ptr->gamma_16_from_1[i][j] =
  194101. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194102. 65535.0, g) * 65535.0 + .5);
  194103. }
  194104. }
  194105. }
  194106. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194107. }
  194108. }
  194109. #endif
  194110. /* To do: install integer version of png_build_gamma_table here */
  194111. #endif
  194112. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194113. /* undoes intrapixel differencing */
  194114. void /* PRIVATE */
  194115. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194116. {
  194117. png_debug(1, "in png_do_read_intrapixel\n");
  194118. if (
  194119. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194120. row != NULL && row_info != NULL &&
  194121. #endif
  194122. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194123. {
  194124. int bytes_per_pixel;
  194125. png_uint_32 row_width = row_info->width;
  194126. if (row_info->bit_depth == 8)
  194127. {
  194128. png_bytep rp;
  194129. png_uint_32 i;
  194130. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194131. bytes_per_pixel = 3;
  194132. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194133. bytes_per_pixel = 4;
  194134. else
  194135. return;
  194136. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194137. {
  194138. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194139. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194140. }
  194141. }
  194142. else if (row_info->bit_depth == 16)
  194143. {
  194144. png_bytep rp;
  194145. png_uint_32 i;
  194146. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194147. bytes_per_pixel = 6;
  194148. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194149. bytes_per_pixel = 8;
  194150. else
  194151. return;
  194152. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194153. {
  194154. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194155. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194156. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194157. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194158. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194159. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194160. *(rp+1) = (png_byte)(red & 0xff);
  194161. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194162. *(rp+5) = (png_byte)(blue & 0xff);
  194163. }
  194164. }
  194165. }
  194166. }
  194167. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194168. #endif /* PNG_READ_SUPPORTED */
  194169. /*** End of inlined file: pngrtran.c ***/
  194170. /*** Start of inlined file: pngrutil.c ***/
  194171. /* pngrutil.c - utilities to read a PNG file
  194172. *
  194173. * Last changed in libpng 1.2.21 [October 4, 2007]
  194174. * For conditions of distribution and use, see copyright notice in png.h
  194175. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194176. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194177. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194178. *
  194179. * This file contains routines that are only called from within
  194180. * libpng itself during the course of reading an image.
  194181. */
  194182. #define PNG_INTERNAL
  194183. #if defined(PNG_READ_SUPPORTED)
  194184. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194185. # define WIN32_WCE_OLD
  194186. #endif
  194187. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194188. # if defined(WIN32_WCE_OLD)
  194189. /* strtod() function is not supported on WindowsCE */
  194190. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194191. {
  194192. double result = 0;
  194193. int len;
  194194. wchar_t *str, *end;
  194195. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194196. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194197. if ( NULL != str )
  194198. {
  194199. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194200. result = wcstod(str, &end);
  194201. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194202. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194203. png_free(png_ptr, str);
  194204. }
  194205. return result;
  194206. }
  194207. # else
  194208. # define png_strtod(p,a,b) strtod(a,b)
  194209. # endif
  194210. #endif
  194211. png_uint_32 PNGAPI
  194212. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194213. {
  194214. png_uint_32 i = png_get_uint_32(buf);
  194215. if (i > PNG_UINT_31_MAX)
  194216. png_error(png_ptr, "PNG unsigned integer out of range.");
  194217. return (i);
  194218. }
  194219. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194220. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194221. png_uint_32 PNGAPI
  194222. png_get_uint_32(png_bytep buf)
  194223. {
  194224. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194225. ((png_uint_32)(*(buf + 1)) << 16) +
  194226. ((png_uint_32)(*(buf + 2)) << 8) +
  194227. (png_uint_32)(*(buf + 3));
  194228. return (i);
  194229. }
  194230. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194231. * data is stored in the PNG file in two's complement format, and it is
  194232. * assumed that the machine format for signed integers is the same. */
  194233. png_int_32 PNGAPI
  194234. png_get_int_32(png_bytep buf)
  194235. {
  194236. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194237. ((png_int_32)(*(buf + 1)) << 16) +
  194238. ((png_int_32)(*(buf + 2)) << 8) +
  194239. (png_int_32)(*(buf + 3));
  194240. return (i);
  194241. }
  194242. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194243. png_uint_16 PNGAPI
  194244. png_get_uint_16(png_bytep buf)
  194245. {
  194246. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194247. (png_uint_16)(*(buf + 1)));
  194248. return (i);
  194249. }
  194250. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194251. /* Read data, and (optionally) run it through the CRC. */
  194252. void /* PRIVATE */
  194253. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194254. {
  194255. if(png_ptr == NULL) return;
  194256. png_read_data(png_ptr, buf, length);
  194257. png_calculate_crc(png_ptr, buf, length);
  194258. }
  194259. /* Optionally skip data and then check the CRC. Depending on whether we
  194260. are reading a ancillary or critical chunk, and how the program has set
  194261. things up, we may calculate the CRC on the data and print a message.
  194262. Returns '1' if there was a CRC error, '0' otherwise. */
  194263. int /* PRIVATE */
  194264. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194265. {
  194266. png_size_t i;
  194267. png_size_t istop = png_ptr->zbuf_size;
  194268. for (i = (png_size_t)skip; i > istop; i -= istop)
  194269. {
  194270. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194271. }
  194272. if (i)
  194273. {
  194274. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194275. }
  194276. if (png_crc_error(png_ptr))
  194277. {
  194278. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194279. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194280. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194281. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194282. {
  194283. png_chunk_warning(png_ptr, "CRC error");
  194284. }
  194285. else
  194286. {
  194287. png_chunk_error(png_ptr, "CRC error");
  194288. }
  194289. return (1);
  194290. }
  194291. return (0);
  194292. }
  194293. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194294. the data it has read thus far. */
  194295. int /* PRIVATE */
  194296. png_crc_error(png_structp png_ptr)
  194297. {
  194298. png_byte crc_bytes[4];
  194299. png_uint_32 crc;
  194300. int need_crc = 1;
  194301. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194302. {
  194303. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194304. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194305. need_crc = 0;
  194306. }
  194307. else /* critical */
  194308. {
  194309. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194310. need_crc = 0;
  194311. }
  194312. png_read_data(png_ptr, crc_bytes, 4);
  194313. if (need_crc)
  194314. {
  194315. crc = png_get_uint_32(crc_bytes);
  194316. return ((int)(crc != png_ptr->crc));
  194317. }
  194318. else
  194319. return (0);
  194320. }
  194321. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194322. defined(PNG_READ_iCCP_SUPPORTED)
  194323. /*
  194324. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194325. * points at an allocated area holding the contents of a chunk with a
  194326. * trailing compressed part. What we get back is an allocated area
  194327. * holding the original prefix part and an uncompressed version of the
  194328. * trailing part (the malloc area passed in is freed).
  194329. */
  194330. png_charp /* PRIVATE */
  194331. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194332. png_charp chunkdata, png_size_t chunklength,
  194333. png_size_t prefix_size, png_size_t *newlength)
  194334. {
  194335. static PNG_CONST char msg[] = "Error decoding compressed text";
  194336. png_charp text;
  194337. png_size_t text_size;
  194338. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194339. {
  194340. int ret = Z_OK;
  194341. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194342. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194343. png_ptr->zstream.next_out = png_ptr->zbuf;
  194344. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194345. text_size = 0;
  194346. text = NULL;
  194347. while (png_ptr->zstream.avail_in)
  194348. {
  194349. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194350. if (ret != Z_OK && ret != Z_STREAM_END)
  194351. {
  194352. if (png_ptr->zstream.msg != NULL)
  194353. png_warning(png_ptr, png_ptr->zstream.msg);
  194354. else
  194355. png_warning(png_ptr, msg);
  194356. inflateReset(&png_ptr->zstream);
  194357. png_ptr->zstream.avail_in = 0;
  194358. if (text == NULL)
  194359. {
  194360. text_size = prefix_size + png_sizeof(msg) + 1;
  194361. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194362. if (text == NULL)
  194363. {
  194364. png_free(png_ptr,chunkdata);
  194365. png_error(png_ptr,"Not enough memory to decompress chunk");
  194366. }
  194367. png_memcpy(text, chunkdata, prefix_size);
  194368. }
  194369. text[text_size - 1] = 0x00;
  194370. /* Copy what we can of the error message into the text chunk */
  194371. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194372. text_size = png_sizeof(msg) > text_size ? text_size :
  194373. png_sizeof(msg);
  194374. png_memcpy(text + prefix_size, msg, text_size + 1);
  194375. break;
  194376. }
  194377. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194378. {
  194379. if (text == NULL)
  194380. {
  194381. text_size = prefix_size +
  194382. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194383. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194384. if (text == NULL)
  194385. {
  194386. png_free(png_ptr,chunkdata);
  194387. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194388. }
  194389. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194390. text_size - prefix_size);
  194391. png_memcpy(text, chunkdata, prefix_size);
  194392. *(text + text_size) = 0x00;
  194393. }
  194394. else
  194395. {
  194396. png_charp tmp;
  194397. tmp = text;
  194398. text = (png_charp)png_malloc_warn(png_ptr,
  194399. (png_uint_32)(text_size +
  194400. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194401. if (text == NULL)
  194402. {
  194403. png_free(png_ptr, tmp);
  194404. png_free(png_ptr, chunkdata);
  194405. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194406. }
  194407. png_memcpy(text, tmp, text_size);
  194408. png_free(png_ptr, tmp);
  194409. png_memcpy(text + text_size, png_ptr->zbuf,
  194410. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194411. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194412. *(text + text_size) = 0x00;
  194413. }
  194414. if (ret == Z_STREAM_END)
  194415. break;
  194416. else
  194417. {
  194418. png_ptr->zstream.next_out = png_ptr->zbuf;
  194419. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194420. }
  194421. }
  194422. }
  194423. if (ret != Z_STREAM_END)
  194424. {
  194425. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194426. char umsg[52];
  194427. if (ret == Z_BUF_ERROR)
  194428. png_snprintf(umsg, 52,
  194429. "Buffer error in compressed datastream in %s chunk",
  194430. png_ptr->chunk_name);
  194431. else if (ret == Z_DATA_ERROR)
  194432. png_snprintf(umsg, 52,
  194433. "Data error in compressed datastream in %s chunk",
  194434. png_ptr->chunk_name);
  194435. else
  194436. png_snprintf(umsg, 52,
  194437. "Incomplete compressed datastream in %s chunk",
  194438. png_ptr->chunk_name);
  194439. png_warning(png_ptr, umsg);
  194440. #else
  194441. png_warning(png_ptr,
  194442. "Incomplete compressed datastream in chunk other than IDAT");
  194443. #endif
  194444. text_size=prefix_size;
  194445. if (text == NULL)
  194446. {
  194447. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194448. if (text == NULL)
  194449. {
  194450. png_free(png_ptr, chunkdata);
  194451. png_error(png_ptr,"Not enough memory for text.");
  194452. }
  194453. png_memcpy(text, chunkdata, prefix_size);
  194454. }
  194455. *(text + text_size) = 0x00;
  194456. }
  194457. inflateReset(&png_ptr->zstream);
  194458. png_ptr->zstream.avail_in = 0;
  194459. png_free(png_ptr, chunkdata);
  194460. chunkdata = text;
  194461. *newlength=text_size;
  194462. }
  194463. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194464. {
  194465. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194466. char umsg[50];
  194467. png_snprintf(umsg, 50,
  194468. "Unknown zTXt compression type %d", comp_type);
  194469. png_warning(png_ptr, umsg);
  194470. #else
  194471. png_warning(png_ptr, "Unknown zTXt compression type");
  194472. #endif
  194473. *(chunkdata + prefix_size) = 0x00;
  194474. *newlength=prefix_size;
  194475. }
  194476. return chunkdata;
  194477. }
  194478. #endif
  194479. /* read and check the IDHR chunk */
  194480. void /* PRIVATE */
  194481. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194482. {
  194483. png_byte buf[13];
  194484. png_uint_32 width, height;
  194485. int bit_depth, color_type, compression_type, filter_type;
  194486. int interlace_type;
  194487. png_debug(1, "in png_handle_IHDR\n");
  194488. if (png_ptr->mode & PNG_HAVE_IHDR)
  194489. png_error(png_ptr, "Out of place IHDR");
  194490. /* check the length */
  194491. if (length != 13)
  194492. png_error(png_ptr, "Invalid IHDR chunk");
  194493. png_ptr->mode |= PNG_HAVE_IHDR;
  194494. png_crc_read(png_ptr, buf, 13);
  194495. png_crc_finish(png_ptr, 0);
  194496. width = png_get_uint_31(png_ptr, buf);
  194497. height = png_get_uint_31(png_ptr, buf + 4);
  194498. bit_depth = buf[8];
  194499. color_type = buf[9];
  194500. compression_type = buf[10];
  194501. filter_type = buf[11];
  194502. interlace_type = buf[12];
  194503. /* set internal variables */
  194504. png_ptr->width = width;
  194505. png_ptr->height = height;
  194506. png_ptr->bit_depth = (png_byte)bit_depth;
  194507. png_ptr->interlaced = (png_byte)interlace_type;
  194508. png_ptr->color_type = (png_byte)color_type;
  194509. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194510. png_ptr->filter_type = (png_byte)filter_type;
  194511. #endif
  194512. png_ptr->compression_type = (png_byte)compression_type;
  194513. /* find number of channels */
  194514. switch (png_ptr->color_type)
  194515. {
  194516. case PNG_COLOR_TYPE_GRAY:
  194517. case PNG_COLOR_TYPE_PALETTE:
  194518. png_ptr->channels = 1;
  194519. break;
  194520. case PNG_COLOR_TYPE_RGB:
  194521. png_ptr->channels = 3;
  194522. break;
  194523. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194524. png_ptr->channels = 2;
  194525. break;
  194526. case PNG_COLOR_TYPE_RGB_ALPHA:
  194527. png_ptr->channels = 4;
  194528. break;
  194529. }
  194530. /* set up other useful info */
  194531. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194532. png_ptr->channels);
  194533. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194534. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194535. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194536. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194537. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194538. color_type, interlace_type, compression_type, filter_type);
  194539. }
  194540. /* read and check the palette */
  194541. void /* PRIVATE */
  194542. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194543. {
  194544. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194545. int num, i;
  194546. #ifndef PNG_NO_POINTER_INDEXING
  194547. png_colorp pal_ptr;
  194548. #endif
  194549. png_debug(1, "in png_handle_PLTE\n");
  194550. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194551. png_error(png_ptr, "Missing IHDR before PLTE");
  194552. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194553. {
  194554. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194555. png_crc_finish(png_ptr, length);
  194556. return;
  194557. }
  194558. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194559. png_error(png_ptr, "Duplicate PLTE chunk");
  194560. png_ptr->mode |= PNG_HAVE_PLTE;
  194561. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194562. {
  194563. png_warning(png_ptr,
  194564. "Ignoring PLTE chunk in grayscale PNG");
  194565. png_crc_finish(png_ptr, length);
  194566. return;
  194567. }
  194568. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194569. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194570. {
  194571. png_crc_finish(png_ptr, length);
  194572. return;
  194573. }
  194574. #endif
  194575. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194576. {
  194577. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194578. {
  194579. png_warning(png_ptr, "Invalid palette chunk");
  194580. png_crc_finish(png_ptr, length);
  194581. return;
  194582. }
  194583. else
  194584. {
  194585. png_error(png_ptr, "Invalid palette chunk");
  194586. }
  194587. }
  194588. num = (int)length / 3;
  194589. #ifndef PNG_NO_POINTER_INDEXING
  194590. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194591. {
  194592. png_byte buf[3];
  194593. png_crc_read(png_ptr, buf, 3);
  194594. pal_ptr->red = buf[0];
  194595. pal_ptr->green = buf[1];
  194596. pal_ptr->blue = buf[2];
  194597. }
  194598. #else
  194599. for (i = 0; i < num; i++)
  194600. {
  194601. png_byte buf[3];
  194602. png_crc_read(png_ptr, buf, 3);
  194603. /* don't depend upon png_color being any order */
  194604. palette[i].red = buf[0];
  194605. palette[i].green = buf[1];
  194606. palette[i].blue = buf[2];
  194607. }
  194608. #endif
  194609. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194610. whatever the normal CRC configuration tells us. However, if we
  194611. have an RGB image, the PLTE can be considered ancillary, so
  194612. we will act as though it is. */
  194613. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194614. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194615. #endif
  194616. {
  194617. png_crc_finish(png_ptr, 0);
  194618. }
  194619. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194620. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194621. {
  194622. /* If we don't want to use the data from an ancillary chunk,
  194623. we have two options: an error abort, or a warning and we
  194624. ignore the data in this chunk (which should be OK, since
  194625. it's considered ancillary for a RGB or RGBA image). */
  194626. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194627. {
  194628. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194629. {
  194630. png_chunk_error(png_ptr, "CRC error");
  194631. }
  194632. else
  194633. {
  194634. png_chunk_warning(png_ptr, "CRC error");
  194635. return;
  194636. }
  194637. }
  194638. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194639. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194640. {
  194641. png_chunk_warning(png_ptr, "CRC error");
  194642. }
  194643. }
  194644. #endif
  194645. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194646. #if defined(PNG_READ_tRNS_SUPPORTED)
  194647. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194648. {
  194649. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194650. {
  194651. if (png_ptr->num_trans > (png_uint_16)num)
  194652. {
  194653. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194654. png_ptr->num_trans = (png_uint_16)num;
  194655. }
  194656. if (info_ptr->num_trans > (png_uint_16)num)
  194657. {
  194658. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194659. info_ptr->num_trans = (png_uint_16)num;
  194660. }
  194661. }
  194662. }
  194663. #endif
  194664. }
  194665. void /* PRIVATE */
  194666. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194667. {
  194668. png_debug(1, "in png_handle_IEND\n");
  194669. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194670. {
  194671. png_error(png_ptr, "No image in file");
  194672. }
  194673. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194674. if (length != 0)
  194675. {
  194676. png_warning(png_ptr, "Incorrect IEND chunk length");
  194677. }
  194678. png_crc_finish(png_ptr, length);
  194679. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194680. }
  194681. #if defined(PNG_READ_gAMA_SUPPORTED)
  194682. void /* PRIVATE */
  194683. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194684. {
  194685. png_fixed_point igamma;
  194686. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194687. float file_gamma;
  194688. #endif
  194689. png_byte buf[4];
  194690. png_debug(1, "in png_handle_gAMA\n");
  194691. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194692. png_error(png_ptr, "Missing IHDR before gAMA");
  194693. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194694. {
  194695. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194696. png_crc_finish(png_ptr, length);
  194697. return;
  194698. }
  194699. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194700. /* Should be an error, but we can cope with it */
  194701. png_warning(png_ptr, "Out of place gAMA chunk");
  194702. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194703. #if defined(PNG_READ_sRGB_SUPPORTED)
  194704. && !(info_ptr->valid & PNG_INFO_sRGB)
  194705. #endif
  194706. )
  194707. {
  194708. png_warning(png_ptr, "Duplicate gAMA chunk");
  194709. png_crc_finish(png_ptr, length);
  194710. return;
  194711. }
  194712. if (length != 4)
  194713. {
  194714. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194715. png_crc_finish(png_ptr, length);
  194716. return;
  194717. }
  194718. png_crc_read(png_ptr, buf, 4);
  194719. if (png_crc_finish(png_ptr, 0))
  194720. return;
  194721. igamma = (png_fixed_point)png_get_uint_32(buf);
  194722. /* check for zero gamma */
  194723. if (igamma == 0)
  194724. {
  194725. png_warning(png_ptr,
  194726. "Ignoring gAMA chunk with gamma=0");
  194727. return;
  194728. }
  194729. #if defined(PNG_READ_sRGB_SUPPORTED)
  194730. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194731. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194732. {
  194733. png_warning(png_ptr,
  194734. "Ignoring incorrect gAMA value when sRGB is also present");
  194735. #ifndef PNG_NO_CONSOLE_IO
  194736. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194737. #endif
  194738. return;
  194739. }
  194740. #endif /* PNG_READ_sRGB_SUPPORTED */
  194741. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194742. file_gamma = (float)igamma / (float)100000.0;
  194743. # ifdef PNG_READ_GAMMA_SUPPORTED
  194744. png_ptr->gamma = file_gamma;
  194745. # endif
  194746. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194747. #endif
  194748. #ifdef PNG_FIXED_POINT_SUPPORTED
  194749. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194750. #endif
  194751. }
  194752. #endif
  194753. #if defined(PNG_READ_sBIT_SUPPORTED)
  194754. void /* PRIVATE */
  194755. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194756. {
  194757. png_size_t truelen;
  194758. png_byte buf[4];
  194759. png_debug(1, "in png_handle_sBIT\n");
  194760. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194761. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194762. png_error(png_ptr, "Missing IHDR before sBIT");
  194763. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194764. {
  194765. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194766. png_crc_finish(png_ptr, length);
  194767. return;
  194768. }
  194769. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194770. {
  194771. /* Should be an error, but we can cope with it */
  194772. png_warning(png_ptr, "Out of place sBIT chunk");
  194773. }
  194774. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194775. {
  194776. png_warning(png_ptr, "Duplicate sBIT chunk");
  194777. png_crc_finish(png_ptr, length);
  194778. return;
  194779. }
  194780. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194781. truelen = 3;
  194782. else
  194783. truelen = (png_size_t)png_ptr->channels;
  194784. if (length != truelen || length > 4)
  194785. {
  194786. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194787. png_crc_finish(png_ptr, length);
  194788. return;
  194789. }
  194790. png_crc_read(png_ptr, buf, truelen);
  194791. if (png_crc_finish(png_ptr, 0))
  194792. return;
  194793. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194794. {
  194795. png_ptr->sig_bit.red = buf[0];
  194796. png_ptr->sig_bit.green = buf[1];
  194797. png_ptr->sig_bit.blue = buf[2];
  194798. png_ptr->sig_bit.alpha = buf[3];
  194799. }
  194800. else
  194801. {
  194802. png_ptr->sig_bit.gray = buf[0];
  194803. png_ptr->sig_bit.red = buf[0];
  194804. png_ptr->sig_bit.green = buf[0];
  194805. png_ptr->sig_bit.blue = buf[0];
  194806. png_ptr->sig_bit.alpha = buf[1];
  194807. }
  194808. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194809. }
  194810. #endif
  194811. #if defined(PNG_READ_cHRM_SUPPORTED)
  194812. void /* PRIVATE */
  194813. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194814. {
  194815. png_byte buf[4];
  194816. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194817. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194818. #endif
  194819. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194820. int_y_green, int_x_blue, int_y_blue;
  194821. png_uint_32 uint_x, uint_y;
  194822. png_debug(1, "in png_handle_cHRM\n");
  194823. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194824. png_error(png_ptr, "Missing IHDR before cHRM");
  194825. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194826. {
  194827. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194828. png_crc_finish(png_ptr, length);
  194829. return;
  194830. }
  194831. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194832. /* Should be an error, but we can cope with it */
  194833. png_warning(png_ptr, "Missing PLTE before cHRM");
  194834. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194835. #if defined(PNG_READ_sRGB_SUPPORTED)
  194836. && !(info_ptr->valid & PNG_INFO_sRGB)
  194837. #endif
  194838. )
  194839. {
  194840. png_warning(png_ptr, "Duplicate cHRM chunk");
  194841. png_crc_finish(png_ptr, length);
  194842. return;
  194843. }
  194844. if (length != 32)
  194845. {
  194846. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194847. png_crc_finish(png_ptr, length);
  194848. return;
  194849. }
  194850. png_crc_read(png_ptr, buf, 4);
  194851. uint_x = png_get_uint_32(buf);
  194852. png_crc_read(png_ptr, buf, 4);
  194853. uint_y = png_get_uint_32(buf);
  194854. if (uint_x > 80000L || uint_y > 80000L ||
  194855. uint_x + uint_y > 100000L)
  194856. {
  194857. png_warning(png_ptr, "Invalid cHRM white point");
  194858. png_crc_finish(png_ptr, 24);
  194859. return;
  194860. }
  194861. int_x_white = (png_fixed_point)uint_x;
  194862. int_y_white = (png_fixed_point)uint_y;
  194863. png_crc_read(png_ptr, buf, 4);
  194864. uint_x = png_get_uint_32(buf);
  194865. png_crc_read(png_ptr, buf, 4);
  194866. uint_y = png_get_uint_32(buf);
  194867. if (uint_x + uint_y > 100000L)
  194868. {
  194869. png_warning(png_ptr, "Invalid cHRM red point");
  194870. png_crc_finish(png_ptr, 16);
  194871. return;
  194872. }
  194873. int_x_red = (png_fixed_point)uint_x;
  194874. int_y_red = (png_fixed_point)uint_y;
  194875. png_crc_read(png_ptr, buf, 4);
  194876. uint_x = png_get_uint_32(buf);
  194877. png_crc_read(png_ptr, buf, 4);
  194878. uint_y = png_get_uint_32(buf);
  194879. if (uint_x + uint_y > 100000L)
  194880. {
  194881. png_warning(png_ptr, "Invalid cHRM green point");
  194882. png_crc_finish(png_ptr, 8);
  194883. return;
  194884. }
  194885. int_x_green = (png_fixed_point)uint_x;
  194886. int_y_green = (png_fixed_point)uint_y;
  194887. png_crc_read(png_ptr, buf, 4);
  194888. uint_x = png_get_uint_32(buf);
  194889. png_crc_read(png_ptr, buf, 4);
  194890. uint_y = png_get_uint_32(buf);
  194891. if (uint_x + uint_y > 100000L)
  194892. {
  194893. png_warning(png_ptr, "Invalid cHRM blue point");
  194894. png_crc_finish(png_ptr, 0);
  194895. return;
  194896. }
  194897. int_x_blue = (png_fixed_point)uint_x;
  194898. int_y_blue = (png_fixed_point)uint_y;
  194899. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194900. white_x = (float)int_x_white / (float)100000.0;
  194901. white_y = (float)int_y_white / (float)100000.0;
  194902. red_x = (float)int_x_red / (float)100000.0;
  194903. red_y = (float)int_y_red / (float)100000.0;
  194904. green_x = (float)int_x_green / (float)100000.0;
  194905. green_y = (float)int_y_green / (float)100000.0;
  194906. blue_x = (float)int_x_blue / (float)100000.0;
  194907. blue_y = (float)int_y_blue / (float)100000.0;
  194908. #endif
  194909. #if defined(PNG_READ_sRGB_SUPPORTED)
  194910. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194911. {
  194912. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194913. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194914. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194915. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194916. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194917. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194918. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194919. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194920. {
  194921. png_warning(png_ptr,
  194922. "Ignoring incorrect cHRM value when sRGB is also present");
  194923. #ifndef PNG_NO_CONSOLE_IO
  194924. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194925. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194926. white_x, white_y, red_x, red_y);
  194927. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194928. green_x, green_y, blue_x, blue_y);
  194929. #else
  194930. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194931. int_x_white, int_y_white, int_x_red, int_y_red);
  194932. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194933. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194934. #endif
  194935. #endif /* PNG_NO_CONSOLE_IO */
  194936. }
  194937. png_crc_finish(png_ptr, 0);
  194938. return;
  194939. }
  194940. #endif /* PNG_READ_sRGB_SUPPORTED */
  194941. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194942. png_set_cHRM(png_ptr, info_ptr,
  194943. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194944. #endif
  194945. #ifdef PNG_FIXED_POINT_SUPPORTED
  194946. png_set_cHRM_fixed(png_ptr, info_ptr,
  194947. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194948. int_y_green, int_x_blue, int_y_blue);
  194949. #endif
  194950. if (png_crc_finish(png_ptr, 0))
  194951. return;
  194952. }
  194953. #endif
  194954. #if defined(PNG_READ_sRGB_SUPPORTED)
  194955. void /* PRIVATE */
  194956. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194957. {
  194958. int intent;
  194959. png_byte buf[1];
  194960. png_debug(1, "in png_handle_sRGB\n");
  194961. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194962. png_error(png_ptr, "Missing IHDR before sRGB");
  194963. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194964. {
  194965. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194966. png_crc_finish(png_ptr, length);
  194967. return;
  194968. }
  194969. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194970. /* Should be an error, but we can cope with it */
  194971. png_warning(png_ptr, "Out of place sRGB chunk");
  194972. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194973. {
  194974. png_warning(png_ptr, "Duplicate sRGB chunk");
  194975. png_crc_finish(png_ptr, length);
  194976. return;
  194977. }
  194978. if (length != 1)
  194979. {
  194980. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194981. png_crc_finish(png_ptr, length);
  194982. return;
  194983. }
  194984. png_crc_read(png_ptr, buf, 1);
  194985. if (png_crc_finish(png_ptr, 0))
  194986. return;
  194987. intent = buf[0];
  194988. /* check for bad intent */
  194989. if (intent >= PNG_sRGB_INTENT_LAST)
  194990. {
  194991. png_warning(png_ptr, "Unknown sRGB intent");
  194992. return;
  194993. }
  194994. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194995. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194996. {
  194997. png_fixed_point igamma;
  194998. #ifdef PNG_FIXED_POINT_SUPPORTED
  194999. igamma=info_ptr->int_gamma;
  195000. #else
  195001. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195002. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  195003. # endif
  195004. #endif
  195005. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  195006. {
  195007. png_warning(png_ptr,
  195008. "Ignoring incorrect gAMA value when sRGB is also present");
  195009. #ifndef PNG_NO_CONSOLE_IO
  195010. # ifdef PNG_FIXED_POINT_SUPPORTED
  195011. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  195012. # else
  195013. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195014. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  195015. # endif
  195016. # endif
  195017. #endif
  195018. }
  195019. }
  195020. #endif /* PNG_READ_gAMA_SUPPORTED */
  195021. #ifdef PNG_READ_cHRM_SUPPORTED
  195022. #ifdef PNG_FIXED_POINT_SUPPORTED
  195023. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  195024. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  195025. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  195026. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  195027. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  195028. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  195029. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  195030. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  195031. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  195032. {
  195033. png_warning(png_ptr,
  195034. "Ignoring incorrect cHRM value when sRGB is also present");
  195035. }
  195036. #endif /* PNG_FIXED_POINT_SUPPORTED */
  195037. #endif /* PNG_READ_cHRM_SUPPORTED */
  195038. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  195039. }
  195040. #endif /* PNG_READ_sRGB_SUPPORTED */
  195041. #if defined(PNG_READ_iCCP_SUPPORTED)
  195042. void /* PRIVATE */
  195043. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195044. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195045. {
  195046. png_charp chunkdata;
  195047. png_byte compression_type;
  195048. png_bytep pC;
  195049. png_charp profile;
  195050. png_uint_32 skip = 0;
  195051. png_uint_32 profile_size, profile_length;
  195052. png_size_t slength, prefix_length, data_length;
  195053. png_debug(1, "in png_handle_iCCP\n");
  195054. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195055. png_error(png_ptr, "Missing IHDR before iCCP");
  195056. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195057. {
  195058. png_warning(png_ptr, "Invalid iCCP after IDAT");
  195059. png_crc_finish(png_ptr, length);
  195060. return;
  195061. }
  195062. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195063. /* Should be an error, but we can cope with it */
  195064. png_warning(png_ptr, "Out of place iCCP chunk");
  195065. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  195066. {
  195067. png_warning(png_ptr, "Duplicate iCCP chunk");
  195068. png_crc_finish(png_ptr, length);
  195069. return;
  195070. }
  195071. #ifdef PNG_MAX_MALLOC_64K
  195072. if (length > (png_uint_32)65535L)
  195073. {
  195074. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  195075. skip = length - (png_uint_32)65535L;
  195076. length = (png_uint_32)65535L;
  195077. }
  195078. #endif
  195079. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  195080. slength = (png_size_t)length;
  195081. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195082. if (png_crc_finish(png_ptr, skip))
  195083. {
  195084. png_free(png_ptr, chunkdata);
  195085. return;
  195086. }
  195087. chunkdata[slength] = 0x00;
  195088. for (profile = chunkdata; *profile; profile++)
  195089. /* empty loop to find end of name */ ;
  195090. ++profile;
  195091. /* there should be at least one zero (the compression type byte)
  195092. following the separator, and we should be on it */
  195093. if ( profile >= chunkdata + slength - 1)
  195094. {
  195095. png_free(png_ptr, chunkdata);
  195096. png_warning(png_ptr, "Malformed iCCP chunk");
  195097. return;
  195098. }
  195099. /* compression_type should always be zero */
  195100. compression_type = *profile++;
  195101. if (compression_type)
  195102. {
  195103. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  195104. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  195105. wrote nonzero) */
  195106. }
  195107. prefix_length = profile - chunkdata;
  195108. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  195109. slength, prefix_length, &data_length);
  195110. profile_length = data_length - prefix_length;
  195111. if ( prefix_length > data_length || profile_length < 4)
  195112. {
  195113. png_free(png_ptr, chunkdata);
  195114. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195115. return;
  195116. }
  195117. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195118. pC = (png_bytep)(chunkdata+prefix_length);
  195119. profile_size = ((*(pC ))<<24) |
  195120. ((*(pC+1))<<16) |
  195121. ((*(pC+2))<< 8) |
  195122. ((*(pC+3)) );
  195123. if(profile_size < profile_length)
  195124. profile_length = profile_size;
  195125. if(profile_size > profile_length)
  195126. {
  195127. png_free(png_ptr, chunkdata);
  195128. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195129. return;
  195130. }
  195131. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195132. chunkdata + prefix_length, profile_length);
  195133. png_free(png_ptr, chunkdata);
  195134. }
  195135. #endif /* PNG_READ_iCCP_SUPPORTED */
  195136. #if defined(PNG_READ_sPLT_SUPPORTED)
  195137. void /* PRIVATE */
  195138. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195139. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195140. {
  195141. png_bytep chunkdata;
  195142. png_bytep entry_start;
  195143. png_sPLT_t new_palette;
  195144. #ifdef PNG_NO_POINTER_INDEXING
  195145. png_sPLT_entryp pp;
  195146. #endif
  195147. int data_length, entry_size, i;
  195148. png_uint_32 skip = 0;
  195149. png_size_t slength;
  195150. png_debug(1, "in png_handle_sPLT\n");
  195151. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195152. png_error(png_ptr, "Missing IHDR before sPLT");
  195153. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195154. {
  195155. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195156. png_crc_finish(png_ptr, length);
  195157. return;
  195158. }
  195159. #ifdef PNG_MAX_MALLOC_64K
  195160. if (length > (png_uint_32)65535L)
  195161. {
  195162. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195163. skip = length - (png_uint_32)65535L;
  195164. length = (png_uint_32)65535L;
  195165. }
  195166. #endif
  195167. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195168. slength = (png_size_t)length;
  195169. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195170. if (png_crc_finish(png_ptr, skip))
  195171. {
  195172. png_free(png_ptr, chunkdata);
  195173. return;
  195174. }
  195175. chunkdata[slength] = 0x00;
  195176. for (entry_start = chunkdata; *entry_start; entry_start++)
  195177. /* empty loop to find end of name */ ;
  195178. ++entry_start;
  195179. /* a sample depth should follow the separator, and we should be on it */
  195180. if (entry_start > chunkdata + slength - 2)
  195181. {
  195182. png_free(png_ptr, chunkdata);
  195183. png_warning(png_ptr, "malformed sPLT chunk");
  195184. return;
  195185. }
  195186. new_palette.depth = *entry_start++;
  195187. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195188. data_length = (slength - (entry_start - chunkdata));
  195189. /* integrity-check the data length */
  195190. if (data_length % entry_size)
  195191. {
  195192. png_free(png_ptr, chunkdata);
  195193. png_warning(png_ptr, "sPLT chunk has bad length");
  195194. return;
  195195. }
  195196. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195197. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195198. png_sizeof(png_sPLT_entry)))
  195199. {
  195200. png_warning(png_ptr, "sPLT chunk too long");
  195201. return;
  195202. }
  195203. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195204. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195205. if (new_palette.entries == NULL)
  195206. {
  195207. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195208. return;
  195209. }
  195210. #ifndef PNG_NO_POINTER_INDEXING
  195211. for (i = 0; i < new_palette.nentries; i++)
  195212. {
  195213. png_sPLT_entryp pp = new_palette.entries + i;
  195214. if (new_palette.depth == 8)
  195215. {
  195216. pp->red = *entry_start++;
  195217. pp->green = *entry_start++;
  195218. pp->blue = *entry_start++;
  195219. pp->alpha = *entry_start++;
  195220. }
  195221. else
  195222. {
  195223. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195224. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195225. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195226. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195227. }
  195228. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195229. }
  195230. #else
  195231. pp = new_palette.entries;
  195232. for (i = 0; i < new_palette.nentries; i++)
  195233. {
  195234. if (new_palette.depth == 8)
  195235. {
  195236. pp[i].red = *entry_start++;
  195237. pp[i].green = *entry_start++;
  195238. pp[i].blue = *entry_start++;
  195239. pp[i].alpha = *entry_start++;
  195240. }
  195241. else
  195242. {
  195243. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195244. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195245. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195246. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195247. }
  195248. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195249. }
  195250. #endif
  195251. /* discard all chunk data except the name and stash that */
  195252. new_palette.name = (png_charp)chunkdata;
  195253. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195254. png_free(png_ptr, chunkdata);
  195255. png_free(png_ptr, new_palette.entries);
  195256. }
  195257. #endif /* PNG_READ_sPLT_SUPPORTED */
  195258. #if defined(PNG_READ_tRNS_SUPPORTED)
  195259. void /* PRIVATE */
  195260. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195261. {
  195262. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195263. int bit_mask;
  195264. png_debug(1, "in png_handle_tRNS\n");
  195265. /* For non-indexed color, mask off any bits in the tRNS value that
  195266. * exceed the bit depth. Some creators were writing extra bits there.
  195267. * This is not needed for indexed color. */
  195268. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195269. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195270. png_error(png_ptr, "Missing IHDR before tRNS");
  195271. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195272. {
  195273. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195274. png_crc_finish(png_ptr, length);
  195275. return;
  195276. }
  195277. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195278. {
  195279. png_warning(png_ptr, "Duplicate tRNS chunk");
  195280. png_crc_finish(png_ptr, length);
  195281. return;
  195282. }
  195283. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195284. {
  195285. png_byte buf[2];
  195286. if (length != 2)
  195287. {
  195288. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195289. png_crc_finish(png_ptr, length);
  195290. return;
  195291. }
  195292. png_crc_read(png_ptr, buf, 2);
  195293. png_ptr->num_trans = 1;
  195294. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195295. }
  195296. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195297. {
  195298. png_byte buf[6];
  195299. if (length != 6)
  195300. {
  195301. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195302. png_crc_finish(png_ptr, length);
  195303. return;
  195304. }
  195305. png_crc_read(png_ptr, buf, (png_size_t)length);
  195306. png_ptr->num_trans = 1;
  195307. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195308. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195309. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195310. }
  195311. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195312. {
  195313. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195314. {
  195315. /* Should be an error, but we can cope with it. */
  195316. png_warning(png_ptr, "Missing PLTE before tRNS");
  195317. }
  195318. if (length > (png_uint_32)png_ptr->num_palette ||
  195319. length > PNG_MAX_PALETTE_LENGTH)
  195320. {
  195321. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195322. png_crc_finish(png_ptr, length);
  195323. return;
  195324. }
  195325. if (length == 0)
  195326. {
  195327. png_warning(png_ptr, "Zero length tRNS chunk");
  195328. png_crc_finish(png_ptr, length);
  195329. return;
  195330. }
  195331. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195332. png_ptr->num_trans = (png_uint_16)length;
  195333. }
  195334. else
  195335. {
  195336. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195337. png_crc_finish(png_ptr, length);
  195338. return;
  195339. }
  195340. if (png_crc_finish(png_ptr, 0))
  195341. {
  195342. png_ptr->num_trans = 0;
  195343. return;
  195344. }
  195345. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195346. &(png_ptr->trans_values));
  195347. }
  195348. #endif
  195349. #if defined(PNG_READ_bKGD_SUPPORTED)
  195350. void /* PRIVATE */
  195351. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195352. {
  195353. png_size_t truelen;
  195354. png_byte buf[6];
  195355. png_debug(1, "in png_handle_bKGD\n");
  195356. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195357. png_error(png_ptr, "Missing IHDR before bKGD");
  195358. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195359. {
  195360. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195361. png_crc_finish(png_ptr, length);
  195362. return;
  195363. }
  195364. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195365. !(png_ptr->mode & PNG_HAVE_PLTE))
  195366. {
  195367. png_warning(png_ptr, "Missing PLTE before bKGD");
  195368. png_crc_finish(png_ptr, length);
  195369. return;
  195370. }
  195371. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195372. {
  195373. png_warning(png_ptr, "Duplicate bKGD chunk");
  195374. png_crc_finish(png_ptr, length);
  195375. return;
  195376. }
  195377. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195378. truelen = 1;
  195379. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195380. truelen = 6;
  195381. else
  195382. truelen = 2;
  195383. if (length != truelen)
  195384. {
  195385. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195386. png_crc_finish(png_ptr, length);
  195387. return;
  195388. }
  195389. png_crc_read(png_ptr, buf, truelen);
  195390. if (png_crc_finish(png_ptr, 0))
  195391. return;
  195392. /* We convert the index value into RGB components so that we can allow
  195393. * arbitrary RGB values for background when we have transparency, and
  195394. * so it is easy to determine the RGB values of the background color
  195395. * from the info_ptr struct. */
  195396. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195397. {
  195398. png_ptr->background.index = buf[0];
  195399. if(info_ptr->num_palette)
  195400. {
  195401. if(buf[0] > info_ptr->num_palette)
  195402. {
  195403. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195404. return;
  195405. }
  195406. png_ptr->background.red =
  195407. (png_uint_16)png_ptr->palette[buf[0]].red;
  195408. png_ptr->background.green =
  195409. (png_uint_16)png_ptr->palette[buf[0]].green;
  195410. png_ptr->background.blue =
  195411. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195412. }
  195413. }
  195414. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195415. {
  195416. png_ptr->background.red =
  195417. png_ptr->background.green =
  195418. png_ptr->background.blue =
  195419. png_ptr->background.gray = png_get_uint_16(buf);
  195420. }
  195421. else
  195422. {
  195423. png_ptr->background.red = png_get_uint_16(buf);
  195424. png_ptr->background.green = png_get_uint_16(buf + 2);
  195425. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195426. }
  195427. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195428. }
  195429. #endif
  195430. #if defined(PNG_READ_hIST_SUPPORTED)
  195431. void /* PRIVATE */
  195432. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195433. {
  195434. unsigned int num, i;
  195435. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195436. png_debug(1, "in png_handle_hIST\n");
  195437. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195438. png_error(png_ptr, "Missing IHDR before hIST");
  195439. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195440. {
  195441. png_warning(png_ptr, "Invalid hIST after IDAT");
  195442. png_crc_finish(png_ptr, length);
  195443. return;
  195444. }
  195445. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195446. {
  195447. png_warning(png_ptr, "Missing PLTE before hIST");
  195448. png_crc_finish(png_ptr, length);
  195449. return;
  195450. }
  195451. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195452. {
  195453. png_warning(png_ptr, "Duplicate hIST chunk");
  195454. png_crc_finish(png_ptr, length);
  195455. return;
  195456. }
  195457. num = length / 2 ;
  195458. if (num != (unsigned int) png_ptr->num_palette || num >
  195459. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195460. {
  195461. png_warning(png_ptr, "Incorrect hIST chunk length");
  195462. png_crc_finish(png_ptr, length);
  195463. return;
  195464. }
  195465. for (i = 0; i < num; i++)
  195466. {
  195467. png_byte buf[2];
  195468. png_crc_read(png_ptr, buf, 2);
  195469. readbuf[i] = png_get_uint_16(buf);
  195470. }
  195471. if (png_crc_finish(png_ptr, 0))
  195472. return;
  195473. png_set_hIST(png_ptr, info_ptr, readbuf);
  195474. }
  195475. #endif
  195476. #if defined(PNG_READ_pHYs_SUPPORTED)
  195477. void /* PRIVATE */
  195478. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195479. {
  195480. png_byte buf[9];
  195481. png_uint_32 res_x, res_y;
  195482. int unit_type;
  195483. png_debug(1, "in png_handle_pHYs\n");
  195484. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195485. png_error(png_ptr, "Missing IHDR before pHYs");
  195486. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195487. {
  195488. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195489. png_crc_finish(png_ptr, length);
  195490. return;
  195491. }
  195492. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195493. {
  195494. png_warning(png_ptr, "Duplicate pHYs chunk");
  195495. png_crc_finish(png_ptr, length);
  195496. return;
  195497. }
  195498. if (length != 9)
  195499. {
  195500. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195501. png_crc_finish(png_ptr, length);
  195502. return;
  195503. }
  195504. png_crc_read(png_ptr, buf, 9);
  195505. if (png_crc_finish(png_ptr, 0))
  195506. return;
  195507. res_x = png_get_uint_32(buf);
  195508. res_y = png_get_uint_32(buf + 4);
  195509. unit_type = buf[8];
  195510. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195511. }
  195512. #endif
  195513. #if defined(PNG_READ_oFFs_SUPPORTED)
  195514. void /* PRIVATE */
  195515. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195516. {
  195517. png_byte buf[9];
  195518. png_int_32 offset_x, offset_y;
  195519. int unit_type;
  195520. png_debug(1, "in png_handle_oFFs\n");
  195521. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195522. png_error(png_ptr, "Missing IHDR before oFFs");
  195523. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195524. {
  195525. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195526. png_crc_finish(png_ptr, length);
  195527. return;
  195528. }
  195529. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195530. {
  195531. png_warning(png_ptr, "Duplicate oFFs chunk");
  195532. png_crc_finish(png_ptr, length);
  195533. return;
  195534. }
  195535. if (length != 9)
  195536. {
  195537. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195538. png_crc_finish(png_ptr, length);
  195539. return;
  195540. }
  195541. png_crc_read(png_ptr, buf, 9);
  195542. if (png_crc_finish(png_ptr, 0))
  195543. return;
  195544. offset_x = png_get_int_32(buf);
  195545. offset_y = png_get_int_32(buf + 4);
  195546. unit_type = buf[8];
  195547. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195548. }
  195549. #endif
  195550. #if defined(PNG_READ_pCAL_SUPPORTED)
  195551. /* read the pCAL chunk (described in the PNG Extensions document) */
  195552. void /* PRIVATE */
  195553. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195554. {
  195555. png_charp purpose;
  195556. png_int_32 X0, X1;
  195557. png_byte type, nparams;
  195558. png_charp buf, units, endptr;
  195559. png_charpp params;
  195560. png_size_t slength;
  195561. int i;
  195562. png_debug(1, "in png_handle_pCAL\n");
  195563. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195564. png_error(png_ptr, "Missing IHDR before pCAL");
  195565. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195566. {
  195567. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195568. png_crc_finish(png_ptr, length);
  195569. return;
  195570. }
  195571. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195572. {
  195573. png_warning(png_ptr, "Duplicate pCAL chunk");
  195574. png_crc_finish(png_ptr, length);
  195575. return;
  195576. }
  195577. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195578. length + 1);
  195579. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195580. if (purpose == NULL)
  195581. {
  195582. png_warning(png_ptr, "No memory for pCAL purpose.");
  195583. return;
  195584. }
  195585. slength = (png_size_t)length;
  195586. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195587. if (png_crc_finish(png_ptr, 0))
  195588. {
  195589. png_free(png_ptr, purpose);
  195590. return;
  195591. }
  195592. purpose[slength] = 0x00; /* null terminate the last string */
  195593. png_debug(3, "Finding end of pCAL purpose string\n");
  195594. for (buf = purpose; *buf; buf++)
  195595. /* empty loop */ ;
  195596. endptr = purpose + slength;
  195597. /* We need to have at least 12 bytes after the purpose string
  195598. in order to get the parameter information. */
  195599. if (endptr <= buf + 12)
  195600. {
  195601. png_warning(png_ptr, "Invalid pCAL data");
  195602. png_free(png_ptr, purpose);
  195603. return;
  195604. }
  195605. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195606. X0 = png_get_int_32((png_bytep)buf+1);
  195607. X1 = png_get_int_32((png_bytep)buf+5);
  195608. type = buf[9];
  195609. nparams = buf[10];
  195610. units = buf + 11;
  195611. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195612. /* Check that we have the right number of parameters for known
  195613. equation types. */
  195614. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195615. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195616. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195617. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195618. {
  195619. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195620. png_free(png_ptr, purpose);
  195621. return;
  195622. }
  195623. else if (type >= PNG_EQUATION_LAST)
  195624. {
  195625. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195626. }
  195627. for (buf = units; *buf; buf++)
  195628. /* Empty loop to move past the units string. */ ;
  195629. png_debug(3, "Allocating pCAL parameters array\n");
  195630. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195631. *png_sizeof(png_charp))) ;
  195632. if (params == NULL)
  195633. {
  195634. png_free(png_ptr, purpose);
  195635. png_warning(png_ptr, "No memory for pCAL params.");
  195636. return;
  195637. }
  195638. /* Get pointers to the start of each parameter string. */
  195639. for (i = 0; i < (int)nparams; i++)
  195640. {
  195641. buf++; /* Skip the null string terminator from previous parameter. */
  195642. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195643. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195644. /* Empty loop to move past each parameter string */ ;
  195645. /* Make sure we haven't run out of data yet */
  195646. if (buf > endptr)
  195647. {
  195648. png_warning(png_ptr, "Invalid pCAL data");
  195649. png_free(png_ptr, purpose);
  195650. png_free(png_ptr, params);
  195651. return;
  195652. }
  195653. }
  195654. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195655. units, params);
  195656. png_free(png_ptr, purpose);
  195657. png_free(png_ptr, params);
  195658. }
  195659. #endif
  195660. #if defined(PNG_READ_sCAL_SUPPORTED)
  195661. /* read the sCAL chunk */
  195662. void /* PRIVATE */
  195663. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195664. {
  195665. png_charp buffer, ep;
  195666. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195667. double width, height;
  195668. png_charp vp;
  195669. #else
  195670. #ifdef PNG_FIXED_POINT_SUPPORTED
  195671. png_charp swidth, sheight;
  195672. #endif
  195673. #endif
  195674. png_size_t slength;
  195675. png_debug(1, "in png_handle_sCAL\n");
  195676. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195677. png_error(png_ptr, "Missing IHDR before sCAL");
  195678. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195679. {
  195680. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195681. png_crc_finish(png_ptr, length);
  195682. return;
  195683. }
  195684. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195685. {
  195686. png_warning(png_ptr, "Duplicate sCAL chunk");
  195687. png_crc_finish(png_ptr, length);
  195688. return;
  195689. }
  195690. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195691. length + 1);
  195692. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195693. if (buffer == NULL)
  195694. {
  195695. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195696. return;
  195697. }
  195698. slength = (png_size_t)length;
  195699. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195700. if (png_crc_finish(png_ptr, 0))
  195701. {
  195702. png_free(png_ptr, buffer);
  195703. return;
  195704. }
  195705. buffer[slength] = 0x00; /* null terminate the last string */
  195706. ep = buffer + 1; /* skip unit byte */
  195707. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195708. width = png_strtod(png_ptr, ep, &vp);
  195709. if (*vp)
  195710. {
  195711. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195712. return;
  195713. }
  195714. #else
  195715. #ifdef PNG_FIXED_POINT_SUPPORTED
  195716. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195717. if (swidth == NULL)
  195718. {
  195719. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195720. return;
  195721. }
  195722. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195723. #endif
  195724. #endif
  195725. for (ep = buffer; *ep; ep++)
  195726. /* empty loop */ ;
  195727. ep++;
  195728. if (buffer + slength < ep)
  195729. {
  195730. png_warning(png_ptr, "Truncated sCAL chunk");
  195731. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195732. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195733. png_free(png_ptr, swidth);
  195734. #endif
  195735. png_free(png_ptr, buffer);
  195736. return;
  195737. }
  195738. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195739. height = png_strtod(png_ptr, ep, &vp);
  195740. if (*vp)
  195741. {
  195742. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195743. return;
  195744. }
  195745. #else
  195746. #ifdef PNG_FIXED_POINT_SUPPORTED
  195747. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195748. if (swidth == NULL)
  195749. {
  195750. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195751. return;
  195752. }
  195753. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195754. #endif
  195755. #endif
  195756. if (buffer + slength < ep
  195757. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195758. || width <= 0. || height <= 0.
  195759. #endif
  195760. )
  195761. {
  195762. png_warning(png_ptr, "Invalid sCAL data");
  195763. png_free(png_ptr, buffer);
  195764. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195765. png_free(png_ptr, swidth);
  195766. png_free(png_ptr, sheight);
  195767. #endif
  195768. return;
  195769. }
  195770. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195771. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195772. #else
  195773. #ifdef PNG_FIXED_POINT_SUPPORTED
  195774. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195775. #endif
  195776. #endif
  195777. png_free(png_ptr, buffer);
  195778. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195779. png_free(png_ptr, swidth);
  195780. png_free(png_ptr, sheight);
  195781. #endif
  195782. }
  195783. #endif
  195784. #if defined(PNG_READ_tIME_SUPPORTED)
  195785. void /* PRIVATE */
  195786. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195787. {
  195788. png_byte buf[7];
  195789. png_time mod_time;
  195790. png_debug(1, "in png_handle_tIME\n");
  195791. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195792. png_error(png_ptr, "Out of place tIME chunk");
  195793. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195794. {
  195795. png_warning(png_ptr, "Duplicate tIME chunk");
  195796. png_crc_finish(png_ptr, length);
  195797. return;
  195798. }
  195799. if (png_ptr->mode & PNG_HAVE_IDAT)
  195800. png_ptr->mode |= PNG_AFTER_IDAT;
  195801. if (length != 7)
  195802. {
  195803. png_warning(png_ptr, "Incorrect tIME chunk length");
  195804. png_crc_finish(png_ptr, length);
  195805. return;
  195806. }
  195807. png_crc_read(png_ptr, buf, 7);
  195808. if (png_crc_finish(png_ptr, 0))
  195809. return;
  195810. mod_time.second = buf[6];
  195811. mod_time.minute = buf[5];
  195812. mod_time.hour = buf[4];
  195813. mod_time.day = buf[3];
  195814. mod_time.month = buf[2];
  195815. mod_time.year = png_get_uint_16(buf);
  195816. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195817. }
  195818. #endif
  195819. #if defined(PNG_READ_tEXt_SUPPORTED)
  195820. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195821. void /* PRIVATE */
  195822. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195823. {
  195824. png_textp text_ptr;
  195825. png_charp key;
  195826. png_charp text;
  195827. png_uint_32 skip = 0;
  195828. png_size_t slength;
  195829. int ret;
  195830. png_debug(1, "in png_handle_tEXt\n");
  195831. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195832. png_error(png_ptr, "Missing IHDR before tEXt");
  195833. if (png_ptr->mode & PNG_HAVE_IDAT)
  195834. png_ptr->mode |= PNG_AFTER_IDAT;
  195835. #ifdef PNG_MAX_MALLOC_64K
  195836. if (length > (png_uint_32)65535L)
  195837. {
  195838. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195839. skip = length - (png_uint_32)65535L;
  195840. length = (png_uint_32)65535L;
  195841. }
  195842. #endif
  195843. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195844. if (key == NULL)
  195845. {
  195846. png_warning(png_ptr, "No memory to process text chunk.");
  195847. return;
  195848. }
  195849. slength = (png_size_t)length;
  195850. png_crc_read(png_ptr, (png_bytep)key, slength);
  195851. if (png_crc_finish(png_ptr, skip))
  195852. {
  195853. png_free(png_ptr, key);
  195854. return;
  195855. }
  195856. key[slength] = 0x00;
  195857. for (text = key; *text; text++)
  195858. /* empty loop to find end of key */ ;
  195859. if (text != key + slength)
  195860. text++;
  195861. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195862. (png_uint_32)png_sizeof(png_text));
  195863. if (text_ptr == NULL)
  195864. {
  195865. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195866. png_free(png_ptr, key);
  195867. return;
  195868. }
  195869. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195870. text_ptr->key = key;
  195871. #ifdef PNG_iTXt_SUPPORTED
  195872. text_ptr->lang = NULL;
  195873. text_ptr->lang_key = NULL;
  195874. text_ptr->itxt_length = 0;
  195875. #endif
  195876. text_ptr->text = text;
  195877. text_ptr->text_length = png_strlen(text);
  195878. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195879. png_free(png_ptr, key);
  195880. png_free(png_ptr, text_ptr);
  195881. if (ret)
  195882. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195883. }
  195884. #endif
  195885. #if defined(PNG_READ_zTXt_SUPPORTED)
  195886. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195887. void /* PRIVATE */
  195888. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195889. {
  195890. png_textp text_ptr;
  195891. png_charp chunkdata;
  195892. png_charp text;
  195893. int comp_type;
  195894. int ret;
  195895. png_size_t slength, prefix_len, data_len;
  195896. png_debug(1, "in png_handle_zTXt\n");
  195897. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195898. png_error(png_ptr, "Missing IHDR before zTXt");
  195899. if (png_ptr->mode & PNG_HAVE_IDAT)
  195900. png_ptr->mode |= PNG_AFTER_IDAT;
  195901. #ifdef PNG_MAX_MALLOC_64K
  195902. /* We will no doubt have problems with chunks even half this size, but
  195903. there is no hard and fast rule to tell us where to stop. */
  195904. if (length > (png_uint_32)65535L)
  195905. {
  195906. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195907. png_crc_finish(png_ptr, length);
  195908. return;
  195909. }
  195910. #endif
  195911. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195912. if (chunkdata == NULL)
  195913. {
  195914. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195915. return;
  195916. }
  195917. slength = (png_size_t)length;
  195918. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195919. if (png_crc_finish(png_ptr, 0))
  195920. {
  195921. png_free(png_ptr, chunkdata);
  195922. return;
  195923. }
  195924. chunkdata[slength] = 0x00;
  195925. for (text = chunkdata; *text; text++)
  195926. /* empty loop */ ;
  195927. /* zTXt must have some text after the chunkdataword */
  195928. if (text >= chunkdata + slength - 2)
  195929. {
  195930. png_warning(png_ptr, "Truncated zTXt chunk");
  195931. png_free(png_ptr, chunkdata);
  195932. return;
  195933. }
  195934. else
  195935. {
  195936. comp_type = *(++text);
  195937. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195938. {
  195939. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195940. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195941. }
  195942. text++; /* skip the compression_method byte */
  195943. }
  195944. prefix_len = text - chunkdata;
  195945. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195946. (png_size_t)length, prefix_len, &data_len);
  195947. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195948. (png_uint_32)png_sizeof(png_text));
  195949. if (text_ptr == NULL)
  195950. {
  195951. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195952. png_free(png_ptr, chunkdata);
  195953. return;
  195954. }
  195955. text_ptr->compression = comp_type;
  195956. text_ptr->key = chunkdata;
  195957. #ifdef PNG_iTXt_SUPPORTED
  195958. text_ptr->lang = NULL;
  195959. text_ptr->lang_key = NULL;
  195960. text_ptr->itxt_length = 0;
  195961. #endif
  195962. text_ptr->text = chunkdata + prefix_len;
  195963. text_ptr->text_length = data_len;
  195964. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195965. png_free(png_ptr, text_ptr);
  195966. png_free(png_ptr, chunkdata);
  195967. if (ret)
  195968. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195969. }
  195970. #endif
  195971. #if defined(PNG_READ_iTXt_SUPPORTED)
  195972. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195973. void /* PRIVATE */
  195974. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195975. {
  195976. png_textp text_ptr;
  195977. png_charp chunkdata;
  195978. png_charp key, lang, text, lang_key;
  195979. int comp_flag;
  195980. int comp_type = 0;
  195981. int ret;
  195982. png_size_t slength, prefix_len, data_len;
  195983. png_debug(1, "in png_handle_iTXt\n");
  195984. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195985. png_error(png_ptr, "Missing IHDR before iTXt");
  195986. if (png_ptr->mode & PNG_HAVE_IDAT)
  195987. png_ptr->mode |= PNG_AFTER_IDAT;
  195988. #ifdef PNG_MAX_MALLOC_64K
  195989. /* We will no doubt have problems with chunks even half this size, but
  195990. there is no hard and fast rule to tell us where to stop. */
  195991. if (length > (png_uint_32)65535L)
  195992. {
  195993. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195994. png_crc_finish(png_ptr, length);
  195995. return;
  195996. }
  195997. #endif
  195998. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195999. if (chunkdata == NULL)
  196000. {
  196001. png_warning(png_ptr, "No memory to process iTXt chunk.");
  196002. return;
  196003. }
  196004. slength = (png_size_t)length;
  196005. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  196006. if (png_crc_finish(png_ptr, 0))
  196007. {
  196008. png_free(png_ptr, chunkdata);
  196009. return;
  196010. }
  196011. chunkdata[slength] = 0x00;
  196012. for (lang = chunkdata; *lang; lang++)
  196013. /* empty loop */ ;
  196014. lang++; /* skip NUL separator */
  196015. /* iTXt must have a language tag (possibly empty), two compression bytes,
  196016. translated keyword (possibly empty), and possibly some text after the
  196017. keyword */
  196018. if (lang >= chunkdata + slength - 3)
  196019. {
  196020. png_warning(png_ptr, "Truncated iTXt chunk");
  196021. png_free(png_ptr, chunkdata);
  196022. return;
  196023. }
  196024. else
  196025. {
  196026. comp_flag = *lang++;
  196027. comp_type = *lang++;
  196028. }
  196029. for (lang_key = lang; *lang_key; lang_key++)
  196030. /* empty loop */ ;
  196031. lang_key++; /* skip NUL separator */
  196032. if (lang_key >= chunkdata + slength)
  196033. {
  196034. png_warning(png_ptr, "Truncated iTXt chunk");
  196035. png_free(png_ptr, chunkdata);
  196036. return;
  196037. }
  196038. for (text = lang_key; *text; text++)
  196039. /* empty loop */ ;
  196040. text++; /* skip NUL separator */
  196041. if (text >= chunkdata + slength)
  196042. {
  196043. png_warning(png_ptr, "Malformed iTXt chunk");
  196044. png_free(png_ptr, chunkdata);
  196045. return;
  196046. }
  196047. prefix_len = text - chunkdata;
  196048. key=chunkdata;
  196049. if (comp_flag)
  196050. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196051. (size_t)length, prefix_len, &data_len);
  196052. else
  196053. data_len=png_strlen(chunkdata + prefix_len);
  196054. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196055. (png_uint_32)png_sizeof(png_text));
  196056. if (text_ptr == NULL)
  196057. {
  196058. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  196059. png_free(png_ptr, chunkdata);
  196060. return;
  196061. }
  196062. text_ptr->compression = (int)comp_flag + 1;
  196063. text_ptr->lang_key = chunkdata+(lang_key-key);
  196064. text_ptr->lang = chunkdata+(lang-key);
  196065. text_ptr->itxt_length = data_len;
  196066. text_ptr->text_length = 0;
  196067. text_ptr->key = chunkdata;
  196068. text_ptr->text = chunkdata + prefix_len;
  196069. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196070. png_free(png_ptr, text_ptr);
  196071. png_free(png_ptr, chunkdata);
  196072. if (ret)
  196073. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  196074. }
  196075. #endif
  196076. /* This function is called when we haven't found a handler for a
  196077. chunk. If there isn't a problem with the chunk itself (ie bad
  196078. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  196079. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  196080. case it will be saved away to be written out later. */
  196081. void /* PRIVATE */
  196082. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196083. {
  196084. png_uint_32 skip = 0;
  196085. png_debug(1, "in png_handle_unknown\n");
  196086. if (png_ptr->mode & PNG_HAVE_IDAT)
  196087. {
  196088. #ifdef PNG_USE_LOCAL_ARRAYS
  196089. PNG_CONST PNG_IDAT;
  196090. #endif
  196091. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  196092. png_ptr->mode |= PNG_AFTER_IDAT;
  196093. }
  196094. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  196095. if (!(png_ptr->chunk_name[0] & 0x20))
  196096. {
  196097. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196098. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196099. PNG_HANDLE_CHUNK_ALWAYS
  196100. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196101. && png_ptr->read_user_chunk_fn == NULL
  196102. #endif
  196103. )
  196104. #endif
  196105. png_chunk_error(png_ptr, "unknown critical chunk");
  196106. }
  196107. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196108. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  196109. (png_ptr->read_user_chunk_fn != NULL))
  196110. {
  196111. #ifdef PNG_MAX_MALLOC_64K
  196112. if (length > (png_uint_32)65535L)
  196113. {
  196114. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196115. skip = length - (png_uint_32)65535L;
  196116. length = (png_uint_32)65535L;
  196117. }
  196118. #endif
  196119. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196120. (png_charp)png_ptr->chunk_name, 5);
  196121. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196122. png_ptr->unknown_chunk.size = (png_size_t)length;
  196123. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196124. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196125. if(png_ptr->read_user_chunk_fn != NULL)
  196126. {
  196127. /* callback to user unknown chunk handler */
  196128. int ret;
  196129. ret = (*(png_ptr->read_user_chunk_fn))
  196130. (png_ptr, &png_ptr->unknown_chunk);
  196131. if (ret < 0)
  196132. png_chunk_error(png_ptr, "error in user chunk");
  196133. if (ret == 0)
  196134. {
  196135. if (!(png_ptr->chunk_name[0] & 0x20))
  196136. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196137. PNG_HANDLE_CHUNK_ALWAYS)
  196138. png_chunk_error(png_ptr, "unknown critical chunk");
  196139. png_set_unknown_chunks(png_ptr, info_ptr,
  196140. &png_ptr->unknown_chunk, 1);
  196141. }
  196142. }
  196143. #else
  196144. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196145. #endif
  196146. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196147. png_ptr->unknown_chunk.data = NULL;
  196148. }
  196149. else
  196150. #endif
  196151. skip = length;
  196152. png_crc_finish(png_ptr, skip);
  196153. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196154. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196155. #endif
  196156. }
  196157. /* This function is called to verify that a chunk name is valid.
  196158. This function can't have the "critical chunk check" incorporated
  196159. into it, since in the future we will need to be able to call user
  196160. functions to handle unknown critical chunks after we check that
  196161. the chunk name itself is valid. */
  196162. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196163. void /* PRIVATE */
  196164. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196165. {
  196166. png_debug(1, "in png_check_chunk_name\n");
  196167. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196168. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196169. {
  196170. png_chunk_error(png_ptr, "invalid chunk type");
  196171. }
  196172. }
  196173. /* Combines the row recently read in with the existing pixels in the
  196174. row. This routine takes care of alpha and transparency if requested.
  196175. This routine also handles the two methods of progressive display
  196176. of interlaced images, depending on the mask value.
  196177. The mask value describes which pixels are to be combined with
  196178. the row. The pattern always repeats every 8 pixels, so just 8
  196179. bits are needed. A one indicates the pixel is to be combined,
  196180. a zero indicates the pixel is to be skipped. This is in addition
  196181. to any alpha or transparency value associated with the pixel. If
  196182. you want all pixels to be combined, pass 0xff (255) in mask. */
  196183. void /* PRIVATE */
  196184. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196185. {
  196186. png_debug(1,"in png_combine_row\n");
  196187. if (mask == 0xff)
  196188. {
  196189. png_memcpy(row, png_ptr->row_buf + 1,
  196190. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196191. }
  196192. else
  196193. {
  196194. switch (png_ptr->row_info.pixel_depth)
  196195. {
  196196. case 1:
  196197. {
  196198. png_bytep sp = png_ptr->row_buf + 1;
  196199. png_bytep dp = row;
  196200. int s_inc, s_start, s_end;
  196201. int m = 0x80;
  196202. int shift;
  196203. png_uint_32 i;
  196204. png_uint_32 row_width = png_ptr->width;
  196205. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196206. if (png_ptr->transformations & PNG_PACKSWAP)
  196207. {
  196208. s_start = 0;
  196209. s_end = 7;
  196210. s_inc = 1;
  196211. }
  196212. else
  196213. #endif
  196214. {
  196215. s_start = 7;
  196216. s_end = 0;
  196217. s_inc = -1;
  196218. }
  196219. shift = s_start;
  196220. for (i = 0; i < row_width; i++)
  196221. {
  196222. if (m & mask)
  196223. {
  196224. int value;
  196225. value = (*sp >> shift) & 0x01;
  196226. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196227. *dp |= (png_byte)(value << shift);
  196228. }
  196229. if (shift == s_end)
  196230. {
  196231. shift = s_start;
  196232. sp++;
  196233. dp++;
  196234. }
  196235. else
  196236. shift += s_inc;
  196237. if (m == 1)
  196238. m = 0x80;
  196239. else
  196240. m >>= 1;
  196241. }
  196242. break;
  196243. }
  196244. case 2:
  196245. {
  196246. png_bytep sp = png_ptr->row_buf + 1;
  196247. png_bytep dp = row;
  196248. int s_start, s_end, s_inc;
  196249. int m = 0x80;
  196250. int shift;
  196251. png_uint_32 i;
  196252. png_uint_32 row_width = png_ptr->width;
  196253. int value;
  196254. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196255. if (png_ptr->transformations & PNG_PACKSWAP)
  196256. {
  196257. s_start = 0;
  196258. s_end = 6;
  196259. s_inc = 2;
  196260. }
  196261. else
  196262. #endif
  196263. {
  196264. s_start = 6;
  196265. s_end = 0;
  196266. s_inc = -2;
  196267. }
  196268. shift = s_start;
  196269. for (i = 0; i < row_width; i++)
  196270. {
  196271. if (m & mask)
  196272. {
  196273. value = (*sp >> shift) & 0x03;
  196274. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196275. *dp |= (png_byte)(value << shift);
  196276. }
  196277. if (shift == s_end)
  196278. {
  196279. shift = s_start;
  196280. sp++;
  196281. dp++;
  196282. }
  196283. else
  196284. shift += s_inc;
  196285. if (m == 1)
  196286. m = 0x80;
  196287. else
  196288. m >>= 1;
  196289. }
  196290. break;
  196291. }
  196292. case 4:
  196293. {
  196294. png_bytep sp = png_ptr->row_buf + 1;
  196295. png_bytep dp = row;
  196296. int s_start, s_end, s_inc;
  196297. int m = 0x80;
  196298. int shift;
  196299. png_uint_32 i;
  196300. png_uint_32 row_width = png_ptr->width;
  196301. int value;
  196302. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196303. if (png_ptr->transformations & PNG_PACKSWAP)
  196304. {
  196305. s_start = 0;
  196306. s_end = 4;
  196307. s_inc = 4;
  196308. }
  196309. else
  196310. #endif
  196311. {
  196312. s_start = 4;
  196313. s_end = 0;
  196314. s_inc = -4;
  196315. }
  196316. shift = s_start;
  196317. for (i = 0; i < row_width; i++)
  196318. {
  196319. if (m & mask)
  196320. {
  196321. value = (*sp >> shift) & 0xf;
  196322. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196323. *dp |= (png_byte)(value << shift);
  196324. }
  196325. if (shift == s_end)
  196326. {
  196327. shift = s_start;
  196328. sp++;
  196329. dp++;
  196330. }
  196331. else
  196332. shift += s_inc;
  196333. if (m == 1)
  196334. m = 0x80;
  196335. else
  196336. m >>= 1;
  196337. }
  196338. break;
  196339. }
  196340. default:
  196341. {
  196342. png_bytep sp = png_ptr->row_buf + 1;
  196343. png_bytep dp = row;
  196344. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196345. png_uint_32 i;
  196346. png_uint_32 row_width = png_ptr->width;
  196347. png_byte m = 0x80;
  196348. for (i = 0; i < row_width; i++)
  196349. {
  196350. if (m & mask)
  196351. {
  196352. png_memcpy(dp, sp, pixel_bytes);
  196353. }
  196354. sp += pixel_bytes;
  196355. dp += pixel_bytes;
  196356. if (m == 1)
  196357. m = 0x80;
  196358. else
  196359. m >>= 1;
  196360. }
  196361. break;
  196362. }
  196363. }
  196364. }
  196365. }
  196366. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196367. /* OLD pre-1.0.9 interface:
  196368. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196369. png_uint_32 transformations)
  196370. */
  196371. void /* PRIVATE */
  196372. png_do_read_interlace(png_structp png_ptr)
  196373. {
  196374. png_row_infop row_info = &(png_ptr->row_info);
  196375. png_bytep row = png_ptr->row_buf + 1;
  196376. int pass = png_ptr->pass;
  196377. png_uint_32 transformations = png_ptr->transformations;
  196378. #ifdef PNG_USE_LOCAL_ARRAYS
  196379. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196380. /* offset to next interlace block */
  196381. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196382. #endif
  196383. png_debug(1,"in png_do_read_interlace\n");
  196384. if (row != NULL && row_info != NULL)
  196385. {
  196386. png_uint_32 final_width;
  196387. final_width = row_info->width * png_pass_inc[pass];
  196388. switch (row_info->pixel_depth)
  196389. {
  196390. case 1:
  196391. {
  196392. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196393. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196394. int sshift, dshift;
  196395. int s_start, s_end, s_inc;
  196396. int jstop = png_pass_inc[pass];
  196397. png_byte v;
  196398. png_uint_32 i;
  196399. int j;
  196400. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196401. if (transformations & PNG_PACKSWAP)
  196402. {
  196403. sshift = (int)((row_info->width + 7) & 0x07);
  196404. dshift = (int)((final_width + 7) & 0x07);
  196405. s_start = 7;
  196406. s_end = 0;
  196407. s_inc = -1;
  196408. }
  196409. else
  196410. #endif
  196411. {
  196412. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196413. dshift = 7 - (int)((final_width + 7) & 0x07);
  196414. s_start = 0;
  196415. s_end = 7;
  196416. s_inc = 1;
  196417. }
  196418. for (i = 0; i < row_info->width; i++)
  196419. {
  196420. v = (png_byte)((*sp >> sshift) & 0x01);
  196421. for (j = 0; j < jstop; j++)
  196422. {
  196423. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196424. *dp |= (png_byte)(v << dshift);
  196425. if (dshift == s_end)
  196426. {
  196427. dshift = s_start;
  196428. dp--;
  196429. }
  196430. else
  196431. dshift += s_inc;
  196432. }
  196433. if (sshift == s_end)
  196434. {
  196435. sshift = s_start;
  196436. sp--;
  196437. }
  196438. else
  196439. sshift += s_inc;
  196440. }
  196441. break;
  196442. }
  196443. case 2:
  196444. {
  196445. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196446. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196447. int sshift, dshift;
  196448. int s_start, s_end, s_inc;
  196449. int jstop = png_pass_inc[pass];
  196450. png_uint_32 i;
  196451. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196452. if (transformations & PNG_PACKSWAP)
  196453. {
  196454. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196455. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196456. s_start = 6;
  196457. s_end = 0;
  196458. s_inc = -2;
  196459. }
  196460. else
  196461. #endif
  196462. {
  196463. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196464. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196465. s_start = 0;
  196466. s_end = 6;
  196467. s_inc = 2;
  196468. }
  196469. for (i = 0; i < row_info->width; i++)
  196470. {
  196471. png_byte v;
  196472. int j;
  196473. v = (png_byte)((*sp >> sshift) & 0x03);
  196474. for (j = 0; j < jstop; j++)
  196475. {
  196476. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196477. *dp |= (png_byte)(v << dshift);
  196478. if (dshift == s_end)
  196479. {
  196480. dshift = s_start;
  196481. dp--;
  196482. }
  196483. else
  196484. dshift += s_inc;
  196485. }
  196486. if (sshift == s_end)
  196487. {
  196488. sshift = s_start;
  196489. sp--;
  196490. }
  196491. else
  196492. sshift += s_inc;
  196493. }
  196494. break;
  196495. }
  196496. case 4:
  196497. {
  196498. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196499. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196500. int sshift, dshift;
  196501. int s_start, s_end, s_inc;
  196502. png_uint_32 i;
  196503. int jstop = png_pass_inc[pass];
  196504. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196505. if (transformations & PNG_PACKSWAP)
  196506. {
  196507. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196508. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196509. s_start = 4;
  196510. s_end = 0;
  196511. s_inc = -4;
  196512. }
  196513. else
  196514. #endif
  196515. {
  196516. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196517. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196518. s_start = 0;
  196519. s_end = 4;
  196520. s_inc = 4;
  196521. }
  196522. for (i = 0; i < row_info->width; i++)
  196523. {
  196524. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196525. int j;
  196526. for (j = 0; j < jstop; j++)
  196527. {
  196528. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196529. *dp |= (png_byte)(v << dshift);
  196530. if (dshift == s_end)
  196531. {
  196532. dshift = s_start;
  196533. dp--;
  196534. }
  196535. else
  196536. dshift += s_inc;
  196537. }
  196538. if (sshift == s_end)
  196539. {
  196540. sshift = s_start;
  196541. sp--;
  196542. }
  196543. else
  196544. sshift += s_inc;
  196545. }
  196546. break;
  196547. }
  196548. default:
  196549. {
  196550. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196551. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196552. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196553. int jstop = png_pass_inc[pass];
  196554. png_uint_32 i;
  196555. for (i = 0; i < row_info->width; i++)
  196556. {
  196557. png_byte v[8];
  196558. int j;
  196559. png_memcpy(v, sp, pixel_bytes);
  196560. for (j = 0; j < jstop; j++)
  196561. {
  196562. png_memcpy(dp, v, pixel_bytes);
  196563. dp -= pixel_bytes;
  196564. }
  196565. sp -= pixel_bytes;
  196566. }
  196567. break;
  196568. }
  196569. }
  196570. row_info->width = final_width;
  196571. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196572. }
  196573. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196574. transformations = transformations; /* silence compiler warning */
  196575. #endif
  196576. }
  196577. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196578. void /* PRIVATE */
  196579. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196580. png_bytep prev_row, int filter)
  196581. {
  196582. png_debug(1, "in png_read_filter_row\n");
  196583. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196584. switch (filter)
  196585. {
  196586. case PNG_FILTER_VALUE_NONE:
  196587. break;
  196588. case PNG_FILTER_VALUE_SUB:
  196589. {
  196590. png_uint_32 i;
  196591. png_uint_32 istop = row_info->rowbytes;
  196592. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196593. png_bytep rp = row + bpp;
  196594. png_bytep lp = row;
  196595. for (i = bpp; i < istop; i++)
  196596. {
  196597. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196598. rp++;
  196599. }
  196600. break;
  196601. }
  196602. case PNG_FILTER_VALUE_UP:
  196603. {
  196604. png_uint_32 i;
  196605. png_uint_32 istop = row_info->rowbytes;
  196606. png_bytep rp = row;
  196607. png_bytep pp = prev_row;
  196608. for (i = 0; i < istop; i++)
  196609. {
  196610. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196611. rp++;
  196612. }
  196613. break;
  196614. }
  196615. case PNG_FILTER_VALUE_AVG:
  196616. {
  196617. png_uint_32 i;
  196618. png_bytep rp = row;
  196619. png_bytep pp = prev_row;
  196620. png_bytep lp = row;
  196621. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196622. png_uint_32 istop = row_info->rowbytes - bpp;
  196623. for (i = 0; i < bpp; i++)
  196624. {
  196625. *rp = (png_byte)(((int)(*rp) +
  196626. ((int)(*pp++) / 2 )) & 0xff);
  196627. rp++;
  196628. }
  196629. for (i = 0; i < istop; i++)
  196630. {
  196631. *rp = (png_byte)(((int)(*rp) +
  196632. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196633. rp++;
  196634. }
  196635. break;
  196636. }
  196637. case PNG_FILTER_VALUE_PAETH:
  196638. {
  196639. png_uint_32 i;
  196640. png_bytep rp = row;
  196641. png_bytep pp = prev_row;
  196642. png_bytep lp = row;
  196643. png_bytep cp = prev_row;
  196644. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196645. png_uint_32 istop=row_info->rowbytes - bpp;
  196646. for (i = 0; i < bpp; i++)
  196647. {
  196648. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196649. rp++;
  196650. }
  196651. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196652. {
  196653. int a, b, c, pa, pb, pc, p;
  196654. a = *lp++;
  196655. b = *pp++;
  196656. c = *cp++;
  196657. p = b - c;
  196658. pc = a - c;
  196659. #ifdef PNG_USE_ABS
  196660. pa = abs(p);
  196661. pb = abs(pc);
  196662. pc = abs(p + pc);
  196663. #else
  196664. pa = p < 0 ? -p : p;
  196665. pb = pc < 0 ? -pc : pc;
  196666. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196667. #endif
  196668. /*
  196669. if (pa <= pb && pa <= pc)
  196670. p = a;
  196671. else if (pb <= pc)
  196672. p = b;
  196673. else
  196674. p = c;
  196675. */
  196676. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196677. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196678. rp++;
  196679. }
  196680. break;
  196681. }
  196682. default:
  196683. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196684. *row=0;
  196685. break;
  196686. }
  196687. }
  196688. void /* PRIVATE */
  196689. png_read_finish_row(png_structp png_ptr)
  196690. {
  196691. #ifdef PNG_USE_LOCAL_ARRAYS
  196692. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196693. /* start of interlace block */
  196694. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196695. /* offset to next interlace block */
  196696. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196697. /* start of interlace block in the y direction */
  196698. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196699. /* offset to next interlace block in the y direction */
  196700. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196701. #endif
  196702. png_debug(1, "in png_read_finish_row\n");
  196703. png_ptr->row_number++;
  196704. if (png_ptr->row_number < png_ptr->num_rows)
  196705. return;
  196706. if (png_ptr->interlaced)
  196707. {
  196708. png_ptr->row_number = 0;
  196709. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196710. png_ptr->rowbytes + 1);
  196711. do
  196712. {
  196713. png_ptr->pass++;
  196714. if (png_ptr->pass >= 7)
  196715. break;
  196716. png_ptr->iwidth = (png_ptr->width +
  196717. png_pass_inc[png_ptr->pass] - 1 -
  196718. png_pass_start[png_ptr->pass]) /
  196719. png_pass_inc[png_ptr->pass];
  196720. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196721. png_ptr->iwidth) + 1;
  196722. if (!(png_ptr->transformations & PNG_INTERLACE))
  196723. {
  196724. png_ptr->num_rows = (png_ptr->height +
  196725. png_pass_yinc[png_ptr->pass] - 1 -
  196726. png_pass_ystart[png_ptr->pass]) /
  196727. png_pass_yinc[png_ptr->pass];
  196728. if (!(png_ptr->num_rows))
  196729. continue;
  196730. }
  196731. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196732. break;
  196733. } while (png_ptr->iwidth == 0);
  196734. if (png_ptr->pass < 7)
  196735. return;
  196736. }
  196737. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196738. {
  196739. #ifdef PNG_USE_LOCAL_ARRAYS
  196740. PNG_CONST PNG_IDAT;
  196741. #endif
  196742. char extra;
  196743. int ret;
  196744. png_ptr->zstream.next_out = (Bytef *)&extra;
  196745. png_ptr->zstream.avail_out = (uInt)1;
  196746. for(;;)
  196747. {
  196748. if (!(png_ptr->zstream.avail_in))
  196749. {
  196750. while (!png_ptr->idat_size)
  196751. {
  196752. png_byte chunk_length[4];
  196753. png_crc_finish(png_ptr, 0);
  196754. png_read_data(png_ptr, chunk_length, 4);
  196755. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196756. png_reset_crc(png_ptr);
  196757. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196758. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196759. png_error(png_ptr, "Not enough image data");
  196760. }
  196761. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196762. png_ptr->zstream.next_in = png_ptr->zbuf;
  196763. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196764. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196765. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196766. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196767. }
  196768. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196769. if (ret == Z_STREAM_END)
  196770. {
  196771. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196772. png_ptr->idat_size)
  196773. png_warning(png_ptr, "Extra compressed data");
  196774. png_ptr->mode |= PNG_AFTER_IDAT;
  196775. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196776. break;
  196777. }
  196778. if (ret != Z_OK)
  196779. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196780. "Decompression Error");
  196781. if (!(png_ptr->zstream.avail_out))
  196782. {
  196783. png_warning(png_ptr, "Extra compressed data.");
  196784. png_ptr->mode |= PNG_AFTER_IDAT;
  196785. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196786. break;
  196787. }
  196788. }
  196789. png_ptr->zstream.avail_out = 0;
  196790. }
  196791. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196792. png_warning(png_ptr, "Extra compression data");
  196793. inflateReset(&png_ptr->zstream);
  196794. png_ptr->mode |= PNG_AFTER_IDAT;
  196795. }
  196796. void /* PRIVATE */
  196797. png_read_start_row(png_structp png_ptr)
  196798. {
  196799. #ifdef PNG_USE_LOCAL_ARRAYS
  196800. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196801. /* start of interlace block */
  196802. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196803. /* offset to next interlace block */
  196804. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196805. /* start of interlace block in the y direction */
  196806. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196807. /* offset to next interlace block in the y direction */
  196808. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196809. #endif
  196810. int max_pixel_depth;
  196811. png_uint_32 row_bytes;
  196812. png_debug(1, "in png_read_start_row\n");
  196813. png_ptr->zstream.avail_in = 0;
  196814. png_init_read_transformations(png_ptr);
  196815. if (png_ptr->interlaced)
  196816. {
  196817. if (!(png_ptr->transformations & PNG_INTERLACE))
  196818. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196819. png_pass_ystart[0]) / png_pass_yinc[0];
  196820. else
  196821. png_ptr->num_rows = png_ptr->height;
  196822. png_ptr->iwidth = (png_ptr->width +
  196823. png_pass_inc[png_ptr->pass] - 1 -
  196824. png_pass_start[png_ptr->pass]) /
  196825. png_pass_inc[png_ptr->pass];
  196826. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196827. png_ptr->irowbytes = (png_size_t)row_bytes;
  196828. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196829. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196830. }
  196831. else
  196832. {
  196833. png_ptr->num_rows = png_ptr->height;
  196834. png_ptr->iwidth = png_ptr->width;
  196835. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196836. }
  196837. max_pixel_depth = png_ptr->pixel_depth;
  196838. #if defined(PNG_READ_PACK_SUPPORTED)
  196839. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196840. max_pixel_depth = 8;
  196841. #endif
  196842. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196843. if (png_ptr->transformations & PNG_EXPAND)
  196844. {
  196845. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196846. {
  196847. if (png_ptr->num_trans)
  196848. max_pixel_depth = 32;
  196849. else
  196850. max_pixel_depth = 24;
  196851. }
  196852. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196853. {
  196854. if (max_pixel_depth < 8)
  196855. max_pixel_depth = 8;
  196856. if (png_ptr->num_trans)
  196857. max_pixel_depth *= 2;
  196858. }
  196859. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196860. {
  196861. if (png_ptr->num_trans)
  196862. {
  196863. max_pixel_depth *= 4;
  196864. max_pixel_depth /= 3;
  196865. }
  196866. }
  196867. }
  196868. #endif
  196869. #if defined(PNG_READ_FILLER_SUPPORTED)
  196870. if (png_ptr->transformations & (PNG_FILLER))
  196871. {
  196872. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196873. max_pixel_depth = 32;
  196874. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196875. {
  196876. if (max_pixel_depth <= 8)
  196877. max_pixel_depth = 16;
  196878. else
  196879. max_pixel_depth = 32;
  196880. }
  196881. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196882. {
  196883. if (max_pixel_depth <= 32)
  196884. max_pixel_depth = 32;
  196885. else
  196886. max_pixel_depth = 64;
  196887. }
  196888. }
  196889. #endif
  196890. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196891. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196892. {
  196893. if (
  196894. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196895. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196896. #endif
  196897. #if defined(PNG_READ_FILLER_SUPPORTED)
  196898. (png_ptr->transformations & (PNG_FILLER)) ||
  196899. #endif
  196900. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196901. {
  196902. if (max_pixel_depth <= 16)
  196903. max_pixel_depth = 32;
  196904. else
  196905. max_pixel_depth = 64;
  196906. }
  196907. else
  196908. {
  196909. if (max_pixel_depth <= 8)
  196910. {
  196911. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196912. max_pixel_depth = 32;
  196913. else
  196914. max_pixel_depth = 24;
  196915. }
  196916. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196917. max_pixel_depth = 64;
  196918. else
  196919. max_pixel_depth = 48;
  196920. }
  196921. }
  196922. #endif
  196923. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196924. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196925. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196926. {
  196927. int user_pixel_depth=png_ptr->user_transform_depth*
  196928. png_ptr->user_transform_channels;
  196929. if(user_pixel_depth > max_pixel_depth)
  196930. max_pixel_depth=user_pixel_depth;
  196931. }
  196932. #endif
  196933. /* align the width on the next larger 8 pixels. Mainly used
  196934. for interlacing */
  196935. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196936. /* calculate the maximum bytes needed, adding a byte and a pixel
  196937. for safety's sake */
  196938. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196939. 1 + ((max_pixel_depth + 7) >> 3);
  196940. #ifdef PNG_MAX_MALLOC_64K
  196941. if (row_bytes > (png_uint_32)65536L)
  196942. png_error(png_ptr, "This image requires a row greater than 64KB");
  196943. #endif
  196944. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196945. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196946. #ifdef PNG_MAX_MALLOC_64K
  196947. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196948. png_error(png_ptr, "This image requires a row greater than 64KB");
  196949. #endif
  196950. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196951. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196952. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196953. png_ptr->rowbytes + 1));
  196954. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196955. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196956. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196957. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196958. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196959. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196960. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196961. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196962. }
  196963. #endif /* PNG_READ_SUPPORTED */
  196964. /*** End of inlined file: pngrutil.c ***/
  196965. /*** Start of inlined file: pngset.c ***/
  196966. /* pngset.c - storage of image information into info struct
  196967. *
  196968. * Last changed in libpng 1.2.21 [October 4, 2007]
  196969. * For conditions of distribution and use, see copyright notice in png.h
  196970. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196971. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196972. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196973. *
  196974. * The functions here are used during reads to store data from the file
  196975. * into the info struct, and during writes to store application data
  196976. * into the info struct for writing into the file. This abstracts the
  196977. * info struct and allows us to change the structure in the future.
  196978. */
  196979. #define PNG_INTERNAL
  196980. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196981. #if defined(PNG_bKGD_SUPPORTED)
  196982. void PNGAPI
  196983. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196984. {
  196985. png_debug1(1, "in %s storage function\n", "bKGD");
  196986. if (png_ptr == NULL || info_ptr == NULL)
  196987. return;
  196988. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196989. info_ptr->valid |= PNG_INFO_bKGD;
  196990. }
  196991. #endif
  196992. #if defined(PNG_cHRM_SUPPORTED)
  196993. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196994. void PNGAPI
  196995. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196996. double white_x, double white_y, double red_x, double red_y,
  196997. double green_x, double green_y, double blue_x, double blue_y)
  196998. {
  196999. png_debug1(1, "in %s storage function\n", "cHRM");
  197000. if (png_ptr == NULL || info_ptr == NULL)
  197001. return;
  197002. if (white_x < 0.0 || white_y < 0.0 ||
  197003. red_x < 0.0 || red_y < 0.0 ||
  197004. green_x < 0.0 || green_y < 0.0 ||
  197005. blue_x < 0.0 || blue_y < 0.0)
  197006. {
  197007. png_warning(png_ptr,
  197008. "Ignoring attempt to set negative chromaticity value");
  197009. return;
  197010. }
  197011. if (white_x > 21474.83 || white_y > 21474.83 ||
  197012. red_x > 21474.83 || red_y > 21474.83 ||
  197013. green_x > 21474.83 || green_y > 21474.83 ||
  197014. blue_x > 21474.83 || blue_y > 21474.83)
  197015. {
  197016. png_warning(png_ptr,
  197017. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197018. return;
  197019. }
  197020. info_ptr->x_white = (float)white_x;
  197021. info_ptr->y_white = (float)white_y;
  197022. info_ptr->x_red = (float)red_x;
  197023. info_ptr->y_red = (float)red_y;
  197024. info_ptr->x_green = (float)green_x;
  197025. info_ptr->y_green = (float)green_y;
  197026. info_ptr->x_blue = (float)blue_x;
  197027. info_ptr->y_blue = (float)blue_y;
  197028. #ifdef PNG_FIXED_POINT_SUPPORTED
  197029. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  197030. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  197031. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  197032. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  197033. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  197034. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  197035. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  197036. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  197037. #endif
  197038. info_ptr->valid |= PNG_INFO_cHRM;
  197039. }
  197040. #endif
  197041. #ifdef PNG_FIXED_POINT_SUPPORTED
  197042. void PNGAPI
  197043. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  197044. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  197045. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  197046. png_fixed_point blue_x, png_fixed_point blue_y)
  197047. {
  197048. png_debug1(1, "in %s storage function\n", "cHRM");
  197049. if (png_ptr == NULL || info_ptr == NULL)
  197050. return;
  197051. if (white_x < 0 || white_y < 0 ||
  197052. red_x < 0 || red_y < 0 ||
  197053. green_x < 0 || green_y < 0 ||
  197054. blue_x < 0 || blue_y < 0)
  197055. {
  197056. png_warning(png_ptr,
  197057. "Ignoring attempt to set negative chromaticity value");
  197058. return;
  197059. }
  197060. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197061. if (white_x > (double) PNG_UINT_31_MAX ||
  197062. white_y > (double) PNG_UINT_31_MAX ||
  197063. red_x > (double) PNG_UINT_31_MAX ||
  197064. red_y > (double) PNG_UINT_31_MAX ||
  197065. green_x > (double) PNG_UINT_31_MAX ||
  197066. green_y > (double) PNG_UINT_31_MAX ||
  197067. blue_x > (double) PNG_UINT_31_MAX ||
  197068. blue_y > (double) PNG_UINT_31_MAX)
  197069. #else
  197070. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197071. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197072. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197073. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197074. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197075. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197076. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197077. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  197078. #endif
  197079. {
  197080. png_warning(png_ptr,
  197081. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197082. return;
  197083. }
  197084. info_ptr->int_x_white = white_x;
  197085. info_ptr->int_y_white = white_y;
  197086. info_ptr->int_x_red = red_x;
  197087. info_ptr->int_y_red = red_y;
  197088. info_ptr->int_x_green = green_x;
  197089. info_ptr->int_y_green = green_y;
  197090. info_ptr->int_x_blue = blue_x;
  197091. info_ptr->int_y_blue = blue_y;
  197092. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197093. info_ptr->x_white = (float)(white_x/100000.);
  197094. info_ptr->y_white = (float)(white_y/100000.);
  197095. info_ptr->x_red = (float)( red_x/100000.);
  197096. info_ptr->y_red = (float)( red_y/100000.);
  197097. info_ptr->x_green = (float)(green_x/100000.);
  197098. info_ptr->y_green = (float)(green_y/100000.);
  197099. info_ptr->x_blue = (float)( blue_x/100000.);
  197100. info_ptr->y_blue = (float)( blue_y/100000.);
  197101. #endif
  197102. info_ptr->valid |= PNG_INFO_cHRM;
  197103. }
  197104. #endif
  197105. #endif
  197106. #if defined(PNG_gAMA_SUPPORTED)
  197107. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197108. void PNGAPI
  197109. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  197110. {
  197111. double gamma;
  197112. png_debug1(1, "in %s storage function\n", "gAMA");
  197113. if (png_ptr == NULL || info_ptr == NULL)
  197114. return;
  197115. /* Check for overflow */
  197116. if (file_gamma > 21474.83)
  197117. {
  197118. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197119. gamma=21474.83;
  197120. }
  197121. else
  197122. gamma=file_gamma;
  197123. info_ptr->gamma = (float)gamma;
  197124. #ifdef PNG_FIXED_POINT_SUPPORTED
  197125. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197126. #endif
  197127. info_ptr->valid |= PNG_INFO_gAMA;
  197128. if(gamma == 0.0)
  197129. png_warning(png_ptr, "Setting gamma=0");
  197130. }
  197131. #endif
  197132. void PNGAPI
  197133. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197134. int_gamma)
  197135. {
  197136. png_fixed_point gamma;
  197137. png_debug1(1, "in %s storage function\n", "gAMA");
  197138. if (png_ptr == NULL || info_ptr == NULL)
  197139. return;
  197140. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197141. {
  197142. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197143. gamma=PNG_UINT_31_MAX;
  197144. }
  197145. else
  197146. {
  197147. if (int_gamma < 0)
  197148. {
  197149. png_warning(png_ptr, "Setting negative gamma to zero");
  197150. gamma=0;
  197151. }
  197152. else
  197153. gamma=int_gamma;
  197154. }
  197155. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197156. info_ptr->gamma = (float)(gamma/100000.);
  197157. #endif
  197158. #ifdef PNG_FIXED_POINT_SUPPORTED
  197159. info_ptr->int_gamma = gamma;
  197160. #endif
  197161. info_ptr->valid |= PNG_INFO_gAMA;
  197162. if(gamma == 0)
  197163. png_warning(png_ptr, "Setting gamma=0");
  197164. }
  197165. #endif
  197166. #if defined(PNG_hIST_SUPPORTED)
  197167. void PNGAPI
  197168. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197169. {
  197170. int i;
  197171. png_debug1(1, "in %s storage function\n", "hIST");
  197172. if (png_ptr == NULL || info_ptr == NULL)
  197173. return;
  197174. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197175. > PNG_MAX_PALETTE_LENGTH)
  197176. {
  197177. png_warning(png_ptr,
  197178. "Invalid palette size, hIST allocation skipped.");
  197179. return;
  197180. }
  197181. #ifdef PNG_FREE_ME_SUPPORTED
  197182. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197183. #endif
  197184. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197185. 1.2.1 */
  197186. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197187. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197188. if (png_ptr->hist == NULL)
  197189. {
  197190. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197191. return;
  197192. }
  197193. for (i = 0; i < info_ptr->num_palette; i++)
  197194. png_ptr->hist[i] = hist[i];
  197195. info_ptr->hist = png_ptr->hist;
  197196. info_ptr->valid |= PNG_INFO_hIST;
  197197. #ifdef PNG_FREE_ME_SUPPORTED
  197198. info_ptr->free_me |= PNG_FREE_HIST;
  197199. #else
  197200. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197201. #endif
  197202. }
  197203. #endif
  197204. void PNGAPI
  197205. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197206. png_uint_32 width, png_uint_32 height, int bit_depth,
  197207. int color_type, int interlace_type, int compression_type,
  197208. int filter_type)
  197209. {
  197210. png_debug1(1, "in %s storage function\n", "IHDR");
  197211. if (png_ptr == NULL || info_ptr == NULL)
  197212. return;
  197213. /* check for width and height valid values */
  197214. if (width == 0 || height == 0)
  197215. png_error(png_ptr, "Image width or height is zero in IHDR");
  197216. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197217. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197218. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197219. #else
  197220. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197221. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197222. #endif
  197223. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197224. png_error(png_ptr, "Invalid image size in IHDR");
  197225. if ( width > (PNG_UINT_32_MAX
  197226. >> 3) /* 8-byte RGBA pixels */
  197227. - 64 /* bigrowbuf hack */
  197228. - 1 /* filter byte */
  197229. - 7*8 /* rounding of width to multiple of 8 pixels */
  197230. - 8) /* extra max_pixel_depth pad */
  197231. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197232. /* check other values */
  197233. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197234. bit_depth != 8 && bit_depth != 16)
  197235. png_error(png_ptr, "Invalid bit depth in IHDR");
  197236. if (color_type < 0 || color_type == 1 ||
  197237. color_type == 5 || color_type > 6)
  197238. png_error(png_ptr, "Invalid color type in IHDR");
  197239. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197240. ((color_type == PNG_COLOR_TYPE_RGB ||
  197241. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197242. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197243. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197244. if (interlace_type >= PNG_INTERLACE_LAST)
  197245. png_error(png_ptr, "Unknown interlace method in IHDR");
  197246. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197247. png_error(png_ptr, "Unknown compression method in IHDR");
  197248. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197249. /* Accept filter_method 64 (intrapixel differencing) only if
  197250. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197251. * 2. Libpng did not read a PNG signature (this filter_method is only
  197252. * used in PNG datastreams that are embedded in MNG datastreams) and
  197253. * 3. The application called png_permit_mng_features with a mask that
  197254. * included PNG_FLAG_MNG_FILTER_64 and
  197255. * 4. The filter_method is 64 and
  197256. * 5. The color_type is RGB or RGBA
  197257. */
  197258. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197259. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197260. if(filter_type != PNG_FILTER_TYPE_BASE)
  197261. {
  197262. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197263. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197264. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197265. (color_type == PNG_COLOR_TYPE_RGB ||
  197266. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197267. png_error(png_ptr, "Unknown filter method in IHDR");
  197268. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197269. png_warning(png_ptr, "Invalid filter method in IHDR");
  197270. }
  197271. #else
  197272. if(filter_type != PNG_FILTER_TYPE_BASE)
  197273. png_error(png_ptr, "Unknown filter method in IHDR");
  197274. #endif
  197275. info_ptr->width = width;
  197276. info_ptr->height = height;
  197277. info_ptr->bit_depth = (png_byte)bit_depth;
  197278. info_ptr->color_type =(png_byte) color_type;
  197279. info_ptr->compression_type = (png_byte)compression_type;
  197280. info_ptr->filter_type = (png_byte)filter_type;
  197281. info_ptr->interlace_type = (png_byte)interlace_type;
  197282. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197283. info_ptr->channels = 1;
  197284. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197285. info_ptr->channels = 3;
  197286. else
  197287. info_ptr->channels = 1;
  197288. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197289. info_ptr->channels++;
  197290. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197291. /* check for potential overflow */
  197292. if (width > (PNG_UINT_32_MAX
  197293. >> 3) /* 8-byte RGBA pixels */
  197294. - 64 /* bigrowbuf hack */
  197295. - 1 /* filter byte */
  197296. - 7*8 /* rounding of width to multiple of 8 pixels */
  197297. - 8) /* extra max_pixel_depth pad */
  197298. info_ptr->rowbytes = (png_size_t)0;
  197299. else
  197300. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197301. }
  197302. #if defined(PNG_oFFs_SUPPORTED)
  197303. void PNGAPI
  197304. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197305. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197306. {
  197307. png_debug1(1, "in %s storage function\n", "oFFs");
  197308. if (png_ptr == NULL || info_ptr == NULL)
  197309. return;
  197310. info_ptr->x_offset = offset_x;
  197311. info_ptr->y_offset = offset_y;
  197312. info_ptr->offset_unit_type = (png_byte)unit_type;
  197313. info_ptr->valid |= PNG_INFO_oFFs;
  197314. }
  197315. #endif
  197316. #if defined(PNG_pCAL_SUPPORTED)
  197317. void PNGAPI
  197318. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197319. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197320. png_charp units, png_charpp params)
  197321. {
  197322. png_uint_32 length;
  197323. int i;
  197324. png_debug1(1, "in %s storage function\n", "pCAL");
  197325. if (png_ptr == NULL || info_ptr == NULL)
  197326. return;
  197327. length = png_strlen(purpose) + 1;
  197328. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197329. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197330. if (info_ptr->pcal_purpose == NULL)
  197331. {
  197332. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197333. return;
  197334. }
  197335. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197336. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197337. info_ptr->pcal_X0 = X0;
  197338. info_ptr->pcal_X1 = X1;
  197339. info_ptr->pcal_type = (png_byte)type;
  197340. info_ptr->pcal_nparams = (png_byte)nparams;
  197341. length = png_strlen(units) + 1;
  197342. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197343. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197344. if (info_ptr->pcal_units == NULL)
  197345. {
  197346. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197347. return;
  197348. }
  197349. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197350. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197351. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197352. if (info_ptr->pcal_params == NULL)
  197353. {
  197354. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197355. return;
  197356. }
  197357. info_ptr->pcal_params[nparams] = NULL;
  197358. for (i = 0; i < nparams; i++)
  197359. {
  197360. length = png_strlen(params[i]) + 1;
  197361. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197362. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197363. if (info_ptr->pcal_params[i] == NULL)
  197364. {
  197365. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197366. return;
  197367. }
  197368. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197369. }
  197370. info_ptr->valid |= PNG_INFO_pCAL;
  197371. #ifdef PNG_FREE_ME_SUPPORTED
  197372. info_ptr->free_me |= PNG_FREE_PCAL;
  197373. #endif
  197374. }
  197375. #endif
  197376. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197377. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197378. void PNGAPI
  197379. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197380. int unit, double width, double height)
  197381. {
  197382. png_debug1(1, "in %s storage function\n", "sCAL");
  197383. if (png_ptr == NULL || info_ptr == NULL)
  197384. return;
  197385. info_ptr->scal_unit = (png_byte)unit;
  197386. info_ptr->scal_pixel_width = width;
  197387. info_ptr->scal_pixel_height = height;
  197388. info_ptr->valid |= PNG_INFO_sCAL;
  197389. }
  197390. #else
  197391. #ifdef PNG_FIXED_POINT_SUPPORTED
  197392. void PNGAPI
  197393. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197394. int unit, png_charp swidth, png_charp sheight)
  197395. {
  197396. png_uint_32 length;
  197397. png_debug1(1, "in %s storage function\n", "sCAL");
  197398. if (png_ptr == NULL || info_ptr == NULL)
  197399. return;
  197400. info_ptr->scal_unit = (png_byte)unit;
  197401. length = png_strlen(swidth) + 1;
  197402. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197403. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197404. if (info_ptr->scal_s_width == NULL)
  197405. {
  197406. png_warning(png_ptr,
  197407. "Memory allocation failed while processing sCAL.");
  197408. }
  197409. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197410. length = png_strlen(sheight) + 1;
  197411. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197412. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197413. if (info_ptr->scal_s_height == NULL)
  197414. {
  197415. png_free (png_ptr, info_ptr->scal_s_width);
  197416. png_warning(png_ptr,
  197417. "Memory allocation failed while processing sCAL.");
  197418. }
  197419. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197420. info_ptr->valid |= PNG_INFO_sCAL;
  197421. #ifdef PNG_FREE_ME_SUPPORTED
  197422. info_ptr->free_me |= PNG_FREE_SCAL;
  197423. #endif
  197424. }
  197425. #endif
  197426. #endif
  197427. #endif
  197428. #if defined(PNG_pHYs_SUPPORTED)
  197429. void PNGAPI
  197430. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197431. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197432. {
  197433. png_debug1(1, "in %s storage function\n", "pHYs");
  197434. if (png_ptr == NULL || info_ptr == NULL)
  197435. return;
  197436. info_ptr->x_pixels_per_unit = res_x;
  197437. info_ptr->y_pixels_per_unit = res_y;
  197438. info_ptr->phys_unit_type = (png_byte)unit_type;
  197439. info_ptr->valid |= PNG_INFO_pHYs;
  197440. }
  197441. #endif
  197442. void PNGAPI
  197443. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197444. png_colorp palette, int num_palette)
  197445. {
  197446. png_debug1(1, "in %s storage function\n", "PLTE");
  197447. if (png_ptr == NULL || info_ptr == NULL)
  197448. return;
  197449. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197450. {
  197451. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197452. png_error(png_ptr, "Invalid palette length");
  197453. else
  197454. {
  197455. png_warning(png_ptr, "Invalid palette length");
  197456. return;
  197457. }
  197458. }
  197459. /*
  197460. * It may not actually be necessary to set png_ptr->palette here;
  197461. * we do it for backward compatibility with the way the png_handle_tRNS
  197462. * function used to do the allocation.
  197463. */
  197464. #ifdef PNG_FREE_ME_SUPPORTED
  197465. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197466. #endif
  197467. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197468. of num_palette entries,
  197469. in case of an invalid PNG file that has too-large sample values. */
  197470. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197471. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197472. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197473. png_sizeof(png_color));
  197474. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197475. info_ptr->palette = png_ptr->palette;
  197476. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197477. #ifdef PNG_FREE_ME_SUPPORTED
  197478. info_ptr->free_me |= PNG_FREE_PLTE;
  197479. #else
  197480. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197481. #endif
  197482. info_ptr->valid |= PNG_INFO_PLTE;
  197483. }
  197484. #if defined(PNG_sBIT_SUPPORTED)
  197485. void PNGAPI
  197486. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197487. png_color_8p sig_bit)
  197488. {
  197489. png_debug1(1, "in %s storage function\n", "sBIT");
  197490. if (png_ptr == NULL || info_ptr == NULL)
  197491. return;
  197492. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197493. info_ptr->valid |= PNG_INFO_sBIT;
  197494. }
  197495. #endif
  197496. #if defined(PNG_sRGB_SUPPORTED)
  197497. void PNGAPI
  197498. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197499. {
  197500. png_debug1(1, "in %s storage function\n", "sRGB");
  197501. if (png_ptr == NULL || info_ptr == NULL)
  197502. return;
  197503. info_ptr->srgb_intent = (png_byte)intent;
  197504. info_ptr->valid |= PNG_INFO_sRGB;
  197505. }
  197506. void PNGAPI
  197507. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197508. int intent)
  197509. {
  197510. #if defined(PNG_gAMA_SUPPORTED)
  197511. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197512. float file_gamma;
  197513. #endif
  197514. #ifdef PNG_FIXED_POINT_SUPPORTED
  197515. png_fixed_point int_file_gamma;
  197516. #endif
  197517. #endif
  197518. #if defined(PNG_cHRM_SUPPORTED)
  197519. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197520. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197521. #endif
  197522. #ifdef PNG_FIXED_POINT_SUPPORTED
  197523. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197524. int_green_y, int_blue_x, int_blue_y;
  197525. #endif
  197526. #endif
  197527. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197528. if (png_ptr == NULL || info_ptr == NULL)
  197529. return;
  197530. png_set_sRGB(png_ptr, info_ptr, intent);
  197531. #if defined(PNG_gAMA_SUPPORTED)
  197532. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197533. file_gamma = (float).45455;
  197534. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197535. #endif
  197536. #ifdef PNG_FIXED_POINT_SUPPORTED
  197537. int_file_gamma = 45455L;
  197538. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197539. #endif
  197540. #endif
  197541. #if defined(PNG_cHRM_SUPPORTED)
  197542. #ifdef PNG_FIXED_POINT_SUPPORTED
  197543. int_white_x = 31270L;
  197544. int_white_y = 32900L;
  197545. int_red_x = 64000L;
  197546. int_red_y = 33000L;
  197547. int_green_x = 30000L;
  197548. int_green_y = 60000L;
  197549. int_blue_x = 15000L;
  197550. int_blue_y = 6000L;
  197551. png_set_cHRM_fixed(png_ptr, info_ptr,
  197552. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197553. int_blue_x, int_blue_y);
  197554. #endif
  197555. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197556. white_x = (float).3127;
  197557. white_y = (float).3290;
  197558. red_x = (float).64;
  197559. red_y = (float).33;
  197560. green_x = (float).30;
  197561. green_y = (float).60;
  197562. blue_x = (float).15;
  197563. blue_y = (float).06;
  197564. png_set_cHRM(png_ptr, info_ptr,
  197565. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197566. #endif
  197567. #endif
  197568. }
  197569. #endif
  197570. #if defined(PNG_iCCP_SUPPORTED)
  197571. void PNGAPI
  197572. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197573. png_charp name, int compression_type,
  197574. png_charp profile, png_uint_32 proflen)
  197575. {
  197576. png_charp new_iccp_name;
  197577. png_charp new_iccp_profile;
  197578. png_debug1(1, "in %s storage function\n", "iCCP");
  197579. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197580. return;
  197581. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197582. if (new_iccp_name == NULL)
  197583. {
  197584. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197585. return;
  197586. }
  197587. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197588. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197589. if (new_iccp_profile == NULL)
  197590. {
  197591. png_free (png_ptr, new_iccp_name);
  197592. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197593. return;
  197594. }
  197595. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197596. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197597. info_ptr->iccp_proflen = proflen;
  197598. info_ptr->iccp_name = new_iccp_name;
  197599. info_ptr->iccp_profile = new_iccp_profile;
  197600. /* Compression is always zero but is here so the API and info structure
  197601. * does not have to change if we introduce multiple compression types */
  197602. info_ptr->iccp_compression = (png_byte)compression_type;
  197603. #ifdef PNG_FREE_ME_SUPPORTED
  197604. info_ptr->free_me |= PNG_FREE_ICCP;
  197605. #endif
  197606. info_ptr->valid |= PNG_INFO_iCCP;
  197607. }
  197608. #endif
  197609. #if defined(PNG_TEXT_SUPPORTED)
  197610. void PNGAPI
  197611. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197612. int num_text)
  197613. {
  197614. int ret;
  197615. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197616. if (ret)
  197617. png_error(png_ptr, "Insufficient memory to store text");
  197618. }
  197619. int /* PRIVATE */
  197620. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197621. int num_text)
  197622. {
  197623. int i;
  197624. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197625. "text" : (png_const_charp)png_ptr->chunk_name));
  197626. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197627. return(0);
  197628. /* Make sure we have enough space in the "text" array in info_struct
  197629. * to hold all of the incoming text_ptr objects.
  197630. */
  197631. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197632. {
  197633. if (info_ptr->text != NULL)
  197634. {
  197635. png_textp old_text;
  197636. int old_max;
  197637. old_max = info_ptr->max_text;
  197638. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197639. old_text = info_ptr->text;
  197640. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197641. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197642. if (info_ptr->text == NULL)
  197643. {
  197644. png_free(png_ptr, old_text);
  197645. return(1);
  197646. }
  197647. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197648. png_sizeof(png_text)));
  197649. png_free(png_ptr, old_text);
  197650. }
  197651. else
  197652. {
  197653. info_ptr->max_text = num_text + 8;
  197654. info_ptr->num_text = 0;
  197655. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197656. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197657. if (info_ptr->text == NULL)
  197658. return(1);
  197659. #ifdef PNG_FREE_ME_SUPPORTED
  197660. info_ptr->free_me |= PNG_FREE_TEXT;
  197661. #endif
  197662. }
  197663. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197664. info_ptr->max_text);
  197665. }
  197666. for (i = 0; i < num_text; i++)
  197667. {
  197668. png_size_t text_length,key_len;
  197669. png_size_t lang_len,lang_key_len;
  197670. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197671. if (text_ptr[i].key == NULL)
  197672. continue;
  197673. key_len = png_strlen(text_ptr[i].key);
  197674. if(text_ptr[i].compression <= 0)
  197675. {
  197676. lang_len = 0;
  197677. lang_key_len = 0;
  197678. }
  197679. else
  197680. #ifdef PNG_iTXt_SUPPORTED
  197681. {
  197682. /* set iTXt data */
  197683. if (text_ptr[i].lang != NULL)
  197684. lang_len = png_strlen(text_ptr[i].lang);
  197685. else
  197686. lang_len = 0;
  197687. if (text_ptr[i].lang_key != NULL)
  197688. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197689. else
  197690. lang_key_len = 0;
  197691. }
  197692. #else
  197693. {
  197694. png_warning(png_ptr, "iTXt chunk not supported.");
  197695. continue;
  197696. }
  197697. #endif
  197698. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197699. {
  197700. text_length = 0;
  197701. #ifdef PNG_iTXt_SUPPORTED
  197702. if(text_ptr[i].compression > 0)
  197703. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197704. else
  197705. #endif
  197706. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197707. }
  197708. else
  197709. {
  197710. text_length = png_strlen(text_ptr[i].text);
  197711. textp->compression = text_ptr[i].compression;
  197712. }
  197713. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197714. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197715. if (textp->key == NULL)
  197716. return(1);
  197717. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197718. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197719. (int)textp->key);
  197720. png_memcpy(textp->key, text_ptr[i].key,
  197721. (png_size_t)(key_len));
  197722. *(textp->key+key_len) = '\0';
  197723. #ifdef PNG_iTXt_SUPPORTED
  197724. if (text_ptr[i].compression > 0)
  197725. {
  197726. textp->lang=textp->key + key_len + 1;
  197727. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197728. *(textp->lang+lang_len) = '\0';
  197729. textp->lang_key=textp->lang + lang_len + 1;
  197730. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197731. *(textp->lang_key+lang_key_len) = '\0';
  197732. textp->text=textp->lang_key + lang_key_len + 1;
  197733. }
  197734. else
  197735. #endif
  197736. {
  197737. #ifdef PNG_iTXt_SUPPORTED
  197738. textp->lang=NULL;
  197739. textp->lang_key=NULL;
  197740. #endif
  197741. textp->text=textp->key + key_len + 1;
  197742. }
  197743. if(text_length)
  197744. png_memcpy(textp->text, text_ptr[i].text,
  197745. (png_size_t)(text_length));
  197746. *(textp->text+text_length) = '\0';
  197747. #ifdef PNG_iTXt_SUPPORTED
  197748. if(textp->compression > 0)
  197749. {
  197750. textp->text_length = 0;
  197751. textp->itxt_length = text_length;
  197752. }
  197753. else
  197754. #endif
  197755. {
  197756. textp->text_length = text_length;
  197757. #ifdef PNG_iTXt_SUPPORTED
  197758. textp->itxt_length = 0;
  197759. #endif
  197760. }
  197761. info_ptr->num_text++;
  197762. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197763. }
  197764. return(0);
  197765. }
  197766. #endif
  197767. #if defined(PNG_tIME_SUPPORTED)
  197768. void PNGAPI
  197769. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197770. {
  197771. png_debug1(1, "in %s storage function\n", "tIME");
  197772. if (png_ptr == NULL || info_ptr == NULL ||
  197773. (png_ptr->mode & PNG_WROTE_tIME))
  197774. return;
  197775. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197776. info_ptr->valid |= PNG_INFO_tIME;
  197777. }
  197778. #endif
  197779. #if defined(PNG_tRNS_SUPPORTED)
  197780. void PNGAPI
  197781. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197782. png_bytep trans, int num_trans, png_color_16p trans_values)
  197783. {
  197784. png_debug1(1, "in %s storage function\n", "tRNS");
  197785. if (png_ptr == NULL || info_ptr == NULL)
  197786. return;
  197787. if (trans != NULL)
  197788. {
  197789. /*
  197790. * It may not actually be necessary to set png_ptr->trans here;
  197791. * we do it for backward compatibility with the way the png_handle_tRNS
  197792. * function used to do the allocation.
  197793. */
  197794. #ifdef PNG_FREE_ME_SUPPORTED
  197795. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197796. #endif
  197797. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197798. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197799. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197800. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197801. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197802. #ifdef PNG_FREE_ME_SUPPORTED
  197803. info_ptr->free_me |= PNG_FREE_TRNS;
  197804. #else
  197805. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197806. #endif
  197807. }
  197808. if (trans_values != NULL)
  197809. {
  197810. png_memcpy(&(info_ptr->trans_values), trans_values,
  197811. png_sizeof(png_color_16));
  197812. if (num_trans == 0)
  197813. num_trans = 1;
  197814. }
  197815. info_ptr->num_trans = (png_uint_16)num_trans;
  197816. info_ptr->valid |= PNG_INFO_tRNS;
  197817. }
  197818. #endif
  197819. #if defined(PNG_sPLT_SUPPORTED)
  197820. void PNGAPI
  197821. png_set_sPLT(png_structp png_ptr,
  197822. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197823. {
  197824. png_sPLT_tp np;
  197825. int i;
  197826. if (png_ptr == NULL || info_ptr == NULL)
  197827. return;
  197828. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197829. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197830. if (np == NULL)
  197831. {
  197832. png_warning(png_ptr, "No memory for sPLT palettes.");
  197833. return;
  197834. }
  197835. png_memcpy(np, info_ptr->splt_palettes,
  197836. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197837. png_free(png_ptr, info_ptr->splt_palettes);
  197838. info_ptr->splt_palettes=NULL;
  197839. for (i = 0; i < nentries; i++)
  197840. {
  197841. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197842. png_sPLT_tp from = entries + i;
  197843. to->name = (png_charp)png_malloc_warn(png_ptr,
  197844. png_strlen(from->name) + 1);
  197845. if (to->name == NULL)
  197846. {
  197847. png_warning(png_ptr,
  197848. "Out of memory while processing sPLT chunk");
  197849. }
  197850. /* TODO: use png_malloc_warn */
  197851. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197852. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197853. from->nentries * png_sizeof(png_sPLT_entry));
  197854. /* TODO: use png_malloc_warn */
  197855. png_memcpy(to->entries, from->entries,
  197856. from->nentries * png_sizeof(png_sPLT_entry));
  197857. if (to->entries == NULL)
  197858. {
  197859. png_warning(png_ptr,
  197860. "Out of memory while processing sPLT chunk");
  197861. png_free(png_ptr,to->name);
  197862. to->name = NULL;
  197863. }
  197864. to->nentries = from->nentries;
  197865. to->depth = from->depth;
  197866. }
  197867. info_ptr->splt_palettes = np;
  197868. info_ptr->splt_palettes_num += nentries;
  197869. info_ptr->valid |= PNG_INFO_sPLT;
  197870. #ifdef PNG_FREE_ME_SUPPORTED
  197871. info_ptr->free_me |= PNG_FREE_SPLT;
  197872. #endif
  197873. }
  197874. #endif /* PNG_sPLT_SUPPORTED */
  197875. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197876. void PNGAPI
  197877. png_set_unknown_chunks(png_structp png_ptr,
  197878. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197879. {
  197880. png_unknown_chunkp np;
  197881. int i;
  197882. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197883. return;
  197884. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197885. (info_ptr->unknown_chunks_num + num_unknowns) *
  197886. png_sizeof(png_unknown_chunk));
  197887. if (np == NULL)
  197888. {
  197889. png_warning(png_ptr,
  197890. "Out of memory while processing unknown chunk.");
  197891. return;
  197892. }
  197893. png_memcpy(np, info_ptr->unknown_chunks,
  197894. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197895. png_free(png_ptr, info_ptr->unknown_chunks);
  197896. info_ptr->unknown_chunks=NULL;
  197897. for (i = 0; i < num_unknowns; i++)
  197898. {
  197899. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197900. png_unknown_chunkp from = unknowns + i;
  197901. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197902. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197903. if (to->data == NULL)
  197904. {
  197905. png_warning(png_ptr,
  197906. "Out of memory while processing unknown chunk.");
  197907. }
  197908. else
  197909. {
  197910. png_memcpy(to->data, from->data, from->size);
  197911. to->size = from->size;
  197912. /* note our location in the read or write sequence */
  197913. to->location = (png_byte)(png_ptr->mode & 0xff);
  197914. }
  197915. }
  197916. info_ptr->unknown_chunks = np;
  197917. info_ptr->unknown_chunks_num += num_unknowns;
  197918. #ifdef PNG_FREE_ME_SUPPORTED
  197919. info_ptr->free_me |= PNG_FREE_UNKN;
  197920. #endif
  197921. }
  197922. void PNGAPI
  197923. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197924. int chunk, int location)
  197925. {
  197926. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197927. (int)info_ptr->unknown_chunks_num)
  197928. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197929. }
  197930. #endif
  197931. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197932. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197933. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197934. void PNGAPI
  197935. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197936. {
  197937. /* This function is deprecated in favor of png_permit_mng_features()
  197938. and will be removed from libpng-1.3.0 */
  197939. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197940. if (png_ptr == NULL)
  197941. return;
  197942. png_ptr->mng_features_permitted = (png_byte)
  197943. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197944. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197945. }
  197946. #endif
  197947. #endif
  197948. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197949. png_uint_32 PNGAPI
  197950. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197951. {
  197952. png_debug(1, "in png_permit_mng_features\n");
  197953. if (png_ptr == NULL)
  197954. return (png_uint_32)0;
  197955. png_ptr->mng_features_permitted =
  197956. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197957. return (png_uint_32)png_ptr->mng_features_permitted;
  197958. }
  197959. #endif
  197960. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197961. void PNGAPI
  197962. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197963. chunk_list, int num_chunks)
  197964. {
  197965. png_bytep new_list, p;
  197966. int i, old_num_chunks;
  197967. if (png_ptr == NULL)
  197968. return;
  197969. if (num_chunks == 0)
  197970. {
  197971. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197972. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197973. else
  197974. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197975. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197976. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197977. else
  197978. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197979. return;
  197980. }
  197981. if (chunk_list == NULL)
  197982. return;
  197983. old_num_chunks=png_ptr->num_chunk_list;
  197984. new_list=(png_bytep)png_malloc(png_ptr,
  197985. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197986. if(png_ptr->chunk_list != NULL)
  197987. {
  197988. png_memcpy(new_list, png_ptr->chunk_list,
  197989. (png_size_t)(5*old_num_chunks));
  197990. png_free(png_ptr, png_ptr->chunk_list);
  197991. png_ptr->chunk_list=NULL;
  197992. }
  197993. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197994. (png_size_t)(5*num_chunks));
  197995. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197996. *p=(png_byte)keep;
  197997. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197998. png_ptr->chunk_list=new_list;
  197999. #ifdef PNG_FREE_ME_SUPPORTED
  198000. png_ptr->free_me |= PNG_FREE_LIST;
  198001. #endif
  198002. }
  198003. #endif
  198004. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  198005. void PNGAPI
  198006. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  198007. png_user_chunk_ptr read_user_chunk_fn)
  198008. {
  198009. png_debug(1, "in png_set_read_user_chunk_fn\n");
  198010. if (png_ptr == NULL)
  198011. return;
  198012. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  198013. png_ptr->user_chunk_ptr = user_chunk_ptr;
  198014. }
  198015. #endif
  198016. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198017. void PNGAPI
  198018. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  198019. {
  198020. png_debug1(1, "in %s storage function\n", "rows");
  198021. if (png_ptr == NULL || info_ptr == NULL)
  198022. return;
  198023. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  198024. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  198025. info_ptr->row_pointers = row_pointers;
  198026. if(row_pointers)
  198027. info_ptr->valid |= PNG_INFO_IDAT;
  198028. }
  198029. #endif
  198030. #ifdef PNG_WRITE_SUPPORTED
  198031. void PNGAPI
  198032. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  198033. {
  198034. if (png_ptr == NULL)
  198035. return;
  198036. if(png_ptr->zbuf)
  198037. png_free(png_ptr, png_ptr->zbuf);
  198038. png_ptr->zbuf_size = (png_size_t)size;
  198039. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  198040. png_ptr->zstream.next_out = png_ptr->zbuf;
  198041. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198042. }
  198043. #endif
  198044. void PNGAPI
  198045. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  198046. {
  198047. if (png_ptr && info_ptr)
  198048. info_ptr->valid &= ~(mask);
  198049. }
  198050. #ifndef PNG_1_0_X
  198051. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  198052. /* function was added to libpng 1.2.0 and should always exist by default */
  198053. void PNGAPI
  198054. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  198055. {
  198056. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198057. if (png_ptr != NULL)
  198058. png_ptr->asm_flags = 0;
  198059. }
  198060. /* this function was added to libpng 1.2.0 */
  198061. void PNGAPI
  198062. png_set_mmx_thresholds (png_structp png_ptr,
  198063. png_byte,
  198064. png_uint_32)
  198065. {
  198066. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198067. if (png_ptr == NULL)
  198068. return;
  198069. }
  198070. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  198071. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198072. /* this function was added to libpng 1.2.6 */
  198073. void PNGAPI
  198074. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  198075. png_uint_32 user_height_max)
  198076. {
  198077. /* Images with dimensions larger than these limits will be
  198078. * rejected by png_set_IHDR(). To accept any PNG datastream
  198079. * regardless of dimensions, set both limits to 0x7ffffffL.
  198080. */
  198081. if(png_ptr == NULL) return;
  198082. png_ptr->user_width_max = user_width_max;
  198083. png_ptr->user_height_max = user_height_max;
  198084. }
  198085. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  198086. #endif /* ?PNG_1_0_X */
  198087. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198088. /*** End of inlined file: pngset.c ***/
  198089. /*** Start of inlined file: pngtrans.c ***/
  198090. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  198091. *
  198092. * Last changed in libpng 1.2.17 May 15, 2007
  198093. * For conditions of distribution and use, see copyright notice in png.h
  198094. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198095. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198096. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198097. */
  198098. #define PNG_INTERNAL
  198099. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  198100. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198101. /* turn on BGR-to-RGB mapping */
  198102. void PNGAPI
  198103. png_set_bgr(png_structp png_ptr)
  198104. {
  198105. png_debug(1, "in png_set_bgr\n");
  198106. if(png_ptr == NULL) return;
  198107. png_ptr->transformations |= PNG_BGR;
  198108. }
  198109. #endif
  198110. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198111. /* turn on 16 bit byte swapping */
  198112. void PNGAPI
  198113. png_set_swap(png_structp png_ptr)
  198114. {
  198115. png_debug(1, "in png_set_swap\n");
  198116. if(png_ptr == NULL) return;
  198117. if (png_ptr->bit_depth == 16)
  198118. png_ptr->transformations |= PNG_SWAP_BYTES;
  198119. }
  198120. #endif
  198121. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198122. /* turn on pixel packing */
  198123. void PNGAPI
  198124. png_set_packing(png_structp png_ptr)
  198125. {
  198126. png_debug(1, "in png_set_packing\n");
  198127. if(png_ptr == NULL) return;
  198128. if (png_ptr->bit_depth < 8)
  198129. {
  198130. png_ptr->transformations |= PNG_PACK;
  198131. png_ptr->usr_bit_depth = 8;
  198132. }
  198133. }
  198134. #endif
  198135. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198136. /* turn on packed pixel swapping */
  198137. void PNGAPI
  198138. png_set_packswap(png_structp png_ptr)
  198139. {
  198140. png_debug(1, "in png_set_packswap\n");
  198141. if(png_ptr == NULL) return;
  198142. if (png_ptr->bit_depth < 8)
  198143. png_ptr->transformations |= PNG_PACKSWAP;
  198144. }
  198145. #endif
  198146. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198147. void PNGAPI
  198148. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198149. {
  198150. png_debug(1, "in png_set_shift\n");
  198151. if(png_ptr == NULL) return;
  198152. png_ptr->transformations |= PNG_SHIFT;
  198153. png_ptr->shift = *true_bits;
  198154. }
  198155. #endif
  198156. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198157. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198158. int PNGAPI
  198159. png_set_interlace_handling(png_structp png_ptr)
  198160. {
  198161. png_debug(1, "in png_set_interlace handling\n");
  198162. if (png_ptr && png_ptr->interlaced)
  198163. {
  198164. png_ptr->transformations |= PNG_INTERLACE;
  198165. return (7);
  198166. }
  198167. return (1);
  198168. }
  198169. #endif
  198170. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198171. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198172. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198173. * for 48-bit input data, as well as to avoid problems with some compilers
  198174. * that don't like bytes as parameters.
  198175. */
  198176. void PNGAPI
  198177. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198178. {
  198179. png_debug(1, "in png_set_filler\n");
  198180. if(png_ptr == NULL) return;
  198181. png_ptr->transformations |= PNG_FILLER;
  198182. png_ptr->filler = (png_byte)filler;
  198183. if (filler_loc == PNG_FILLER_AFTER)
  198184. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198185. else
  198186. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198187. /* This should probably go in the "do_read_filler" routine.
  198188. * I attempted to do that in libpng-1.0.1a but that caused problems
  198189. * so I restored it in libpng-1.0.2a
  198190. */
  198191. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198192. {
  198193. png_ptr->usr_channels = 4;
  198194. }
  198195. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198196. * a less-than-8-bit grayscale to GA? */
  198197. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198198. {
  198199. png_ptr->usr_channels = 2;
  198200. }
  198201. }
  198202. #if !defined(PNG_1_0_X)
  198203. /* Added to libpng-1.2.7 */
  198204. void PNGAPI
  198205. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198206. {
  198207. png_debug(1, "in png_set_add_alpha\n");
  198208. if(png_ptr == NULL) return;
  198209. png_set_filler(png_ptr, filler, filler_loc);
  198210. png_ptr->transformations |= PNG_ADD_ALPHA;
  198211. }
  198212. #endif
  198213. #endif
  198214. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198215. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198216. void PNGAPI
  198217. png_set_swap_alpha(png_structp png_ptr)
  198218. {
  198219. png_debug(1, "in png_set_swap_alpha\n");
  198220. if(png_ptr == NULL) return;
  198221. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198222. }
  198223. #endif
  198224. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198225. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198226. void PNGAPI
  198227. png_set_invert_alpha(png_structp png_ptr)
  198228. {
  198229. png_debug(1, "in png_set_invert_alpha\n");
  198230. if(png_ptr == NULL) return;
  198231. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198232. }
  198233. #endif
  198234. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198235. void PNGAPI
  198236. png_set_invert_mono(png_structp png_ptr)
  198237. {
  198238. png_debug(1, "in png_set_invert_mono\n");
  198239. if(png_ptr == NULL) return;
  198240. png_ptr->transformations |= PNG_INVERT_MONO;
  198241. }
  198242. /* invert monochrome grayscale data */
  198243. void /* PRIVATE */
  198244. png_do_invert(png_row_infop row_info, png_bytep row)
  198245. {
  198246. png_debug(1, "in png_do_invert\n");
  198247. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198248. * if (row_info->bit_depth == 1 &&
  198249. */
  198250. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198251. if (row == NULL || row_info == NULL)
  198252. return;
  198253. #endif
  198254. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198255. {
  198256. png_bytep rp = row;
  198257. png_uint_32 i;
  198258. png_uint_32 istop = row_info->rowbytes;
  198259. for (i = 0; i < istop; i++)
  198260. {
  198261. *rp = (png_byte)(~(*rp));
  198262. rp++;
  198263. }
  198264. }
  198265. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198266. row_info->bit_depth == 8)
  198267. {
  198268. png_bytep rp = row;
  198269. png_uint_32 i;
  198270. png_uint_32 istop = row_info->rowbytes;
  198271. for (i = 0; i < istop; i+=2)
  198272. {
  198273. *rp = (png_byte)(~(*rp));
  198274. rp+=2;
  198275. }
  198276. }
  198277. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198278. row_info->bit_depth == 16)
  198279. {
  198280. png_bytep rp = row;
  198281. png_uint_32 i;
  198282. png_uint_32 istop = row_info->rowbytes;
  198283. for (i = 0; i < istop; i+=4)
  198284. {
  198285. *rp = (png_byte)(~(*rp));
  198286. *(rp+1) = (png_byte)(~(*(rp+1)));
  198287. rp+=4;
  198288. }
  198289. }
  198290. }
  198291. #endif
  198292. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198293. /* swaps byte order on 16 bit depth images */
  198294. void /* PRIVATE */
  198295. png_do_swap(png_row_infop row_info, png_bytep row)
  198296. {
  198297. png_debug(1, "in png_do_swap\n");
  198298. if (
  198299. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198300. row != NULL && row_info != NULL &&
  198301. #endif
  198302. row_info->bit_depth == 16)
  198303. {
  198304. png_bytep rp = row;
  198305. png_uint_32 i;
  198306. png_uint_32 istop= row_info->width * row_info->channels;
  198307. for (i = 0; i < istop; i++, rp += 2)
  198308. {
  198309. png_byte t = *rp;
  198310. *rp = *(rp + 1);
  198311. *(rp + 1) = t;
  198312. }
  198313. }
  198314. }
  198315. #endif
  198316. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198317. static PNG_CONST png_byte onebppswaptable[256] = {
  198318. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198319. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198320. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198321. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198322. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198323. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198324. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198325. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198326. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198327. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198328. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198329. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198330. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198331. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198332. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198333. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198334. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198335. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198336. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198337. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198338. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198339. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198340. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198341. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198342. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198343. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198344. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198345. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198346. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198347. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198348. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198349. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198350. };
  198351. static PNG_CONST png_byte twobppswaptable[256] = {
  198352. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198353. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198354. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198355. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198356. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198357. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198358. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198359. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198360. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198361. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198362. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198363. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198364. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198365. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198366. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198367. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198368. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198369. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198370. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198371. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198372. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198373. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198374. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198375. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198376. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198377. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198378. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198379. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198380. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198381. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198382. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198383. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198384. };
  198385. static PNG_CONST png_byte fourbppswaptable[256] = {
  198386. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198387. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198388. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198389. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198390. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198391. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198392. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198393. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198394. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198395. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198396. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198397. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198398. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198399. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198400. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198401. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198402. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198403. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198404. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198405. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198406. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198407. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198408. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198409. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198410. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198411. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198412. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198413. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198414. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198415. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198416. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198417. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198418. };
  198419. /* swaps pixel packing order within bytes */
  198420. void /* PRIVATE */
  198421. png_do_packswap(png_row_infop row_info, png_bytep row)
  198422. {
  198423. png_debug(1, "in png_do_packswap\n");
  198424. if (
  198425. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198426. row != NULL && row_info != NULL &&
  198427. #endif
  198428. row_info->bit_depth < 8)
  198429. {
  198430. png_bytep rp, end, table;
  198431. end = row + row_info->rowbytes;
  198432. if (row_info->bit_depth == 1)
  198433. table = (png_bytep)onebppswaptable;
  198434. else if (row_info->bit_depth == 2)
  198435. table = (png_bytep)twobppswaptable;
  198436. else if (row_info->bit_depth == 4)
  198437. table = (png_bytep)fourbppswaptable;
  198438. else
  198439. return;
  198440. for (rp = row; rp < end; rp++)
  198441. *rp = table[*rp];
  198442. }
  198443. }
  198444. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198445. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198446. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198447. /* remove filler or alpha byte(s) */
  198448. void /* PRIVATE */
  198449. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198450. {
  198451. png_debug(1, "in png_do_strip_filler\n");
  198452. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198453. if (row != NULL && row_info != NULL)
  198454. #endif
  198455. {
  198456. png_bytep sp=row;
  198457. png_bytep dp=row;
  198458. png_uint_32 row_width=row_info->width;
  198459. png_uint_32 i;
  198460. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198461. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198462. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198463. row_info->channels == 4)
  198464. {
  198465. if (row_info->bit_depth == 8)
  198466. {
  198467. /* This converts from RGBX or RGBA to RGB */
  198468. if (flags & PNG_FLAG_FILLER_AFTER)
  198469. {
  198470. dp+=3; sp+=4;
  198471. for (i = 1; i < row_width; i++)
  198472. {
  198473. *dp++ = *sp++;
  198474. *dp++ = *sp++;
  198475. *dp++ = *sp++;
  198476. sp++;
  198477. }
  198478. }
  198479. /* This converts from XRGB or ARGB to RGB */
  198480. else
  198481. {
  198482. for (i = 0; i < row_width; i++)
  198483. {
  198484. sp++;
  198485. *dp++ = *sp++;
  198486. *dp++ = *sp++;
  198487. *dp++ = *sp++;
  198488. }
  198489. }
  198490. row_info->pixel_depth = 24;
  198491. row_info->rowbytes = row_width * 3;
  198492. }
  198493. else /* if (row_info->bit_depth == 16) */
  198494. {
  198495. if (flags & PNG_FLAG_FILLER_AFTER)
  198496. {
  198497. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198498. sp += 8; dp += 6;
  198499. for (i = 1; i < row_width; i++)
  198500. {
  198501. /* This could be (although png_memcpy is probably slower):
  198502. png_memcpy(dp, sp, 6);
  198503. sp += 8;
  198504. dp += 6;
  198505. */
  198506. *dp++ = *sp++;
  198507. *dp++ = *sp++;
  198508. *dp++ = *sp++;
  198509. *dp++ = *sp++;
  198510. *dp++ = *sp++;
  198511. *dp++ = *sp++;
  198512. sp += 2;
  198513. }
  198514. }
  198515. else
  198516. {
  198517. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198518. for (i = 0; i < row_width; i++)
  198519. {
  198520. /* This could be (although png_memcpy is probably slower):
  198521. png_memcpy(dp, sp, 6);
  198522. sp += 8;
  198523. dp += 6;
  198524. */
  198525. sp+=2;
  198526. *dp++ = *sp++;
  198527. *dp++ = *sp++;
  198528. *dp++ = *sp++;
  198529. *dp++ = *sp++;
  198530. *dp++ = *sp++;
  198531. *dp++ = *sp++;
  198532. }
  198533. }
  198534. row_info->pixel_depth = 48;
  198535. row_info->rowbytes = row_width * 6;
  198536. }
  198537. row_info->channels = 3;
  198538. }
  198539. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198540. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198541. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198542. row_info->channels == 2)
  198543. {
  198544. if (row_info->bit_depth == 8)
  198545. {
  198546. /* This converts from GX or GA to G */
  198547. if (flags & PNG_FLAG_FILLER_AFTER)
  198548. {
  198549. for (i = 0; i < row_width; i++)
  198550. {
  198551. *dp++ = *sp++;
  198552. sp++;
  198553. }
  198554. }
  198555. /* This converts from XG or AG to G */
  198556. else
  198557. {
  198558. for (i = 0; i < row_width; i++)
  198559. {
  198560. sp++;
  198561. *dp++ = *sp++;
  198562. }
  198563. }
  198564. row_info->pixel_depth = 8;
  198565. row_info->rowbytes = row_width;
  198566. }
  198567. else /* if (row_info->bit_depth == 16) */
  198568. {
  198569. if (flags & PNG_FLAG_FILLER_AFTER)
  198570. {
  198571. /* This converts from GGXX or GGAA to GG */
  198572. sp += 4; dp += 2;
  198573. for (i = 1; i < row_width; i++)
  198574. {
  198575. *dp++ = *sp++;
  198576. *dp++ = *sp++;
  198577. sp += 2;
  198578. }
  198579. }
  198580. else
  198581. {
  198582. /* This converts from XXGG or AAGG to GG */
  198583. for (i = 0; i < row_width; i++)
  198584. {
  198585. sp += 2;
  198586. *dp++ = *sp++;
  198587. *dp++ = *sp++;
  198588. }
  198589. }
  198590. row_info->pixel_depth = 16;
  198591. row_info->rowbytes = row_width * 2;
  198592. }
  198593. row_info->channels = 1;
  198594. }
  198595. if (flags & PNG_FLAG_STRIP_ALPHA)
  198596. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198597. }
  198598. }
  198599. #endif
  198600. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198601. /* swaps red and blue bytes within a pixel */
  198602. void /* PRIVATE */
  198603. png_do_bgr(png_row_infop row_info, png_bytep row)
  198604. {
  198605. png_debug(1, "in png_do_bgr\n");
  198606. if (
  198607. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198608. row != NULL && row_info != NULL &&
  198609. #endif
  198610. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198611. {
  198612. png_uint_32 row_width = row_info->width;
  198613. if (row_info->bit_depth == 8)
  198614. {
  198615. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198616. {
  198617. png_bytep rp;
  198618. png_uint_32 i;
  198619. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198620. {
  198621. png_byte save = *rp;
  198622. *rp = *(rp + 2);
  198623. *(rp + 2) = save;
  198624. }
  198625. }
  198626. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198627. {
  198628. png_bytep rp;
  198629. png_uint_32 i;
  198630. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198631. {
  198632. png_byte save = *rp;
  198633. *rp = *(rp + 2);
  198634. *(rp + 2) = save;
  198635. }
  198636. }
  198637. }
  198638. else if (row_info->bit_depth == 16)
  198639. {
  198640. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198641. {
  198642. png_bytep rp;
  198643. png_uint_32 i;
  198644. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198645. {
  198646. png_byte save = *rp;
  198647. *rp = *(rp + 4);
  198648. *(rp + 4) = save;
  198649. save = *(rp + 1);
  198650. *(rp + 1) = *(rp + 5);
  198651. *(rp + 5) = save;
  198652. }
  198653. }
  198654. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198655. {
  198656. png_bytep rp;
  198657. png_uint_32 i;
  198658. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198659. {
  198660. png_byte save = *rp;
  198661. *rp = *(rp + 4);
  198662. *(rp + 4) = save;
  198663. save = *(rp + 1);
  198664. *(rp + 1) = *(rp + 5);
  198665. *(rp + 5) = save;
  198666. }
  198667. }
  198668. }
  198669. }
  198670. }
  198671. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198672. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198673. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198674. defined(PNG_LEGACY_SUPPORTED)
  198675. void PNGAPI
  198676. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198677. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198678. {
  198679. png_debug(1, "in png_set_user_transform_info\n");
  198680. if(png_ptr == NULL) return;
  198681. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198682. png_ptr->user_transform_ptr = user_transform_ptr;
  198683. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198684. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198685. #else
  198686. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198687. png_warning(png_ptr,
  198688. "This version of libpng does not support user transform info");
  198689. #endif
  198690. }
  198691. #endif
  198692. /* This function returns a pointer to the user_transform_ptr associated with
  198693. * the user transform functions. The application should free any memory
  198694. * associated with this pointer before png_write_destroy and png_read_destroy
  198695. * are called.
  198696. */
  198697. png_voidp PNGAPI
  198698. png_get_user_transform_ptr(png_structp png_ptr)
  198699. {
  198700. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198701. if (png_ptr == NULL) return (NULL);
  198702. return ((png_voidp)png_ptr->user_transform_ptr);
  198703. #else
  198704. return (NULL);
  198705. #endif
  198706. }
  198707. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198708. /*** End of inlined file: pngtrans.c ***/
  198709. /*** Start of inlined file: pngwio.c ***/
  198710. /* pngwio.c - functions for data output
  198711. *
  198712. * Last changed in libpng 1.2.13 November 13, 2006
  198713. * For conditions of distribution and use, see copyright notice in png.h
  198714. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198715. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198716. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198717. *
  198718. * This file provides a location for all output. Users who need
  198719. * special handling are expected to write functions that have the same
  198720. * arguments as these and perform similar functions, but that possibly
  198721. * use different output methods. Note that you shouldn't change these
  198722. * functions, but rather write replacement functions and then change
  198723. * them at run time with png_set_write_fn(...).
  198724. */
  198725. #define PNG_INTERNAL
  198726. #ifdef PNG_WRITE_SUPPORTED
  198727. /* Write the data to whatever output you are using. The default routine
  198728. writes to a file pointer. Note that this routine sometimes gets called
  198729. with very small lengths, so you should implement some kind of simple
  198730. buffering if you are using unbuffered writes. This should never be asked
  198731. to write more than 64K on a 16 bit machine. */
  198732. void /* PRIVATE */
  198733. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198734. {
  198735. if (png_ptr->write_data_fn != NULL )
  198736. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198737. else
  198738. png_error(png_ptr, "Call to NULL write function");
  198739. }
  198740. #if !defined(PNG_NO_STDIO)
  198741. /* This is the function that does the actual writing of data. If you are
  198742. not writing to a standard C stream, you should create a replacement
  198743. write_data function and use it at run time with png_set_write_fn(), rather
  198744. than changing the library. */
  198745. #ifndef USE_FAR_KEYWORD
  198746. void PNGAPI
  198747. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198748. {
  198749. png_uint_32 check;
  198750. if(png_ptr == NULL) return;
  198751. #if defined(_WIN32_WCE)
  198752. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198753. check = 0;
  198754. #else
  198755. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198756. #endif
  198757. if (check != length)
  198758. png_error(png_ptr, "Write Error");
  198759. }
  198760. #else
  198761. /* this is the model-independent version. Since the standard I/O library
  198762. can't handle far buffers in the medium and small models, we have to copy
  198763. the data.
  198764. */
  198765. #define NEAR_BUF_SIZE 1024
  198766. #define MIN(a,b) (a <= b ? a : b)
  198767. void PNGAPI
  198768. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198769. {
  198770. png_uint_32 check;
  198771. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198772. png_FILE_p io_ptr;
  198773. if(png_ptr == NULL) return;
  198774. /* Check if data really is near. If so, use usual code. */
  198775. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198776. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198777. if ((png_bytep)near_data == data)
  198778. {
  198779. #if defined(_WIN32_WCE)
  198780. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198781. check = 0;
  198782. #else
  198783. check = fwrite(near_data, 1, length, io_ptr);
  198784. #endif
  198785. }
  198786. else
  198787. {
  198788. png_byte buf[NEAR_BUF_SIZE];
  198789. png_size_t written, remaining, err;
  198790. check = 0;
  198791. remaining = length;
  198792. do
  198793. {
  198794. written = MIN(NEAR_BUF_SIZE, remaining);
  198795. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198796. #if defined(_WIN32_WCE)
  198797. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198798. err = 0;
  198799. #else
  198800. err = fwrite(buf, 1, written, io_ptr);
  198801. #endif
  198802. if (err != written)
  198803. break;
  198804. else
  198805. check += err;
  198806. data += written;
  198807. remaining -= written;
  198808. }
  198809. while (remaining != 0);
  198810. }
  198811. if (check != length)
  198812. png_error(png_ptr, "Write Error");
  198813. }
  198814. #endif
  198815. #endif
  198816. /* This function is called to output any data pending writing (normally
  198817. to disk). After png_flush is called, there should be no data pending
  198818. writing in any buffers. */
  198819. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198820. void /* PRIVATE */
  198821. png_flush(png_structp png_ptr)
  198822. {
  198823. if (png_ptr->output_flush_fn != NULL)
  198824. (*(png_ptr->output_flush_fn))(png_ptr);
  198825. }
  198826. #if !defined(PNG_NO_STDIO)
  198827. void PNGAPI
  198828. png_default_flush(png_structp png_ptr)
  198829. {
  198830. #if !defined(_WIN32_WCE)
  198831. png_FILE_p io_ptr;
  198832. #endif
  198833. if(png_ptr == NULL) return;
  198834. #if !defined(_WIN32_WCE)
  198835. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198836. if (io_ptr != NULL)
  198837. fflush(io_ptr);
  198838. #endif
  198839. }
  198840. #endif
  198841. #endif
  198842. /* This function allows the application to supply new output functions for
  198843. libpng if standard C streams aren't being used.
  198844. This function takes as its arguments:
  198845. png_ptr - pointer to a png output data structure
  198846. io_ptr - pointer to user supplied structure containing info about
  198847. the output functions. May be NULL.
  198848. write_data_fn - pointer to a new output function that takes as its
  198849. arguments a pointer to a png_struct, a pointer to
  198850. data to be written, and a 32-bit unsigned int that is
  198851. the number of bytes to be written. The new write
  198852. function should call png_error(png_ptr, "Error msg")
  198853. to exit and output any fatal error messages.
  198854. flush_data_fn - pointer to a new flush function that takes as its
  198855. arguments a pointer to a png_struct. After a call to
  198856. the flush function, there should be no data in any buffers
  198857. or pending transmission. If the output method doesn't do
  198858. any buffering of ouput, a function prototype must still be
  198859. supplied although it doesn't have to do anything. If
  198860. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198861. time, output_flush_fn will be ignored, although it must be
  198862. supplied for compatibility. */
  198863. void PNGAPI
  198864. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198865. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198866. {
  198867. if(png_ptr == NULL) return;
  198868. png_ptr->io_ptr = io_ptr;
  198869. #if !defined(PNG_NO_STDIO)
  198870. if (write_data_fn != NULL)
  198871. png_ptr->write_data_fn = write_data_fn;
  198872. else
  198873. png_ptr->write_data_fn = png_default_write_data;
  198874. #else
  198875. png_ptr->write_data_fn = write_data_fn;
  198876. #endif
  198877. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198878. #if !defined(PNG_NO_STDIO)
  198879. if (output_flush_fn != NULL)
  198880. png_ptr->output_flush_fn = output_flush_fn;
  198881. else
  198882. png_ptr->output_flush_fn = png_default_flush;
  198883. #else
  198884. png_ptr->output_flush_fn = output_flush_fn;
  198885. #endif
  198886. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198887. /* It is an error to read while writing a png file */
  198888. if (png_ptr->read_data_fn != NULL)
  198889. {
  198890. png_ptr->read_data_fn = NULL;
  198891. png_warning(png_ptr,
  198892. "Attempted to set both read_data_fn and write_data_fn in");
  198893. png_warning(png_ptr,
  198894. "the same structure. Resetting read_data_fn to NULL.");
  198895. }
  198896. }
  198897. #if defined(USE_FAR_KEYWORD)
  198898. #if defined(_MSC_VER)
  198899. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198900. {
  198901. void *near_ptr;
  198902. void FAR *far_ptr;
  198903. FP_OFF(near_ptr) = FP_OFF(ptr);
  198904. far_ptr = (void FAR *)near_ptr;
  198905. if(check != 0)
  198906. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198907. png_error(png_ptr,"segment lost in conversion");
  198908. return(near_ptr);
  198909. }
  198910. # else
  198911. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198912. {
  198913. void *near_ptr;
  198914. void FAR *far_ptr;
  198915. near_ptr = (void FAR *)ptr;
  198916. far_ptr = (void FAR *)near_ptr;
  198917. if(check != 0)
  198918. if(far_ptr != ptr)
  198919. png_error(png_ptr,"segment lost in conversion");
  198920. return(near_ptr);
  198921. }
  198922. # endif
  198923. # endif
  198924. #endif /* PNG_WRITE_SUPPORTED */
  198925. /*** End of inlined file: pngwio.c ***/
  198926. /*** Start of inlined file: pngwrite.c ***/
  198927. /* pngwrite.c - general routines to write a PNG file
  198928. *
  198929. * Last changed in libpng 1.2.15 January 5, 2007
  198930. * For conditions of distribution and use, see copyright notice in png.h
  198931. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198932. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198933. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198934. */
  198935. /* get internal access to png.h */
  198936. #define PNG_INTERNAL
  198937. #ifdef PNG_WRITE_SUPPORTED
  198938. /* Writes all the PNG information. This is the suggested way to use the
  198939. * library. If you have a new chunk to add, make a function to write it,
  198940. * and put it in the correct location here. If you want the chunk written
  198941. * after the image data, put it in png_write_end(). I strongly encourage
  198942. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198943. * the chunk, as that will keep the code from breaking if you want to just
  198944. * write a plain PNG file. If you have long comments, I suggest writing
  198945. * them in png_write_end(), and compressing them.
  198946. */
  198947. void PNGAPI
  198948. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198949. {
  198950. png_debug(1, "in png_write_info_before_PLTE\n");
  198951. if (png_ptr == NULL || info_ptr == NULL)
  198952. return;
  198953. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198954. {
  198955. png_write_sig(png_ptr); /* write PNG signature */
  198956. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198957. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198958. {
  198959. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198960. png_ptr->mng_features_permitted=0;
  198961. }
  198962. #endif
  198963. /* write IHDR information. */
  198964. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198965. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198966. info_ptr->filter_type,
  198967. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198968. info_ptr->interlace_type);
  198969. #else
  198970. 0);
  198971. #endif
  198972. /* the rest of these check to see if the valid field has the appropriate
  198973. flag set, and if it does, writes the chunk. */
  198974. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198975. if (info_ptr->valid & PNG_INFO_gAMA)
  198976. {
  198977. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198978. png_write_gAMA(png_ptr, info_ptr->gamma);
  198979. #else
  198980. #ifdef PNG_FIXED_POINT_SUPPORTED
  198981. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198982. # endif
  198983. #endif
  198984. }
  198985. #endif
  198986. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198987. if (info_ptr->valid & PNG_INFO_sRGB)
  198988. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198989. #endif
  198990. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198991. if (info_ptr->valid & PNG_INFO_iCCP)
  198992. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198993. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198994. #endif
  198995. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198996. if (info_ptr->valid & PNG_INFO_sBIT)
  198997. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198998. #endif
  198999. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  199000. if (info_ptr->valid & PNG_INFO_cHRM)
  199001. {
  199002. #ifdef PNG_FLOATING_POINT_SUPPORTED
  199003. png_write_cHRM(png_ptr,
  199004. info_ptr->x_white, info_ptr->y_white,
  199005. info_ptr->x_red, info_ptr->y_red,
  199006. info_ptr->x_green, info_ptr->y_green,
  199007. info_ptr->x_blue, info_ptr->y_blue);
  199008. #else
  199009. # ifdef PNG_FIXED_POINT_SUPPORTED
  199010. png_write_cHRM_fixed(png_ptr,
  199011. info_ptr->int_x_white, info_ptr->int_y_white,
  199012. info_ptr->int_x_red, info_ptr->int_y_red,
  199013. info_ptr->int_x_green, info_ptr->int_y_green,
  199014. info_ptr->int_x_blue, info_ptr->int_y_blue);
  199015. # endif
  199016. #endif
  199017. }
  199018. #endif
  199019. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199020. if (info_ptr->unknown_chunks_num)
  199021. {
  199022. png_unknown_chunk *up;
  199023. png_debug(5, "writing extra chunks\n");
  199024. for (up = info_ptr->unknown_chunks;
  199025. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199026. up++)
  199027. {
  199028. int keep=png_handle_as_unknown(png_ptr, up->name);
  199029. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199030. up->location && !(up->location & PNG_HAVE_PLTE) &&
  199031. !(up->location & PNG_HAVE_IDAT) &&
  199032. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199033. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199034. {
  199035. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199036. }
  199037. }
  199038. }
  199039. #endif
  199040. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  199041. }
  199042. }
  199043. void PNGAPI
  199044. png_write_info(png_structp png_ptr, png_infop info_ptr)
  199045. {
  199046. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  199047. int i;
  199048. #endif
  199049. png_debug(1, "in png_write_info\n");
  199050. if (png_ptr == NULL || info_ptr == NULL)
  199051. return;
  199052. png_write_info_before_PLTE(png_ptr, info_ptr);
  199053. if (info_ptr->valid & PNG_INFO_PLTE)
  199054. png_write_PLTE(png_ptr, info_ptr->palette,
  199055. (png_uint_32)info_ptr->num_palette);
  199056. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199057. png_error(png_ptr, "Valid palette required for paletted images");
  199058. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  199059. if (info_ptr->valid & PNG_INFO_tRNS)
  199060. {
  199061. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199062. /* invert the alpha channel (in tRNS) */
  199063. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  199064. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199065. {
  199066. int j;
  199067. for (j=0; j<(int)info_ptr->num_trans; j++)
  199068. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  199069. }
  199070. #endif
  199071. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  199072. info_ptr->num_trans, info_ptr->color_type);
  199073. }
  199074. #endif
  199075. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  199076. if (info_ptr->valid & PNG_INFO_bKGD)
  199077. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  199078. #endif
  199079. #if defined(PNG_WRITE_hIST_SUPPORTED)
  199080. if (info_ptr->valid & PNG_INFO_hIST)
  199081. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  199082. #endif
  199083. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199084. if (info_ptr->valid & PNG_INFO_oFFs)
  199085. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  199086. info_ptr->offset_unit_type);
  199087. #endif
  199088. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199089. if (info_ptr->valid & PNG_INFO_pCAL)
  199090. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  199091. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  199092. info_ptr->pcal_units, info_ptr->pcal_params);
  199093. #endif
  199094. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199095. if (info_ptr->valid & PNG_INFO_sCAL)
  199096. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199097. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  199098. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  199099. #else
  199100. #ifdef PNG_FIXED_POINT_SUPPORTED
  199101. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  199102. info_ptr->scal_s_width, info_ptr->scal_s_height);
  199103. #else
  199104. png_warning(png_ptr,
  199105. "png_write_sCAL not supported; sCAL chunk not written.");
  199106. #endif
  199107. #endif
  199108. #endif
  199109. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199110. if (info_ptr->valid & PNG_INFO_pHYs)
  199111. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  199112. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  199113. #endif
  199114. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199115. if (info_ptr->valid & PNG_INFO_tIME)
  199116. {
  199117. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199118. png_ptr->mode |= PNG_WROTE_tIME;
  199119. }
  199120. #endif
  199121. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199122. if (info_ptr->valid & PNG_INFO_sPLT)
  199123. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199124. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199125. #endif
  199126. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199127. /* Check to see if we need to write text chunks */
  199128. for (i = 0; i < info_ptr->num_text; i++)
  199129. {
  199130. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199131. info_ptr->text[i].compression);
  199132. /* an internationalized chunk? */
  199133. if (info_ptr->text[i].compression > 0)
  199134. {
  199135. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199136. /* write international chunk */
  199137. png_write_iTXt(png_ptr,
  199138. info_ptr->text[i].compression,
  199139. info_ptr->text[i].key,
  199140. info_ptr->text[i].lang,
  199141. info_ptr->text[i].lang_key,
  199142. info_ptr->text[i].text);
  199143. #else
  199144. png_warning(png_ptr, "Unable to write international text");
  199145. #endif
  199146. /* Mark this chunk as written */
  199147. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199148. }
  199149. /* If we want a compressed text chunk */
  199150. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199151. {
  199152. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199153. /* write compressed chunk */
  199154. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199155. info_ptr->text[i].text, 0,
  199156. info_ptr->text[i].compression);
  199157. #else
  199158. png_warning(png_ptr, "Unable to write compressed text");
  199159. #endif
  199160. /* Mark this chunk as written */
  199161. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199162. }
  199163. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199164. {
  199165. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199166. /* write uncompressed chunk */
  199167. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199168. info_ptr->text[i].text,
  199169. 0);
  199170. #else
  199171. png_warning(png_ptr, "Unable to write uncompressed text");
  199172. #endif
  199173. /* Mark this chunk as written */
  199174. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199175. }
  199176. }
  199177. #endif
  199178. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199179. if (info_ptr->unknown_chunks_num)
  199180. {
  199181. png_unknown_chunk *up;
  199182. png_debug(5, "writing extra chunks\n");
  199183. for (up = info_ptr->unknown_chunks;
  199184. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199185. up++)
  199186. {
  199187. int keep=png_handle_as_unknown(png_ptr, up->name);
  199188. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199189. up->location && (up->location & PNG_HAVE_PLTE) &&
  199190. !(up->location & PNG_HAVE_IDAT) &&
  199191. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199192. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199193. {
  199194. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199195. }
  199196. }
  199197. }
  199198. #endif
  199199. }
  199200. /* Writes the end of the PNG file. If you don't want to write comments or
  199201. * time information, you can pass NULL for info. If you already wrote these
  199202. * in png_write_info(), do not write them again here. If you have long
  199203. * comments, I suggest writing them here, and compressing them.
  199204. */
  199205. void PNGAPI
  199206. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199207. {
  199208. png_debug(1, "in png_write_end\n");
  199209. if (png_ptr == NULL)
  199210. return;
  199211. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199212. png_error(png_ptr, "No IDATs written into file");
  199213. /* see if user wants us to write information chunks */
  199214. if (info_ptr != NULL)
  199215. {
  199216. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199217. int i; /* local index variable */
  199218. #endif
  199219. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199220. /* check to see if user has supplied a time chunk */
  199221. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199222. !(png_ptr->mode & PNG_WROTE_tIME))
  199223. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199224. #endif
  199225. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199226. /* loop through comment chunks */
  199227. for (i = 0; i < info_ptr->num_text; i++)
  199228. {
  199229. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199230. info_ptr->text[i].compression);
  199231. /* an internationalized chunk? */
  199232. if (info_ptr->text[i].compression > 0)
  199233. {
  199234. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199235. /* write international chunk */
  199236. png_write_iTXt(png_ptr,
  199237. info_ptr->text[i].compression,
  199238. info_ptr->text[i].key,
  199239. info_ptr->text[i].lang,
  199240. info_ptr->text[i].lang_key,
  199241. info_ptr->text[i].text);
  199242. #else
  199243. png_warning(png_ptr, "Unable to write international text");
  199244. #endif
  199245. /* Mark this chunk as written */
  199246. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199247. }
  199248. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199249. {
  199250. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199251. /* write compressed chunk */
  199252. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199253. info_ptr->text[i].text, 0,
  199254. info_ptr->text[i].compression);
  199255. #else
  199256. png_warning(png_ptr, "Unable to write compressed text");
  199257. #endif
  199258. /* Mark this chunk as written */
  199259. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199260. }
  199261. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199262. {
  199263. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199264. /* write uncompressed chunk */
  199265. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199266. info_ptr->text[i].text, 0);
  199267. #else
  199268. png_warning(png_ptr, "Unable to write uncompressed text");
  199269. #endif
  199270. /* Mark this chunk as written */
  199271. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199272. }
  199273. }
  199274. #endif
  199275. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199276. if (info_ptr->unknown_chunks_num)
  199277. {
  199278. png_unknown_chunk *up;
  199279. png_debug(5, "writing extra chunks\n");
  199280. for (up = info_ptr->unknown_chunks;
  199281. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199282. up++)
  199283. {
  199284. int keep=png_handle_as_unknown(png_ptr, up->name);
  199285. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199286. up->location && (up->location & PNG_AFTER_IDAT) &&
  199287. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199288. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199289. {
  199290. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199291. }
  199292. }
  199293. }
  199294. #endif
  199295. }
  199296. png_ptr->mode |= PNG_AFTER_IDAT;
  199297. /* write end of PNG file */
  199298. png_write_IEND(png_ptr);
  199299. }
  199300. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199301. #if !defined(_WIN32_WCE)
  199302. /* "time.h" functions are not supported on WindowsCE */
  199303. void PNGAPI
  199304. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199305. {
  199306. png_debug(1, "in png_convert_from_struct_tm\n");
  199307. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199308. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199309. ptime->day = (png_byte)ttime->tm_mday;
  199310. ptime->hour = (png_byte)ttime->tm_hour;
  199311. ptime->minute = (png_byte)ttime->tm_min;
  199312. ptime->second = (png_byte)ttime->tm_sec;
  199313. }
  199314. void PNGAPI
  199315. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199316. {
  199317. struct tm *tbuf;
  199318. png_debug(1, "in png_convert_from_time_t\n");
  199319. tbuf = gmtime(&ttime);
  199320. png_convert_from_struct_tm(ptime, tbuf);
  199321. }
  199322. #endif
  199323. #endif
  199324. /* Initialize png_ptr structure, and allocate any memory needed */
  199325. png_structp PNGAPI
  199326. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199327. png_error_ptr error_fn, png_error_ptr warn_fn)
  199328. {
  199329. #ifdef PNG_USER_MEM_SUPPORTED
  199330. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199331. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199332. }
  199333. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199334. png_structp PNGAPI
  199335. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199336. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199337. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199338. {
  199339. #endif /* PNG_USER_MEM_SUPPORTED */
  199340. png_structp png_ptr;
  199341. #ifdef PNG_SETJMP_SUPPORTED
  199342. #ifdef USE_FAR_KEYWORD
  199343. jmp_buf jmpbuf;
  199344. #endif
  199345. #endif
  199346. int i;
  199347. png_debug(1, "in png_create_write_struct\n");
  199348. #ifdef PNG_USER_MEM_SUPPORTED
  199349. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199350. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199351. #else
  199352. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199353. #endif /* PNG_USER_MEM_SUPPORTED */
  199354. if (png_ptr == NULL)
  199355. return (NULL);
  199356. /* added at libpng-1.2.6 */
  199357. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199358. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199359. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199360. #endif
  199361. #ifdef PNG_SETJMP_SUPPORTED
  199362. #ifdef USE_FAR_KEYWORD
  199363. if (setjmp(jmpbuf))
  199364. #else
  199365. if (setjmp(png_ptr->jmpbuf))
  199366. #endif
  199367. {
  199368. png_free(png_ptr, png_ptr->zbuf);
  199369. png_ptr->zbuf=NULL;
  199370. png_destroy_struct(png_ptr);
  199371. return (NULL);
  199372. }
  199373. #ifdef USE_FAR_KEYWORD
  199374. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199375. #endif
  199376. #endif
  199377. #ifdef PNG_USER_MEM_SUPPORTED
  199378. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199379. #endif /* PNG_USER_MEM_SUPPORTED */
  199380. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199381. i=0;
  199382. do
  199383. {
  199384. if(user_png_ver[i] != png_libpng_ver[i])
  199385. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199386. } while (png_libpng_ver[i++]);
  199387. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199388. {
  199389. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199390. * we must recompile any applications that use any older library version.
  199391. * For versions after libpng 1.0, we will be compatible, so we need
  199392. * only check the first digit.
  199393. */
  199394. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199395. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199396. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199397. {
  199398. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199399. char msg[80];
  199400. if (user_png_ver)
  199401. {
  199402. png_snprintf(msg, 80,
  199403. "Application was compiled with png.h from libpng-%.20s",
  199404. user_png_ver);
  199405. png_warning(png_ptr, msg);
  199406. }
  199407. png_snprintf(msg, 80,
  199408. "Application is running with png.c from libpng-%.20s",
  199409. png_libpng_ver);
  199410. png_warning(png_ptr, msg);
  199411. #endif
  199412. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199413. png_ptr->flags=0;
  199414. #endif
  199415. png_error(png_ptr,
  199416. "Incompatible libpng version in application and library");
  199417. }
  199418. }
  199419. /* initialize zbuf - compression buffer */
  199420. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199421. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199422. (png_uint_32)png_ptr->zbuf_size);
  199423. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199424. png_flush_ptr_NULL);
  199425. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199426. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199427. 1, png_doublep_NULL, png_doublep_NULL);
  199428. #endif
  199429. #ifdef PNG_SETJMP_SUPPORTED
  199430. /* Applications that neglect to set up their own setjmp() and then encounter
  199431. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199432. abort instead of returning. */
  199433. #ifdef USE_FAR_KEYWORD
  199434. if (setjmp(jmpbuf))
  199435. PNG_ABORT();
  199436. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199437. #else
  199438. if (setjmp(png_ptr->jmpbuf))
  199439. PNG_ABORT();
  199440. #endif
  199441. #endif
  199442. return (png_ptr);
  199443. }
  199444. /* Initialize png_ptr structure, and allocate any memory needed */
  199445. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199446. /* Deprecated. */
  199447. #undef png_write_init
  199448. void PNGAPI
  199449. png_write_init(png_structp png_ptr)
  199450. {
  199451. /* We only come here via pre-1.0.7-compiled applications */
  199452. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199453. }
  199454. void PNGAPI
  199455. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199456. png_size_t png_struct_size, png_size_t png_info_size)
  199457. {
  199458. /* We only come here via pre-1.0.12-compiled applications */
  199459. if(png_ptr == NULL) return;
  199460. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199461. if(png_sizeof(png_struct) > png_struct_size ||
  199462. png_sizeof(png_info) > png_info_size)
  199463. {
  199464. char msg[80];
  199465. png_ptr->warning_fn=NULL;
  199466. if (user_png_ver)
  199467. {
  199468. png_snprintf(msg, 80,
  199469. "Application was compiled with png.h from libpng-%.20s",
  199470. user_png_ver);
  199471. png_warning(png_ptr, msg);
  199472. }
  199473. png_snprintf(msg, 80,
  199474. "Application is running with png.c from libpng-%.20s",
  199475. png_libpng_ver);
  199476. png_warning(png_ptr, msg);
  199477. }
  199478. #endif
  199479. if(png_sizeof(png_struct) > png_struct_size)
  199480. {
  199481. png_ptr->error_fn=NULL;
  199482. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199483. png_ptr->flags=0;
  199484. #endif
  199485. png_error(png_ptr,
  199486. "The png struct allocated by the application for writing is too small.");
  199487. }
  199488. if(png_sizeof(png_info) > png_info_size)
  199489. {
  199490. png_ptr->error_fn=NULL;
  199491. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199492. png_ptr->flags=0;
  199493. #endif
  199494. png_error(png_ptr,
  199495. "The info struct allocated by the application for writing is too small.");
  199496. }
  199497. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199498. }
  199499. #endif /* PNG_1_0_X || PNG_1_2_X */
  199500. void PNGAPI
  199501. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199502. png_size_t png_struct_size)
  199503. {
  199504. png_structp png_ptr=*ptr_ptr;
  199505. #ifdef PNG_SETJMP_SUPPORTED
  199506. jmp_buf tmp_jmp; /* to save current jump buffer */
  199507. #endif
  199508. int i = 0;
  199509. if (png_ptr == NULL)
  199510. return;
  199511. do
  199512. {
  199513. if (user_png_ver[i] != png_libpng_ver[i])
  199514. {
  199515. #ifdef PNG_LEGACY_SUPPORTED
  199516. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199517. #else
  199518. png_ptr->warning_fn=NULL;
  199519. png_warning(png_ptr,
  199520. "Application uses deprecated png_write_init() and should be recompiled.");
  199521. break;
  199522. #endif
  199523. }
  199524. } while (png_libpng_ver[i++]);
  199525. png_debug(1, "in png_write_init_3\n");
  199526. #ifdef PNG_SETJMP_SUPPORTED
  199527. /* save jump buffer and error functions */
  199528. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199529. #endif
  199530. if (png_sizeof(png_struct) > png_struct_size)
  199531. {
  199532. png_destroy_struct(png_ptr);
  199533. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199534. *ptr_ptr = png_ptr;
  199535. }
  199536. /* reset all variables to 0 */
  199537. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199538. /* added at libpng-1.2.6 */
  199539. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199540. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199541. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199542. #endif
  199543. #ifdef PNG_SETJMP_SUPPORTED
  199544. /* restore jump buffer */
  199545. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199546. #endif
  199547. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199548. png_flush_ptr_NULL);
  199549. /* initialize zbuf - compression buffer */
  199550. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199551. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199552. (png_uint_32)png_ptr->zbuf_size);
  199553. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199554. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199555. 1, png_doublep_NULL, png_doublep_NULL);
  199556. #endif
  199557. }
  199558. /* Write a few rows of image data. If the image is interlaced,
  199559. * either you will have to write the 7 sub images, or, if you
  199560. * have called png_set_interlace_handling(), you will have to
  199561. * "write" the image seven times.
  199562. */
  199563. void PNGAPI
  199564. png_write_rows(png_structp png_ptr, png_bytepp row,
  199565. png_uint_32 num_rows)
  199566. {
  199567. png_uint_32 i; /* row counter */
  199568. png_bytepp rp; /* row pointer */
  199569. png_debug(1, "in png_write_rows\n");
  199570. if (png_ptr == NULL)
  199571. return;
  199572. /* loop through the rows */
  199573. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199574. {
  199575. png_write_row(png_ptr, *rp);
  199576. }
  199577. }
  199578. /* Write the image. You only need to call this function once, even
  199579. * if you are writing an interlaced image.
  199580. */
  199581. void PNGAPI
  199582. png_write_image(png_structp png_ptr, png_bytepp image)
  199583. {
  199584. png_uint_32 i; /* row index */
  199585. int pass, num_pass; /* pass variables */
  199586. png_bytepp rp; /* points to current row */
  199587. if (png_ptr == NULL)
  199588. return;
  199589. png_debug(1, "in png_write_image\n");
  199590. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199591. /* intialize interlace handling. If image is not interlaced,
  199592. this will set pass to 1 */
  199593. num_pass = png_set_interlace_handling(png_ptr);
  199594. #else
  199595. num_pass = 1;
  199596. #endif
  199597. /* loop through passes */
  199598. for (pass = 0; pass < num_pass; pass++)
  199599. {
  199600. /* loop through image */
  199601. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199602. {
  199603. png_write_row(png_ptr, *rp);
  199604. }
  199605. }
  199606. }
  199607. /* called by user to write a row of image data */
  199608. void PNGAPI
  199609. png_write_row(png_structp png_ptr, png_bytep row)
  199610. {
  199611. if (png_ptr == NULL)
  199612. return;
  199613. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199614. png_ptr->row_number, png_ptr->pass);
  199615. /* initialize transformations and other stuff if first time */
  199616. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199617. {
  199618. /* make sure we wrote the header info */
  199619. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199620. png_error(png_ptr,
  199621. "png_write_info was never called before png_write_row.");
  199622. /* check for transforms that have been set but were defined out */
  199623. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199624. if (png_ptr->transformations & PNG_INVERT_MONO)
  199625. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199626. #endif
  199627. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199628. if (png_ptr->transformations & PNG_FILLER)
  199629. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199630. #endif
  199631. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199632. if (png_ptr->transformations & PNG_PACKSWAP)
  199633. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199634. #endif
  199635. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199636. if (png_ptr->transformations & PNG_PACK)
  199637. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199638. #endif
  199639. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199640. if (png_ptr->transformations & PNG_SHIFT)
  199641. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199642. #endif
  199643. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199644. if (png_ptr->transformations & PNG_BGR)
  199645. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199646. #endif
  199647. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199648. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199649. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199650. #endif
  199651. png_write_start_row(png_ptr);
  199652. }
  199653. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199654. /* if interlaced and not interested in row, return */
  199655. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199656. {
  199657. switch (png_ptr->pass)
  199658. {
  199659. case 0:
  199660. if (png_ptr->row_number & 0x07)
  199661. {
  199662. png_write_finish_row(png_ptr);
  199663. return;
  199664. }
  199665. break;
  199666. case 1:
  199667. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199668. {
  199669. png_write_finish_row(png_ptr);
  199670. return;
  199671. }
  199672. break;
  199673. case 2:
  199674. if ((png_ptr->row_number & 0x07) != 4)
  199675. {
  199676. png_write_finish_row(png_ptr);
  199677. return;
  199678. }
  199679. break;
  199680. case 3:
  199681. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199682. {
  199683. png_write_finish_row(png_ptr);
  199684. return;
  199685. }
  199686. break;
  199687. case 4:
  199688. if ((png_ptr->row_number & 0x03) != 2)
  199689. {
  199690. png_write_finish_row(png_ptr);
  199691. return;
  199692. }
  199693. break;
  199694. case 5:
  199695. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199696. {
  199697. png_write_finish_row(png_ptr);
  199698. return;
  199699. }
  199700. break;
  199701. case 6:
  199702. if (!(png_ptr->row_number & 0x01))
  199703. {
  199704. png_write_finish_row(png_ptr);
  199705. return;
  199706. }
  199707. break;
  199708. }
  199709. }
  199710. #endif
  199711. /* set up row info for transformations */
  199712. png_ptr->row_info.color_type = png_ptr->color_type;
  199713. png_ptr->row_info.width = png_ptr->usr_width;
  199714. png_ptr->row_info.channels = png_ptr->usr_channels;
  199715. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199716. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199717. png_ptr->row_info.channels);
  199718. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199719. png_ptr->row_info.width);
  199720. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199721. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199722. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199723. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199724. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199725. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199726. /* Copy user's row into buffer, leaving room for filter byte. */
  199727. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199728. png_ptr->row_info.rowbytes);
  199729. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199730. /* handle interlacing */
  199731. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199732. (png_ptr->transformations & PNG_INTERLACE))
  199733. {
  199734. png_do_write_interlace(&(png_ptr->row_info),
  199735. png_ptr->row_buf + 1, png_ptr->pass);
  199736. /* this should always get caught above, but still ... */
  199737. if (!(png_ptr->row_info.width))
  199738. {
  199739. png_write_finish_row(png_ptr);
  199740. return;
  199741. }
  199742. }
  199743. #endif
  199744. /* handle other transformations */
  199745. if (png_ptr->transformations)
  199746. png_do_write_transformations(png_ptr);
  199747. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199748. /* Write filter_method 64 (intrapixel differencing) only if
  199749. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199750. * 2. Libpng did not write a PNG signature (this filter_method is only
  199751. * used in PNG datastreams that are embedded in MNG datastreams) and
  199752. * 3. The application called png_permit_mng_features with a mask that
  199753. * included PNG_FLAG_MNG_FILTER_64 and
  199754. * 4. The filter_method is 64 and
  199755. * 5. The color_type is RGB or RGBA
  199756. */
  199757. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199758. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199759. {
  199760. /* Intrapixel differencing */
  199761. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199762. }
  199763. #endif
  199764. /* Find a filter if necessary, filter the row and write it out. */
  199765. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199766. if (png_ptr->write_row_fn != NULL)
  199767. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199768. }
  199769. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199770. /* Set the automatic flush interval or 0 to turn flushing off */
  199771. void PNGAPI
  199772. png_set_flush(png_structp png_ptr, int nrows)
  199773. {
  199774. png_debug(1, "in png_set_flush\n");
  199775. if (png_ptr == NULL)
  199776. return;
  199777. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199778. }
  199779. /* flush the current output buffers now */
  199780. void PNGAPI
  199781. png_write_flush(png_structp png_ptr)
  199782. {
  199783. int wrote_IDAT;
  199784. png_debug(1, "in png_write_flush\n");
  199785. if (png_ptr == NULL)
  199786. return;
  199787. /* We have already written out all of the data */
  199788. if (png_ptr->row_number >= png_ptr->num_rows)
  199789. return;
  199790. do
  199791. {
  199792. int ret;
  199793. /* compress the data */
  199794. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199795. wrote_IDAT = 0;
  199796. /* check for compression errors */
  199797. if (ret != Z_OK)
  199798. {
  199799. if (png_ptr->zstream.msg != NULL)
  199800. png_error(png_ptr, png_ptr->zstream.msg);
  199801. else
  199802. png_error(png_ptr, "zlib error");
  199803. }
  199804. if (!(png_ptr->zstream.avail_out))
  199805. {
  199806. /* write the IDAT and reset the zlib output buffer */
  199807. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199808. png_ptr->zbuf_size);
  199809. png_ptr->zstream.next_out = png_ptr->zbuf;
  199810. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199811. wrote_IDAT = 1;
  199812. }
  199813. } while(wrote_IDAT == 1);
  199814. /* If there is any data left to be output, write it into a new IDAT */
  199815. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199816. {
  199817. /* write the IDAT and reset the zlib output buffer */
  199818. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199819. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199820. png_ptr->zstream.next_out = png_ptr->zbuf;
  199821. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199822. }
  199823. png_ptr->flush_rows = 0;
  199824. png_flush(png_ptr);
  199825. }
  199826. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199827. /* free all memory used by the write */
  199828. void PNGAPI
  199829. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199830. {
  199831. png_structp png_ptr = NULL;
  199832. png_infop info_ptr = NULL;
  199833. #ifdef PNG_USER_MEM_SUPPORTED
  199834. png_free_ptr free_fn = NULL;
  199835. png_voidp mem_ptr = NULL;
  199836. #endif
  199837. png_debug(1, "in png_destroy_write_struct\n");
  199838. if (png_ptr_ptr != NULL)
  199839. {
  199840. png_ptr = *png_ptr_ptr;
  199841. #ifdef PNG_USER_MEM_SUPPORTED
  199842. free_fn = png_ptr->free_fn;
  199843. mem_ptr = png_ptr->mem_ptr;
  199844. #endif
  199845. }
  199846. if (info_ptr_ptr != NULL)
  199847. info_ptr = *info_ptr_ptr;
  199848. if (info_ptr != NULL)
  199849. {
  199850. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199851. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199852. if (png_ptr->num_chunk_list)
  199853. {
  199854. png_free(png_ptr, png_ptr->chunk_list);
  199855. png_ptr->chunk_list=NULL;
  199856. png_ptr->num_chunk_list=0;
  199857. }
  199858. #endif
  199859. #ifdef PNG_USER_MEM_SUPPORTED
  199860. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199861. (png_voidp)mem_ptr);
  199862. #else
  199863. png_destroy_struct((png_voidp)info_ptr);
  199864. #endif
  199865. *info_ptr_ptr = NULL;
  199866. }
  199867. if (png_ptr != NULL)
  199868. {
  199869. png_write_destroy(png_ptr);
  199870. #ifdef PNG_USER_MEM_SUPPORTED
  199871. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199872. (png_voidp)mem_ptr);
  199873. #else
  199874. png_destroy_struct((png_voidp)png_ptr);
  199875. #endif
  199876. *png_ptr_ptr = NULL;
  199877. }
  199878. }
  199879. /* Free any memory used in png_ptr struct (old method) */
  199880. void /* PRIVATE */
  199881. png_write_destroy(png_structp png_ptr)
  199882. {
  199883. #ifdef PNG_SETJMP_SUPPORTED
  199884. jmp_buf tmp_jmp; /* save jump buffer */
  199885. #endif
  199886. png_error_ptr error_fn;
  199887. png_error_ptr warning_fn;
  199888. png_voidp error_ptr;
  199889. #ifdef PNG_USER_MEM_SUPPORTED
  199890. png_free_ptr free_fn;
  199891. #endif
  199892. png_debug(1, "in png_write_destroy\n");
  199893. /* free any memory zlib uses */
  199894. deflateEnd(&png_ptr->zstream);
  199895. /* free our memory. png_free checks NULL for us. */
  199896. png_free(png_ptr, png_ptr->zbuf);
  199897. png_free(png_ptr, png_ptr->row_buf);
  199898. png_free(png_ptr, png_ptr->prev_row);
  199899. png_free(png_ptr, png_ptr->sub_row);
  199900. png_free(png_ptr, png_ptr->up_row);
  199901. png_free(png_ptr, png_ptr->avg_row);
  199902. png_free(png_ptr, png_ptr->paeth_row);
  199903. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199904. png_free(png_ptr, png_ptr->time_buffer);
  199905. #endif
  199906. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199907. png_free(png_ptr, png_ptr->prev_filters);
  199908. png_free(png_ptr, png_ptr->filter_weights);
  199909. png_free(png_ptr, png_ptr->inv_filter_weights);
  199910. png_free(png_ptr, png_ptr->filter_costs);
  199911. png_free(png_ptr, png_ptr->inv_filter_costs);
  199912. #endif
  199913. #ifdef PNG_SETJMP_SUPPORTED
  199914. /* reset structure */
  199915. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199916. #endif
  199917. error_fn = png_ptr->error_fn;
  199918. warning_fn = png_ptr->warning_fn;
  199919. error_ptr = png_ptr->error_ptr;
  199920. #ifdef PNG_USER_MEM_SUPPORTED
  199921. free_fn = png_ptr->free_fn;
  199922. #endif
  199923. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199924. png_ptr->error_fn = error_fn;
  199925. png_ptr->warning_fn = warning_fn;
  199926. png_ptr->error_ptr = error_ptr;
  199927. #ifdef PNG_USER_MEM_SUPPORTED
  199928. png_ptr->free_fn = free_fn;
  199929. #endif
  199930. #ifdef PNG_SETJMP_SUPPORTED
  199931. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199932. #endif
  199933. }
  199934. /* Allow the application to select one or more row filters to use. */
  199935. void PNGAPI
  199936. png_set_filter(png_structp png_ptr, int method, int filters)
  199937. {
  199938. png_debug(1, "in png_set_filter\n");
  199939. if (png_ptr == NULL)
  199940. return;
  199941. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199942. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199943. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199944. method = PNG_FILTER_TYPE_BASE;
  199945. #endif
  199946. if (method == PNG_FILTER_TYPE_BASE)
  199947. {
  199948. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199949. {
  199950. #ifndef PNG_NO_WRITE_FILTER
  199951. case 5:
  199952. case 6:
  199953. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199954. #endif /* PNG_NO_WRITE_FILTER */
  199955. case PNG_FILTER_VALUE_NONE:
  199956. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199957. #ifndef PNG_NO_WRITE_FILTER
  199958. case PNG_FILTER_VALUE_SUB:
  199959. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199960. case PNG_FILTER_VALUE_UP:
  199961. png_ptr->do_filter=PNG_FILTER_UP; break;
  199962. case PNG_FILTER_VALUE_AVG:
  199963. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199964. case PNG_FILTER_VALUE_PAETH:
  199965. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199966. default: png_ptr->do_filter = (png_byte)filters; break;
  199967. #else
  199968. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199969. #endif /* PNG_NO_WRITE_FILTER */
  199970. }
  199971. /* If we have allocated the row_buf, this means we have already started
  199972. * with the image and we should have allocated all of the filter buffers
  199973. * that have been selected. If prev_row isn't already allocated, then
  199974. * it is too late to start using the filters that need it, since we
  199975. * will be missing the data in the previous row. If an application
  199976. * wants to start and stop using particular filters during compression,
  199977. * it should start out with all of the filters, and then add and
  199978. * remove them after the start of compression.
  199979. */
  199980. if (png_ptr->row_buf != NULL)
  199981. {
  199982. #ifndef PNG_NO_WRITE_FILTER
  199983. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199984. {
  199985. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199986. (png_ptr->rowbytes + 1));
  199987. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199988. }
  199989. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199990. {
  199991. if (png_ptr->prev_row == NULL)
  199992. {
  199993. png_warning(png_ptr, "Can't add Up filter after starting");
  199994. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199995. }
  199996. else
  199997. {
  199998. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199999. (png_ptr->rowbytes + 1));
  200000. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  200001. }
  200002. }
  200003. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  200004. {
  200005. if (png_ptr->prev_row == NULL)
  200006. {
  200007. png_warning(png_ptr, "Can't add Average filter after starting");
  200008. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  200009. }
  200010. else
  200011. {
  200012. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  200013. (png_ptr->rowbytes + 1));
  200014. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  200015. }
  200016. }
  200017. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  200018. png_ptr->paeth_row == NULL)
  200019. {
  200020. if (png_ptr->prev_row == NULL)
  200021. {
  200022. png_warning(png_ptr, "Can't add Paeth filter after starting");
  200023. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  200024. }
  200025. else
  200026. {
  200027. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  200028. (png_ptr->rowbytes + 1));
  200029. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  200030. }
  200031. }
  200032. if (png_ptr->do_filter == PNG_NO_FILTERS)
  200033. #endif /* PNG_NO_WRITE_FILTER */
  200034. png_ptr->do_filter = PNG_FILTER_NONE;
  200035. }
  200036. }
  200037. else
  200038. png_error(png_ptr, "Unknown custom filter method");
  200039. }
  200040. /* This allows us to influence the way in which libpng chooses the "best"
  200041. * filter for the current scanline. While the "minimum-sum-of-absolute-
  200042. * differences metric is relatively fast and effective, there is some
  200043. * question as to whether it can be improved upon by trying to keep the
  200044. * filtered data going to zlib more consistent, hopefully resulting in
  200045. * better compression.
  200046. */
  200047. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  200048. void PNGAPI
  200049. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  200050. int num_weights, png_doublep filter_weights,
  200051. png_doublep filter_costs)
  200052. {
  200053. int i;
  200054. png_debug(1, "in png_set_filter_heuristics\n");
  200055. if (png_ptr == NULL)
  200056. return;
  200057. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  200058. {
  200059. png_warning(png_ptr, "Unknown filter heuristic method");
  200060. return;
  200061. }
  200062. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  200063. {
  200064. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  200065. }
  200066. if (num_weights < 0 || filter_weights == NULL ||
  200067. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  200068. {
  200069. num_weights = 0;
  200070. }
  200071. png_ptr->num_prev_filters = (png_byte)num_weights;
  200072. png_ptr->heuristic_method = (png_byte)heuristic_method;
  200073. if (num_weights > 0)
  200074. {
  200075. if (png_ptr->prev_filters == NULL)
  200076. {
  200077. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  200078. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  200079. /* To make sure that the weighting starts out fairly */
  200080. for (i = 0; i < num_weights; i++)
  200081. {
  200082. png_ptr->prev_filters[i] = 255;
  200083. }
  200084. }
  200085. if (png_ptr->filter_weights == NULL)
  200086. {
  200087. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200088. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200089. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200090. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200091. for (i = 0; i < num_weights; i++)
  200092. {
  200093. png_ptr->inv_filter_weights[i] =
  200094. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200095. }
  200096. }
  200097. for (i = 0; i < num_weights; i++)
  200098. {
  200099. if (filter_weights[i] < 0.0)
  200100. {
  200101. png_ptr->inv_filter_weights[i] =
  200102. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200103. }
  200104. else
  200105. {
  200106. png_ptr->inv_filter_weights[i] =
  200107. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  200108. png_ptr->filter_weights[i] =
  200109. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  200110. }
  200111. }
  200112. }
  200113. /* If, in the future, there are other filter methods, this would
  200114. * need to be based on png_ptr->filter.
  200115. */
  200116. if (png_ptr->filter_costs == NULL)
  200117. {
  200118. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200119. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200120. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200121. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200122. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200123. {
  200124. png_ptr->inv_filter_costs[i] =
  200125. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200126. }
  200127. }
  200128. /* Here is where we set the relative costs of the different filters. We
  200129. * should take the desired compression level into account when setting
  200130. * the costs, so that Paeth, for instance, has a high relative cost at low
  200131. * compression levels, while it has a lower relative cost at higher
  200132. * compression settings. The filter types are in order of increasing
  200133. * relative cost, so it would be possible to do this with an algorithm.
  200134. */
  200135. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200136. {
  200137. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200138. {
  200139. png_ptr->inv_filter_costs[i] =
  200140. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200141. }
  200142. else if (filter_costs[i] >= 1.0)
  200143. {
  200144. png_ptr->inv_filter_costs[i] =
  200145. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200146. png_ptr->filter_costs[i] =
  200147. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200148. }
  200149. }
  200150. }
  200151. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200152. void PNGAPI
  200153. png_set_compression_level(png_structp png_ptr, int level)
  200154. {
  200155. png_debug(1, "in png_set_compression_level\n");
  200156. if (png_ptr == NULL)
  200157. return;
  200158. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200159. png_ptr->zlib_level = level;
  200160. }
  200161. void PNGAPI
  200162. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200163. {
  200164. png_debug(1, "in png_set_compression_mem_level\n");
  200165. if (png_ptr == NULL)
  200166. return;
  200167. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200168. png_ptr->zlib_mem_level = mem_level;
  200169. }
  200170. void PNGAPI
  200171. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200172. {
  200173. png_debug(1, "in png_set_compression_strategy\n");
  200174. if (png_ptr == NULL)
  200175. return;
  200176. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200177. png_ptr->zlib_strategy = strategy;
  200178. }
  200179. void PNGAPI
  200180. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200181. {
  200182. if (png_ptr == NULL)
  200183. return;
  200184. if (window_bits > 15)
  200185. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200186. else if (window_bits < 8)
  200187. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200188. #ifndef WBITS_8_OK
  200189. /* avoid libpng bug with 256-byte windows */
  200190. if (window_bits == 8)
  200191. {
  200192. png_warning(png_ptr, "Compression window is being reset to 512");
  200193. window_bits=9;
  200194. }
  200195. #endif
  200196. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200197. png_ptr->zlib_window_bits = window_bits;
  200198. }
  200199. void PNGAPI
  200200. png_set_compression_method(png_structp png_ptr, int method)
  200201. {
  200202. png_debug(1, "in png_set_compression_method\n");
  200203. if (png_ptr == NULL)
  200204. return;
  200205. if (method != 8)
  200206. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200207. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200208. png_ptr->zlib_method = method;
  200209. }
  200210. void PNGAPI
  200211. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200212. {
  200213. if (png_ptr == NULL)
  200214. return;
  200215. png_ptr->write_row_fn = write_row_fn;
  200216. }
  200217. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200218. void PNGAPI
  200219. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200220. write_user_transform_fn)
  200221. {
  200222. png_debug(1, "in png_set_write_user_transform_fn\n");
  200223. if (png_ptr == NULL)
  200224. return;
  200225. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200226. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200227. }
  200228. #endif
  200229. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200230. void PNGAPI
  200231. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200232. int transforms, voidp params)
  200233. {
  200234. if (png_ptr == NULL || info_ptr == NULL)
  200235. return;
  200236. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200237. /* invert the alpha channel from opacity to transparency */
  200238. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200239. png_set_invert_alpha(png_ptr);
  200240. #endif
  200241. /* Write the file header information. */
  200242. png_write_info(png_ptr, info_ptr);
  200243. /* ------ these transformations don't touch the info structure ------- */
  200244. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200245. /* invert monochrome pixels */
  200246. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200247. png_set_invert_mono(png_ptr);
  200248. #endif
  200249. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200250. /* Shift the pixels up to a legal bit depth and fill in
  200251. * as appropriate to correctly scale the image.
  200252. */
  200253. if ((transforms & PNG_TRANSFORM_SHIFT)
  200254. && (info_ptr->valid & PNG_INFO_sBIT))
  200255. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200256. #endif
  200257. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200258. /* pack pixels into bytes */
  200259. if (transforms & PNG_TRANSFORM_PACKING)
  200260. png_set_packing(png_ptr);
  200261. #endif
  200262. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200263. /* swap location of alpha bytes from ARGB to RGBA */
  200264. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200265. png_set_swap_alpha(png_ptr);
  200266. #endif
  200267. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200268. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200269. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200270. */
  200271. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200272. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200273. #endif
  200274. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200275. /* flip BGR pixels to RGB */
  200276. if (transforms & PNG_TRANSFORM_BGR)
  200277. png_set_bgr(png_ptr);
  200278. #endif
  200279. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200280. /* swap bytes of 16-bit files to most significant byte first */
  200281. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200282. png_set_swap(png_ptr);
  200283. #endif
  200284. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200285. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200286. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200287. png_set_packswap(png_ptr);
  200288. #endif
  200289. /* ----------------------- end of transformations ------------------- */
  200290. /* write the bits */
  200291. if (info_ptr->valid & PNG_INFO_IDAT)
  200292. png_write_image(png_ptr, info_ptr->row_pointers);
  200293. /* It is REQUIRED to call this to finish writing the rest of the file */
  200294. png_write_end(png_ptr, info_ptr);
  200295. transforms = transforms; /* quiet compiler warnings */
  200296. params = params;
  200297. }
  200298. #endif
  200299. #endif /* PNG_WRITE_SUPPORTED */
  200300. /*** End of inlined file: pngwrite.c ***/
  200301. /*** Start of inlined file: pngwtran.c ***/
  200302. /* pngwtran.c - transforms the data in a row for PNG writers
  200303. *
  200304. * Last changed in libpng 1.2.9 April 14, 2006
  200305. * For conditions of distribution and use, see copyright notice in png.h
  200306. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200307. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200308. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200309. */
  200310. #define PNG_INTERNAL
  200311. #ifdef PNG_WRITE_SUPPORTED
  200312. /* Transform the data according to the user's wishes. The order of
  200313. * transformations is significant.
  200314. */
  200315. void /* PRIVATE */
  200316. png_do_write_transformations(png_structp png_ptr)
  200317. {
  200318. png_debug(1, "in png_do_write_transformations\n");
  200319. if (png_ptr == NULL)
  200320. return;
  200321. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200322. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200323. if(png_ptr->write_user_transform_fn != NULL)
  200324. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200325. (png_ptr, /* png_ptr */
  200326. &(png_ptr->row_info), /* row_info: */
  200327. /* png_uint_32 width; width of row */
  200328. /* png_uint_32 rowbytes; number of bytes in row */
  200329. /* png_byte color_type; color type of pixels */
  200330. /* png_byte bit_depth; bit depth of samples */
  200331. /* png_byte channels; number of channels (1-4) */
  200332. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200333. png_ptr->row_buf + 1); /* start of pixel data for row */
  200334. #endif
  200335. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200336. if (png_ptr->transformations & PNG_FILLER)
  200337. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200338. png_ptr->flags);
  200339. #endif
  200340. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200341. if (png_ptr->transformations & PNG_PACKSWAP)
  200342. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200343. #endif
  200344. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200345. if (png_ptr->transformations & PNG_PACK)
  200346. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200347. (png_uint_32)png_ptr->bit_depth);
  200348. #endif
  200349. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200350. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200351. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200352. #endif
  200353. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200354. if (png_ptr->transformations & PNG_SHIFT)
  200355. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200356. &(png_ptr->shift));
  200357. #endif
  200358. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200359. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200360. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200361. #endif
  200362. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200363. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200364. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200365. #endif
  200366. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200367. if (png_ptr->transformations & PNG_BGR)
  200368. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200369. #endif
  200370. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200371. if (png_ptr->transformations & PNG_INVERT_MONO)
  200372. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200373. #endif
  200374. }
  200375. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200376. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200377. * row_info bit depth should be 8 (one pixel per byte). The channels
  200378. * should be 1 (this only happens on grayscale and paletted images).
  200379. */
  200380. void /* PRIVATE */
  200381. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200382. {
  200383. png_debug(1, "in png_do_pack\n");
  200384. if (row_info->bit_depth == 8 &&
  200385. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200386. row != NULL && row_info != NULL &&
  200387. #endif
  200388. row_info->channels == 1)
  200389. {
  200390. switch ((int)bit_depth)
  200391. {
  200392. case 1:
  200393. {
  200394. png_bytep sp, dp;
  200395. int mask, v;
  200396. png_uint_32 i;
  200397. png_uint_32 row_width = row_info->width;
  200398. sp = row;
  200399. dp = row;
  200400. mask = 0x80;
  200401. v = 0;
  200402. for (i = 0; i < row_width; i++)
  200403. {
  200404. if (*sp != 0)
  200405. v |= mask;
  200406. sp++;
  200407. if (mask > 1)
  200408. mask >>= 1;
  200409. else
  200410. {
  200411. mask = 0x80;
  200412. *dp = (png_byte)v;
  200413. dp++;
  200414. v = 0;
  200415. }
  200416. }
  200417. if (mask != 0x80)
  200418. *dp = (png_byte)v;
  200419. break;
  200420. }
  200421. case 2:
  200422. {
  200423. png_bytep sp, dp;
  200424. int shift, v;
  200425. png_uint_32 i;
  200426. png_uint_32 row_width = row_info->width;
  200427. sp = row;
  200428. dp = row;
  200429. shift = 6;
  200430. v = 0;
  200431. for (i = 0; i < row_width; i++)
  200432. {
  200433. png_byte value;
  200434. value = (png_byte)(*sp & 0x03);
  200435. v |= (value << shift);
  200436. if (shift == 0)
  200437. {
  200438. shift = 6;
  200439. *dp = (png_byte)v;
  200440. dp++;
  200441. v = 0;
  200442. }
  200443. else
  200444. shift -= 2;
  200445. sp++;
  200446. }
  200447. if (shift != 6)
  200448. *dp = (png_byte)v;
  200449. break;
  200450. }
  200451. case 4:
  200452. {
  200453. png_bytep sp, dp;
  200454. int shift, v;
  200455. png_uint_32 i;
  200456. png_uint_32 row_width = row_info->width;
  200457. sp = row;
  200458. dp = row;
  200459. shift = 4;
  200460. v = 0;
  200461. for (i = 0; i < row_width; i++)
  200462. {
  200463. png_byte value;
  200464. value = (png_byte)(*sp & 0x0f);
  200465. v |= (value << shift);
  200466. if (shift == 0)
  200467. {
  200468. shift = 4;
  200469. *dp = (png_byte)v;
  200470. dp++;
  200471. v = 0;
  200472. }
  200473. else
  200474. shift -= 4;
  200475. sp++;
  200476. }
  200477. if (shift != 4)
  200478. *dp = (png_byte)v;
  200479. break;
  200480. }
  200481. }
  200482. row_info->bit_depth = (png_byte)bit_depth;
  200483. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200484. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200485. row_info->width);
  200486. }
  200487. }
  200488. #endif
  200489. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200490. /* Shift pixel values to take advantage of whole range. Pass the
  200491. * true number of bits in bit_depth. The row should be packed
  200492. * according to row_info->bit_depth. Thus, if you had a row of
  200493. * bit depth 4, but the pixels only had values from 0 to 7, you
  200494. * would pass 3 as bit_depth, and this routine would translate the
  200495. * data to 0 to 15.
  200496. */
  200497. void /* PRIVATE */
  200498. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200499. {
  200500. png_debug(1, "in png_do_shift\n");
  200501. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200502. if (row != NULL && row_info != NULL &&
  200503. #else
  200504. if (
  200505. #endif
  200506. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200507. {
  200508. int shift_start[4], shift_dec[4];
  200509. int channels = 0;
  200510. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200511. {
  200512. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200513. shift_dec[channels] = bit_depth->red;
  200514. channels++;
  200515. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200516. shift_dec[channels] = bit_depth->green;
  200517. channels++;
  200518. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200519. shift_dec[channels] = bit_depth->blue;
  200520. channels++;
  200521. }
  200522. else
  200523. {
  200524. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200525. shift_dec[channels] = bit_depth->gray;
  200526. channels++;
  200527. }
  200528. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200529. {
  200530. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200531. shift_dec[channels] = bit_depth->alpha;
  200532. channels++;
  200533. }
  200534. /* with low row depths, could only be grayscale, so one channel */
  200535. if (row_info->bit_depth < 8)
  200536. {
  200537. png_bytep bp = row;
  200538. png_uint_32 i;
  200539. png_byte mask;
  200540. png_uint_32 row_bytes = row_info->rowbytes;
  200541. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200542. mask = 0x55;
  200543. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200544. mask = 0x11;
  200545. else
  200546. mask = 0xff;
  200547. for (i = 0; i < row_bytes; i++, bp++)
  200548. {
  200549. png_uint_16 v;
  200550. int j;
  200551. v = *bp;
  200552. *bp = 0;
  200553. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200554. {
  200555. if (j > 0)
  200556. *bp |= (png_byte)((v << j) & 0xff);
  200557. else
  200558. *bp |= (png_byte)((v >> (-j)) & mask);
  200559. }
  200560. }
  200561. }
  200562. else if (row_info->bit_depth == 8)
  200563. {
  200564. png_bytep bp = row;
  200565. png_uint_32 i;
  200566. png_uint_32 istop = channels * row_info->width;
  200567. for (i = 0; i < istop; i++, bp++)
  200568. {
  200569. png_uint_16 v;
  200570. int j;
  200571. int c = (int)(i%channels);
  200572. v = *bp;
  200573. *bp = 0;
  200574. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200575. {
  200576. if (j > 0)
  200577. *bp |= (png_byte)((v << j) & 0xff);
  200578. else
  200579. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200580. }
  200581. }
  200582. }
  200583. else
  200584. {
  200585. png_bytep bp;
  200586. png_uint_32 i;
  200587. png_uint_32 istop = channels * row_info->width;
  200588. for (bp = row, i = 0; i < istop; i++)
  200589. {
  200590. int c = (int)(i%channels);
  200591. png_uint_16 value, v;
  200592. int j;
  200593. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200594. value = 0;
  200595. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200596. {
  200597. if (j > 0)
  200598. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200599. else
  200600. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200601. }
  200602. *bp++ = (png_byte)(value >> 8);
  200603. *bp++ = (png_byte)(value & 0xff);
  200604. }
  200605. }
  200606. }
  200607. }
  200608. #endif
  200609. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200610. void /* PRIVATE */
  200611. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200612. {
  200613. png_debug(1, "in png_do_write_swap_alpha\n");
  200614. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200615. if (row != NULL && row_info != NULL)
  200616. #endif
  200617. {
  200618. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200619. {
  200620. /* This converts from ARGB to RGBA */
  200621. if (row_info->bit_depth == 8)
  200622. {
  200623. png_bytep sp, dp;
  200624. png_uint_32 i;
  200625. png_uint_32 row_width = row_info->width;
  200626. for (i = 0, sp = dp = row; i < row_width; i++)
  200627. {
  200628. png_byte save = *(sp++);
  200629. *(dp++) = *(sp++);
  200630. *(dp++) = *(sp++);
  200631. *(dp++) = *(sp++);
  200632. *(dp++) = save;
  200633. }
  200634. }
  200635. /* This converts from AARRGGBB to RRGGBBAA */
  200636. else
  200637. {
  200638. png_bytep sp, dp;
  200639. png_uint_32 i;
  200640. png_uint_32 row_width = row_info->width;
  200641. for (i = 0, sp = dp = row; i < row_width; i++)
  200642. {
  200643. png_byte save[2];
  200644. save[0] = *(sp++);
  200645. save[1] = *(sp++);
  200646. *(dp++) = *(sp++);
  200647. *(dp++) = *(sp++);
  200648. *(dp++) = *(sp++);
  200649. *(dp++) = *(sp++);
  200650. *(dp++) = *(sp++);
  200651. *(dp++) = *(sp++);
  200652. *(dp++) = save[0];
  200653. *(dp++) = save[1];
  200654. }
  200655. }
  200656. }
  200657. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200658. {
  200659. /* This converts from AG to GA */
  200660. if (row_info->bit_depth == 8)
  200661. {
  200662. png_bytep sp, dp;
  200663. png_uint_32 i;
  200664. png_uint_32 row_width = row_info->width;
  200665. for (i = 0, sp = dp = row; i < row_width; i++)
  200666. {
  200667. png_byte save = *(sp++);
  200668. *(dp++) = *(sp++);
  200669. *(dp++) = save;
  200670. }
  200671. }
  200672. /* This converts from AAGG to GGAA */
  200673. else
  200674. {
  200675. png_bytep sp, dp;
  200676. png_uint_32 i;
  200677. png_uint_32 row_width = row_info->width;
  200678. for (i = 0, sp = dp = row; i < row_width; i++)
  200679. {
  200680. png_byte save[2];
  200681. save[0] = *(sp++);
  200682. save[1] = *(sp++);
  200683. *(dp++) = *(sp++);
  200684. *(dp++) = *(sp++);
  200685. *(dp++) = save[0];
  200686. *(dp++) = save[1];
  200687. }
  200688. }
  200689. }
  200690. }
  200691. }
  200692. #endif
  200693. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200694. void /* PRIVATE */
  200695. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200696. {
  200697. png_debug(1, "in png_do_write_invert_alpha\n");
  200698. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200699. if (row != NULL && row_info != NULL)
  200700. #endif
  200701. {
  200702. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200703. {
  200704. /* This inverts the alpha channel in RGBA */
  200705. if (row_info->bit_depth == 8)
  200706. {
  200707. png_bytep sp, dp;
  200708. png_uint_32 i;
  200709. png_uint_32 row_width = row_info->width;
  200710. for (i = 0, sp = dp = row; i < row_width; i++)
  200711. {
  200712. /* does nothing
  200713. *(dp++) = *(sp++);
  200714. *(dp++) = *(sp++);
  200715. *(dp++) = *(sp++);
  200716. */
  200717. sp+=3; dp = sp;
  200718. *(dp++) = (png_byte)(255 - *(sp++));
  200719. }
  200720. }
  200721. /* This inverts the alpha channel in RRGGBBAA */
  200722. else
  200723. {
  200724. png_bytep sp, dp;
  200725. png_uint_32 i;
  200726. png_uint_32 row_width = row_info->width;
  200727. for (i = 0, sp = dp = row; i < row_width; i++)
  200728. {
  200729. /* does nothing
  200730. *(dp++) = *(sp++);
  200731. *(dp++) = *(sp++);
  200732. *(dp++) = *(sp++);
  200733. *(dp++) = *(sp++);
  200734. *(dp++) = *(sp++);
  200735. *(dp++) = *(sp++);
  200736. */
  200737. sp+=6; dp = sp;
  200738. *(dp++) = (png_byte)(255 - *(sp++));
  200739. *(dp++) = (png_byte)(255 - *(sp++));
  200740. }
  200741. }
  200742. }
  200743. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200744. {
  200745. /* This inverts the alpha channel in GA */
  200746. if (row_info->bit_depth == 8)
  200747. {
  200748. png_bytep sp, dp;
  200749. png_uint_32 i;
  200750. png_uint_32 row_width = row_info->width;
  200751. for (i = 0, sp = dp = row; i < row_width; i++)
  200752. {
  200753. *(dp++) = *(sp++);
  200754. *(dp++) = (png_byte)(255 - *(sp++));
  200755. }
  200756. }
  200757. /* This inverts the alpha channel in GGAA */
  200758. else
  200759. {
  200760. png_bytep sp, dp;
  200761. png_uint_32 i;
  200762. png_uint_32 row_width = row_info->width;
  200763. for (i = 0, sp = dp = row; i < row_width; i++)
  200764. {
  200765. /* does nothing
  200766. *(dp++) = *(sp++);
  200767. *(dp++) = *(sp++);
  200768. */
  200769. sp+=2; dp = sp;
  200770. *(dp++) = (png_byte)(255 - *(sp++));
  200771. *(dp++) = (png_byte)(255 - *(sp++));
  200772. }
  200773. }
  200774. }
  200775. }
  200776. }
  200777. #endif
  200778. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200779. /* undoes intrapixel differencing */
  200780. void /* PRIVATE */
  200781. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200782. {
  200783. png_debug(1, "in png_do_write_intrapixel\n");
  200784. if (
  200785. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200786. row != NULL && row_info != NULL &&
  200787. #endif
  200788. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200789. {
  200790. int bytes_per_pixel;
  200791. png_uint_32 row_width = row_info->width;
  200792. if (row_info->bit_depth == 8)
  200793. {
  200794. png_bytep rp;
  200795. png_uint_32 i;
  200796. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200797. bytes_per_pixel = 3;
  200798. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200799. bytes_per_pixel = 4;
  200800. else
  200801. return;
  200802. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200803. {
  200804. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200805. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200806. }
  200807. }
  200808. else if (row_info->bit_depth == 16)
  200809. {
  200810. png_bytep rp;
  200811. png_uint_32 i;
  200812. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200813. bytes_per_pixel = 6;
  200814. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200815. bytes_per_pixel = 8;
  200816. else
  200817. return;
  200818. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200819. {
  200820. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200821. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200822. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200823. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200824. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200825. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200826. *(rp+1) = (png_byte)(red & 0xff);
  200827. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200828. *(rp+5) = (png_byte)(blue & 0xff);
  200829. }
  200830. }
  200831. }
  200832. }
  200833. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200834. #endif /* PNG_WRITE_SUPPORTED */
  200835. /*** End of inlined file: pngwtran.c ***/
  200836. /*** Start of inlined file: pngwutil.c ***/
  200837. /* pngwutil.c - utilities to write a PNG file
  200838. *
  200839. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200840. * For conditions of distribution and use, see copyright notice in png.h
  200841. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200842. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200843. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200844. */
  200845. #define PNG_INTERNAL
  200846. #ifdef PNG_WRITE_SUPPORTED
  200847. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200848. * with unsigned numbers for convenience, although one supported
  200849. * ancillary chunk uses signed (two's complement) numbers.
  200850. */
  200851. void PNGAPI
  200852. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200853. {
  200854. buf[0] = (png_byte)((i >> 24) & 0xff);
  200855. buf[1] = (png_byte)((i >> 16) & 0xff);
  200856. buf[2] = (png_byte)((i >> 8) & 0xff);
  200857. buf[3] = (png_byte)(i & 0xff);
  200858. }
  200859. /* The png_save_int_32 function assumes integers are stored in two's
  200860. * complement format. If this isn't the case, then this routine needs to
  200861. * be modified to write data in two's complement format.
  200862. */
  200863. void PNGAPI
  200864. png_save_int_32(png_bytep buf, png_int_32 i)
  200865. {
  200866. buf[0] = (png_byte)((i >> 24) & 0xff);
  200867. buf[1] = (png_byte)((i >> 16) & 0xff);
  200868. buf[2] = (png_byte)((i >> 8) & 0xff);
  200869. buf[3] = (png_byte)(i & 0xff);
  200870. }
  200871. /* Place a 16-bit number into a buffer in PNG byte order.
  200872. * The parameter is declared unsigned int, not png_uint_16,
  200873. * just to avoid potential problems on pre-ANSI C compilers.
  200874. */
  200875. void PNGAPI
  200876. png_save_uint_16(png_bytep buf, unsigned int i)
  200877. {
  200878. buf[0] = (png_byte)((i >> 8) & 0xff);
  200879. buf[1] = (png_byte)(i & 0xff);
  200880. }
  200881. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200882. * representing the chunk name. The array must be at least 4 bytes in
  200883. * length, and does not need to be null terminated. To be safe, pass the
  200884. * pre-defined chunk names here, and if you need a new one, define it
  200885. * where the others are defined. The length is the length of the data.
  200886. * All the data must be present. If that is not possible, use the
  200887. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200888. * functions instead.
  200889. */
  200890. void PNGAPI
  200891. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200892. png_bytep data, png_size_t length)
  200893. {
  200894. if(png_ptr == NULL) return;
  200895. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200896. png_write_chunk_data(png_ptr, data, length);
  200897. png_write_chunk_end(png_ptr);
  200898. }
  200899. /* Write the start of a PNG chunk. The type is the chunk type.
  200900. * The total_length is the sum of the lengths of all the data you will be
  200901. * passing in png_write_chunk_data().
  200902. */
  200903. void PNGAPI
  200904. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200905. png_uint_32 length)
  200906. {
  200907. png_byte buf[4];
  200908. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200909. if(png_ptr == NULL) return;
  200910. /* write the length */
  200911. png_save_uint_32(buf, length);
  200912. png_write_data(png_ptr, buf, (png_size_t)4);
  200913. /* write the chunk name */
  200914. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200915. /* reset the crc and run it over the chunk name */
  200916. png_reset_crc(png_ptr);
  200917. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200918. }
  200919. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200920. * Note that multiple calls to this function are allowed, and that the
  200921. * sum of the lengths from these calls *must* add up to the total_length
  200922. * given to png_write_chunk_start().
  200923. */
  200924. void PNGAPI
  200925. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200926. {
  200927. /* write the data, and run the CRC over it */
  200928. if(png_ptr == NULL) return;
  200929. if (data != NULL && length > 0)
  200930. {
  200931. png_calculate_crc(png_ptr, data, length);
  200932. png_write_data(png_ptr, data, length);
  200933. }
  200934. }
  200935. /* Finish a chunk started with png_write_chunk_start(). */
  200936. void PNGAPI
  200937. png_write_chunk_end(png_structp png_ptr)
  200938. {
  200939. png_byte buf[4];
  200940. if(png_ptr == NULL) return;
  200941. /* write the crc */
  200942. png_save_uint_32(buf, png_ptr->crc);
  200943. png_write_data(png_ptr, buf, (png_size_t)4);
  200944. }
  200945. /* Simple function to write the signature. If we have already written
  200946. * the magic bytes of the signature, or more likely, the PNG stream is
  200947. * being embedded into another stream and doesn't need its own signature,
  200948. * we should call png_set_sig_bytes() to tell libpng how many of the
  200949. * bytes have already been written.
  200950. */
  200951. void /* PRIVATE */
  200952. png_write_sig(png_structp png_ptr)
  200953. {
  200954. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200955. /* write the rest of the 8 byte signature */
  200956. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200957. (png_size_t)8 - png_ptr->sig_bytes);
  200958. if(png_ptr->sig_bytes < 3)
  200959. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200960. }
  200961. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200962. /*
  200963. * This pair of functions encapsulates the operation of (a) compressing a
  200964. * text string, and (b) issuing it later as a series of chunk data writes.
  200965. * The compression_state structure is shared context for these functions
  200966. * set up by the caller in order to make the whole mess thread-safe.
  200967. */
  200968. typedef struct
  200969. {
  200970. char *input; /* the uncompressed input data */
  200971. int input_len; /* its length */
  200972. int num_output_ptr; /* number of output pointers used */
  200973. int max_output_ptr; /* size of output_ptr */
  200974. png_charpp output_ptr; /* array of pointers to output */
  200975. } compression_state;
  200976. /* compress given text into storage in the png_ptr structure */
  200977. static int /* PRIVATE */
  200978. png_text_compress(png_structp png_ptr,
  200979. png_charp text, png_size_t text_len, int compression,
  200980. compression_state *comp)
  200981. {
  200982. int ret;
  200983. comp->num_output_ptr = 0;
  200984. comp->max_output_ptr = 0;
  200985. comp->output_ptr = NULL;
  200986. comp->input = NULL;
  200987. comp->input_len = 0;
  200988. /* we may just want to pass the text right through */
  200989. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200990. {
  200991. comp->input = text;
  200992. comp->input_len = text_len;
  200993. return((int)text_len);
  200994. }
  200995. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200996. {
  200997. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200998. char msg[50];
  200999. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  201000. png_warning(png_ptr, msg);
  201001. #else
  201002. png_warning(png_ptr, "Unknown compression type");
  201003. #endif
  201004. }
  201005. /* We can't write the chunk until we find out how much data we have,
  201006. * which means we need to run the compressor first and save the
  201007. * output. This shouldn't be a problem, as the vast majority of
  201008. * comments should be reasonable, but we will set up an array of
  201009. * malloc'd pointers to be sure.
  201010. *
  201011. * If we knew the application was well behaved, we could simplify this
  201012. * greatly by assuming we can always malloc an output buffer large
  201013. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  201014. * and malloc this directly. The only time this would be a bad idea is
  201015. * if we can't malloc more than 64K and we have 64K of random input
  201016. * data, or if the input string is incredibly large (although this
  201017. * wouldn't cause a failure, just a slowdown due to swapping).
  201018. */
  201019. /* set up the compression buffers */
  201020. png_ptr->zstream.avail_in = (uInt)text_len;
  201021. png_ptr->zstream.next_in = (Bytef *)text;
  201022. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201023. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  201024. /* this is the same compression loop as in png_write_row() */
  201025. do
  201026. {
  201027. /* compress the data */
  201028. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  201029. if (ret != Z_OK)
  201030. {
  201031. /* error */
  201032. if (png_ptr->zstream.msg != NULL)
  201033. png_error(png_ptr, png_ptr->zstream.msg);
  201034. else
  201035. png_error(png_ptr, "zlib error");
  201036. }
  201037. /* check to see if we need more room */
  201038. if (!(png_ptr->zstream.avail_out))
  201039. {
  201040. /* make sure the output array has room */
  201041. if (comp->num_output_ptr >= comp->max_output_ptr)
  201042. {
  201043. int old_max;
  201044. old_max = comp->max_output_ptr;
  201045. comp->max_output_ptr = comp->num_output_ptr + 4;
  201046. if (comp->output_ptr != NULL)
  201047. {
  201048. png_charpp old_ptr;
  201049. old_ptr = comp->output_ptr;
  201050. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201051. (png_uint_32)(comp->max_output_ptr *
  201052. png_sizeof (png_charpp)));
  201053. png_memcpy(comp->output_ptr, old_ptr, old_max
  201054. * png_sizeof (png_charp));
  201055. png_free(png_ptr, old_ptr);
  201056. }
  201057. else
  201058. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201059. (png_uint_32)(comp->max_output_ptr *
  201060. png_sizeof (png_charp)));
  201061. }
  201062. /* save the data */
  201063. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  201064. (png_uint_32)png_ptr->zbuf_size);
  201065. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201066. png_ptr->zbuf_size);
  201067. comp->num_output_ptr++;
  201068. /* and reset the buffer */
  201069. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201070. png_ptr->zstream.next_out = png_ptr->zbuf;
  201071. }
  201072. /* continue until we don't have any more to compress */
  201073. } while (png_ptr->zstream.avail_in);
  201074. /* finish the compression */
  201075. do
  201076. {
  201077. /* tell zlib we are finished */
  201078. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201079. if (ret == Z_OK)
  201080. {
  201081. /* check to see if we need more room */
  201082. if (!(png_ptr->zstream.avail_out))
  201083. {
  201084. /* check to make sure our output array has room */
  201085. if (comp->num_output_ptr >= comp->max_output_ptr)
  201086. {
  201087. int old_max;
  201088. old_max = comp->max_output_ptr;
  201089. comp->max_output_ptr = comp->num_output_ptr + 4;
  201090. if (comp->output_ptr != NULL)
  201091. {
  201092. png_charpp old_ptr;
  201093. old_ptr = comp->output_ptr;
  201094. /* This could be optimized to realloc() */
  201095. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201096. (png_uint_32)(comp->max_output_ptr *
  201097. png_sizeof (png_charpp)));
  201098. png_memcpy(comp->output_ptr, old_ptr,
  201099. old_max * png_sizeof (png_charp));
  201100. png_free(png_ptr, old_ptr);
  201101. }
  201102. else
  201103. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201104. (png_uint_32)(comp->max_output_ptr *
  201105. png_sizeof (png_charp)));
  201106. }
  201107. /* save off the data */
  201108. comp->output_ptr[comp->num_output_ptr] =
  201109. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  201110. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201111. png_ptr->zbuf_size);
  201112. comp->num_output_ptr++;
  201113. /* and reset the buffer pointers */
  201114. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201115. png_ptr->zstream.next_out = png_ptr->zbuf;
  201116. }
  201117. }
  201118. else if (ret != Z_STREAM_END)
  201119. {
  201120. /* we got an error */
  201121. if (png_ptr->zstream.msg != NULL)
  201122. png_error(png_ptr, png_ptr->zstream.msg);
  201123. else
  201124. png_error(png_ptr, "zlib error");
  201125. }
  201126. } while (ret != Z_STREAM_END);
  201127. /* text length is number of buffers plus last buffer */
  201128. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201129. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201130. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201131. return((int)text_len);
  201132. }
  201133. /* ship the compressed text out via chunk writes */
  201134. static void /* PRIVATE */
  201135. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201136. {
  201137. int i;
  201138. /* handle the no-compression case */
  201139. if (comp->input)
  201140. {
  201141. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201142. (png_size_t)comp->input_len);
  201143. return;
  201144. }
  201145. /* write saved output buffers, if any */
  201146. for (i = 0; i < comp->num_output_ptr; i++)
  201147. {
  201148. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201149. png_ptr->zbuf_size);
  201150. png_free(png_ptr, comp->output_ptr[i]);
  201151. comp->output_ptr[i]=NULL;
  201152. }
  201153. if (comp->max_output_ptr != 0)
  201154. png_free(png_ptr, comp->output_ptr);
  201155. comp->output_ptr=NULL;
  201156. /* write anything left in zbuf */
  201157. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201158. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201159. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201160. /* reset zlib for another zTXt/iTXt or image data */
  201161. deflateReset(&png_ptr->zstream);
  201162. png_ptr->zstream.data_type = Z_BINARY;
  201163. }
  201164. #endif
  201165. /* Write the IHDR chunk, and update the png_struct with the necessary
  201166. * information. Note that the rest of this code depends upon this
  201167. * information being correct.
  201168. */
  201169. void /* PRIVATE */
  201170. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201171. int bit_depth, int color_type, int compression_type, int filter_type,
  201172. int interlace_type)
  201173. {
  201174. #ifdef PNG_USE_LOCAL_ARRAYS
  201175. PNG_IHDR;
  201176. #endif
  201177. png_byte buf[13]; /* buffer to store the IHDR info */
  201178. png_debug(1, "in png_write_IHDR\n");
  201179. /* Check that we have valid input data from the application info */
  201180. switch (color_type)
  201181. {
  201182. case PNG_COLOR_TYPE_GRAY:
  201183. switch (bit_depth)
  201184. {
  201185. case 1:
  201186. case 2:
  201187. case 4:
  201188. case 8:
  201189. case 16: png_ptr->channels = 1; break;
  201190. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201191. }
  201192. break;
  201193. case PNG_COLOR_TYPE_RGB:
  201194. if (bit_depth != 8 && bit_depth != 16)
  201195. png_error(png_ptr, "Invalid bit depth for RGB image");
  201196. png_ptr->channels = 3;
  201197. break;
  201198. case PNG_COLOR_TYPE_PALETTE:
  201199. switch (bit_depth)
  201200. {
  201201. case 1:
  201202. case 2:
  201203. case 4:
  201204. case 8: png_ptr->channels = 1; break;
  201205. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201206. }
  201207. break;
  201208. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201209. if (bit_depth != 8 && bit_depth != 16)
  201210. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201211. png_ptr->channels = 2;
  201212. break;
  201213. case PNG_COLOR_TYPE_RGB_ALPHA:
  201214. if (bit_depth != 8 && bit_depth != 16)
  201215. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201216. png_ptr->channels = 4;
  201217. break;
  201218. default:
  201219. png_error(png_ptr, "Invalid image color type specified");
  201220. }
  201221. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201222. {
  201223. png_warning(png_ptr, "Invalid compression type specified");
  201224. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201225. }
  201226. /* Write filter_method 64 (intrapixel differencing) only if
  201227. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201228. * 2. Libpng did not write a PNG signature (this filter_method is only
  201229. * used in PNG datastreams that are embedded in MNG datastreams) and
  201230. * 3. The application called png_permit_mng_features with a mask that
  201231. * included PNG_FLAG_MNG_FILTER_64 and
  201232. * 4. The filter_method is 64 and
  201233. * 5. The color_type is RGB or RGBA
  201234. */
  201235. if (
  201236. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201237. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201238. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201239. (color_type == PNG_COLOR_TYPE_RGB ||
  201240. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201241. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201242. #endif
  201243. filter_type != PNG_FILTER_TYPE_BASE)
  201244. {
  201245. png_warning(png_ptr, "Invalid filter type specified");
  201246. filter_type = PNG_FILTER_TYPE_BASE;
  201247. }
  201248. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201249. if (interlace_type != PNG_INTERLACE_NONE &&
  201250. interlace_type != PNG_INTERLACE_ADAM7)
  201251. {
  201252. png_warning(png_ptr, "Invalid interlace type specified");
  201253. interlace_type = PNG_INTERLACE_ADAM7;
  201254. }
  201255. #else
  201256. interlace_type=PNG_INTERLACE_NONE;
  201257. #endif
  201258. /* save off the relevent information */
  201259. png_ptr->bit_depth = (png_byte)bit_depth;
  201260. png_ptr->color_type = (png_byte)color_type;
  201261. png_ptr->interlaced = (png_byte)interlace_type;
  201262. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201263. png_ptr->filter_type = (png_byte)filter_type;
  201264. #endif
  201265. png_ptr->compression_type = (png_byte)compression_type;
  201266. png_ptr->width = width;
  201267. png_ptr->height = height;
  201268. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201269. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201270. /* set the usr info, so any transformations can modify it */
  201271. png_ptr->usr_width = png_ptr->width;
  201272. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201273. png_ptr->usr_channels = png_ptr->channels;
  201274. /* pack the header information into the buffer */
  201275. png_save_uint_32(buf, width);
  201276. png_save_uint_32(buf + 4, height);
  201277. buf[8] = (png_byte)bit_depth;
  201278. buf[9] = (png_byte)color_type;
  201279. buf[10] = (png_byte)compression_type;
  201280. buf[11] = (png_byte)filter_type;
  201281. buf[12] = (png_byte)interlace_type;
  201282. /* write the chunk */
  201283. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201284. /* initialize zlib with PNG info */
  201285. png_ptr->zstream.zalloc = png_zalloc;
  201286. png_ptr->zstream.zfree = png_zfree;
  201287. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201288. if (!(png_ptr->do_filter))
  201289. {
  201290. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201291. png_ptr->bit_depth < 8)
  201292. png_ptr->do_filter = PNG_FILTER_NONE;
  201293. else
  201294. png_ptr->do_filter = PNG_ALL_FILTERS;
  201295. }
  201296. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201297. {
  201298. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201299. png_ptr->zlib_strategy = Z_FILTERED;
  201300. else
  201301. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201302. }
  201303. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201304. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201305. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201306. png_ptr->zlib_mem_level = 8;
  201307. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201308. png_ptr->zlib_window_bits = 15;
  201309. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201310. png_ptr->zlib_method = 8;
  201311. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201312. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201313. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201314. png_error(png_ptr, "zlib failed to initialize compressor");
  201315. png_ptr->zstream.next_out = png_ptr->zbuf;
  201316. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201317. /* libpng is not interested in zstream.data_type */
  201318. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201319. png_ptr->zstream.data_type = Z_BINARY;
  201320. png_ptr->mode = PNG_HAVE_IHDR;
  201321. }
  201322. /* write the palette. We are careful not to trust png_color to be in the
  201323. * correct order for PNG, so people can redefine it to any convenient
  201324. * structure.
  201325. */
  201326. void /* PRIVATE */
  201327. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201328. {
  201329. #ifdef PNG_USE_LOCAL_ARRAYS
  201330. PNG_PLTE;
  201331. #endif
  201332. png_uint_32 i;
  201333. png_colorp pal_ptr;
  201334. png_byte buf[3];
  201335. png_debug(1, "in png_write_PLTE\n");
  201336. if ((
  201337. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201338. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201339. #endif
  201340. num_pal == 0) || num_pal > 256)
  201341. {
  201342. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201343. {
  201344. png_error(png_ptr, "Invalid number of colors in palette");
  201345. }
  201346. else
  201347. {
  201348. png_warning(png_ptr, "Invalid number of colors in palette");
  201349. return;
  201350. }
  201351. }
  201352. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201353. {
  201354. png_warning(png_ptr,
  201355. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201356. return;
  201357. }
  201358. png_ptr->num_palette = (png_uint_16)num_pal;
  201359. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201360. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201361. #ifndef PNG_NO_POINTER_INDEXING
  201362. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201363. {
  201364. buf[0] = pal_ptr->red;
  201365. buf[1] = pal_ptr->green;
  201366. buf[2] = pal_ptr->blue;
  201367. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201368. }
  201369. #else
  201370. /* This is a little slower but some buggy compilers need to do this instead */
  201371. pal_ptr=palette;
  201372. for (i = 0; i < num_pal; i++)
  201373. {
  201374. buf[0] = pal_ptr[i].red;
  201375. buf[1] = pal_ptr[i].green;
  201376. buf[2] = pal_ptr[i].blue;
  201377. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201378. }
  201379. #endif
  201380. png_write_chunk_end(png_ptr);
  201381. png_ptr->mode |= PNG_HAVE_PLTE;
  201382. }
  201383. /* write an IDAT chunk */
  201384. void /* PRIVATE */
  201385. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201386. {
  201387. #ifdef PNG_USE_LOCAL_ARRAYS
  201388. PNG_IDAT;
  201389. #endif
  201390. png_debug(1, "in png_write_IDAT\n");
  201391. /* Optimize the CMF field in the zlib stream. */
  201392. /* This hack of the zlib stream is compliant to the stream specification. */
  201393. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201394. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201395. {
  201396. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201397. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201398. {
  201399. /* Avoid memory underflows and multiplication overflows. */
  201400. /* The conditions below are practically always satisfied;
  201401. however, they still must be checked. */
  201402. if (length >= 2 &&
  201403. png_ptr->height < 16384 && png_ptr->width < 16384)
  201404. {
  201405. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201406. ((png_ptr->width *
  201407. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201408. unsigned int z_cinfo = z_cmf >> 4;
  201409. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201410. while (uncompressed_idat_size <= half_z_window_size &&
  201411. half_z_window_size >= 256)
  201412. {
  201413. z_cinfo--;
  201414. half_z_window_size >>= 1;
  201415. }
  201416. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201417. if (data[0] != (png_byte)z_cmf)
  201418. {
  201419. data[0] = (png_byte)z_cmf;
  201420. data[1] &= 0xe0;
  201421. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201422. }
  201423. }
  201424. }
  201425. else
  201426. png_error(png_ptr,
  201427. "Invalid zlib compression method or flags in IDAT");
  201428. }
  201429. png_write_chunk(png_ptr, png_IDAT, data, length);
  201430. png_ptr->mode |= PNG_HAVE_IDAT;
  201431. }
  201432. /* write an IEND chunk */
  201433. void /* PRIVATE */
  201434. png_write_IEND(png_structp png_ptr)
  201435. {
  201436. #ifdef PNG_USE_LOCAL_ARRAYS
  201437. PNG_IEND;
  201438. #endif
  201439. png_debug(1, "in png_write_IEND\n");
  201440. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201441. (png_size_t)0);
  201442. png_ptr->mode |= PNG_HAVE_IEND;
  201443. }
  201444. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201445. /* write a gAMA chunk */
  201446. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201447. void /* PRIVATE */
  201448. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201449. {
  201450. #ifdef PNG_USE_LOCAL_ARRAYS
  201451. PNG_gAMA;
  201452. #endif
  201453. png_uint_32 igamma;
  201454. png_byte buf[4];
  201455. png_debug(1, "in png_write_gAMA\n");
  201456. /* file_gamma is saved in 1/100,000ths */
  201457. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201458. png_save_uint_32(buf, igamma);
  201459. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201460. }
  201461. #endif
  201462. #ifdef PNG_FIXED_POINT_SUPPORTED
  201463. void /* PRIVATE */
  201464. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201465. {
  201466. #ifdef PNG_USE_LOCAL_ARRAYS
  201467. PNG_gAMA;
  201468. #endif
  201469. png_byte buf[4];
  201470. png_debug(1, "in png_write_gAMA\n");
  201471. /* file_gamma is saved in 1/100,000ths */
  201472. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201473. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201474. }
  201475. #endif
  201476. #endif
  201477. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201478. /* write a sRGB chunk */
  201479. void /* PRIVATE */
  201480. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201481. {
  201482. #ifdef PNG_USE_LOCAL_ARRAYS
  201483. PNG_sRGB;
  201484. #endif
  201485. png_byte buf[1];
  201486. png_debug(1, "in png_write_sRGB\n");
  201487. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201488. png_warning(png_ptr,
  201489. "Invalid sRGB rendering intent specified");
  201490. buf[0]=(png_byte)srgb_intent;
  201491. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201492. }
  201493. #endif
  201494. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201495. /* write an iCCP chunk */
  201496. void /* PRIVATE */
  201497. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201498. png_charp profile, int profile_len)
  201499. {
  201500. #ifdef PNG_USE_LOCAL_ARRAYS
  201501. PNG_iCCP;
  201502. #endif
  201503. png_size_t name_len;
  201504. png_charp new_name;
  201505. compression_state comp;
  201506. int embedded_profile_len = 0;
  201507. png_debug(1, "in png_write_iCCP\n");
  201508. comp.num_output_ptr = 0;
  201509. comp.max_output_ptr = 0;
  201510. comp.output_ptr = NULL;
  201511. comp.input = NULL;
  201512. comp.input_len = 0;
  201513. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201514. &new_name)) == 0)
  201515. {
  201516. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201517. return;
  201518. }
  201519. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201520. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201521. if (profile == NULL)
  201522. profile_len = 0;
  201523. if (profile_len > 3)
  201524. embedded_profile_len =
  201525. ((*( (png_bytep)profile ))<<24) |
  201526. ((*( (png_bytep)profile+1))<<16) |
  201527. ((*( (png_bytep)profile+2))<< 8) |
  201528. ((*( (png_bytep)profile+3)) );
  201529. if (profile_len < embedded_profile_len)
  201530. {
  201531. png_warning(png_ptr,
  201532. "Embedded profile length too large in iCCP chunk");
  201533. return;
  201534. }
  201535. if (profile_len > embedded_profile_len)
  201536. {
  201537. png_warning(png_ptr,
  201538. "Truncating profile to actual length in iCCP chunk");
  201539. profile_len = embedded_profile_len;
  201540. }
  201541. if (profile_len)
  201542. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201543. PNG_COMPRESSION_TYPE_BASE, &comp);
  201544. /* make sure we include the NULL after the name and the compression type */
  201545. png_write_chunk_start(png_ptr, png_iCCP,
  201546. (png_uint_32)name_len+profile_len+2);
  201547. new_name[name_len+1]=0x00;
  201548. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201549. if (profile_len)
  201550. png_write_compressed_data_out(png_ptr, &comp);
  201551. png_write_chunk_end(png_ptr);
  201552. png_free(png_ptr, new_name);
  201553. }
  201554. #endif
  201555. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201556. /* write a sPLT chunk */
  201557. void /* PRIVATE */
  201558. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201559. {
  201560. #ifdef PNG_USE_LOCAL_ARRAYS
  201561. PNG_sPLT;
  201562. #endif
  201563. png_size_t name_len;
  201564. png_charp new_name;
  201565. png_byte entrybuf[10];
  201566. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201567. int palette_size = entry_size * spalette->nentries;
  201568. png_sPLT_entryp ep;
  201569. #ifdef PNG_NO_POINTER_INDEXING
  201570. int i;
  201571. #endif
  201572. png_debug(1, "in png_write_sPLT\n");
  201573. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201574. spalette->name, &new_name))==0)
  201575. {
  201576. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201577. return;
  201578. }
  201579. /* make sure we include the NULL after the name */
  201580. png_write_chunk_start(png_ptr, png_sPLT,
  201581. (png_uint_32)(name_len + 2 + palette_size));
  201582. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201583. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201584. /* loop through each palette entry, writing appropriately */
  201585. #ifndef PNG_NO_POINTER_INDEXING
  201586. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201587. {
  201588. if (spalette->depth == 8)
  201589. {
  201590. entrybuf[0] = (png_byte)ep->red;
  201591. entrybuf[1] = (png_byte)ep->green;
  201592. entrybuf[2] = (png_byte)ep->blue;
  201593. entrybuf[3] = (png_byte)ep->alpha;
  201594. png_save_uint_16(entrybuf + 4, ep->frequency);
  201595. }
  201596. else
  201597. {
  201598. png_save_uint_16(entrybuf + 0, ep->red);
  201599. png_save_uint_16(entrybuf + 2, ep->green);
  201600. png_save_uint_16(entrybuf + 4, ep->blue);
  201601. png_save_uint_16(entrybuf + 6, ep->alpha);
  201602. png_save_uint_16(entrybuf + 8, ep->frequency);
  201603. }
  201604. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201605. }
  201606. #else
  201607. ep=spalette->entries;
  201608. for (i=0; i>spalette->nentries; i++)
  201609. {
  201610. if (spalette->depth == 8)
  201611. {
  201612. entrybuf[0] = (png_byte)ep[i].red;
  201613. entrybuf[1] = (png_byte)ep[i].green;
  201614. entrybuf[2] = (png_byte)ep[i].blue;
  201615. entrybuf[3] = (png_byte)ep[i].alpha;
  201616. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201617. }
  201618. else
  201619. {
  201620. png_save_uint_16(entrybuf + 0, ep[i].red);
  201621. png_save_uint_16(entrybuf + 2, ep[i].green);
  201622. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201623. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201624. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201625. }
  201626. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201627. }
  201628. #endif
  201629. png_write_chunk_end(png_ptr);
  201630. png_free(png_ptr, new_name);
  201631. }
  201632. #endif
  201633. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201634. /* write the sBIT chunk */
  201635. void /* PRIVATE */
  201636. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201637. {
  201638. #ifdef PNG_USE_LOCAL_ARRAYS
  201639. PNG_sBIT;
  201640. #endif
  201641. png_byte buf[4];
  201642. png_size_t size;
  201643. png_debug(1, "in png_write_sBIT\n");
  201644. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201645. if (color_type & PNG_COLOR_MASK_COLOR)
  201646. {
  201647. png_byte maxbits;
  201648. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201649. png_ptr->usr_bit_depth);
  201650. if (sbit->red == 0 || sbit->red > maxbits ||
  201651. sbit->green == 0 || sbit->green > maxbits ||
  201652. sbit->blue == 0 || sbit->blue > maxbits)
  201653. {
  201654. png_warning(png_ptr, "Invalid sBIT depth specified");
  201655. return;
  201656. }
  201657. buf[0] = sbit->red;
  201658. buf[1] = sbit->green;
  201659. buf[2] = sbit->blue;
  201660. size = 3;
  201661. }
  201662. else
  201663. {
  201664. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201665. {
  201666. png_warning(png_ptr, "Invalid sBIT depth specified");
  201667. return;
  201668. }
  201669. buf[0] = sbit->gray;
  201670. size = 1;
  201671. }
  201672. if (color_type & PNG_COLOR_MASK_ALPHA)
  201673. {
  201674. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201675. {
  201676. png_warning(png_ptr, "Invalid sBIT depth specified");
  201677. return;
  201678. }
  201679. buf[size++] = sbit->alpha;
  201680. }
  201681. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201682. }
  201683. #endif
  201684. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201685. /* write the cHRM chunk */
  201686. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201687. void /* PRIVATE */
  201688. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201689. double red_x, double red_y, double green_x, double green_y,
  201690. double blue_x, double blue_y)
  201691. {
  201692. #ifdef PNG_USE_LOCAL_ARRAYS
  201693. PNG_cHRM;
  201694. #endif
  201695. png_byte buf[32];
  201696. png_uint_32 itemp;
  201697. png_debug(1, "in png_write_cHRM\n");
  201698. /* each value is saved in 1/100,000ths */
  201699. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201700. white_x + white_y > 1.0)
  201701. {
  201702. png_warning(png_ptr, "Invalid cHRM white point specified");
  201703. #if !defined(PNG_NO_CONSOLE_IO)
  201704. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201705. #endif
  201706. return;
  201707. }
  201708. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201709. png_save_uint_32(buf, itemp);
  201710. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201711. png_save_uint_32(buf + 4, itemp);
  201712. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201713. {
  201714. png_warning(png_ptr, "Invalid cHRM red point specified");
  201715. return;
  201716. }
  201717. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201718. png_save_uint_32(buf + 8, itemp);
  201719. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201720. png_save_uint_32(buf + 12, itemp);
  201721. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201722. {
  201723. png_warning(png_ptr, "Invalid cHRM green point specified");
  201724. return;
  201725. }
  201726. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201727. png_save_uint_32(buf + 16, itemp);
  201728. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201729. png_save_uint_32(buf + 20, itemp);
  201730. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201731. {
  201732. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201733. return;
  201734. }
  201735. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201736. png_save_uint_32(buf + 24, itemp);
  201737. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201738. png_save_uint_32(buf + 28, itemp);
  201739. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201740. }
  201741. #endif
  201742. #ifdef PNG_FIXED_POINT_SUPPORTED
  201743. void /* PRIVATE */
  201744. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201745. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201746. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201747. png_fixed_point blue_y)
  201748. {
  201749. #ifdef PNG_USE_LOCAL_ARRAYS
  201750. PNG_cHRM;
  201751. #endif
  201752. png_byte buf[32];
  201753. png_debug(1, "in png_write_cHRM\n");
  201754. /* each value is saved in 1/100,000ths */
  201755. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201756. {
  201757. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201758. #if !defined(PNG_NO_CONSOLE_IO)
  201759. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201760. #endif
  201761. return;
  201762. }
  201763. png_save_uint_32(buf, (png_uint_32)white_x);
  201764. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201765. if (red_x + red_y > 100000L)
  201766. {
  201767. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201768. return;
  201769. }
  201770. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201771. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201772. if (green_x + green_y > 100000L)
  201773. {
  201774. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201775. return;
  201776. }
  201777. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201778. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201779. if (blue_x + blue_y > 100000L)
  201780. {
  201781. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201782. return;
  201783. }
  201784. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201785. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201786. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201787. }
  201788. #endif
  201789. #endif
  201790. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201791. /* write the tRNS chunk */
  201792. void /* PRIVATE */
  201793. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201794. int num_trans, int color_type)
  201795. {
  201796. #ifdef PNG_USE_LOCAL_ARRAYS
  201797. PNG_tRNS;
  201798. #endif
  201799. png_byte buf[6];
  201800. png_debug(1, "in png_write_tRNS\n");
  201801. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201802. {
  201803. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201804. {
  201805. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201806. return;
  201807. }
  201808. /* write the chunk out as it is */
  201809. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201810. }
  201811. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201812. {
  201813. /* one 16 bit value */
  201814. if(tran->gray >= (1 << png_ptr->bit_depth))
  201815. {
  201816. png_warning(png_ptr,
  201817. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201818. return;
  201819. }
  201820. png_save_uint_16(buf, tran->gray);
  201821. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201822. }
  201823. else if (color_type == PNG_COLOR_TYPE_RGB)
  201824. {
  201825. /* three 16 bit values */
  201826. png_save_uint_16(buf, tran->red);
  201827. png_save_uint_16(buf + 2, tran->green);
  201828. png_save_uint_16(buf + 4, tran->blue);
  201829. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201830. {
  201831. png_warning(png_ptr,
  201832. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201833. return;
  201834. }
  201835. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201836. }
  201837. else
  201838. {
  201839. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201840. }
  201841. }
  201842. #endif
  201843. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201844. /* write the background chunk */
  201845. void /* PRIVATE */
  201846. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201847. {
  201848. #ifdef PNG_USE_LOCAL_ARRAYS
  201849. PNG_bKGD;
  201850. #endif
  201851. png_byte buf[6];
  201852. png_debug(1, "in png_write_bKGD\n");
  201853. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201854. {
  201855. if (
  201856. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201857. (png_ptr->num_palette ||
  201858. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201859. #endif
  201860. back->index > png_ptr->num_palette)
  201861. {
  201862. png_warning(png_ptr, "Invalid background palette index");
  201863. return;
  201864. }
  201865. buf[0] = back->index;
  201866. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201867. }
  201868. else if (color_type & PNG_COLOR_MASK_COLOR)
  201869. {
  201870. png_save_uint_16(buf, back->red);
  201871. png_save_uint_16(buf + 2, back->green);
  201872. png_save_uint_16(buf + 4, back->blue);
  201873. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201874. {
  201875. png_warning(png_ptr,
  201876. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201877. return;
  201878. }
  201879. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201880. }
  201881. else
  201882. {
  201883. if(back->gray >= (1 << png_ptr->bit_depth))
  201884. {
  201885. png_warning(png_ptr,
  201886. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201887. return;
  201888. }
  201889. png_save_uint_16(buf, back->gray);
  201890. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201891. }
  201892. }
  201893. #endif
  201894. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201895. /* write the histogram */
  201896. void /* PRIVATE */
  201897. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201898. {
  201899. #ifdef PNG_USE_LOCAL_ARRAYS
  201900. PNG_hIST;
  201901. #endif
  201902. int i;
  201903. png_byte buf[3];
  201904. png_debug(1, "in png_write_hIST\n");
  201905. if (num_hist > (int)png_ptr->num_palette)
  201906. {
  201907. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201908. png_ptr->num_palette);
  201909. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201910. return;
  201911. }
  201912. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201913. for (i = 0; i < num_hist; i++)
  201914. {
  201915. png_save_uint_16(buf, hist[i]);
  201916. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201917. }
  201918. png_write_chunk_end(png_ptr);
  201919. }
  201920. #endif
  201921. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201922. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201923. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201924. * and if invalid, correct the keyword rather than discarding the entire
  201925. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201926. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201927. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201928. *
  201929. * The new_key is allocated to hold the corrected keyword and must be freed
  201930. * by the calling routine. This avoids problems with trying to write to
  201931. * static keywords without having to have duplicate copies of the strings.
  201932. */
  201933. png_size_t /* PRIVATE */
  201934. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201935. {
  201936. png_size_t key_len;
  201937. png_charp kp, dp;
  201938. int kflag;
  201939. int kwarn=0;
  201940. png_debug(1, "in png_check_keyword\n");
  201941. *new_key = NULL;
  201942. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201943. {
  201944. png_warning(png_ptr, "zero length keyword");
  201945. return ((png_size_t)0);
  201946. }
  201947. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201948. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201949. if (*new_key == NULL)
  201950. {
  201951. png_warning(png_ptr, "Out of memory while procesing keyword");
  201952. return ((png_size_t)0);
  201953. }
  201954. /* Replace non-printing characters with a blank and print a warning */
  201955. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201956. {
  201957. if ((png_byte)*kp < 0x20 ||
  201958. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201959. {
  201960. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201961. char msg[40];
  201962. png_snprintf(msg, 40,
  201963. "invalid keyword character 0x%02X", (png_byte)*kp);
  201964. png_warning(png_ptr, msg);
  201965. #else
  201966. png_warning(png_ptr, "invalid character in keyword");
  201967. #endif
  201968. *dp = ' ';
  201969. }
  201970. else
  201971. {
  201972. *dp = *kp;
  201973. }
  201974. }
  201975. *dp = '\0';
  201976. /* Remove any trailing white space. */
  201977. kp = *new_key + key_len - 1;
  201978. if (*kp == ' ')
  201979. {
  201980. png_warning(png_ptr, "trailing spaces removed from keyword");
  201981. while (*kp == ' ')
  201982. {
  201983. *(kp--) = '\0';
  201984. key_len--;
  201985. }
  201986. }
  201987. /* Remove any leading white space. */
  201988. kp = *new_key;
  201989. if (*kp == ' ')
  201990. {
  201991. png_warning(png_ptr, "leading spaces removed from keyword");
  201992. while (*kp == ' ')
  201993. {
  201994. kp++;
  201995. key_len--;
  201996. }
  201997. }
  201998. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201999. /* Remove multiple internal spaces. */
  202000. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  202001. {
  202002. if (*kp == ' ' && kflag == 0)
  202003. {
  202004. *(dp++) = *kp;
  202005. kflag = 1;
  202006. }
  202007. else if (*kp == ' ')
  202008. {
  202009. key_len--;
  202010. kwarn=1;
  202011. }
  202012. else
  202013. {
  202014. *(dp++) = *kp;
  202015. kflag = 0;
  202016. }
  202017. }
  202018. *dp = '\0';
  202019. if(kwarn)
  202020. png_warning(png_ptr, "extra interior spaces removed from keyword");
  202021. if (key_len == 0)
  202022. {
  202023. png_free(png_ptr, *new_key);
  202024. *new_key=NULL;
  202025. png_warning(png_ptr, "Zero length keyword");
  202026. }
  202027. if (key_len > 79)
  202028. {
  202029. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  202030. new_key[79] = '\0';
  202031. key_len = 79;
  202032. }
  202033. return (key_len);
  202034. }
  202035. #endif
  202036. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  202037. /* write a tEXt chunk */
  202038. void /* PRIVATE */
  202039. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  202040. png_size_t text_len)
  202041. {
  202042. #ifdef PNG_USE_LOCAL_ARRAYS
  202043. PNG_tEXt;
  202044. #endif
  202045. png_size_t key_len;
  202046. png_charp new_key;
  202047. png_debug(1, "in png_write_tEXt\n");
  202048. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202049. {
  202050. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  202051. return;
  202052. }
  202053. if (text == NULL || *text == '\0')
  202054. text_len = 0;
  202055. else
  202056. text_len = png_strlen(text);
  202057. /* make sure we include the 0 after the key */
  202058. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  202059. /*
  202060. * We leave it to the application to meet PNG-1.0 requirements on the
  202061. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202062. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202063. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202064. */
  202065. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202066. if (text_len)
  202067. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  202068. png_write_chunk_end(png_ptr);
  202069. png_free(png_ptr, new_key);
  202070. }
  202071. #endif
  202072. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  202073. /* write a compressed text chunk */
  202074. void /* PRIVATE */
  202075. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  202076. png_size_t text_len, int compression)
  202077. {
  202078. #ifdef PNG_USE_LOCAL_ARRAYS
  202079. PNG_zTXt;
  202080. #endif
  202081. png_size_t key_len;
  202082. char buf[1];
  202083. png_charp new_key;
  202084. compression_state comp;
  202085. png_debug(1, "in png_write_zTXt\n");
  202086. comp.num_output_ptr = 0;
  202087. comp.max_output_ptr = 0;
  202088. comp.output_ptr = NULL;
  202089. comp.input = NULL;
  202090. comp.input_len = 0;
  202091. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202092. {
  202093. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  202094. return;
  202095. }
  202096. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  202097. {
  202098. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  202099. png_free(png_ptr, new_key);
  202100. return;
  202101. }
  202102. text_len = png_strlen(text);
  202103. /* compute the compressed data; do it now for the length */
  202104. text_len = png_text_compress(png_ptr, text, text_len, compression,
  202105. &comp);
  202106. /* write start of chunk */
  202107. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  202108. (key_len+text_len+2));
  202109. /* write key */
  202110. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202111. png_free(png_ptr, new_key);
  202112. buf[0] = (png_byte)compression;
  202113. /* write compression */
  202114. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202115. /* write the compressed data */
  202116. png_write_compressed_data_out(png_ptr, &comp);
  202117. /* close the chunk */
  202118. png_write_chunk_end(png_ptr);
  202119. }
  202120. #endif
  202121. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202122. /* write an iTXt chunk */
  202123. void /* PRIVATE */
  202124. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202125. png_charp lang, png_charp lang_key, png_charp text)
  202126. {
  202127. #ifdef PNG_USE_LOCAL_ARRAYS
  202128. PNG_iTXt;
  202129. #endif
  202130. png_size_t lang_len, key_len, lang_key_len, text_len;
  202131. png_charp new_lang, new_key;
  202132. png_byte cbuf[2];
  202133. compression_state comp;
  202134. png_debug(1, "in png_write_iTXt\n");
  202135. comp.num_output_ptr = 0;
  202136. comp.max_output_ptr = 0;
  202137. comp.output_ptr = NULL;
  202138. comp.input = NULL;
  202139. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202140. {
  202141. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202142. return;
  202143. }
  202144. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202145. {
  202146. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202147. new_lang = NULL;
  202148. lang_len = 0;
  202149. }
  202150. if (lang_key == NULL)
  202151. lang_key_len = 0;
  202152. else
  202153. lang_key_len = png_strlen(lang_key);
  202154. if (text == NULL)
  202155. text_len = 0;
  202156. else
  202157. text_len = png_strlen(text);
  202158. /* compute the compressed data; do it now for the length */
  202159. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202160. &comp);
  202161. /* make sure we include the compression flag, the compression byte,
  202162. * and the NULs after the key, lang, and lang_key parts */
  202163. png_write_chunk_start(png_ptr, png_iTXt,
  202164. (png_uint_32)(
  202165. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202166. + key_len
  202167. + lang_len
  202168. + lang_key_len
  202169. + text_len));
  202170. /*
  202171. * We leave it to the application to meet PNG-1.0 requirements on the
  202172. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202173. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202174. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202175. */
  202176. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202177. /* set the compression flag */
  202178. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202179. compression == PNG_TEXT_COMPRESSION_NONE)
  202180. cbuf[0] = 0;
  202181. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202182. cbuf[0] = 1;
  202183. /* set the compression method */
  202184. cbuf[1] = 0;
  202185. png_write_chunk_data(png_ptr, cbuf, 2);
  202186. cbuf[0] = 0;
  202187. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202188. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202189. png_write_compressed_data_out(png_ptr, &comp);
  202190. png_write_chunk_end(png_ptr);
  202191. png_free(png_ptr, new_key);
  202192. if (new_lang)
  202193. png_free(png_ptr, new_lang);
  202194. }
  202195. #endif
  202196. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202197. /* write the oFFs chunk */
  202198. void /* PRIVATE */
  202199. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202200. int unit_type)
  202201. {
  202202. #ifdef PNG_USE_LOCAL_ARRAYS
  202203. PNG_oFFs;
  202204. #endif
  202205. png_byte buf[9];
  202206. png_debug(1, "in png_write_oFFs\n");
  202207. if (unit_type >= PNG_OFFSET_LAST)
  202208. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202209. png_save_int_32(buf, x_offset);
  202210. png_save_int_32(buf + 4, y_offset);
  202211. buf[8] = (png_byte)unit_type;
  202212. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202213. }
  202214. #endif
  202215. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202216. /* write the pCAL chunk (described in the PNG extensions document) */
  202217. void /* PRIVATE */
  202218. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202219. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202220. {
  202221. #ifdef PNG_USE_LOCAL_ARRAYS
  202222. PNG_pCAL;
  202223. #endif
  202224. png_size_t purpose_len, units_len, total_len;
  202225. png_uint_32p params_len;
  202226. png_byte buf[10];
  202227. png_charp new_purpose;
  202228. int i;
  202229. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202230. if (type >= PNG_EQUATION_LAST)
  202231. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202232. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202233. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202234. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202235. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202236. total_len = purpose_len + units_len + 10;
  202237. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202238. *png_sizeof(png_uint_32)));
  202239. /* Find the length of each parameter, making sure we don't count the
  202240. null terminator for the last parameter. */
  202241. for (i = 0; i < nparams; i++)
  202242. {
  202243. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202244. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202245. total_len += (png_size_t)params_len[i];
  202246. }
  202247. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202248. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202249. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202250. png_save_int_32(buf, X0);
  202251. png_save_int_32(buf + 4, X1);
  202252. buf[8] = (png_byte)type;
  202253. buf[9] = (png_byte)nparams;
  202254. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202255. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202256. png_free(png_ptr, new_purpose);
  202257. for (i = 0; i < nparams; i++)
  202258. {
  202259. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202260. (png_size_t)params_len[i]);
  202261. }
  202262. png_free(png_ptr, params_len);
  202263. png_write_chunk_end(png_ptr);
  202264. }
  202265. #endif
  202266. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202267. /* write the sCAL chunk */
  202268. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202269. void /* PRIVATE */
  202270. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202271. {
  202272. #ifdef PNG_USE_LOCAL_ARRAYS
  202273. PNG_sCAL;
  202274. #endif
  202275. char buf[64];
  202276. png_size_t total_len;
  202277. png_debug(1, "in png_write_sCAL\n");
  202278. buf[0] = (char)unit;
  202279. #if defined(_WIN32_WCE)
  202280. /* sprintf() function is not supported on WindowsCE */
  202281. {
  202282. wchar_t wc_buf[32];
  202283. size_t wc_len;
  202284. swprintf(wc_buf, TEXT("%12.12e"), width);
  202285. wc_len = wcslen(wc_buf);
  202286. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202287. total_len = wc_len + 2;
  202288. swprintf(wc_buf, TEXT("%12.12e"), height);
  202289. wc_len = wcslen(wc_buf);
  202290. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202291. NULL, NULL);
  202292. total_len += wc_len;
  202293. }
  202294. #else
  202295. png_snprintf(buf + 1, 63, "%12.12e", width);
  202296. total_len = 1 + png_strlen(buf + 1) + 1;
  202297. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202298. total_len += png_strlen(buf + total_len);
  202299. #endif
  202300. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202301. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202302. }
  202303. #else
  202304. #ifdef PNG_FIXED_POINT_SUPPORTED
  202305. void /* PRIVATE */
  202306. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202307. png_charp height)
  202308. {
  202309. #ifdef PNG_USE_LOCAL_ARRAYS
  202310. PNG_sCAL;
  202311. #endif
  202312. png_byte buf[64];
  202313. png_size_t wlen, hlen, total_len;
  202314. png_debug(1, "in png_write_sCAL_s\n");
  202315. wlen = png_strlen(width);
  202316. hlen = png_strlen(height);
  202317. total_len = wlen + hlen + 2;
  202318. if (total_len > 64)
  202319. {
  202320. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202321. return;
  202322. }
  202323. buf[0] = (png_byte)unit;
  202324. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202325. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202326. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202327. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202328. }
  202329. #endif
  202330. #endif
  202331. #endif
  202332. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202333. /* write the pHYs chunk */
  202334. void /* PRIVATE */
  202335. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202336. png_uint_32 y_pixels_per_unit,
  202337. int unit_type)
  202338. {
  202339. #ifdef PNG_USE_LOCAL_ARRAYS
  202340. PNG_pHYs;
  202341. #endif
  202342. png_byte buf[9];
  202343. png_debug(1, "in png_write_pHYs\n");
  202344. if (unit_type >= PNG_RESOLUTION_LAST)
  202345. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202346. png_save_uint_32(buf, x_pixels_per_unit);
  202347. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202348. buf[8] = (png_byte)unit_type;
  202349. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202350. }
  202351. #endif
  202352. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202353. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202354. * or png_convert_from_time_t(), or fill in the structure yourself.
  202355. */
  202356. void /* PRIVATE */
  202357. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202358. {
  202359. #ifdef PNG_USE_LOCAL_ARRAYS
  202360. PNG_tIME;
  202361. #endif
  202362. png_byte buf[7];
  202363. png_debug(1, "in png_write_tIME\n");
  202364. if (mod_time->month > 12 || mod_time->month < 1 ||
  202365. mod_time->day > 31 || mod_time->day < 1 ||
  202366. mod_time->hour > 23 || mod_time->second > 60)
  202367. {
  202368. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202369. return;
  202370. }
  202371. png_save_uint_16(buf, mod_time->year);
  202372. buf[2] = mod_time->month;
  202373. buf[3] = mod_time->day;
  202374. buf[4] = mod_time->hour;
  202375. buf[5] = mod_time->minute;
  202376. buf[6] = mod_time->second;
  202377. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202378. }
  202379. #endif
  202380. /* initializes the row writing capability of libpng */
  202381. void /* PRIVATE */
  202382. png_write_start_row(png_structp png_ptr)
  202383. {
  202384. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202385. #ifdef PNG_USE_LOCAL_ARRAYS
  202386. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202387. /* start of interlace block */
  202388. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202389. /* offset to next interlace block */
  202390. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202391. /* start of interlace block in the y direction */
  202392. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202393. /* offset to next interlace block in the y direction */
  202394. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202395. #endif
  202396. #endif
  202397. png_size_t buf_size;
  202398. png_debug(1, "in png_write_start_row\n");
  202399. buf_size = (png_size_t)(PNG_ROWBYTES(
  202400. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202401. /* set up row buffer */
  202402. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202403. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202404. #ifndef PNG_NO_WRITE_FILTERING
  202405. /* set up filtering buffer, if using this filter */
  202406. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202407. {
  202408. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202409. (png_ptr->rowbytes + 1));
  202410. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202411. }
  202412. /* We only need to keep the previous row if we are using one of these. */
  202413. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202414. {
  202415. /* set up previous row buffer */
  202416. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202417. png_memset(png_ptr->prev_row, 0, buf_size);
  202418. if (png_ptr->do_filter & PNG_FILTER_UP)
  202419. {
  202420. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202421. (png_ptr->rowbytes + 1));
  202422. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202423. }
  202424. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202425. {
  202426. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202427. (png_ptr->rowbytes + 1));
  202428. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202429. }
  202430. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202431. {
  202432. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202433. (png_ptr->rowbytes + 1));
  202434. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202435. }
  202436. #endif /* PNG_NO_WRITE_FILTERING */
  202437. }
  202438. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202439. /* if interlaced, we need to set up width and height of pass */
  202440. if (png_ptr->interlaced)
  202441. {
  202442. if (!(png_ptr->transformations & PNG_INTERLACE))
  202443. {
  202444. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202445. png_pass_ystart[0]) / png_pass_yinc[0];
  202446. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202447. png_pass_start[0]) / png_pass_inc[0];
  202448. }
  202449. else
  202450. {
  202451. png_ptr->num_rows = png_ptr->height;
  202452. png_ptr->usr_width = png_ptr->width;
  202453. }
  202454. }
  202455. else
  202456. #endif
  202457. {
  202458. png_ptr->num_rows = png_ptr->height;
  202459. png_ptr->usr_width = png_ptr->width;
  202460. }
  202461. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202462. png_ptr->zstream.next_out = png_ptr->zbuf;
  202463. }
  202464. /* Internal use only. Called when finished processing a row of data. */
  202465. void /* PRIVATE */
  202466. png_write_finish_row(png_structp png_ptr)
  202467. {
  202468. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202469. #ifdef PNG_USE_LOCAL_ARRAYS
  202470. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202471. /* start of interlace block */
  202472. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202473. /* offset to next interlace block */
  202474. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202475. /* start of interlace block in the y direction */
  202476. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202477. /* offset to next interlace block in the y direction */
  202478. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202479. #endif
  202480. #endif
  202481. int ret;
  202482. png_debug(1, "in png_write_finish_row\n");
  202483. /* next row */
  202484. png_ptr->row_number++;
  202485. /* see if we are done */
  202486. if (png_ptr->row_number < png_ptr->num_rows)
  202487. return;
  202488. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202489. /* if interlaced, go to next pass */
  202490. if (png_ptr->interlaced)
  202491. {
  202492. png_ptr->row_number = 0;
  202493. if (png_ptr->transformations & PNG_INTERLACE)
  202494. {
  202495. png_ptr->pass++;
  202496. }
  202497. else
  202498. {
  202499. /* loop until we find a non-zero width or height pass */
  202500. do
  202501. {
  202502. png_ptr->pass++;
  202503. if (png_ptr->pass >= 7)
  202504. break;
  202505. png_ptr->usr_width = (png_ptr->width +
  202506. png_pass_inc[png_ptr->pass] - 1 -
  202507. png_pass_start[png_ptr->pass]) /
  202508. png_pass_inc[png_ptr->pass];
  202509. png_ptr->num_rows = (png_ptr->height +
  202510. png_pass_yinc[png_ptr->pass] - 1 -
  202511. png_pass_ystart[png_ptr->pass]) /
  202512. png_pass_yinc[png_ptr->pass];
  202513. if (png_ptr->transformations & PNG_INTERLACE)
  202514. break;
  202515. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202516. }
  202517. /* reset the row above the image for the next pass */
  202518. if (png_ptr->pass < 7)
  202519. {
  202520. if (png_ptr->prev_row != NULL)
  202521. png_memset(png_ptr->prev_row, 0,
  202522. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202523. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202524. return;
  202525. }
  202526. }
  202527. #endif
  202528. /* if we get here, we've just written the last row, so we need
  202529. to flush the compressor */
  202530. do
  202531. {
  202532. /* tell the compressor we are done */
  202533. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202534. /* check for an error */
  202535. if (ret == Z_OK)
  202536. {
  202537. /* check to see if we need more room */
  202538. if (!(png_ptr->zstream.avail_out))
  202539. {
  202540. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202541. png_ptr->zstream.next_out = png_ptr->zbuf;
  202542. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202543. }
  202544. }
  202545. else if (ret != Z_STREAM_END)
  202546. {
  202547. if (png_ptr->zstream.msg != NULL)
  202548. png_error(png_ptr, png_ptr->zstream.msg);
  202549. else
  202550. png_error(png_ptr, "zlib error");
  202551. }
  202552. } while (ret != Z_STREAM_END);
  202553. /* write any extra space */
  202554. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202555. {
  202556. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202557. png_ptr->zstream.avail_out);
  202558. }
  202559. deflateReset(&png_ptr->zstream);
  202560. png_ptr->zstream.data_type = Z_BINARY;
  202561. }
  202562. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202563. /* Pick out the correct pixels for the interlace pass.
  202564. * The basic idea here is to go through the row with a source
  202565. * pointer and a destination pointer (sp and dp), and copy the
  202566. * correct pixels for the pass. As the row gets compacted,
  202567. * sp will always be >= dp, so we should never overwrite anything.
  202568. * See the default: case for the easiest code to understand.
  202569. */
  202570. void /* PRIVATE */
  202571. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202572. {
  202573. #ifdef PNG_USE_LOCAL_ARRAYS
  202574. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202575. /* start of interlace block */
  202576. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202577. /* offset to next interlace block */
  202578. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202579. #endif
  202580. png_debug(1, "in png_do_write_interlace\n");
  202581. /* we don't have to do anything on the last pass (6) */
  202582. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202583. if (row != NULL && row_info != NULL && pass < 6)
  202584. #else
  202585. if (pass < 6)
  202586. #endif
  202587. {
  202588. /* each pixel depth is handled separately */
  202589. switch (row_info->pixel_depth)
  202590. {
  202591. case 1:
  202592. {
  202593. png_bytep sp;
  202594. png_bytep dp;
  202595. int shift;
  202596. int d;
  202597. int value;
  202598. png_uint_32 i;
  202599. png_uint_32 row_width = row_info->width;
  202600. dp = row;
  202601. d = 0;
  202602. shift = 7;
  202603. for (i = png_pass_start[pass]; i < row_width;
  202604. i += png_pass_inc[pass])
  202605. {
  202606. sp = row + (png_size_t)(i >> 3);
  202607. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202608. d |= (value << shift);
  202609. if (shift == 0)
  202610. {
  202611. shift = 7;
  202612. *dp++ = (png_byte)d;
  202613. d = 0;
  202614. }
  202615. else
  202616. shift--;
  202617. }
  202618. if (shift != 7)
  202619. *dp = (png_byte)d;
  202620. break;
  202621. }
  202622. case 2:
  202623. {
  202624. png_bytep sp;
  202625. png_bytep dp;
  202626. int shift;
  202627. int d;
  202628. int value;
  202629. png_uint_32 i;
  202630. png_uint_32 row_width = row_info->width;
  202631. dp = row;
  202632. shift = 6;
  202633. d = 0;
  202634. for (i = png_pass_start[pass]; i < row_width;
  202635. i += png_pass_inc[pass])
  202636. {
  202637. sp = row + (png_size_t)(i >> 2);
  202638. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202639. d |= (value << shift);
  202640. if (shift == 0)
  202641. {
  202642. shift = 6;
  202643. *dp++ = (png_byte)d;
  202644. d = 0;
  202645. }
  202646. else
  202647. shift -= 2;
  202648. }
  202649. if (shift != 6)
  202650. *dp = (png_byte)d;
  202651. break;
  202652. }
  202653. case 4:
  202654. {
  202655. png_bytep sp;
  202656. png_bytep dp;
  202657. int shift;
  202658. int d;
  202659. int value;
  202660. png_uint_32 i;
  202661. png_uint_32 row_width = row_info->width;
  202662. dp = row;
  202663. shift = 4;
  202664. d = 0;
  202665. for (i = png_pass_start[pass]; i < row_width;
  202666. i += png_pass_inc[pass])
  202667. {
  202668. sp = row + (png_size_t)(i >> 1);
  202669. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202670. d |= (value << shift);
  202671. if (shift == 0)
  202672. {
  202673. shift = 4;
  202674. *dp++ = (png_byte)d;
  202675. d = 0;
  202676. }
  202677. else
  202678. shift -= 4;
  202679. }
  202680. if (shift != 4)
  202681. *dp = (png_byte)d;
  202682. break;
  202683. }
  202684. default:
  202685. {
  202686. png_bytep sp;
  202687. png_bytep dp;
  202688. png_uint_32 i;
  202689. png_uint_32 row_width = row_info->width;
  202690. png_size_t pixel_bytes;
  202691. /* start at the beginning */
  202692. dp = row;
  202693. /* find out how many bytes each pixel takes up */
  202694. pixel_bytes = (row_info->pixel_depth >> 3);
  202695. /* loop through the row, only looking at the pixels that
  202696. matter */
  202697. for (i = png_pass_start[pass]; i < row_width;
  202698. i += png_pass_inc[pass])
  202699. {
  202700. /* find out where the original pixel is */
  202701. sp = row + (png_size_t)i * pixel_bytes;
  202702. /* move the pixel */
  202703. if (dp != sp)
  202704. png_memcpy(dp, sp, pixel_bytes);
  202705. /* next pixel */
  202706. dp += pixel_bytes;
  202707. }
  202708. break;
  202709. }
  202710. }
  202711. /* set new row width */
  202712. row_info->width = (row_info->width +
  202713. png_pass_inc[pass] - 1 -
  202714. png_pass_start[pass]) /
  202715. png_pass_inc[pass];
  202716. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202717. row_info->width);
  202718. }
  202719. }
  202720. #endif
  202721. /* This filters the row, chooses which filter to use, if it has not already
  202722. * been specified by the application, and then writes the row out with the
  202723. * chosen filter.
  202724. */
  202725. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202726. #define PNG_HISHIFT 10
  202727. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202728. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202729. void /* PRIVATE */
  202730. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202731. {
  202732. png_bytep best_row;
  202733. #ifndef PNG_NO_WRITE_FILTER
  202734. png_bytep prev_row, row_buf;
  202735. png_uint_32 mins, bpp;
  202736. png_byte filter_to_do = png_ptr->do_filter;
  202737. png_uint_32 row_bytes = row_info->rowbytes;
  202738. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202739. int num_p_filters = (int)png_ptr->num_prev_filters;
  202740. #endif
  202741. png_debug(1, "in png_write_find_filter\n");
  202742. /* find out how many bytes offset each pixel is */
  202743. bpp = (row_info->pixel_depth + 7) >> 3;
  202744. prev_row = png_ptr->prev_row;
  202745. #endif
  202746. best_row = png_ptr->row_buf;
  202747. #ifndef PNG_NO_WRITE_FILTER
  202748. row_buf = best_row;
  202749. mins = PNG_MAXSUM;
  202750. /* The prediction method we use is to find which method provides the
  202751. * smallest value when summing the absolute values of the distances
  202752. * from zero, using anything >= 128 as negative numbers. This is known
  202753. * as the "minimum sum of absolute differences" heuristic. Other
  202754. * heuristics are the "weighted minimum sum of absolute differences"
  202755. * (experimental and can in theory improve compression), and the "zlib
  202756. * predictive" method (not implemented yet), which does test compressions
  202757. * of lines using different filter methods, and then chooses the
  202758. * (series of) filter(s) that give minimum compressed data size (VERY
  202759. * computationally expensive).
  202760. *
  202761. * GRR 980525: consider also
  202762. * (1) minimum sum of absolute differences from running average (i.e.,
  202763. * keep running sum of non-absolute differences & count of bytes)
  202764. * [track dispersion, too? restart average if dispersion too large?]
  202765. * (1b) minimum sum of absolute differences from sliding average, probably
  202766. * with window size <= deflate window (usually 32K)
  202767. * (2) minimum sum of squared differences from zero or running average
  202768. * (i.e., ~ root-mean-square approach)
  202769. */
  202770. /* We don't need to test the 'no filter' case if this is the only filter
  202771. * that has been chosen, as it doesn't actually do anything to the data.
  202772. */
  202773. if ((filter_to_do & PNG_FILTER_NONE) &&
  202774. filter_to_do != PNG_FILTER_NONE)
  202775. {
  202776. png_bytep rp;
  202777. png_uint_32 sum = 0;
  202778. png_uint_32 i;
  202779. int v;
  202780. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202781. {
  202782. v = *rp;
  202783. sum += (v < 128) ? v : 256 - v;
  202784. }
  202785. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202786. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202787. {
  202788. png_uint_32 sumhi, sumlo;
  202789. int j;
  202790. sumlo = sum & PNG_LOMASK;
  202791. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202792. /* Reduce the sum if we match any of the previous rows */
  202793. for (j = 0; j < num_p_filters; j++)
  202794. {
  202795. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202796. {
  202797. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202798. PNG_WEIGHT_SHIFT;
  202799. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202800. PNG_WEIGHT_SHIFT;
  202801. }
  202802. }
  202803. /* Factor in the cost of this filter (this is here for completeness,
  202804. * but it makes no sense to have a "cost" for the NONE filter, as
  202805. * it has the minimum possible computational cost - none).
  202806. */
  202807. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202808. PNG_COST_SHIFT;
  202809. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202810. PNG_COST_SHIFT;
  202811. if (sumhi > PNG_HIMASK)
  202812. sum = PNG_MAXSUM;
  202813. else
  202814. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202815. }
  202816. #endif
  202817. mins = sum;
  202818. }
  202819. /* sub filter */
  202820. if (filter_to_do == PNG_FILTER_SUB)
  202821. /* it's the only filter so no testing is needed */
  202822. {
  202823. png_bytep rp, lp, dp;
  202824. png_uint_32 i;
  202825. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202826. i++, rp++, dp++)
  202827. {
  202828. *dp = *rp;
  202829. }
  202830. for (lp = row_buf + 1; i < row_bytes;
  202831. i++, rp++, lp++, dp++)
  202832. {
  202833. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202834. }
  202835. best_row = png_ptr->sub_row;
  202836. }
  202837. else if (filter_to_do & PNG_FILTER_SUB)
  202838. {
  202839. png_bytep rp, dp, lp;
  202840. png_uint_32 sum = 0, lmins = mins;
  202841. png_uint_32 i;
  202842. int v;
  202843. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202844. /* We temporarily increase the "minimum sum" by the factor we
  202845. * would reduce the sum of this filter, so that we can do the
  202846. * early exit comparison without scaling the sum each time.
  202847. */
  202848. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202849. {
  202850. int j;
  202851. png_uint_32 lmhi, lmlo;
  202852. lmlo = lmins & PNG_LOMASK;
  202853. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202854. for (j = 0; j < num_p_filters; j++)
  202855. {
  202856. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202857. {
  202858. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202859. PNG_WEIGHT_SHIFT;
  202860. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202861. PNG_WEIGHT_SHIFT;
  202862. }
  202863. }
  202864. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202865. PNG_COST_SHIFT;
  202866. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202867. PNG_COST_SHIFT;
  202868. if (lmhi > PNG_HIMASK)
  202869. lmins = PNG_MAXSUM;
  202870. else
  202871. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202872. }
  202873. #endif
  202874. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202875. i++, rp++, dp++)
  202876. {
  202877. v = *dp = *rp;
  202878. sum += (v < 128) ? v : 256 - v;
  202879. }
  202880. for (lp = row_buf + 1; i < row_bytes;
  202881. i++, rp++, lp++, dp++)
  202882. {
  202883. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202884. sum += (v < 128) ? v : 256 - v;
  202885. if (sum > lmins) /* We are already worse, don't continue. */
  202886. break;
  202887. }
  202888. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202889. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202890. {
  202891. int j;
  202892. png_uint_32 sumhi, sumlo;
  202893. sumlo = sum & PNG_LOMASK;
  202894. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202895. for (j = 0; j < num_p_filters; j++)
  202896. {
  202897. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202898. {
  202899. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202900. PNG_WEIGHT_SHIFT;
  202901. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202902. PNG_WEIGHT_SHIFT;
  202903. }
  202904. }
  202905. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202906. PNG_COST_SHIFT;
  202907. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202908. PNG_COST_SHIFT;
  202909. if (sumhi > PNG_HIMASK)
  202910. sum = PNG_MAXSUM;
  202911. else
  202912. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202913. }
  202914. #endif
  202915. if (sum < mins)
  202916. {
  202917. mins = sum;
  202918. best_row = png_ptr->sub_row;
  202919. }
  202920. }
  202921. /* up filter */
  202922. if (filter_to_do == PNG_FILTER_UP)
  202923. {
  202924. png_bytep rp, dp, pp;
  202925. png_uint_32 i;
  202926. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202927. pp = prev_row + 1; i < row_bytes;
  202928. i++, rp++, pp++, dp++)
  202929. {
  202930. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202931. }
  202932. best_row = png_ptr->up_row;
  202933. }
  202934. else if (filter_to_do & PNG_FILTER_UP)
  202935. {
  202936. png_bytep rp, dp, pp;
  202937. png_uint_32 sum = 0, lmins = mins;
  202938. png_uint_32 i;
  202939. int v;
  202940. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202941. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202942. {
  202943. int j;
  202944. png_uint_32 lmhi, lmlo;
  202945. lmlo = lmins & PNG_LOMASK;
  202946. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202947. for (j = 0; j < num_p_filters; j++)
  202948. {
  202949. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202950. {
  202951. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202952. PNG_WEIGHT_SHIFT;
  202953. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202954. PNG_WEIGHT_SHIFT;
  202955. }
  202956. }
  202957. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202958. PNG_COST_SHIFT;
  202959. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202960. PNG_COST_SHIFT;
  202961. if (lmhi > PNG_HIMASK)
  202962. lmins = PNG_MAXSUM;
  202963. else
  202964. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202965. }
  202966. #endif
  202967. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202968. pp = prev_row + 1; i < row_bytes; i++)
  202969. {
  202970. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202971. sum += (v < 128) ? v : 256 - v;
  202972. if (sum > lmins) /* We are already worse, don't continue. */
  202973. break;
  202974. }
  202975. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202976. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202977. {
  202978. int j;
  202979. png_uint_32 sumhi, sumlo;
  202980. sumlo = sum & PNG_LOMASK;
  202981. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202982. for (j = 0; j < num_p_filters; j++)
  202983. {
  202984. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202985. {
  202986. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202987. PNG_WEIGHT_SHIFT;
  202988. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202989. PNG_WEIGHT_SHIFT;
  202990. }
  202991. }
  202992. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202993. PNG_COST_SHIFT;
  202994. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202995. PNG_COST_SHIFT;
  202996. if (sumhi > PNG_HIMASK)
  202997. sum = PNG_MAXSUM;
  202998. else
  202999. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203000. }
  203001. #endif
  203002. if (sum < mins)
  203003. {
  203004. mins = sum;
  203005. best_row = png_ptr->up_row;
  203006. }
  203007. }
  203008. /* avg filter */
  203009. if (filter_to_do == PNG_FILTER_AVG)
  203010. {
  203011. png_bytep rp, dp, pp, lp;
  203012. png_uint_32 i;
  203013. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203014. pp = prev_row + 1; i < bpp; i++)
  203015. {
  203016. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203017. }
  203018. for (lp = row_buf + 1; i < row_bytes; i++)
  203019. {
  203020. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  203021. & 0xff);
  203022. }
  203023. best_row = png_ptr->avg_row;
  203024. }
  203025. else if (filter_to_do & PNG_FILTER_AVG)
  203026. {
  203027. png_bytep rp, dp, pp, lp;
  203028. png_uint_32 sum = 0, lmins = mins;
  203029. png_uint_32 i;
  203030. int v;
  203031. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203032. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203033. {
  203034. int j;
  203035. png_uint_32 lmhi, lmlo;
  203036. lmlo = lmins & PNG_LOMASK;
  203037. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203038. for (j = 0; j < num_p_filters; j++)
  203039. {
  203040. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  203041. {
  203042. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203043. PNG_WEIGHT_SHIFT;
  203044. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203045. PNG_WEIGHT_SHIFT;
  203046. }
  203047. }
  203048. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203049. PNG_COST_SHIFT;
  203050. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203051. PNG_COST_SHIFT;
  203052. if (lmhi > PNG_HIMASK)
  203053. lmins = PNG_MAXSUM;
  203054. else
  203055. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203056. }
  203057. #endif
  203058. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203059. pp = prev_row + 1; i < bpp; i++)
  203060. {
  203061. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203062. sum += (v < 128) ? v : 256 - v;
  203063. }
  203064. for (lp = row_buf + 1; i < row_bytes; i++)
  203065. {
  203066. v = *dp++ =
  203067. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  203068. sum += (v < 128) ? v : 256 - v;
  203069. if (sum > lmins) /* We are already worse, don't continue. */
  203070. break;
  203071. }
  203072. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203073. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203074. {
  203075. int j;
  203076. png_uint_32 sumhi, sumlo;
  203077. sumlo = sum & PNG_LOMASK;
  203078. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203079. for (j = 0; j < num_p_filters; j++)
  203080. {
  203081. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203082. {
  203083. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203084. PNG_WEIGHT_SHIFT;
  203085. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203086. PNG_WEIGHT_SHIFT;
  203087. }
  203088. }
  203089. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203090. PNG_COST_SHIFT;
  203091. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203092. PNG_COST_SHIFT;
  203093. if (sumhi > PNG_HIMASK)
  203094. sum = PNG_MAXSUM;
  203095. else
  203096. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203097. }
  203098. #endif
  203099. if (sum < mins)
  203100. {
  203101. mins = sum;
  203102. best_row = png_ptr->avg_row;
  203103. }
  203104. }
  203105. /* Paeth filter */
  203106. if (filter_to_do == PNG_FILTER_PAETH)
  203107. {
  203108. png_bytep rp, dp, pp, cp, lp;
  203109. png_uint_32 i;
  203110. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203111. pp = prev_row + 1; i < bpp; i++)
  203112. {
  203113. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203114. }
  203115. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203116. {
  203117. int a, b, c, pa, pb, pc, p;
  203118. b = *pp++;
  203119. c = *cp++;
  203120. a = *lp++;
  203121. p = b - c;
  203122. pc = a - c;
  203123. #ifdef PNG_USE_ABS
  203124. pa = abs(p);
  203125. pb = abs(pc);
  203126. pc = abs(p + pc);
  203127. #else
  203128. pa = p < 0 ? -p : p;
  203129. pb = pc < 0 ? -pc : pc;
  203130. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203131. #endif
  203132. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203133. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203134. }
  203135. best_row = png_ptr->paeth_row;
  203136. }
  203137. else if (filter_to_do & PNG_FILTER_PAETH)
  203138. {
  203139. png_bytep rp, dp, pp, cp, lp;
  203140. png_uint_32 sum = 0, lmins = mins;
  203141. png_uint_32 i;
  203142. int v;
  203143. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203144. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203145. {
  203146. int j;
  203147. png_uint_32 lmhi, lmlo;
  203148. lmlo = lmins & PNG_LOMASK;
  203149. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203150. for (j = 0; j < num_p_filters; j++)
  203151. {
  203152. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203153. {
  203154. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203155. PNG_WEIGHT_SHIFT;
  203156. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203157. PNG_WEIGHT_SHIFT;
  203158. }
  203159. }
  203160. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203161. PNG_COST_SHIFT;
  203162. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203163. PNG_COST_SHIFT;
  203164. if (lmhi > PNG_HIMASK)
  203165. lmins = PNG_MAXSUM;
  203166. else
  203167. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203168. }
  203169. #endif
  203170. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203171. pp = prev_row + 1; i < bpp; i++)
  203172. {
  203173. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203174. sum += (v < 128) ? v : 256 - v;
  203175. }
  203176. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203177. {
  203178. int a, b, c, pa, pb, pc, p;
  203179. b = *pp++;
  203180. c = *cp++;
  203181. a = *lp++;
  203182. #ifndef PNG_SLOW_PAETH
  203183. p = b - c;
  203184. pc = a - c;
  203185. #ifdef PNG_USE_ABS
  203186. pa = abs(p);
  203187. pb = abs(pc);
  203188. pc = abs(p + pc);
  203189. #else
  203190. pa = p < 0 ? -p : p;
  203191. pb = pc < 0 ? -pc : pc;
  203192. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203193. #endif
  203194. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203195. #else /* PNG_SLOW_PAETH */
  203196. p = a + b - c;
  203197. pa = abs(p - a);
  203198. pb = abs(p - b);
  203199. pc = abs(p - c);
  203200. if (pa <= pb && pa <= pc)
  203201. p = a;
  203202. else if (pb <= pc)
  203203. p = b;
  203204. else
  203205. p = c;
  203206. #endif /* PNG_SLOW_PAETH */
  203207. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203208. sum += (v < 128) ? v : 256 - v;
  203209. if (sum > lmins) /* We are already worse, don't continue. */
  203210. break;
  203211. }
  203212. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203213. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203214. {
  203215. int j;
  203216. png_uint_32 sumhi, sumlo;
  203217. sumlo = sum & PNG_LOMASK;
  203218. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203219. for (j = 0; j < num_p_filters; j++)
  203220. {
  203221. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203222. {
  203223. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203224. PNG_WEIGHT_SHIFT;
  203225. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203226. PNG_WEIGHT_SHIFT;
  203227. }
  203228. }
  203229. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203230. PNG_COST_SHIFT;
  203231. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203232. PNG_COST_SHIFT;
  203233. if (sumhi > PNG_HIMASK)
  203234. sum = PNG_MAXSUM;
  203235. else
  203236. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203237. }
  203238. #endif
  203239. if (sum < mins)
  203240. {
  203241. best_row = png_ptr->paeth_row;
  203242. }
  203243. }
  203244. #endif /* PNG_NO_WRITE_FILTER */
  203245. /* Do the actual writing of the filtered row data from the chosen filter. */
  203246. png_write_filtered_row(png_ptr, best_row);
  203247. #ifndef PNG_NO_WRITE_FILTER
  203248. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203249. /* Save the type of filter we picked this time for future calculations */
  203250. if (png_ptr->num_prev_filters > 0)
  203251. {
  203252. int j;
  203253. for (j = 1; j < num_p_filters; j++)
  203254. {
  203255. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203256. }
  203257. png_ptr->prev_filters[j] = best_row[0];
  203258. }
  203259. #endif
  203260. #endif /* PNG_NO_WRITE_FILTER */
  203261. }
  203262. /* Do the actual writing of a previously filtered row. */
  203263. void /* PRIVATE */
  203264. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203265. {
  203266. png_debug(1, "in png_write_filtered_row\n");
  203267. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203268. /* set up the zlib input buffer */
  203269. png_ptr->zstream.next_in = filtered_row;
  203270. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203271. /* repeat until we have compressed all the data */
  203272. do
  203273. {
  203274. int ret; /* return of zlib */
  203275. /* compress the data */
  203276. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203277. /* check for compression errors */
  203278. if (ret != Z_OK)
  203279. {
  203280. if (png_ptr->zstream.msg != NULL)
  203281. png_error(png_ptr, png_ptr->zstream.msg);
  203282. else
  203283. png_error(png_ptr, "zlib error");
  203284. }
  203285. /* see if it is time to write another IDAT */
  203286. if (!(png_ptr->zstream.avail_out))
  203287. {
  203288. /* write the IDAT and reset the zlib output buffer */
  203289. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203290. png_ptr->zstream.next_out = png_ptr->zbuf;
  203291. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203292. }
  203293. /* repeat until all data has been compressed */
  203294. } while (png_ptr->zstream.avail_in);
  203295. /* swap the current and previous rows */
  203296. if (png_ptr->prev_row != NULL)
  203297. {
  203298. png_bytep tptr;
  203299. tptr = png_ptr->prev_row;
  203300. png_ptr->prev_row = png_ptr->row_buf;
  203301. png_ptr->row_buf = tptr;
  203302. }
  203303. /* finish row - updates counters and flushes zlib if last row */
  203304. png_write_finish_row(png_ptr);
  203305. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203306. png_ptr->flush_rows++;
  203307. if (png_ptr->flush_dist > 0 &&
  203308. png_ptr->flush_rows >= png_ptr->flush_dist)
  203309. {
  203310. png_write_flush(png_ptr);
  203311. }
  203312. #endif
  203313. }
  203314. #endif /* PNG_WRITE_SUPPORTED */
  203315. /*** End of inlined file: pngwutil.c ***/
  203316. #else
  203317. extern "C"
  203318. {
  203319. #include <png.h>
  203320. #include <pngconf.h>
  203321. }
  203322. #endif
  203323. }
  203324. #undef max
  203325. #undef min
  203326. #if JUCE_MSVC
  203327. #pragma warning (pop)
  203328. #endif
  203329. BEGIN_JUCE_NAMESPACE
  203330. using ::calloc;
  203331. using ::malloc;
  203332. using ::free;
  203333. namespace PNGHelpers
  203334. {
  203335. using namespace pnglibNamespace;
  203336. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  203337. {
  203338. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203339. }
  203340. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203341. {
  203342. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203343. }
  203344. struct PNGErrorStruct {};
  203345. static void errorCallback (png_structp, png_const_charp)
  203346. {
  203347. throw PNGErrorStruct();
  203348. }
  203349. }
  203350. PNGImageFormat::PNGImageFormat() {}
  203351. PNGImageFormat::~PNGImageFormat() {}
  203352. const String PNGImageFormat::getFormatName()
  203353. {
  203354. return "PNG";
  203355. }
  203356. bool PNGImageFormat::canUnderstand (InputStream& in)
  203357. {
  203358. const int bytesNeeded = 4;
  203359. char header [bytesNeeded];
  203360. return in.read (header, bytesNeeded) == bytesNeeded
  203361. && header[1] == 'P'
  203362. && header[2] == 'N'
  203363. && header[3] == 'G';
  203364. }
  203365. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203366. const Image juce_loadWithCoreImage (InputStream& input);
  203367. #endif
  203368. const Image PNGImageFormat::decodeImage (InputStream& in)
  203369. {
  203370. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203371. return juce_loadWithCoreImage (in);
  203372. #else
  203373. using namespace pnglibNamespace;
  203374. Image image;
  203375. png_structp pngReadStruct;
  203376. png_infop pngInfoStruct;
  203377. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203378. if (pngReadStruct != 0)
  203379. {
  203380. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203381. if (pngInfoStruct == 0)
  203382. {
  203383. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203384. return Image::null;
  203385. }
  203386. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203387. // read the header..
  203388. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203389. png_uint_32 width, height;
  203390. int bitDepth, colorType, interlaceType;
  203391. png_read_info (pngReadStruct, pngInfoStruct);
  203392. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203393. &width, &height,
  203394. &bitDepth, &colorType,
  203395. &interlaceType, 0, 0);
  203396. if (bitDepth == 16)
  203397. png_set_strip_16 (pngReadStruct);
  203398. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203399. png_set_expand (pngReadStruct);
  203400. if (bitDepth < 8)
  203401. png_set_expand (pngReadStruct);
  203402. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203403. png_set_expand (pngReadStruct);
  203404. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203405. png_set_gray_to_rgb (pngReadStruct);
  203406. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203407. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203408. || pngInfoStruct->num_trans > 0;
  203409. // Load the image into a temp buffer in the pnglib format..
  203410. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203411. {
  203412. HeapBlock <png_bytep> rows (height);
  203413. for (int y = (int) height; --y >= 0;)
  203414. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203415. png_read_image (pngReadStruct, rows);
  203416. png_read_end (pngReadStruct, pngInfoStruct);
  203417. }
  203418. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203419. // now convert the data to a juce image format..
  203420. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203421. (int) width, (int) height, hasAlphaChan);
  203422. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203423. const Image::BitmapData destData (image, true);
  203424. uint8* srcRow = tempBuffer;
  203425. uint8* destRow = destData.data;
  203426. for (int y = 0; y < (int) height; ++y)
  203427. {
  203428. const uint8* src = srcRow;
  203429. srcRow += (width << 2);
  203430. uint8* dest = destRow;
  203431. destRow += destData.lineStride;
  203432. if (hasAlphaChan)
  203433. {
  203434. for (int i = (int) width; --i >= 0;)
  203435. {
  203436. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203437. ((PixelARGB*) dest)->premultiply();
  203438. dest += destData.pixelStride;
  203439. src += 4;
  203440. }
  203441. }
  203442. else
  203443. {
  203444. for (int i = (int) width; --i >= 0;)
  203445. {
  203446. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203447. dest += destData.pixelStride;
  203448. src += 4;
  203449. }
  203450. }
  203451. }
  203452. }
  203453. return image;
  203454. #endif
  203455. }
  203456. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203457. {
  203458. using namespace pnglibNamespace;
  203459. const int width = image.getWidth();
  203460. const int height = image.getHeight();
  203461. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203462. if (pngWriteStruct == 0)
  203463. return false;
  203464. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203465. if (pngInfoStruct == 0)
  203466. {
  203467. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203468. return false;
  203469. }
  203470. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203471. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203472. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203473. : PNG_COLOR_TYPE_RGB,
  203474. PNG_INTERLACE_NONE,
  203475. PNG_COMPRESSION_TYPE_BASE,
  203476. PNG_FILTER_TYPE_BASE);
  203477. HeapBlock <uint8> rowData (width * 4);
  203478. png_color_8 sig_bit;
  203479. sig_bit.red = 8;
  203480. sig_bit.green = 8;
  203481. sig_bit.blue = 8;
  203482. sig_bit.alpha = 8;
  203483. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203484. png_write_info (pngWriteStruct, pngInfoStruct);
  203485. png_set_shift (pngWriteStruct, &sig_bit);
  203486. png_set_packing (pngWriteStruct);
  203487. const Image::BitmapData srcData (image, false);
  203488. for (int y = 0; y < height; ++y)
  203489. {
  203490. uint8* dst = rowData;
  203491. const uint8* src = srcData.getLinePointer (y);
  203492. if (image.hasAlphaChannel())
  203493. {
  203494. for (int i = width; --i >= 0;)
  203495. {
  203496. PixelARGB p (*(const PixelARGB*) src);
  203497. p.unpremultiply();
  203498. *dst++ = p.getRed();
  203499. *dst++ = p.getGreen();
  203500. *dst++ = p.getBlue();
  203501. *dst++ = p.getAlpha();
  203502. src += srcData.pixelStride;
  203503. }
  203504. }
  203505. else
  203506. {
  203507. for (int i = width; --i >= 0;)
  203508. {
  203509. *dst++ = ((const PixelRGB*) src)->getRed();
  203510. *dst++ = ((const PixelRGB*) src)->getGreen();
  203511. *dst++ = ((const PixelRGB*) src)->getBlue();
  203512. src += srcData.pixelStride;
  203513. }
  203514. }
  203515. png_write_rows (pngWriteStruct, &rowData, 1);
  203516. }
  203517. png_write_end (pngWriteStruct, pngInfoStruct);
  203518. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203519. out.flush();
  203520. return true;
  203521. }
  203522. END_JUCE_NAMESPACE
  203523. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203524. #endif
  203525. //==============================================================================
  203526. #if JUCE_BUILD_NATIVE
  203527. #if JUCE_WINDOWS
  203528. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203529. /*
  203530. This file wraps together all the win32-specific code, so that
  203531. we can include all the native headers just once, and compile all our
  203532. platform-specific stuff in one big lump, keeping it out of the way of
  203533. the rest of the codebase.
  203534. */
  203535. #if JUCE_WINDOWS
  203536. BEGIN_JUCE_NAMESPACE
  203537. #define JUCE_INCLUDED_FILE 1
  203538. // Now include the actual code files..
  203539. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203540. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203541. // compiled on its own).
  203542. #if JUCE_INCLUDED_FILE
  203543. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203544. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203545. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203546. #ifndef DOXYGEN
  203547. // use with DynamicLibraryLoader to simplify importing functions
  203548. //
  203549. // functionName: function to import
  203550. // localFunctionName: name you want to use to actually call it (must be different)
  203551. // returnType: the return type
  203552. // object: the DynamicLibraryLoader to use
  203553. // params: list of params (bracketed)
  203554. //
  203555. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203556. typedef returnType (WINAPI *type##localFunctionName) params; \
  203557. type##localFunctionName localFunctionName \
  203558. = (type##localFunctionName)object.findProcAddress (#functionName);
  203559. // loads and unloads a DLL automatically
  203560. class JUCE_API DynamicLibraryLoader
  203561. {
  203562. public:
  203563. DynamicLibraryLoader (const String& name);
  203564. ~DynamicLibraryLoader();
  203565. void* findProcAddress (const String& functionName);
  203566. private:
  203567. void* libHandle;
  203568. };
  203569. #endif
  203570. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203571. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203572. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203573. {
  203574. libHandle = LoadLibrary (name);
  203575. }
  203576. DynamicLibraryLoader::~DynamicLibraryLoader()
  203577. {
  203578. FreeLibrary ((HMODULE) libHandle);
  203579. }
  203580. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203581. {
  203582. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  203583. }
  203584. #endif
  203585. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203586. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203587. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203588. // compiled on its own).
  203589. #if JUCE_INCLUDED_FILE
  203590. extern void juce_initialiseThreadEvents();
  203591. void Logger::outputDebugString (const String& text)
  203592. {
  203593. OutputDebugString (text + "\n");
  203594. }
  203595. static int64 hiResTicksPerSecond;
  203596. static double hiResTicksScaleFactor;
  203597. #if JUCE_USE_INTRINSICS
  203598. // CPU info functions using intrinsics...
  203599. #pragma intrinsic (__cpuid)
  203600. #pragma intrinsic (__rdtsc)
  203601. const String SystemStats::getCpuVendor()
  203602. {
  203603. int info [4];
  203604. __cpuid (info, 0);
  203605. char v [12];
  203606. memcpy (v, info + 1, 4);
  203607. memcpy (v + 4, info + 3, 4);
  203608. memcpy (v + 8, info + 2, 4);
  203609. return String (v, 12);
  203610. }
  203611. #else
  203612. // CPU info functions using old fashioned inline asm...
  203613. static void juce_getCpuVendor (char* const v)
  203614. {
  203615. int vendor[4];
  203616. zeromem (vendor, 16);
  203617. #ifdef JUCE_64BIT
  203618. #else
  203619. #ifndef __MINGW32__
  203620. __try
  203621. #endif
  203622. {
  203623. #if JUCE_GCC
  203624. unsigned int dummy = 0;
  203625. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203626. #else
  203627. __asm
  203628. {
  203629. mov eax, 0
  203630. cpuid
  203631. mov [vendor], ebx
  203632. mov [vendor + 4], edx
  203633. mov [vendor + 8], ecx
  203634. }
  203635. #endif
  203636. }
  203637. #ifndef __MINGW32__
  203638. __except (EXCEPTION_EXECUTE_HANDLER)
  203639. {
  203640. *v = 0;
  203641. }
  203642. #endif
  203643. #endif
  203644. memcpy (v, vendor, 16);
  203645. }
  203646. const String SystemStats::getCpuVendor()
  203647. {
  203648. char v [16];
  203649. juce_getCpuVendor (v);
  203650. return String (v, 16);
  203651. }
  203652. #endif
  203653. void SystemStats::initialiseStats()
  203654. {
  203655. juce_initialiseThreadEvents();
  203656. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203657. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203658. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203659. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203660. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203661. #else
  203662. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203663. #endif
  203664. {
  203665. SYSTEM_INFO systemInfo;
  203666. GetSystemInfo (&systemInfo);
  203667. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203668. }
  203669. LARGE_INTEGER f;
  203670. QueryPerformanceFrequency (&f);
  203671. hiResTicksPerSecond = f.QuadPart;
  203672. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203673. String s (SystemStats::getJUCEVersion());
  203674. const MMRESULT res = timeBeginPeriod (1);
  203675. (void) res;
  203676. jassert (res == TIMERR_NOERROR);
  203677. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203678. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203679. #endif
  203680. }
  203681. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203682. {
  203683. OSVERSIONINFO info;
  203684. info.dwOSVersionInfoSize = sizeof (info);
  203685. GetVersionEx (&info);
  203686. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203687. {
  203688. switch (info.dwMajorVersion)
  203689. {
  203690. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203691. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203692. default: jassertfalse; break; // !! not a supported OS!
  203693. }
  203694. }
  203695. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203696. {
  203697. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203698. return Win98;
  203699. }
  203700. return UnknownOS;
  203701. }
  203702. const String SystemStats::getOperatingSystemName()
  203703. {
  203704. const char* name = "Unknown OS";
  203705. switch (getOperatingSystemType())
  203706. {
  203707. case Windows7: name = "Windows 7"; break;
  203708. case WinVista: name = "Windows Vista"; break;
  203709. case WinXP: name = "Windows XP"; break;
  203710. case Win2000: name = "Windows 2000"; break;
  203711. case Win98: name = "Windows 98"; break;
  203712. default: jassertfalse; break; // !! new type of OS?
  203713. }
  203714. return name;
  203715. }
  203716. bool SystemStats::isOperatingSystem64Bit()
  203717. {
  203718. #ifdef _WIN64
  203719. return true;
  203720. #else
  203721. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203722. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203723. BOOL isWow64 = FALSE;
  203724. return (fnIsWow64Process != 0)
  203725. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203726. && (isWow64 != FALSE);
  203727. #endif
  203728. }
  203729. int SystemStats::getMemorySizeInMegabytes()
  203730. {
  203731. MEMORYSTATUSEX mem;
  203732. mem.dwLength = sizeof (mem);
  203733. GlobalMemoryStatusEx (&mem);
  203734. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203735. }
  203736. uint32 juce_millisecondsSinceStartup() throw()
  203737. {
  203738. return (uint32) GetTickCount();
  203739. }
  203740. int64 Time::getHighResolutionTicks() throw()
  203741. {
  203742. LARGE_INTEGER ticks;
  203743. QueryPerformanceCounter (&ticks);
  203744. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203745. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203746. // fix for a very obscure PCI hardware bug that can make the counter
  203747. // sometimes jump forwards by a few seconds..
  203748. static int64 hiResTicksOffset = 0;
  203749. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203750. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203751. hiResTicksOffset = newOffset;
  203752. return ticks.QuadPart + hiResTicksOffset;
  203753. }
  203754. double Time::getMillisecondCounterHiRes() throw()
  203755. {
  203756. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203757. }
  203758. int64 Time::getHighResolutionTicksPerSecond() throw()
  203759. {
  203760. return hiResTicksPerSecond;
  203761. }
  203762. static int64 juce_getClockCycleCounter() throw()
  203763. {
  203764. #if JUCE_USE_INTRINSICS
  203765. // MS intrinsics version...
  203766. return __rdtsc();
  203767. #elif JUCE_GCC
  203768. // GNU inline asm version...
  203769. unsigned int hi = 0, lo = 0;
  203770. __asm__ __volatile__ (
  203771. "xor %%eax, %%eax \n\
  203772. xor %%edx, %%edx \n\
  203773. rdtsc \n\
  203774. movl %%eax, %[lo] \n\
  203775. movl %%edx, %[hi]"
  203776. :
  203777. : [hi] "m" (hi),
  203778. [lo] "m" (lo)
  203779. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203780. return (int64) ((((uint64) hi) << 32) | lo);
  203781. #else
  203782. // MSVC inline asm version...
  203783. unsigned int hi = 0, lo = 0;
  203784. __asm
  203785. {
  203786. xor eax, eax
  203787. xor edx, edx
  203788. rdtsc
  203789. mov lo, eax
  203790. mov hi, edx
  203791. }
  203792. return (int64) ((((uint64) hi) << 32) | lo);
  203793. #endif
  203794. }
  203795. int SystemStats::getCpuSpeedInMegaherz()
  203796. {
  203797. const int64 cycles = juce_getClockCycleCounter();
  203798. const uint32 millis = Time::getMillisecondCounter();
  203799. int lastResult = 0;
  203800. for (;;)
  203801. {
  203802. int n = 1000000;
  203803. while (--n > 0) {}
  203804. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203805. const int64 cyclesNow = juce_getClockCycleCounter();
  203806. if (millisElapsed > 80)
  203807. {
  203808. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203809. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203810. return newResult;
  203811. lastResult = newResult;
  203812. }
  203813. }
  203814. }
  203815. bool Time::setSystemTimeToThisTime() const
  203816. {
  203817. SYSTEMTIME st;
  203818. st.wDayOfWeek = 0;
  203819. st.wYear = (WORD) getYear();
  203820. st.wMonth = (WORD) (getMonth() + 1);
  203821. st.wDay = (WORD) getDayOfMonth();
  203822. st.wHour = (WORD) getHours();
  203823. st.wMinute = (WORD) getMinutes();
  203824. st.wSecond = (WORD) getSeconds();
  203825. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203826. // do this twice because of daylight saving conversion problems - the
  203827. // first one sets it up, the second one kicks it in.
  203828. return SetLocalTime (&st) != 0
  203829. && SetLocalTime (&st) != 0;
  203830. }
  203831. int SystemStats::getPageSize()
  203832. {
  203833. SYSTEM_INFO systemInfo;
  203834. GetSystemInfo (&systemInfo);
  203835. return systemInfo.dwPageSize;
  203836. }
  203837. const String SystemStats::getLogonName()
  203838. {
  203839. TCHAR text [256];
  203840. DWORD len = numElementsInArray (text) - 2;
  203841. zerostruct (text);
  203842. GetUserName (text, &len);
  203843. return String (text, len);
  203844. }
  203845. const String SystemStats::getFullUserName()
  203846. {
  203847. return getLogonName();
  203848. }
  203849. #endif
  203850. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203851. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203852. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203853. // compiled on its own).
  203854. #if JUCE_INCLUDED_FILE
  203855. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203856. extern HWND juce_messageWindowHandle;
  203857. #endif
  203858. #if ! JUCE_USE_INTRINSICS
  203859. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203860. // older ones we have to actually call the ops as win32 functions..
  203861. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203862. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203863. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203864. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203865. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203866. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203867. {
  203868. jassertfalse; // This operation isn't available in old MS compiler versions!
  203869. __int64 oldValue = *value;
  203870. if (oldValue == valueToCompare)
  203871. *value = newValue;
  203872. return oldValue;
  203873. }
  203874. #endif
  203875. CriticalSection::CriticalSection() throw()
  203876. {
  203877. // (just to check the MS haven't changed this structure and broken things...)
  203878. #if _MSC_VER >= 1400
  203879. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203880. #else
  203881. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203882. #endif
  203883. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203884. }
  203885. CriticalSection::~CriticalSection() throw()
  203886. {
  203887. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203888. }
  203889. void CriticalSection::enter() const throw()
  203890. {
  203891. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203892. }
  203893. bool CriticalSection::tryEnter() const throw()
  203894. {
  203895. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203896. }
  203897. void CriticalSection::exit() const throw()
  203898. {
  203899. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203900. }
  203901. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203902. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203903. {
  203904. }
  203905. WaitableEvent::~WaitableEvent() throw()
  203906. {
  203907. CloseHandle (internal);
  203908. }
  203909. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203910. {
  203911. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203912. }
  203913. void WaitableEvent::signal() const throw()
  203914. {
  203915. SetEvent (internal);
  203916. }
  203917. void WaitableEvent::reset() const throw()
  203918. {
  203919. ResetEvent (internal);
  203920. }
  203921. void JUCE_API juce_threadEntryPoint (void*);
  203922. static unsigned int __stdcall threadEntryProc (void* userData)
  203923. {
  203924. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203925. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203926. GetCurrentThreadId(), TRUE);
  203927. #endif
  203928. juce_threadEntryPoint (userData);
  203929. _endthreadex (0);
  203930. return 0;
  203931. }
  203932. void juce_CloseThreadHandle (void* handle)
  203933. {
  203934. CloseHandle ((HANDLE) handle);
  203935. }
  203936. void* juce_createThread (void* userData)
  203937. {
  203938. unsigned int threadId;
  203939. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203940. }
  203941. void juce_killThread (void* handle)
  203942. {
  203943. if (handle != 0)
  203944. {
  203945. #if JUCE_DEBUG
  203946. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203947. #endif
  203948. TerminateThread (handle, 0);
  203949. }
  203950. }
  203951. void juce_setCurrentThreadName (const String& name)
  203952. {
  203953. #if JUCE_DEBUG && JUCE_MSVC
  203954. struct
  203955. {
  203956. DWORD dwType;
  203957. LPCSTR szName;
  203958. DWORD dwThreadID;
  203959. DWORD dwFlags;
  203960. } info;
  203961. info.dwType = 0x1000;
  203962. info.szName = name.toCString();
  203963. info.dwThreadID = GetCurrentThreadId();
  203964. info.dwFlags = 0;
  203965. __try
  203966. {
  203967. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203968. }
  203969. __except (EXCEPTION_CONTINUE_EXECUTION)
  203970. {}
  203971. #else
  203972. (void) name;
  203973. #endif
  203974. }
  203975. Thread::ThreadID Thread::getCurrentThreadId()
  203976. {
  203977. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203978. }
  203979. // priority 1 to 10 where 5=normal, 1=low
  203980. bool juce_setThreadPriority (void* threadHandle, int priority)
  203981. {
  203982. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203983. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203984. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203985. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203986. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203987. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203988. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203989. if (threadHandle == 0)
  203990. threadHandle = GetCurrentThread();
  203991. return SetThreadPriority (threadHandle, pri) != FALSE;
  203992. }
  203993. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203994. {
  203995. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203996. }
  203997. static HANDLE sleepEvent = 0;
  203998. void juce_initialiseThreadEvents()
  203999. {
  204000. if (sleepEvent == 0)
  204001. #if JUCE_DEBUG
  204002. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  204003. #else
  204004. sleepEvent = CreateEvent (0, 0, 0, 0);
  204005. #endif
  204006. }
  204007. void Thread::yield()
  204008. {
  204009. Sleep (0);
  204010. }
  204011. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  204012. {
  204013. if (millisecs >= 10)
  204014. {
  204015. Sleep (millisecs);
  204016. }
  204017. else
  204018. {
  204019. jassert (sleepEvent != 0);
  204020. // unlike Sleep() this is guaranteed to return to the current thread after
  204021. // the time expires, so we'll use this for short waits, which are more likely
  204022. // to need to be accurate
  204023. WaitForSingleObject (sleepEvent, millisecs);
  204024. }
  204025. }
  204026. static int lastProcessPriority = -1;
  204027. // called by WindowDriver because Windows does wierd things to process priority
  204028. // when you swap apps, and this forces an update when the app is brought to the front.
  204029. void juce_repeatLastProcessPriority()
  204030. {
  204031. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204032. {
  204033. DWORD p;
  204034. switch (lastProcessPriority)
  204035. {
  204036. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  204037. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  204038. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  204039. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  204040. default: jassertfalse; return; // bad priority value
  204041. }
  204042. SetPriorityClass (GetCurrentProcess(), p);
  204043. }
  204044. }
  204045. void Process::setPriority (ProcessPriority prior)
  204046. {
  204047. if (lastProcessPriority != (int) prior)
  204048. {
  204049. lastProcessPriority = (int) prior;
  204050. juce_repeatLastProcessPriority();
  204051. }
  204052. }
  204053. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  204054. {
  204055. return IsDebuggerPresent() != FALSE;
  204056. }
  204057. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204058. {
  204059. return juce_isRunningUnderDebugger();
  204060. }
  204061. void Process::raisePrivilege()
  204062. {
  204063. jassertfalse; // xxx not implemented
  204064. }
  204065. void Process::lowerPrivilege()
  204066. {
  204067. jassertfalse; // xxx not implemented
  204068. }
  204069. void Process::terminate()
  204070. {
  204071. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204072. _CrtDumpMemoryLeaks();
  204073. #endif
  204074. // bullet in the head in case there's a problem shutting down..
  204075. ExitProcess (0);
  204076. }
  204077. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204078. {
  204079. void* result = 0;
  204080. JUCE_TRY
  204081. {
  204082. result = LoadLibrary (name);
  204083. }
  204084. JUCE_CATCH_ALL
  204085. return result;
  204086. }
  204087. void PlatformUtilities::freeDynamicLibrary (void* h)
  204088. {
  204089. JUCE_TRY
  204090. {
  204091. if (h != 0)
  204092. FreeLibrary ((HMODULE) h);
  204093. }
  204094. JUCE_CATCH_ALL
  204095. }
  204096. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204097. {
  204098. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  204099. }
  204100. class InterProcessLock::Pimpl
  204101. {
  204102. public:
  204103. Pimpl (const String& name, const int timeOutMillisecs)
  204104. : handle (0), refCount (1)
  204105. {
  204106. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204107. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204108. {
  204109. if (timeOutMillisecs == 0)
  204110. {
  204111. close();
  204112. return;
  204113. }
  204114. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204115. {
  204116. case WAIT_OBJECT_0:
  204117. case WAIT_ABANDONED:
  204118. break;
  204119. case WAIT_TIMEOUT:
  204120. default:
  204121. close();
  204122. break;
  204123. }
  204124. }
  204125. }
  204126. ~Pimpl()
  204127. {
  204128. close();
  204129. }
  204130. void close()
  204131. {
  204132. if (handle != 0)
  204133. {
  204134. ReleaseMutex (handle);
  204135. CloseHandle (handle);
  204136. handle = 0;
  204137. }
  204138. }
  204139. HANDLE handle;
  204140. int refCount;
  204141. };
  204142. InterProcessLock::InterProcessLock (const String& name_)
  204143. : name (name_)
  204144. {
  204145. }
  204146. InterProcessLock::~InterProcessLock()
  204147. {
  204148. }
  204149. bool InterProcessLock::enter (const int timeOutMillisecs)
  204150. {
  204151. const ScopedLock sl (lock);
  204152. if (pimpl == 0)
  204153. {
  204154. pimpl = new Pimpl (name, timeOutMillisecs);
  204155. if (pimpl->handle == 0)
  204156. pimpl = 0;
  204157. }
  204158. else
  204159. {
  204160. pimpl->refCount++;
  204161. }
  204162. return pimpl != 0;
  204163. }
  204164. void InterProcessLock::exit()
  204165. {
  204166. const ScopedLock sl (lock);
  204167. // Trying to release the lock too many times!
  204168. jassert (pimpl != 0);
  204169. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204170. pimpl = 0;
  204171. }
  204172. #endif
  204173. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204174. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204175. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204176. // compiled on its own).
  204177. #if JUCE_INCLUDED_FILE
  204178. #ifndef CSIDL_MYMUSIC
  204179. #define CSIDL_MYMUSIC 0x000d
  204180. #endif
  204181. #ifndef CSIDL_MYVIDEO
  204182. #define CSIDL_MYVIDEO 0x000e
  204183. #endif
  204184. #ifndef INVALID_FILE_ATTRIBUTES
  204185. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204186. #endif
  204187. const juce_wchar File::separator = '\\';
  204188. const String File::separatorString ("\\");
  204189. bool File::exists() const
  204190. {
  204191. return fullPath.isNotEmpty()
  204192. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204193. }
  204194. bool File::existsAsFile() const
  204195. {
  204196. return fullPath.isNotEmpty()
  204197. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204198. }
  204199. bool File::isDirectory() const
  204200. {
  204201. const DWORD attr = GetFileAttributes (fullPath);
  204202. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204203. }
  204204. bool File::hasWriteAccess() const
  204205. {
  204206. if (exists())
  204207. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204208. // on windows, it seems that even read-only directories can still be written into,
  204209. // so checking the parent directory's permissions would return the wrong result..
  204210. return true;
  204211. }
  204212. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204213. {
  204214. DWORD attr = GetFileAttributes (fullPath);
  204215. if (attr == INVALID_FILE_ATTRIBUTES)
  204216. return false;
  204217. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204218. return true;
  204219. if (shouldBeReadOnly)
  204220. attr |= FILE_ATTRIBUTE_READONLY;
  204221. else
  204222. attr &= ~FILE_ATTRIBUTE_READONLY;
  204223. return SetFileAttributes (fullPath, attr) != FALSE;
  204224. }
  204225. bool File::isHidden() const
  204226. {
  204227. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204228. }
  204229. bool File::deleteFile() const
  204230. {
  204231. if (! exists())
  204232. return true;
  204233. else if (isDirectory())
  204234. return RemoveDirectory (fullPath) != 0;
  204235. else
  204236. return DeleteFile (fullPath) != 0;
  204237. }
  204238. bool File::moveToTrash() const
  204239. {
  204240. if (! exists())
  204241. return true;
  204242. SHFILEOPSTRUCT fos;
  204243. zerostruct (fos);
  204244. // The string we pass in must be double null terminated..
  204245. String doubleNullTermPath (getFullPathName() + " ");
  204246. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204247. p [getFullPathName().length()] = 0;
  204248. fos.wFunc = FO_DELETE;
  204249. fos.pFrom = p;
  204250. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204251. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204252. return SHFileOperation (&fos) == 0;
  204253. }
  204254. bool File::copyInternal (const File& dest) const
  204255. {
  204256. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204257. }
  204258. bool File::moveInternal (const File& dest) const
  204259. {
  204260. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204261. }
  204262. void File::createDirectoryInternal (const String& fileName) const
  204263. {
  204264. CreateDirectory (fileName, 0);
  204265. }
  204266. int64 juce_fileSetPosition (void* handle, int64 pos)
  204267. {
  204268. LARGE_INTEGER li;
  204269. li.QuadPart = pos;
  204270. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204271. return li.QuadPart;
  204272. }
  204273. void FileInputStream::openHandle()
  204274. {
  204275. totalSize = file.getSize();
  204276. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204277. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204278. if (h != INVALID_HANDLE_VALUE)
  204279. fileHandle = (void*) h;
  204280. }
  204281. void FileInputStream::closeHandle()
  204282. {
  204283. CloseHandle ((HANDLE) fileHandle);
  204284. }
  204285. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204286. {
  204287. if (fileHandle != 0)
  204288. {
  204289. DWORD actualNum = 0;
  204290. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204291. return (size_t) actualNum;
  204292. }
  204293. return 0;
  204294. }
  204295. void FileOutputStream::openHandle()
  204296. {
  204297. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204298. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204299. if (h != INVALID_HANDLE_VALUE)
  204300. {
  204301. LARGE_INTEGER li;
  204302. li.QuadPart = 0;
  204303. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204304. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204305. {
  204306. fileHandle = (void*) h;
  204307. currentPosition = li.QuadPart;
  204308. }
  204309. }
  204310. }
  204311. void FileOutputStream::closeHandle()
  204312. {
  204313. CloseHandle ((HANDLE) fileHandle);
  204314. }
  204315. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204316. {
  204317. if (fileHandle != 0)
  204318. {
  204319. DWORD actualNum = 0;
  204320. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204321. return (int) actualNum;
  204322. }
  204323. return 0;
  204324. }
  204325. void FileOutputStream::flushInternal()
  204326. {
  204327. if (fileHandle != 0)
  204328. FlushFileBuffers ((HANDLE) fileHandle);
  204329. }
  204330. int64 File::getSize() const
  204331. {
  204332. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204333. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204334. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204335. return 0;
  204336. }
  204337. static int64 fileTimeToTime (const FILETIME* const ft)
  204338. {
  204339. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204340. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204341. }
  204342. static void timeToFileTime (const int64 time, FILETIME* const ft)
  204343. {
  204344. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204345. }
  204346. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204347. {
  204348. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204349. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204350. {
  204351. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204352. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204353. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204354. }
  204355. else
  204356. {
  204357. creationTime = accessTime = modificationTime = 0;
  204358. }
  204359. }
  204360. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204361. {
  204362. bool ok = false;
  204363. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204364. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204365. if (h != INVALID_HANDLE_VALUE)
  204366. {
  204367. FILETIME m, a, c;
  204368. timeToFileTime (modificationTime, &m);
  204369. timeToFileTime (accessTime, &a);
  204370. timeToFileTime (creationTime, &c);
  204371. ok = SetFileTime (h,
  204372. creationTime > 0 ? &c : 0,
  204373. accessTime > 0 ? &a : 0,
  204374. modificationTime > 0 ? &m : 0) != 0;
  204375. CloseHandle (h);
  204376. }
  204377. return ok;
  204378. }
  204379. void File::findFileSystemRoots (Array<File>& destArray)
  204380. {
  204381. TCHAR buffer [2048];
  204382. buffer[0] = 0;
  204383. buffer[1] = 0;
  204384. GetLogicalDriveStrings (2048, buffer);
  204385. const TCHAR* n = buffer;
  204386. StringArray roots;
  204387. while (*n != 0)
  204388. {
  204389. roots.add (String (n));
  204390. while (*n++ != 0)
  204391. {}
  204392. }
  204393. roots.sort (true);
  204394. for (int i = 0; i < roots.size(); ++i)
  204395. destArray.add (roots [i]);
  204396. }
  204397. static const String getDriveFromPath (const String& path)
  204398. {
  204399. if (path.isNotEmpty() && path[1] == ':')
  204400. return path.substring (0, 2) + '\\';
  204401. return path;
  204402. }
  204403. const String File::getVolumeLabel() const
  204404. {
  204405. TCHAR dest[64];
  204406. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204407. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204408. dest[0] = 0;
  204409. return dest;
  204410. }
  204411. int File::getVolumeSerialNumber() const
  204412. {
  204413. TCHAR dest[64];
  204414. DWORD serialNum;
  204415. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204416. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204417. return 0;
  204418. return (int) serialNum;
  204419. }
  204420. static int64 getDiskSpaceInfo (const String& path, const bool total)
  204421. {
  204422. ULARGE_INTEGER spc, tot, totFree;
  204423. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204424. return total ? (int64) tot.QuadPart
  204425. : (int64) spc.QuadPart;
  204426. return 0;
  204427. }
  204428. int64 File::getBytesFreeOnVolume() const
  204429. {
  204430. return getDiskSpaceInfo (getFullPathName(), false);
  204431. }
  204432. int64 File::getVolumeTotalSize() const
  204433. {
  204434. return getDiskSpaceInfo (getFullPathName(), true);
  204435. }
  204436. static unsigned int getWindowsDriveType (const String& path)
  204437. {
  204438. return GetDriveType (getDriveFromPath (path));
  204439. }
  204440. bool File::isOnCDRomDrive() const
  204441. {
  204442. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204443. }
  204444. bool File::isOnHardDisk() const
  204445. {
  204446. if (fullPath.isEmpty())
  204447. return false;
  204448. const unsigned int n = getWindowsDriveType (getFullPathName());
  204449. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204450. return n != DRIVE_REMOVABLE;
  204451. else
  204452. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204453. }
  204454. bool File::isOnRemovableDrive() const
  204455. {
  204456. if (fullPath.isEmpty())
  204457. return false;
  204458. const unsigned int n = getWindowsDriveType (getFullPathName());
  204459. return n == DRIVE_CDROM
  204460. || n == DRIVE_REMOTE
  204461. || n == DRIVE_REMOVABLE
  204462. || n == DRIVE_RAMDISK;
  204463. }
  204464. static const File juce_getSpecialFolderPath (int type)
  204465. {
  204466. WCHAR path [MAX_PATH + 256];
  204467. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204468. return File (String (path));
  204469. return File::nonexistent;
  204470. }
  204471. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204472. {
  204473. int csidlType = 0;
  204474. switch (type)
  204475. {
  204476. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204477. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204478. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204479. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204480. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204481. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204482. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204483. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204484. case tempDirectory:
  204485. {
  204486. WCHAR dest [2048];
  204487. dest[0] = 0;
  204488. GetTempPath (numElementsInArray (dest), dest);
  204489. return File (String (dest));
  204490. }
  204491. case invokedExecutableFile:
  204492. case currentExecutableFile:
  204493. case currentApplicationFile:
  204494. {
  204495. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204496. WCHAR dest [MAX_PATH + 256];
  204497. dest[0] = 0;
  204498. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204499. return File (String (dest));
  204500. }
  204501. case hostApplicationPath:
  204502. {
  204503. WCHAR dest [MAX_PATH + 256];
  204504. dest[0] = 0;
  204505. GetModuleFileName (0, dest, numElementsInArray (dest));
  204506. return File (String (dest));
  204507. }
  204508. default:
  204509. jassertfalse; // unknown type?
  204510. return File::nonexistent;
  204511. }
  204512. return juce_getSpecialFolderPath (csidlType);
  204513. }
  204514. const File File::getCurrentWorkingDirectory()
  204515. {
  204516. WCHAR dest [MAX_PATH + 256];
  204517. dest[0] = 0;
  204518. GetCurrentDirectory (numElementsInArray (dest), dest);
  204519. return File (String (dest));
  204520. }
  204521. bool File::setAsCurrentWorkingDirectory() const
  204522. {
  204523. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204524. }
  204525. const String File::getVersion() const
  204526. {
  204527. String result;
  204528. DWORD handle = 0;
  204529. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204530. HeapBlock<char> buffer;
  204531. buffer.calloc (bufferSize);
  204532. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204533. {
  204534. VS_FIXEDFILEINFO* vffi;
  204535. UINT len = 0;
  204536. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204537. {
  204538. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204539. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204540. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204541. << (int) LOWORD (vffi->dwFileVersionLS);
  204542. }
  204543. }
  204544. return result;
  204545. }
  204546. const File File::getLinkedTarget() const
  204547. {
  204548. File result (*this);
  204549. String p (getFullPathName());
  204550. if (! exists())
  204551. p += ".lnk";
  204552. else if (getFileExtension() != ".lnk")
  204553. return result;
  204554. ComSmartPtr <IShellLink> shellLink;
  204555. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204556. {
  204557. ComSmartPtr <IPersistFile> persistFile;
  204558. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  204559. {
  204560. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204561. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204562. {
  204563. WIN32_FIND_DATA winFindData;
  204564. WCHAR resolvedPath [MAX_PATH];
  204565. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204566. result = File (resolvedPath);
  204567. }
  204568. }
  204569. }
  204570. return result;
  204571. }
  204572. class DirectoryIterator::NativeIterator::Pimpl
  204573. {
  204574. public:
  204575. Pimpl (const File& directory, const String& wildCard)
  204576. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204577. handle (INVALID_HANDLE_VALUE)
  204578. {
  204579. }
  204580. ~Pimpl()
  204581. {
  204582. if (handle != INVALID_HANDLE_VALUE)
  204583. FindClose (handle);
  204584. }
  204585. bool next (String& filenameFound,
  204586. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204587. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204588. {
  204589. WIN32_FIND_DATA findData;
  204590. if (handle == INVALID_HANDLE_VALUE)
  204591. {
  204592. handle = FindFirstFile (directoryWithWildCard, &findData);
  204593. if (handle == INVALID_HANDLE_VALUE)
  204594. return false;
  204595. }
  204596. else
  204597. {
  204598. if (FindNextFile (handle, &findData) == 0)
  204599. return false;
  204600. }
  204601. filenameFound = findData.cFileName;
  204602. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204603. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204604. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204605. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204606. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204607. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204608. return true;
  204609. }
  204610. juce_UseDebuggingNewOperator
  204611. private:
  204612. const String directoryWithWildCard;
  204613. HANDLE handle;
  204614. Pimpl (const Pimpl&);
  204615. Pimpl& operator= (const Pimpl&);
  204616. };
  204617. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204618. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204619. {
  204620. }
  204621. DirectoryIterator::NativeIterator::~NativeIterator()
  204622. {
  204623. }
  204624. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204625. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204626. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204627. {
  204628. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204629. }
  204630. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204631. {
  204632. HINSTANCE hInstance = 0;
  204633. JUCE_TRY
  204634. {
  204635. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204636. }
  204637. JUCE_CATCH_ALL
  204638. return hInstance > (HINSTANCE) 32;
  204639. }
  204640. void File::revealToUser() const
  204641. {
  204642. if (isDirectory())
  204643. startAsProcess();
  204644. else if (getParentDirectory().exists())
  204645. getParentDirectory().startAsProcess();
  204646. }
  204647. class NamedPipeInternal
  204648. {
  204649. public:
  204650. NamedPipeInternal (const String& file, const bool isPipe_)
  204651. : pipeH (0),
  204652. cancelEvent (0),
  204653. connected (false),
  204654. isPipe (isPipe_)
  204655. {
  204656. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204657. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204658. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204659. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204660. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204661. }
  204662. ~NamedPipeInternal()
  204663. {
  204664. disconnectPipe();
  204665. if (pipeH != 0)
  204666. CloseHandle (pipeH);
  204667. CloseHandle (cancelEvent);
  204668. }
  204669. bool connect (const int timeOutMs)
  204670. {
  204671. if (! isPipe)
  204672. return true;
  204673. if (! connected)
  204674. {
  204675. OVERLAPPED over;
  204676. zerostruct (over);
  204677. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204678. if (ConnectNamedPipe (pipeH, &over))
  204679. {
  204680. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204681. }
  204682. else
  204683. {
  204684. const int err = GetLastError();
  204685. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204686. {
  204687. HANDLE handles[] = { over.hEvent, cancelEvent };
  204688. if (WaitForMultipleObjects (2, handles, FALSE,
  204689. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204690. connected = true;
  204691. }
  204692. else if (err == ERROR_PIPE_CONNECTED)
  204693. {
  204694. connected = true;
  204695. }
  204696. }
  204697. CloseHandle (over.hEvent);
  204698. }
  204699. return connected;
  204700. }
  204701. void disconnectPipe()
  204702. {
  204703. if (connected)
  204704. {
  204705. DisconnectNamedPipe (pipeH);
  204706. connected = false;
  204707. }
  204708. }
  204709. HANDLE pipeH;
  204710. HANDLE cancelEvent;
  204711. bool connected, isPipe;
  204712. };
  204713. void NamedPipe::close()
  204714. {
  204715. cancelPendingReads();
  204716. const ScopedLock sl (lock);
  204717. delete static_cast<NamedPipeInternal*> (internal);
  204718. internal = 0;
  204719. }
  204720. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204721. {
  204722. close();
  204723. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204724. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204725. {
  204726. internal = intern.release();
  204727. return true;
  204728. }
  204729. return false;
  204730. }
  204731. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204732. {
  204733. const ScopedLock sl (lock);
  204734. int bytesRead = -1;
  204735. bool waitAgain = true;
  204736. while (waitAgain && internal != 0)
  204737. {
  204738. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204739. waitAgain = false;
  204740. if (! intern->connect (timeOutMilliseconds))
  204741. break;
  204742. if (maxBytesToRead <= 0)
  204743. return 0;
  204744. OVERLAPPED over;
  204745. zerostruct (over);
  204746. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204747. unsigned long numRead;
  204748. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204749. {
  204750. bytesRead = (int) numRead;
  204751. }
  204752. else if (GetLastError() == ERROR_IO_PENDING)
  204753. {
  204754. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204755. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204756. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204757. : INFINITE);
  204758. if (waitResult != WAIT_OBJECT_0)
  204759. {
  204760. // if the operation timed out, let's cancel it...
  204761. CancelIo (intern->pipeH);
  204762. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204763. }
  204764. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204765. {
  204766. bytesRead = (int) numRead;
  204767. }
  204768. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204769. {
  204770. intern->disconnectPipe();
  204771. waitAgain = true;
  204772. }
  204773. }
  204774. else
  204775. {
  204776. waitAgain = internal != 0;
  204777. Sleep (5);
  204778. }
  204779. CloseHandle (over.hEvent);
  204780. }
  204781. return bytesRead;
  204782. }
  204783. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204784. {
  204785. int bytesWritten = -1;
  204786. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204787. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204788. {
  204789. if (numBytesToWrite <= 0)
  204790. return 0;
  204791. OVERLAPPED over;
  204792. zerostruct (over);
  204793. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204794. unsigned long numWritten;
  204795. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204796. {
  204797. bytesWritten = (int) numWritten;
  204798. }
  204799. else if (GetLastError() == ERROR_IO_PENDING)
  204800. {
  204801. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204802. DWORD waitResult;
  204803. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204804. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204805. : INFINITE);
  204806. if (waitResult != WAIT_OBJECT_0)
  204807. {
  204808. CancelIo (intern->pipeH);
  204809. WaitForSingleObject (over.hEvent, INFINITE);
  204810. }
  204811. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204812. {
  204813. bytesWritten = (int) numWritten;
  204814. }
  204815. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204816. {
  204817. intern->disconnectPipe();
  204818. }
  204819. }
  204820. CloseHandle (over.hEvent);
  204821. }
  204822. return bytesWritten;
  204823. }
  204824. void NamedPipe::cancelPendingReads()
  204825. {
  204826. if (internal != 0)
  204827. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204828. }
  204829. #endif
  204830. /*** End of inlined file: juce_win32_Files.cpp ***/
  204831. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204832. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204833. // compiled on its own).
  204834. #if JUCE_INCLUDED_FILE
  204835. #ifndef INTERNET_FLAG_NEED_FILE
  204836. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204837. #endif
  204838. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204839. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204840. #endif
  204841. struct ConnectionAndRequestStruct
  204842. {
  204843. HINTERNET connection, request;
  204844. };
  204845. static HINTERNET sessionHandle = 0;
  204846. #ifndef WORKAROUND_TIMEOUT_BUG
  204847. //#define WORKAROUND_TIMEOUT_BUG 1
  204848. #endif
  204849. #if WORKAROUND_TIMEOUT_BUG
  204850. // Required because of a Microsoft bug in setting a timeout
  204851. class InternetConnectThread : public Thread
  204852. {
  204853. public:
  204854. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204855. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204856. {
  204857. startThread();
  204858. }
  204859. ~InternetConnectThread()
  204860. {
  204861. stopThread (60000);
  204862. }
  204863. void run()
  204864. {
  204865. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204866. uc.nPort, _T(""), _T(""),
  204867. isFtp ? INTERNET_SERVICE_FTP
  204868. : INTERNET_SERVICE_HTTP,
  204869. 0, 0);
  204870. notify();
  204871. }
  204872. juce_UseDebuggingNewOperator
  204873. private:
  204874. URL_COMPONENTS& uc;
  204875. HINTERNET& connection;
  204876. const bool isFtp;
  204877. InternetConnectThread (const InternetConnectThread&);
  204878. InternetConnectThread& operator= (const InternetConnectThread&);
  204879. };
  204880. #endif
  204881. void* juce_openInternetFile (const String& url,
  204882. const String& headers,
  204883. const MemoryBlock& postData,
  204884. const bool isPost,
  204885. URL::OpenStreamProgressCallback* callback,
  204886. void* callbackContext,
  204887. int timeOutMs)
  204888. {
  204889. if (sessionHandle == 0)
  204890. sessionHandle = InternetOpen (_T("juce"),
  204891. INTERNET_OPEN_TYPE_PRECONFIG,
  204892. 0, 0, 0);
  204893. if (sessionHandle != 0)
  204894. {
  204895. // break up the url..
  204896. TCHAR file[1024], server[1024];
  204897. URL_COMPONENTS uc;
  204898. zerostruct (uc);
  204899. uc.dwStructSize = sizeof (uc);
  204900. uc.dwUrlPathLength = sizeof (file);
  204901. uc.dwHostNameLength = sizeof (server);
  204902. uc.lpszUrlPath = file;
  204903. uc.lpszHostName = server;
  204904. if (InternetCrackUrl (url, 0, 0, &uc))
  204905. {
  204906. int disable = 1;
  204907. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204908. if (timeOutMs == 0)
  204909. timeOutMs = 30000;
  204910. else if (timeOutMs < 0)
  204911. timeOutMs = -1;
  204912. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204913. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204914. #if WORKAROUND_TIMEOUT_BUG
  204915. HINTERNET connection = 0;
  204916. {
  204917. InternetConnectThread connectThread (uc, connection, isFtp);
  204918. connectThread.wait (timeOutMs);
  204919. if (connection == 0)
  204920. {
  204921. InternetCloseHandle (sessionHandle);
  204922. sessionHandle = 0;
  204923. }
  204924. }
  204925. #else
  204926. HINTERNET connection = InternetConnect (sessionHandle,
  204927. uc.lpszHostName,
  204928. uc.nPort,
  204929. _T(""), _T(""),
  204930. isFtp ? INTERNET_SERVICE_FTP
  204931. : INTERNET_SERVICE_HTTP,
  204932. 0, 0);
  204933. #endif
  204934. if (connection != 0)
  204935. {
  204936. if (isFtp)
  204937. {
  204938. HINTERNET request = FtpOpenFile (connection,
  204939. uc.lpszUrlPath,
  204940. GENERIC_READ,
  204941. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204942. 0);
  204943. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204944. result->connection = connection;
  204945. result->request = request;
  204946. return result;
  204947. }
  204948. else
  204949. {
  204950. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204951. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204952. if (url.startsWithIgnoreCase ("https:"))
  204953. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204954. // IE7 seems to automatically work out when it's https)
  204955. HINTERNET request = HttpOpenRequest (connection,
  204956. isPost ? _T("POST")
  204957. : _T("GET"),
  204958. uc.lpszUrlPath,
  204959. 0, 0, mimeTypes, flags, 0);
  204960. if (request != 0)
  204961. {
  204962. INTERNET_BUFFERS buffers;
  204963. zerostruct (buffers);
  204964. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204965. buffers.lpcszHeader = (LPCTSTR) headers;
  204966. buffers.dwHeadersLength = headers.length();
  204967. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204968. ConnectionAndRequestStruct* result = 0;
  204969. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204970. {
  204971. int bytesSent = 0;
  204972. for (;;)
  204973. {
  204974. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204975. DWORD bytesDone = 0;
  204976. if (bytesToDo > 0
  204977. && ! InternetWriteFile (request,
  204978. static_cast <const char*> (postData.getData()) + bytesSent,
  204979. bytesToDo, &bytesDone))
  204980. {
  204981. break;
  204982. }
  204983. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204984. {
  204985. result = new ConnectionAndRequestStruct();
  204986. result->connection = connection;
  204987. result->request = request;
  204988. if (! HttpEndRequest (request, 0, 0, 0))
  204989. break;
  204990. return result;
  204991. }
  204992. bytesSent += bytesDone;
  204993. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204994. break;
  204995. }
  204996. }
  204997. InternetCloseHandle (request);
  204998. }
  204999. InternetCloseHandle (connection);
  205000. }
  205001. }
  205002. }
  205003. }
  205004. return 0;
  205005. }
  205006. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  205007. {
  205008. DWORD bytesRead = 0;
  205009. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205010. if (crs != 0)
  205011. InternetReadFile (crs->request,
  205012. buffer, bytesToRead,
  205013. &bytesRead);
  205014. return bytesRead;
  205015. }
  205016. int juce_seekInInternetFile (void* handle, int newPosition)
  205017. {
  205018. if (handle != 0)
  205019. {
  205020. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205021. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  205022. }
  205023. return -1;
  205024. }
  205025. int64 juce_getInternetFileContentLength (void* handle)
  205026. {
  205027. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205028. if (crs != 0)
  205029. {
  205030. DWORD index = 0, result = 0, size = sizeof (result);
  205031. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  205032. return (int64) result;
  205033. }
  205034. return -1;
  205035. }
  205036. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  205037. {
  205038. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205039. if (crs != 0)
  205040. {
  205041. DWORD bufferSizeBytes = 4096;
  205042. for (;;)
  205043. {
  205044. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  205045. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  205046. {
  205047. StringArray headersArray;
  205048. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  205049. for (int i = 0; i < headersArray.size(); ++i)
  205050. {
  205051. const String& header = headersArray[i];
  205052. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205053. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205054. const String previousValue (headers [key]);
  205055. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205056. }
  205057. break;
  205058. }
  205059. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205060. break;
  205061. }
  205062. }
  205063. }
  205064. void juce_closeInternetFile (void* handle)
  205065. {
  205066. if (handle != 0)
  205067. {
  205068. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  205069. InternetCloseHandle (crs->request);
  205070. InternetCloseHandle (crs->connection);
  205071. }
  205072. }
  205073. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  205074. {
  205075. int numFound = 0;
  205076. DynamicLibraryLoader dll ("iphlpapi.dll");
  205077. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205078. if (getAdaptersInfo != 0)
  205079. {
  205080. ULONG len = sizeof (IP_ADAPTER_INFO);
  205081. MemoryBlock mb;
  205082. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205083. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205084. {
  205085. mb.setSize (len);
  205086. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205087. }
  205088. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205089. {
  205090. PIP_ADAPTER_INFO adapter = adapterInfo;
  205091. while (adapter != 0)
  205092. {
  205093. int64 mac = 0;
  205094. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  205095. mac = (mac << 8) | adapter->Address[i];
  205096. if (littleEndian)
  205097. mac = (int64) ByteOrder::swap ((uint64) mac);
  205098. if (numFound < maxNum && mac != 0)
  205099. addresses [numFound++] = mac;
  205100. adapter = adapter->Next;
  205101. }
  205102. }
  205103. }
  205104. return numFound;
  205105. }
  205106. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  205107. {
  205108. int numFound = 0;
  205109. DynamicLibraryLoader dll ("netapi32.dll");
  205110. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205111. if (NetbiosCall != 0)
  205112. {
  205113. NCB ncb;
  205114. zerostruct (ncb);
  205115. struct ASTAT
  205116. {
  205117. ADAPTER_STATUS adapt;
  205118. NAME_BUFFER NameBuff [30];
  205119. };
  205120. ASTAT astat;
  205121. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205122. LANA_ENUM enums;
  205123. zerostruct (enums);
  205124. ncb.ncb_command = NCBENUM;
  205125. ncb.ncb_buffer = (unsigned char*) &enums;
  205126. ncb.ncb_length = sizeof (LANA_ENUM);
  205127. NetbiosCall (&ncb);
  205128. for (int i = 0; i < enums.length; ++i)
  205129. {
  205130. zerostruct (ncb);
  205131. ncb.ncb_command = NCBRESET;
  205132. ncb.ncb_lana_num = enums.lana[i];
  205133. if (NetbiosCall (&ncb) == 0)
  205134. {
  205135. zerostruct (ncb);
  205136. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205137. ncb.ncb_command = NCBASTAT;
  205138. ncb.ncb_lana_num = enums.lana[i];
  205139. ncb.ncb_buffer = (unsigned char*) &astat;
  205140. ncb.ncb_length = sizeof (ASTAT);
  205141. if (NetbiosCall (&ncb) == 0)
  205142. {
  205143. if (astat.adapt.adapter_type == 0xfe)
  205144. {
  205145. uint64 mac = 0;
  205146. for (int i = 6; --i >= 0;)
  205147. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  205148. if (numFound < maxNum && mac != 0)
  205149. addresses [numFound++] = mac;
  205150. }
  205151. }
  205152. }
  205153. }
  205154. }
  205155. return numFound;
  205156. }
  205157. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  205158. {
  205159. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  205160. if (numFound == 0)
  205161. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  205162. return numFound;
  205163. }
  205164. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205165. const String& emailSubject,
  205166. const String& bodyText,
  205167. const StringArray& filesToAttach)
  205168. {
  205169. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205170. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205171. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205172. bool ok = false;
  205173. if (mapiSendMail != 0)
  205174. {
  205175. MapiMessage message;
  205176. zerostruct (message);
  205177. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205178. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205179. MapiRecipDesc recip;
  205180. zerostruct (recip);
  205181. recip.ulRecipClass = MAPI_TO;
  205182. String targetEmailAddress_ (targetEmailAddress);
  205183. if (targetEmailAddress_.isEmpty())
  205184. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205185. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205186. message.nRecipCount = 1;
  205187. message.lpRecips = &recip;
  205188. HeapBlock <MapiFileDesc> files;
  205189. files.calloc (filesToAttach.size());
  205190. message.nFileCount = filesToAttach.size();
  205191. message.lpFiles = files;
  205192. for (int i = 0; i < filesToAttach.size(); ++i)
  205193. {
  205194. files[i].nPosition = (ULONG) -1;
  205195. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205196. }
  205197. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205198. }
  205199. FreeLibrary (h);
  205200. return ok;
  205201. }
  205202. #endif
  205203. /*** End of inlined file: juce_win32_Network.cpp ***/
  205204. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205205. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205206. // compiled on its own).
  205207. #if JUCE_INCLUDED_FILE
  205208. static HKEY findKeyForPath (String name,
  205209. const bool createForWriting,
  205210. String& valueName)
  205211. {
  205212. HKEY rootKey = 0;
  205213. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205214. rootKey = HKEY_CURRENT_USER;
  205215. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205216. rootKey = HKEY_LOCAL_MACHINE;
  205217. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205218. rootKey = HKEY_CLASSES_ROOT;
  205219. if (rootKey != 0)
  205220. {
  205221. name = name.substring (name.indexOfChar ('\\') + 1);
  205222. const int lastSlash = name.lastIndexOfChar ('\\');
  205223. valueName = name.substring (lastSlash + 1);
  205224. name = name.substring (0, lastSlash);
  205225. HKEY key;
  205226. DWORD result;
  205227. if (createForWriting)
  205228. {
  205229. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205230. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205231. return key;
  205232. }
  205233. else
  205234. {
  205235. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205236. return key;
  205237. }
  205238. }
  205239. return 0;
  205240. }
  205241. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205242. const String& defaultValue)
  205243. {
  205244. String valueName, result (defaultValue);
  205245. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205246. if (k != 0)
  205247. {
  205248. WCHAR buffer [2048];
  205249. unsigned long bufferSize = sizeof (buffer);
  205250. DWORD type = REG_SZ;
  205251. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205252. {
  205253. if (type == REG_SZ)
  205254. result = buffer;
  205255. else if (type == REG_DWORD)
  205256. result = String ((int) *(DWORD*) buffer);
  205257. }
  205258. RegCloseKey (k);
  205259. }
  205260. return result;
  205261. }
  205262. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205263. const String& value)
  205264. {
  205265. String valueName;
  205266. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205267. if (k != 0)
  205268. {
  205269. RegSetValueEx (k, valueName, 0, REG_SZ,
  205270. (const BYTE*) (const WCHAR*) value,
  205271. sizeof (WCHAR) * (value.length() + 1));
  205272. RegCloseKey (k);
  205273. }
  205274. }
  205275. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205276. {
  205277. bool exists = false;
  205278. String valueName;
  205279. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205280. if (k != 0)
  205281. {
  205282. unsigned char buffer [2048];
  205283. unsigned long bufferSize = sizeof (buffer);
  205284. DWORD type = 0;
  205285. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205286. exists = true;
  205287. RegCloseKey (k);
  205288. }
  205289. return exists;
  205290. }
  205291. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205292. {
  205293. String valueName;
  205294. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205295. if (k != 0)
  205296. {
  205297. RegDeleteValue (k, valueName);
  205298. RegCloseKey (k);
  205299. }
  205300. }
  205301. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205302. {
  205303. String valueName;
  205304. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205305. if (k != 0)
  205306. {
  205307. RegDeleteKey (k, valueName);
  205308. RegCloseKey (k);
  205309. }
  205310. }
  205311. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205312. const String& symbolicDescription,
  205313. const String& fullDescription,
  205314. const File& targetExecutable,
  205315. int iconResourceNumber)
  205316. {
  205317. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205318. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205319. if (iconResourceNumber != 0)
  205320. setRegistryValue (key + "\\DefaultIcon\\",
  205321. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205322. setRegistryValue (key + "\\", fullDescription);
  205323. setRegistryValue (key + "\\shell\\open\\command\\",
  205324. targetExecutable.getFullPathName() + " %1");
  205325. }
  205326. bool juce_IsRunningInWine()
  205327. {
  205328. HKEY key;
  205329. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205330. {
  205331. RegCloseKey (key);
  205332. return true;
  205333. }
  205334. return false;
  205335. }
  205336. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205337. {
  205338. String s (::GetCommandLineW());
  205339. StringArray tokens;
  205340. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205341. return tokens.joinIntoString (" ", 1);
  205342. }
  205343. static void* currentModuleHandle = 0;
  205344. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205345. {
  205346. if (currentModuleHandle == 0)
  205347. currentModuleHandle = GetModuleHandle (0);
  205348. return currentModuleHandle;
  205349. }
  205350. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205351. {
  205352. currentModuleHandle = newHandle;
  205353. }
  205354. void PlatformUtilities::fpuReset()
  205355. {
  205356. #if JUCE_MSVC
  205357. _clearfp();
  205358. #endif
  205359. }
  205360. void PlatformUtilities::beep()
  205361. {
  205362. MessageBeep (MB_OK);
  205363. }
  205364. #endif
  205365. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205366. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205367. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205368. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205369. // compiled on its own).
  205370. #if JUCE_INCLUDED_FILE
  205371. static const unsigned int specialId = WM_APP + 0x4400;
  205372. static const unsigned int broadcastId = WM_APP + 0x4403;
  205373. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205374. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205375. HWND juce_messageWindowHandle = 0;
  205376. extern long improbableWindowNumber; // defined in windowing.cpp
  205377. #ifndef WM_APPCOMMAND
  205378. #define WM_APPCOMMAND 0x0319
  205379. #endif
  205380. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205381. const UINT message,
  205382. const WPARAM wParam,
  205383. const LPARAM lParam) throw()
  205384. {
  205385. JUCE_TRY
  205386. {
  205387. if (h == juce_messageWindowHandle)
  205388. {
  205389. if (message == specialCallbackId)
  205390. {
  205391. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205392. return (LRESULT) (*func) ((void*) lParam);
  205393. }
  205394. else if (message == specialId)
  205395. {
  205396. // these are trapped early in the dispatch call, but must also be checked
  205397. // here in case there are windows modal dialog boxes doing their own
  205398. // dispatch loop and not calling our version
  205399. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205400. return 0;
  205401. }
  205402. else if (message == broadcastId)
  205403. {
  205404. const ScopedPointer <String> messageString ((String*) lParam);
  205405. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205406. return 0;
  205407. }
  205408. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205409. {
  205410. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205411. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205412. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205413. return 0;
  205414. }
  205415. }
  205416. }
  205417. JUCE_CATCH_EXCEPTION
  205418. return DefWindowProc (h, message, wParam, lParam);
  205419. }
  205420. static bool isEventBlockedByModalComps (MSG& m)
  205421. {
  205422. if (Component::getNumCurrentlyModalComponents() == 0
  205423. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205424. return false;
  205425. switch (m.message)
  205426. {
  205427. case WM_MOUSEMOVE:
  205428. case WM_NCMOUSEMOVE:
  205429. case 0x020A: /* WM_MOUSEWHEEL */
  205430. case 0x020E: /* WM_MOUSEHWHEEL */
  205431. case WM_KEYUP:
  205432. case WM_SYSKEYUP:
  205433. case WM_CHAR:
  205434. case WM_APPCOMMAND:
  205435. case WM_LBUTTONUP:
  205436. case WM_MBUTTONUP:
  205437. case WM_RBUTTONUP:
  205438. case WM_MOUSEACTIVATE:
  205439. case WM_NCMOUSEHOVER:
  205440. case WM_MOUSEHOVER:
  205441. return true;
  205442. case WM_NCLBUTTONDOWN:
  205443. case WM_NCLBUTTONDBLCLK:
  205444. case WM_NCRBUTTONDOWN:
  205445. case WM_NCRBUTTONDBLCLK:
  205446. case WM_NCMBUTTONDOWN:
  205447. case WM_NCMBUTTONDBLCLK:
  205448. case WM_LBUTTONDOWN:
  205449. case WM_LBUTTONDBLCLK:
  205450. case WM_MBUTTONDOWN:
  205451. case WM_MBUTTONDBLCLK:
  205452. case WM_RBUTTONDOWN:
  205453. case WM_RBUTTONDBLCLK:
  205454. case WM_KEYDOWN:
  205455. case WM_SYSKEYDOWN:
  205456. {
  205457. Component* const modal = Component::getCurrentlyModalComponent (0);
  205458. if (modal != 0)
  205459. modal->inputAttemptWhenModal();
  205460. return true;
  205461. }
  205462. default:
  205463. break;
  205464. }
  205465. return false;
  205466. }
  205467. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205468. {
  205469. MSG m;
  205470. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205471. return false;
  205472. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205473. {
  205474. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205475. {
  205476. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205477. }
  205478. else if (m.message == WM_QUIT)
  205479. {
  205480. if (JUCEApplication::getInstance() != 0)
  205481. JUCEApplication::getInstance()->systemRequestedQuit();
  205482. }
  205483. else if (! isEventBlockedByModalComps (m))
  205484. {
  205485. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205486. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205487. {
  205488. // if it's someone else's window being clicked on, and the focus is
  205489. // currently on a juce window, pass the kb focus over..
  205490. HWND currentFocus = GetFocus();
  205491. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205492. SetFocus (m.hwnd);
  205493. }
  205494. TranslateMessage (&m);
  205495. DispatchMessage (&m);
  205496. }
  205497. }
  205498. return true;
  205499. }
  205500. bool juce_postMessageToSystemQueue (Message* message)
  205501. {
  205502. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205503. }
  205504. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205505. void* userData)
  205506. {
  205507. if (MessageManager::getInstance()->isThisTheMessageThread())
  205508. {
  205509. return (*callback) (userData);
  205510. }
  205511. else
  205512. {
  205513. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205514. // deadlock because the message manager is blocked from running, and can't
  205515. // call your function..
  205516. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205517. return (void*) SendMessage (juce_messageWindowHandle,
  205518. specialCallbackId,
  205519. (WPARAM) callback,
  205520. (LPARAM) userData);
  205521. }
  205522. }
  205523. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205524. {
  205525. if (hwnd != juce_messageWindowHandle)
  205526. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205527. return TRUE;
  205528. }
  205529. void MessageManager::broadcastMessage (const String& value)
  205530. {
  205531. Array<void*> windows;
  205532. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205533. const String localCopy (value);
  205534. COPYDATASTRUCT data;
  205535. data.dwData = broadcastId;
  205536. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205537. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205538. for (int i = windows.size(); --i >= 0;)
  205539. {
  205540. HWND hwnd = (HWND) windows.getUnchecked(i);
  205541. TCHAR windowName [64]; // no need to read longer strings than this
  205542. GetWindowText (hwnd, windowName, 64);
  205543. windowName [63] = 0;
  205544. if (String (windowName) == messageWindowName)
  205545. {
  205546. DWORD_PTR result;
  205547. SendMessageTimeout (hwnd, WM_COPYDATA,
  205548. (WPARAM) juce_messageWindowHandle,
  205549. (LPARAM) &data,
  205550. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205551. 8000,
  205552. &result);
  205553. }
  205554. }
  205555. }
  205556. static const String getMessageWindowClassName()
  205557. {
  205558. // this name has to be different for each app/dll instance because otherwise
  205559. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205560. // window class).
  205561. static int number = 0;
  205562. if (number == 0)
  205563. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205564. return "JUCEcs_" + String (number);
  205565. }
  205566. void MessageManager::doPlatformSpecificInitialisation()
  205567. {
  205568. OleInitialize (0);
  205569. const String className (getMessageWindowClassName());
  205570. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205571. WNDCLASSEX wc;
  205572. zerostruct (wc);
  205573. wc.cbSize = sizeof (wc);
  205574. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205575. wc.cbWndExtra = 4;
  205576. wc.hInstance = hmod;
  205577. wc.lpszClassName = className;
  205578. RegisterClassEx (&wc);
  205579. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205580. messageWindowName,
  205581. 0, 0, 0, 0, 0, 0, 0,
  205582. hmod, 0);
  205583. }
  205584. void MessageManager::doPlatformSpecificShutdown()
  205585. {
  205586. DestroyWindow (juce_messageWindowHandle);
  205587. UnregisterClass (getMessageWindowClassName(), 0);
  205588. OleUninitialize();
  205589. }
  205590. #endif
  205591. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205592. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205593. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205594. // compiled on its own).
  205595. #if JUCE_INCLUDED_FILE
  205596. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205597. NEWTEXTMETRICEXW*,
  205598. int type,
  205599. LPARAM lParam)
  205600. {
  205601. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205602. {
  205603. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205604. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205605. }
  205606. return 1;
  205607. }
  205608. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205609. NEWTEXTMETRICEXW*,
  205610. int type,
  205611. LPARAM lParam)
  205612. {
  205613. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205614. {
  205615. LOGFONTW lf;
  205616. zerostruct (lf);
  205617. lf.lfWeight = FW_DONTCARE;
  205618. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205619. lf.lfQuality = DEFAULT_QUALITY;
  205620. lf.lfCharSet = DEFAULT_CHARSET;
  205621. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205622. lf.lfPitchAndFamily = FF_DONTCARE;
  205623. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205624. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205625. HDC dc = CreateCompatibleDC (0);
  205626. EnumFontFamiliesEx (dc, &lf,
  205627. (FONTENUMPROCW) &wfontEnum2,
  205628. lParam, 0);
  205629. DeleteDC (dc);
  205630. }
  205631. return 1;
  205632. }
  205633. const StringArray Font::findAllTypefaceNames()
  205634. {
  205635. StringArray results;
  205636. HDC dc = CreateCompatibleDC (0);
  205637. {
  205638. LOGFONTW lf;
  205639. zerostruct (lf);
  205640. lf.lfWeight = FW_DONTCARE;
  205641. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205642. lf.lfQuality = DEFAULT_QUALITY;
  205643. lf.lfCharSet = DEFAULT_CHARSET;
  205644. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205645. lf.lfPitchAndFamily = FF_DONTCARE;
  205646. lf.lfFaceName[0] = 0;
  205647. EnumFontFamiliesEx (dc, &lf,
  205648. (FONTENUMPROCW) &wfontEnum1,
  205649. (LPARAM) &results, 0);
  205650. }
  205651. DeleteDC (dc);
  205652. results.sort (true);
  205653. return results;
  205654. }
  205655. extern bool juce_IsRunningInWine();
  205656. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205657. {
  205658. if (juce_IsRunningInWine())
  205659. {
  205660. // If we're running in Wine, then use fonts that might be available on Linux..
  205661. defaultSans = "Bitstream Vera Sans";
  205662. defaultSerif = "Bitstream Vera Serif";
  205663. defaultFixed = "Bitstream Vera Sans Mono";
  205664. }
  205665. else
  205666. {
  205667. defaultSans = "Verdana";
  205668. defaultSerif = "Times";
  205669. defaultFixed = "Lucida Console";
  205670. }
  205671. }
  205672. class FontDCHolder : private DeletedAtShutdown
  205673. {
  205674. public:
  205675. FontDCHolder()
  205676. : dc (0), numKPs (0), size (0),
  205677. bold (false), italic (false)
  205678. {
  205679. }
  205680. ~FontDCHolder()
  205681. {
  205682. if (dc != 0)
  205683. {
  205684. DeleteDC (dc);
  205685. DeleteObject (fontH);
  205686. }
  205687. clearSingletonInstance();
  205688. }
  205689. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205690. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205691. {
  205692. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205693. {
  205694. fontName = fontName_;
  205695. bold = bold_;
  205696. italic = italic_;
  205697. size = size_;
  205698. if (dc != 0)
  205699. {
  205700. DeleteDC (dc);
  205701. DeleteObject (fontH);
  205702. kps.free();
  205703. }
  205704. fontH = 0;
  205705. dc = CreateCompatibleDC (0);
  205706. SetMapperFlags (dc, 0);
  205707. SetMapMode (dc, MM_TEXT);
  205708. LOGFONTW lfw;
  205709. zerostruct (lfw);
  205710. lfw.lfCharSet = DEFAULT_CHARSET;
  205711. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205712. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205713. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205714. lfw.lfQuality = PROOF_QUALITY;
  205715. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205716. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205717. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205718. lfw.lfHeight = size > 0 ? size : -256;
  205719. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205720. if (standardSizedFont != 0)
  205721. {
  205722. if (SelectObject (dc, standardSizedFont) != 0)
  205723. {
  205724. fontH = standardSizedFont;
  205725. if (size == 0)
  205726. {
  205727. OUTLINETEXTMETRIC otm;
  205728. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205729. {
  205730. lfw.lfHeight = -(int) otm.otmEMSquare;
  205731. fontH = CreateFontIndirect (&lfw);
  205732. SelectObject (dc, fontH);
  205733. DeleteObject (standardSizedFont);
  205734. }
  205735. }
  205736. }
  205737. else
  205738. {
  205739. jassertfalse;
  205740. }
  205741. }
  205742. else
  205743. {
  205744. jassertfalse;
  205745. }
  205746. }
  205747. return dc;
  205748. }
  205749. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205750. {
  205751. if (kps == 0)
  205752. {
  205753. numKPs = GetKerningPairs (dc, 0, 0);
  205754. kps.calloc (numKPs);
  205755. GetKerningPairs (dc, numKPs, kps);
  205756. }
  205757. numKPs_ = numKPs;
  205758. return kps;
  205759. }
  205760. private:
  205761. HFONT fontH;
  205762. HDC dc;
  205763. String fontName;
  205764. HeapBlock <KERNINGPAIR> kps;
  205765. int numKPs, size;
  205766. bool bold, italic;
  205767. FontDCHolder (const FontDCHolder&);
  205768. FontDCHolder& operator= (const FontDCHolder&);
  205769. };
  205770. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205771. class WindowsTypeface : public CustomTypeface
  205772. {
  205773. public:
  205774. WindowsTypeface (const Font& font)
  205775. {
  205776. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205777. font.isBold(), font.isItalic(), 0);
  205778. TEXTMETRIC tm;
  205779. tm.tmAscent = tm.tmHeight = 1;
  205780. tm.tmDefaultChar = 0;
  205781. GetTextMetrics (dc, &tm);
  205782. setCharacteristics (font.getTypefaceName(),
  205783. tm.tmAscent / (float) tm.tmHeight,
  205784. font.isBold(), font.isItalic(),
  205785. tm.tmDefaultChar);
  205786. }
  205787. bool loadGlyphIfPossible (juce_wchar character)
  205788. {
  205789. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205790. GLYPHMETRICS gm;
  205791. {
  205792. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205793. WORD index = 0;
  205794. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205795. && index == 0xffff)
  205796. {
  205797. return false;
  205798. }
  205799. }
  205800. Path glyphPath;
  205801. TEXTMETRIC tm;
  205802. if (! GetTextMetrics (dc, &tm))
  205803. {
  205804. addGlyph (character, glyphPath, 0);
  205805. return true;
  205806. }
  205807. const float height = (float) tm.tmHeight;
  205808. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205809. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205810. &gm, 0, 0, &identityMatrix);
  205811. if (bufSize > 0)
  205812. {
  205813. HeapBlock<char> data (bufSize);
  205814. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205815. bufSize, data, &identityMatrix);
  205816. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205817. const float scaleX = 1.0f / height;
  205818. const float scaleY = -1.0f / height;
  205819. while ((char*) pheader < data + bufSize)
  205820. {
  205821. float x = scaleX * pheader->pfxStart.x.value;
  205822. float y = scaleY * pheader->pfxStart.y.value;
  205823. glyphPath.startNewSubPath (x, y);
  205824. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205825. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205826. while ((const char*) curve < curveEnd)
  205827. {
  205828. if (curve->wType == TT_PRIM_LINE)
  205829. {
  205830. for (int i = 0; i < curve->cpfx; ++i)
  205831. {
  205832. x = scaleX * curve->apfx[i].x.value;
  205833. y = scaleY * curve->apfx[i].y.value;
  205834. glyphPath.lineTo (x, y);
  205835. }
  205836. }
  205837. else if (curve->wType == TT_PRIM_QSPLINE)
  205838. {
  205839. for (int i = 0; i < curve->cpfx - 1; ++i)
  205840. {
  205841. const float x2 = scaleX * curve->apfx[i].x.value;
  205842. const float y2 = scaleY * curve->apfx[i].y.value;
  205843. float x3, y3;
  205844. if (i < curve->cpfx - 2)
  205845. {
  205846. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205847. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205848. }
  205849. else
  205850. {
  205851. x3 = scaleX * curve->apfx[i + 1].x.value;
  205852. y3 = scaleY * curve->apfx[i + 1].y.value;
  205853. }
  205854. glyphPath.quadraticTo (x2, y2, x3, y3);
  205855. x = x3;
  205856. y = y3;
  205857. }
  205858. }
  205859. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205860. }
  205861. pheader = (const TTPOLYGONHEADER*) curve;
  205862. glyphPath.closeSubPath();
  205863. }
  205864. }
  205865. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205866. int numKPs;
  205867. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205868. for (int i = 0; i < numKPs; ++i)
  205869. {
  205870. if (kps[i].wFirst == character)
  205871. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205872. kps[i].iKernAmount / height);
  205873. }
  205874. return true;
  205875. }
  205876. juce_UseDebuggingNewOperator
  205877. };
  205878. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205879. {
  205880. return new WindowsTypeface (font);
  205881. }
  205882. #endif
  205883. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205884. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205885. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205886. // compiled on its own).
  205887. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205888. class SharedD2DFactory : public DeletedAtShutdown
  205889. {
  205890. public:
  205891. SharedD2DFactory()
  205892. {
  205893. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205894. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205895. if (directWriteFactory != 0)
  205896. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205897. }
  205898. ~SharedD2DFactory()
  205899. {
  205900. clearSingletonInstance();
  205901. }
  205902. juce_DeclareSingleton (SharedD2DFactory, false);
  205903. ComSmartPtr <ID2D1Factory> d2dFactory;
  205904. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205905. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205906. };
  205907. juce_ImplementSingleton (SharedD2DFactory)
  205908. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205909. {
  205910. public:
  205911. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205912. : hwnd (hwnd_),
  205913. currentState (0)
  205914. {
  205915. RECT windowRect;
  205916. GetClientRect (hwnd, &windowRect);
  205917. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205918. bounds.setSize (size.width, size.height);
  205919. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205920. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205921. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205922. // xxx check for error
  205923. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205924. }
  205925. ~Direct2DLowLevelGraphicsContext()
  205926. {
  205927. states.clear();
  205928. }
  205929. void resized()
  205930. {
  205931. RECT windowRect;
  205932. GetClientRect (hwnd, &windowRect);
  205933. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205934. renderingTarget->Resize (size);
  205935. bounds.setSize (size.width, size.height);
  205936. }
  205937. void clear()
  205938. {
  205939. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205940. }
  205941. void start()
  205942. {
  205943. renderingTarget->BeginDraw();
  205944. saveState();
  205945. }
  205946. void end()
  205947. {
  205948. states.clear();
  205949. currentState = 0;
  205950. renderingTarget->EndDraw();
  205951. renderingTarget->CheckWindowState();
  205952. }
  205953. bool isVectorDevice() const { return false; }
  205954. void setOrigin (int x, int y)
  205955. {
  205956. currentState->origin.addXY (x, y);
  205957. }
  205958. bool clipToRectangle (const Rectangle<int>& r)
  205959. {
  205960. currentState->clipToRectangle (r);
  205961. return ! isClipEmpty();
  205962. }
  205963. bool clipToRectangleList (const RectangleList& clipRegion)
  205964. {
  205965. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205966. return ! isClipEmpty();
  205967. }
  205968. void excludeClipRectangle (const Rectangle<int>&)
  205969. {
  205970. //xxx
  205971. }
  205972. void clipToPath (const Path& path, const AffineTransform& transform)
  205973. {
  205974. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205975. }
  205976. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205977. {
  205978. currentState->clipToImage (sourceImage,transform);
  205979. }
  205980. bool clipRegionIntersects (const Rectangle<int>& r)
  205981. {
  205982. const Rectangle<int> r2 (r + currentState->origin);
  205983. return currentState->clipRect.intersects (r2);
  205984. }
  205985. const Rectangle<int> getClipBounds() const
  205986. {
  205987. // xxx could this take into account complex clip regions?
  205988. return currentState->clipRect - currentState->origin;
  205989. }
  205990. bool isClipEmpty() const
  205991. {
  205992. return currentState->clipRect.isEmpty();
  205993. }
  205994. void saveState()
  205995. {
  205996. states.add (new SavedState (*this));
  205997. currentState = states.getLast();
  205998. }
  205999. void restoreState()
  206000. {
  206001. jassert (states.size() > 1) //you should never pop the last state!
  206002. states.removeLast (1);
  206003. currentState = states.getLast();
  206004. }
  206005. void setFill (const FillType& fillType)
  206006. {
  206007. currentState->setFill (fillType);
  206008. }
  206009. void setOpacity (float newOpacity)
  206010. {
  206011. currentState->setOpacity (newOpacity);
  206012. }
  206013. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  206014. {
  206015. }
  206016. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  206017. {
  206018. currentState->createBrush();
  206019. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  206020. }
  206021. void fillPath (const Path& p, const AffineTransform& transform)
  206022. {
  206023. currentState->createBrush();
  206024. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  206025. if (renderingTarget != 0)
  206026. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  206027. }
  206028. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  206029. {
  206030. const int x = currentState->origin.getX();
  206031. const int y = currentState->origin.getY();
  206032. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206033. D2D1_SIZE_U size;
  206034. size.width = image.getWidth();
  206035. size.height = image.getHeight();
  206036. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206037. Image img (image.convertedToFormat (Image::ARGB));
  206038. Image::BitmapData bd (img, false);
  206039. bp.pixelFormat = renderingTarget->GetPixelFormat();
  206040. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206041. {
  206042. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206043. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  206044. if (tempBitmap != 0)
  206045. renderingTarget->DrawBitmap (tempBitmap);
  206046. }
  206047. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206048. }
  206049. void drawLine (const Line <float>& line)
  206050. {
  206051. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206052. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206053. line.getEnd() + currentState->origin.toFloat());
  206054. currentState->createBrush();
  206055. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206056. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206057. currentState->currentBrush);
  206058. }
  206059. void drawVerticalLine (int x, float top, float bottom)
  206060. {
  206061. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206062. currentState->createBrush();
  206063. x += currentState->origin.getX();
  206064. const int y = currentState->origin.getY();
  206065. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206066. D2D1::Point2F (x, y + bottom),
  206067. currentState->currentBrush);
  206068. }
  206069. void drawHorizontalLine (int y, float left, float right)
  206070. {
  206071. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206072. currentState->createBrush();
  206073. y += currentState->origin.getY();
  206074. const int x = currentState->origin.getX();
  206075. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206076. D2D1::Point2F (x + right, y),
  206077. currentState->currentBrush);
  206078. }
  206079. void setFont (const Font& newFont)
  206080. {
  206081. currentState->setFont (newFont);
  206082. }
  206083. const Font getFont()
  206084. {
  206085. return currentState->font;
  206086. }
  206087. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206088. {
  206089. const float x = currentState->origin.getX();
  206090. const float y = currentState->origin.getY();
  206091. currentState->createBrush();
  206092. currentState->createFont();
  206093. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206094. float hScale = currentState->font.getHorizontalScale();
  206095. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206096. float dpiX = 0, dpiY = 0;
  206097. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206098. UINT32 glyphNum = glyphNumber;
  206099. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206100. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206101. DWRITE_GLYPH_OFFSET offset;
  206102. offset.advanceOffset = 0;
  206103. offset.ascenderOffset = 0;
  206104. float glyphAdvances = 0;
  206105. DWRITE_GLYPH_RUN glyph;
  206106. glyph.fontFace = currentState->currentFontFace;
  206107. glyph.glyphCount = 1;
  206108. glyph.glyphIndices = &glyphNum1;
  206109. glyph.isSideways = FALSE;
  206110. glyph.glyphAdvances = &glyphAdvances;
  206111. glyph.glyphOffsets = &offset;
  206112. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206113. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206114. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206115. }
  206116. class SavedState
  206117. {
  206118. public:
  206119. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206120. : owner (owner_), currentBrush (0),
  206121. fontScaling (1.0f), currentFontFace (0),
  206122. clipsRect (false), shouldClipRect (false),
  206123. clipsRectList (false), shouldClipRectList (false),
  206124. clipsComplex (false), shouldClipComplex (false),
  206125. clipsBitmap (false), shouldClipBitmap (false)
  206126. {
  206127. if (owner.currentState != 0)
  206128. {
  206129. // xxx seems like a very slow way to create one of these, and this is a performance
  206130. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206131. setFill (owner.currentState->fillType);
  206132. currentBrush = owner.currentState->currentBrush;
  206133. origin = owner.currentState->origin;
  206134. clipRect = owner.currentState->clipRect;
  206135. font = owner.currentState->font;
  206136. currentFontFace = owner.currentState->currentFontFace;
  206137. }
  206138. else
  206139. {
  206140. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206141. clipRect.setSize (size.width, size.height);
  206142. setFill (FillType (Colours::black));
  206143. }
  206144. }
  206145. ~SavedState()
  206146. {
  206147. clearClip();
  206148. clearFont();
  206149. clearFill();
  206150. clearPathClip();
  206151. clearImageClip();
  206152. complexClipLayer = 0;
  206153. bitmapMaskLayer = 0;
  206154. }
  206155. void clearClip()
  206156. {
  206157. popClips();
  206158. shouldClipRect = false;
  206159. }
  206160. void clipToRectangle (const Rectangle<int>& r)
  206161. {
  206162. clearClip();
  206163. clipRect = r + origin;
  206164. shouldClipRect = true;
  206165. pushClips();
  206166. }
  206167. void clearPathClip()
  206168. {
  206169. popClips();
  206170. if (shouldClipComplex)
  206171. {
  206172. complexClipGeometry = 0;
  206173. shouldClipComplex = false;
  206174. }
  206175. }
  206176. void clipToPath (ID2D1Geometry* geometry)
  206177. {
  206178. clearPathClip();
  206179. if (complexClipLayer == 0)
  206180. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206181. complexClipGeometry = geometry;
  206182. shouldClipComplex = true;
  206183. pushClips();
  206184. }
  206185. void clearRectListClip()
  206186. {
  206187. popClips();
  206188. if (shouldClipRectList)
  206189. {
  206190. rectListGeometry = 0;
  206191. shouldClipRectList = false;
  206192. }
  206193. }
  206194. void clipToRectList (ID2D1Geometry* geometry)
  206195. {
  206196. clearRectListClip();
  206197. if (rectListLayer == 0)
  206198. owner.renderingTarget->CreateLayer (&rectListLayer);
  206199. rectListGeometry = geometry;
  206200. shouldClipRectList = true;
  206201. pushClips();
  206202. }
  206203. void clearImageClip()
  206204. {
  206205. popClips();
  206206. if (shouldClipBitmap)
  206207. {
  206208. maskBitmap = 0;
  206209. bitmapMaskBrush = 0;
  206210. shouldClipBitmap = false;
  206211. }
  206212. }
  206213. void clipToImage (const Image& image, const AffineTransform& transform)
  206214. {
  206215. clearImageClip();
  206216. if (bitmapMaskLayer == 0)
  206217. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206218. D2D1_BRUSH_PROPERTIES brushProps;
  206219. brushProps.opacity = 1;
  206220. brushProps.transform = transfromToMatrix (transform);
  206221. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206222. D2D1_SIZE_U size;
  206223. size.width = image.getWidth();
  206224. size.height = image.getHeight();
  206225. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206226. maskImage = image.convertedToFormat (Image::ARGB);
  206227. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206228. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206229. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206230. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206231. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206232. imageMaskLayerParams = D2D1::LayerParameters();
  206233. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206234. shouldClipBitmap = true;
  206235. pushClips();
  206236. }
  206237. void popClips()
  206238. {
  206239. if (clipsBitmap)
  206240. {
  206241. owner.renderingTarget->PopLayer();
  206242. clipsBitmap = false;
  206243. }
  206244. if (clipsComplex)
  206245. {
  206246. owner.renderingTarget->PopLayer();
  206247. clipsComplex = false;
  206248. }
  206249. if (clipsRectList)
  206250. {
  206251. owner.renderingTarget->PopLayer();
  206252. clipsRectList = false;
  206253. }
  206254. if (clipsRect)
  206255. {
  206256. owner.renderingTarget->PopAxisAlignedClip();
  206257. clipsRect = false;
  206258. }
  206259. }
  206260. void pushClips()
  206261. {
  206262. if (shouldClipRect && ! clipsRect)
  206263. {
  206264. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206265. clipsRect = true;
  206266. }
  206267. if (shouldClipRectList && ! clipsRectList)
  206268. {
  206269. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206270. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206271. layerParams.geometricMask = rectListGeometry;
  206272. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206273. clipsRectList = true;
  206274. }
  206275. if (shouldClipComplex && ! clipsComplex)
  206276. {
  206277. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206278. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206279. layerParams.geometricMask = complexClipGeometry;
  206280. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206281. clipsComplex = true;
  206282. }
  206283. if (shouldClipBitmap && ! clipsBitmap)
  206284. {
  206285. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206286. clipsBitmap = true;
  206287. }
  206288. }
  206289. void setFill (const FillType& newFillType)
  206290. {
  206291. if (fillType != newFillType)
  206292. {
  206293. fillType = newFillType;
  206294. clearFill();
  206295. }
  206296. }
  206297. void clearFont()
  206298. {
  206299. currentFontFace = localFontFace = 0;
  206300. }
  206301. void setFont (const Font& newFont)
  206302. {
  206303. if (font != newFont)
  206304. {
  206305. font = newFont;
  206306. clearFont();
  206307. }
  206308. }
  206309. void createFont()
  206310. {
  206311. // xxx The font shouldn't be managed by the graphics context.
  206312. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206313. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206314. // WindowsTypeface class.
  206315. if (currentFontFace == 0)
  206316. {
  206317. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206318. fontScaling = systemType->getAscent();
  206319. BOOL fontFound;
  206320. uint32 fontIndex;
  206321. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206322. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206323. if (! fontFound)
  206324. fontIndex = 0;
  206325. ComSmartPtr <IDWriteFontFamily> fontFam;
  206326. fonts->GetFontFamily (fontIndex, &fontFam);
  206327. ComSmartPtr <IDWriteFont> font;
  206328. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206329. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206330. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206331. font->CreateFontFace (&localFontFace);
  206332. currentFontFace = localFontFace;
  206333. }
  206334. }
  206335. void setOpacity (float newOpacity)
  206336. {
  206337. fillType.setOpacity (newOpacity);
  206338. if (currentBrush != 0)
  206339. currentBrush->SetOpacity (newOpacity);
  206340. }
  206341. void clearFill()
  206342. {
  206343. gradientStops = 0;
  206344. linearGradient = 0;
  206345. radialGradient = 0;
  206346. bitmap = 0;
  206347. bitmapBrush = 0;
  206348. currentBrush = 0;
  206349. }
  206350. void createBrush()
  206351. {
  206352. if (currentBrush == 0)
  206353. {
  206354. const int x = origin.getX();
  206355. const int y = origin.getY();
  206356. if (fillType.isColour())
  206357. {
  206358. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206359. owner.colourBrush->SetColor (colour);
  206360. currentBrush = owner.colourBrush;
  206361. }
  206362. else if (fillType.isTiledImage())
  206363. {
  206364. D2D1_BRUSH_PROPERTIES brushProps;
  206365. brushProps.opacity = fillType.getOpacity();
  206366. brushProps.transform = transfromToMatrix (fillType.transform);
  206367. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206368. image = fillType.image;
  206369. D2D1_SIZE_U size;
  206370. size.width = image.getWidth();
  206371. size.height = image.getHeight();
  206372. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206373. this->image = image.convertedToFormat (Image::ARGB);
  206374. Image::BitmapData bd (this->image, false);
  206375. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206376. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206377. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206378. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206379. currentBrush = bitmapBrush;
  206380. }
  206381. else if (fillType.isGradient())
  206382. {
  206383. gradientStops = 0;
  206384. D2D1_BRUSH_PROPERTIES brushProps;
  206385. brushProps.opacity = fillType.getOpacity();
  206386. brushProps.transform = transfromToMatrix (fillType.transform);
  206387. const int numColors = fillType.gradient->getNumColours();
  206388. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206389. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206390. {
  206391. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206392. stops[i].position = fillType.gradient->getColourPosition(i);
  206393. }
  206394. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206395. if (fillType.gradient->isRadial)
  206396. {
  206397. radialGradient = 0;
  206398. const Point<float>& p1 = fillType.gradient->point1;
  206399. const Point<float>& p2 = fillType.gradient->point2;
  206400. float r = p1.getDistanceFrom (p2);
  206401. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206402. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206403. D2D1::Point2F (0, 0),
  206404. r, r);
  206405. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206406. currentBrush = radialGradient;
  206407. }
  206408. else
  206409. {
  206410. linearGradient = 0;
  206411. const Point<float>& p1 = fillType.gradient->point1;
  206412. const Point<float>& p2 = fillType.gradient->point2;
  206413. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206414. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206415. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206416. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206417. currentBrush = linearGradient;
  206418. }
  206419. }
  206420. }
  206421. }
  206422. juce_UseDebuggingNewOperator
  206423. //xxx most of these members should probably be private...
  206424. Direct2DLowLevelGraphicsContext& owner;
  206425. Point<int> origin;
  206426. Font font;
  206427. float fontScaling;
  206428. IDWriteFontFace* currentFontFace;
  206429. ComSmartPtr <IDWriteFontFace> localFontFace;
  206430. FillType fillType;
  206431. Image image;
  206432. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206433. Rectangle<int> clipRect;
  206434. bool clipsRect, shouldClipRect;
  206435. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206436. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206437. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206438. bool clipsComplex, shouldClipComplex;
  206439. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206440. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206441. ComSmartPtr <ID2D1Layer> rectListLayer;
  206442. bool clipsRectList, shouldClipRectList;
  206443. Image maskImage;
  206444. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206445. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206446. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206447. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206448. bool clipsBitmap, shouldClipBitmap;
  206449. ID2D1Brush* currentBrush;
  206450. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206451. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206452. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206453. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206454. private:
  206455. SavedState (const SavedState&);
  206456. SavedState& operator= (const SavedState& other);
  206457. };
  206458. juce_UseDebuggingNewOperator
  206459. private:
  206460. HWND hwnd;
  206461. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206462. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206463. Rectangle<int> bounds;
  206464. SavedState* currentState;
  206465. OwnedArray<SavedState> states;
  206466. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206467. {
  206468. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206469. }
  206470. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206471. {
  206472. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206473. }
  206474. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206475. {
  206476. transform.transformPoint (x, y);
  206477. return D2D1::Point2F (x, y);
  206478. }
  206479. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206480. {
  206481. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206482. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206483. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206484. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206485. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206486. }
  206487. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206488. {
  206489. ID2D1PathGeometry* p = 0;
  206490. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206491. ComSmartPtr <ID2D1GeometrySink> sink;
  206492. HRESULT hr = p->Open (&sink); // xxx handle error
  206493. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206494. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206495. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206496. hr = sink->Close();
  206497. return p;
  206498. }
  206499. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206500. {
  206501. Path::Iterator it (path);
  206502. while (it.next())
  206503. {
  206504. switch (it.elementType)
  206505. {
  206506. case Path::Iterator::cubicTo:
  206507. {
  206508. D2D1_BEZIER_SEGMENT seg;
  206509. transform.transformPoint (it.x1, it.y1);
  206510. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206511. transform.transformPoint (it.x2, it.y2);
  206512. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206513. transform.transformPoint(it.x3, it.y3);
  206514. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206515. sink->AddBezier (seg);
  206516. break;
  206517. }
  206518. case Path::Iterator::lineTo:
  206519. {
  206520. transform.transformPoint (it.x1, it.y1);
  206521. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206522. break;
  206523. }
  206524. case Path::Iterator::quadraticTo:
  206525. {
  206526. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206527. transform.transformPoint (it.x1, it.y1);
  206528. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206529. transform.transformPoint (it.x2, it.y2);
  206530. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206531. sink->AddQuadraticBezier (seg);
  206532. break;
  206533. }
  206534. case Path::Iterator::closePath:
  206535. {
  206536. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206537. break;
  206538. }
  206539. case Path::Iterator::startNewSubPath:
  206540. {
  206541. transform.transformPoint (it.x1, it.y1);
  206542. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206543. break;
  206544. }
  206545. }
  206546. }
  206547. }
  206548. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206549. {
  206550. ID2D1PathGeometry* p = 0;
  206551. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206552. ComSmartPtr <ID2D1GeometrySink> sink;
  206553. HRESULT hr = p->Open (&sink);
  206554. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206555. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206556. hr = sink->Close();
  206557. return p;
  206558. }
  206559. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206560. {
  206561. D2D1::Matrix3x2F matrix;
  206562. matrix._11 = transform.mat00;
  206563. matrix._12 = transform.mat10;
  206564. matrix._21 = transform.mat01;
  206565. matrix._22 = transform.mat11;
  206566. matrix._31 = transform.mat02;
  206567. matrix._32 = transform.mat12;
  206568. return matrix;
  206569. }
  206570. };
  206571. #endif
  206572. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206573. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206574. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206575. // compiled on its own).
  206576. #if JUCE_INCLUDED_FILE
  206577. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206578. // these are in the windows SDK, but need to be repeated here for GCC..
  206579. #ifndef GET_APPCOMMAND_LPARAM
  206580. #define FAPPCOMMAND_MASK 0xF000
  206581. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206582. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206583. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206584. #define APPCOMMAND_MEDIA_STOP 13
  206585. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206586. #define WM_APPCOMMAND 0x0319
  206587. #endif
  206588. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206589. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206590. extern bool juce_IsRunningInWine();
  206591. #ifndef ULW_ALPHA
  206592. #define ULW_ALPHA 0x00000002
  206593. #endif
  206594. #ifndef AC_SRC_ALPHA
  206595. #define AC_SRC_ALPHA 0x01
  206596. #endif
  206597. static HPALETTE palette = 0;
  206598. static bool createPaletteIfNeeded = true;
  206599. static bool shouldDeactivateTitleBar = true;
  206600. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  206601. #define WM_TRAYNOTIFY WM_USER + 100
  206602. using ::abs;
  206603. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206604. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206605. bool Desktop::canUseSemiTransparentWindows() throw()
  206606. {
  206607. if (updateLayeredWindow == 0)
  206608. {
  206609. if (! juce_IsRunningInWine())
  206610. {
  206611. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206612. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206613. }
  206614. }
  206615. return updateLayeredWindow != 0;
  206616. }
  206617. const int extendedKeyModifier = 0x10000;
  206618. const int KeyPress::spaceKey = VK_SPACE;
  206619. const int KeyPress::returnKey = VK_RETURN;
  206620. const int KeyPress::escapeKey = VK_ESCAPE;
  206621. const int KeyPress::backspaceKey = VK_BACK;
  206622. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206623. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206624. const int KeyPress::tabKey = VK_TAB;
  206625. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206626. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206627. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206628. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206629. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206630. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206631. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206632. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206633. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206634. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206635. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206636. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206637. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206638. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206639. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206640. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206641. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206642. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206643. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206644. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206645. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206646. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206647. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206648. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206649. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206650. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206651. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206652. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206653. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206654. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206655. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206656. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206657. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206658. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206659. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206660. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206661. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206662. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206663. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206664. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206665. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206666. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206667. const int KeyPress::playKey = 0x30000;
  206668. const int KeyPress::stopKey = 0x30001;
  206669. const int KeyPress::fastForwardKey = 0x30002;
  206670. const int KeyPress::rewindKey = 0x30003;
  206671. class WindowsBitmapImage : public Image::SharedImage
  206672. {
  206673. public:
  206674. HBITMAP hBitmap;
  206675. BITMAPV4HEADER bitmapInfo;
  206676. HDC hdc;
  206677. unsigned char* bitmapData;
  206678. WindowsBitmapImage (const Image::PixelFormat format_,
  206679. const int w, const int h, const bool clearImage)
  206680. : Image::SharedImage (format_, w, h)
  206681. {
  206682. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206683. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206684. zerostruct (bitmapInfo);
  206685. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206686. bitmapInfo.bV4Width = w;
  206687. bitmapInfo.bV4Height = h;
  206688. bitmapInfo.bV4Planes = 1;
  206689. bitmapInfo.bV4CSType = 1;
  206690. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206691. if (format_ == Image::ARGB)
  206692. {
  206693. bitmapInfo.bV4AlphaMask = 0xff000000;
  206694. bitmapInfo.bV4RedMask = 0xff0000;
  206695. bitmapInfo.bV4GreenMask = 0xff00;
  206696. bitmapInfo.bV4BlueMask = 0xff;
  206697. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206698. }
  206699. else
  206700. {
  206701. bitmapInfo.bV4V4Compression = BI_RGB;
  206702. }
  206703. lineStride = -((w * pixelStride + 3) & ~3);
  206704. HDC dc = GetDC (0);
  206705. hdc = CreateCompatibleDC (dc);
  206706. ReleaseDC (0, dc);
  206707. SetMapMode (hdc, MM_TEXT);
  206708. hBitmap = CreateDIBSection (hdc,
  206709. (BITMAPINFO*) &(bitmapInfo),
  206710. DIB_RGB_COLORS,
  206711. (void**) &bitmapData,
  206712. 0, 0);
  206713. SelectObject (hdc, hBitmap);
  206714. if (format_ == Image::ARGB && clearImage)
  206715. zeromem (bitmapData, abs (h * lineStride));
  206716. imageData = bitmapData - (lineStride * (h - 1));
  206717. }
  206718. ~WindowsBitmapImage()
  206719. {
  206720. DeleteDC (hdc);
  206721. DeleteObject (hBitmap);
  206722. }
  206723. Image::ImageType getType() const { return Image::NativeImage; }
  206724. LowLevelGraphicsContext* createLowLevelContext()
  206725. {
  206726. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206727. }
  206728. SharedImage* clone()
  206729. {
  206730. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206731. for (int i = 0; i < height; ++i)
  206732. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206733. return im;
  206734. }
  206735. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206736. const int x, const int y,
  206737. const RectangleList& maskedRegion) throw()
  206738. {
  206739. static HDRAWDIB hdd = 0;
  206740. static bool needToCreateDrawDib = true;
  206741. if (needToCreateDrawDib)
  206742. {
  206743. needToCreateDrawDib = false;
  206744. HDC dc = GetDC (0);
  206745. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206746. ReleaseDC (0, dc);
  206747. // only open if we're not palettised
  206748. if (n > 8)
  206749. hdd = DrawDibOpen();
  206750. }
  206751. if (createPaletteIfNeeded)
  206752. {
  206753. HDC dc = GetDC (0);
  206754. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206755. ReleaseDC (0, dc);
  206756. if (n <= 8)
  206757. palette = CreateHalftonePalette (dc);
  206758. createPaletteIfNeeded = false;
  206759. }
  206760. if (palette != 0)
  206761. {
  206762. SelectPalette (dc, palette, FALSE);
  206763. RealizePalette (dc);
  206764. SetStretchBltMode (dc, HALFTONE);
  206765. }
  206766. SetMapMode (dc, MM_TEXT);
  206767. if (transparent)
  206768. {
  206769. POINT p, pos;
  206770. SIZE size;
  206771. RECT windowBounds;
  206772. GetWindowRect (hwnd, &windowBounds);
  206773. p.x = -x;
  206774. p.y = -y;
  206775. pos.x = windowBounds.left;
  206776. pos.y = windowBounds.top;
  206777. size.cx = windowBounds.right - windowBounds.left;
  206778. size.cy = windowBounds.bottom - windowBounds.top;
  206779. BLENDFUNCTION bf;
  206780. bf.AlphaFormat = AC_SRC_ALPHA;
  206781. bf.BlendFlags = 0;
  206782. bf.BlendOp = AC_SRC_OVER;
  206783. bf.SourceConstantAlpha = 0xff;
  206784. if (! maskedRegion.isEmpty())
  206785. {
  206786. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206787. {
  206788. const Rectangle<int>& r = *i.getRectangle();
  206789. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206790. }
  206791. }
  206792. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206793. }
  206794. else
  206795. {
  206796. int savedDC = 0;
  206797. if (! maskedRegion.isEmpty())
  206798. {
  206799. savedDC = SaveDC (dc);
  206800. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206801. {
  206802. const Rectangle<int>& r = *i.getRectangle();
  206803. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206804. }
  206805. }
  206806. if (hdd == 0)
  206807. {
  206808. StretchDIBits (dc,
  206809. x, y, width, height,
  206810. 0, 0, width, height,
  206811. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206812. DIB_RGB_COLORS, SRCCOPY);
  206813. }
  206814. else
  206815. {
  206816. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206817. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206818. 0, 0, width, height, 0);
  206819. }
  206820. if (! maskedRegion.isEmpty())
  206821. RestoreDC (dc, savedDC);
  206822. }
  206823. }
  206824. juce_UseDebuggingNewOperator
  206825. private:
  206826. WindowsBitmapImage (const WindowsBitmapImage&);
  206827. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206828. };
  206829. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206830. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206831. {
  206832. SHORT k = (SHORT) keyCode;
  206833. if ((keyCode & extendedKeyModifier) == 0
  206834. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206835. k += (SHORT) 'A' - (SHORT) 'a';
  206836. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206837. (SHORT) '+', VK_OEM_PLUS,
  206838. (SHORT) '-', VK_OEM_MINUS,
  206839. (SHORT) '.', VK_OEM_PERIOD,
  206840. (SHORT) ';', VK_OEM_1,
  206841. (SHORT) ':', VK_OEM_1,
  206842. (SHORT) '/', VK_OEM_2,
  206843. (SHORT) '?', VK_OEM_2,
  206844. (SHORT) '[', VK_OEM_4,
  206845. (SHORT) ']', VK_OEM_6 };
  206846. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206847. if (k == translatedValues [i])
  206848. k = translatedValues [i + 1];
  206849. return (GetKeyState (k) & 0x8000) != 0;
  206850. }
  206851. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  206852. {
  206853. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  206854. return callback (userData);
  206855. else
  206856. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  206857. }
  206858. class Win32ComponentPeer : public ComponentPeer
  206859. {
  206860. public:
  206861. enum RenderingEngineType
  206862. {
  206863. softwareRenderingEngine = 0,
  206864. direct2DRenderingEngine
  206865. };
  206866. Win32ComponentPeer (Component* const component,
  206867. const int windowStyleFlags,
  206868. HWND parentToAddTo_)
  206869. : ComponentPeer (component, windowStyleFlags),
  206870. dontRepaint (false),
  206871. #if JUCE_DIRECT2D
  206872. currentRenderingEngine (direct2DRenderingEngine),
  206873. #else
  206874. currentRenderingEngine (softwareRenderingEngine),
  206875. #endif
  206876. fullScreen (false),
  206877. isDragging (false),
  206878. isMouseOver (false),
  206879. hasCreatedCaret (false),
  206880. currentWindowIcon (0),
  206881. dropTarget (0),
  206882. parentToAddTo (parentToAddTo_)
  206883. {
  206884. callFunctionIfNotLocked (&createWindowCallback, this);
  206885. setTitle (component->getName());
  206886. if ((windowStyleFlags & windowHasDropShadow) != 0
  206887. && Desktop::canUseSemiTransparentWindows())
  206888. {
  206889. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206890. if (shadower != 0)
  206891. shadower->setOwner (component);
  206892. }
  206893. }
  206894. ~Win32ComponentPeer()
  206895. {
  206896. setTaskBarIcon (Image());
  206897. shadower = 0;
  206898. // do this before the next bit to avoid messages arriving for this window
  206899. // before it's destroyed
  206900. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206901. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206902. if (currentWindowIcon != 0)
  206903. DestroyIcon (currentWindowIcon);
  206904. if (dropTarget != 0)
  206905. {
  206906. dropTarget->Release();
  206907. dropTarget = 0;
  206908. }
  206909. #if JUCE_DIRECT2D
  206910. direct2DContext = 0;
  206911. #endif
  206912. }
  206913. void* getNativeHandle() const
  206914. {
  206915. return hwnd;
  206916. }
  206917. void setVisible (bool shouldBeVisible)
  206918. {
  206919. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206920. if (shouldBeVisible)
  206921. InvalidateRect (hwnd, 0, 0);
  206922. else
  206923. lastPaintTime = 0;
  206924. }
  206925. void setTitle (const String& title)
  206926. {
  206927. SetWindowText (hwnd, title);
  206928. }
  206929. void setPosition (int x, int y)
  206930. {
  206931. offsetWithinParent (x, y);
  206932. SetWindowPos (hwnd, 0,
  206933. x - windowBorder.getLeft(),
  206934. y - windowBorder.getTop(),
  206935. 0, 0,
  206936. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206937. }
  206938. void repaintNowIfTransparent()
  206939. {
  206940. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206941. handlePaintMessage();
  206942. }
  206943. void updateBorderSize()
  206944. {
  206945. WINDOWINFO info;
  206946. info.cbSize = sizeof (info);
  206947. if (GetWindowInfo (hwnd, &info))
  206948. {
  206949. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206950. info.rcClient.left - info.rcWindow.left,
  206951. info.rcWindow.bottom - info.rcClient.bottom,
  206952. info.rcWindow.right - info.rcClient.right);
  206953. }
  206954. #if JUCE_DIRECT2D
  206955. if (direct2DContext != 0)
  206956. direct2DContext->resized();
  206957. #endif
  206958. }
  206959. void setSize (int w, int h)
  206960. {
  206961. SetWindowPos (hwnd, 0, 0, 0,
  206962. w + windowBorder.getLeftAndRight(),
  206963. h + windowBorder.getTopAndBottom(),
  206964. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206965. updateBorderSize();
  206966. repaintNowIfTransparent();
  206967. }
  206968. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206969. {
  206970. fullScreen = isNowFullScreen;
  206971. offsetWithinParent (x, y);
  206972. SetWindowPos (hwnd, 0,
  206973. x - windowBorder.getLeft(),
  206974. y - windowBorder.getTop(),
  206975. w + windowBorder.getLeftAndRight(),
  206976. h + windowBorder.getTopAndBottom(),
  206977. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206978. updateBorderSize();
  206979. repaintNowIfTransparent();
  206980. }
  206981. const Rectangle<int> getBounds() const
  206982. {
  206983. RECT r;
  206984. GetWindowRect (hwnd, &r);
  206985. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206986. HWND parentH = GetParent (hwnd);
  206987. if (parentH != 0)
  206988. {
  206989. GetWindowRect (parentH, &r);
  206990. bounds.translate (-r.left, -r.top);
  206991. }
  206992. return windowBorder.subtractedFrom (bounds);
  206993. }
  206994. const Point<int> getScreenPosition() const
  206995. {
  206996. RECT r;
  206997. GetWindowRect (hwnd, &r);
  206998. return Point<int> (r.left + windowBorder.getLeft(),
  206999. r.top + windowBorder.getTop());
  207000. }
  207001. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  207002. {
  207003. return relativePosition + getScreenPosition();
  207004. }
  207005. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  207006. {
  207007. return screenPosition - getScreenPosition();
  207008. }
  207009. void setMinimised (bool shouldBeMinimised)
  207010. {
  207011. if (shouldBeMinimised != isMinimised())
  207012. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207013. }
  207014. bool isMinimised() const
  207015. {
  207016. WINDOWPLACEMENT wp;
  207017. wp.length = sizeof (WINDOWPLACEMENT);
  207018. GetWindowPlacement (hwnd, &wp);
  207019. return wp.showCmd == SW_SHOWMINIMIZED;
  207020. }
  207021. void setFullScreen (bool shouldBeFullScreen)
  207022. {
  207023. setMinimised (false);
  207024. if (fullScreen != shouldBeFullScreen)
  207025. {
  207026. fullScreen = shouldBeFullScreen;
  207027. const Component::SafePointer<Component> deletionChecker (component);
  207028. if (! fullScreen)
  207029. {
  207030. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207031. if (hasTitleBar())
  207032. ShowWindow (hwnd, SW_SHOWNORMAL);
  207033. if (! boundsCopy.isEmpty())
  207034. {
  207035. setBounds (boundsCopy.getX(),
  207036. boundsCopy.getY(),
  207037. boundsCopy.getWidth(),
  207038. boundsCopy.getHeight(),
  207039. false);
  207040. }
  207041. }
  207042. else
  207043. {
  207044. if (hasTitleBar())
  207045. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207046. else
  207047. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207048. }
  207049. if (deletionChecker != 0)
  207050. handleMovedOrResized();
  207051. }
  207052. }
  207053. bool isFullScreen() const
  207054. {
  207055. if (! hasTitleBar())
  207056. return fullScreen;
  207057. WINDOWPLACEMENT wp;
  207058. wp.length = sizeof (wp);
  207059. GetWindowPlacement (hwnd, &wp);
  207060. return wp.showCmd == SW_SHOWMAXIMIZED;
  207061. }
  207062. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207063. {
  207064. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  207065. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  207066. return false;
  207067. RECT r;
  207068. GetWindowRect (hwnd, &r);
  207069. POINT p;
  207070. p.x = position.getX() + r.left + windowBorder.getLeft();
  207071. p.y = position.getY() + r.top + windowBorder.getTop();
  207072. HWND w = WindowFromPoint (p);
  207073. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207074. }
  207075. const BorderSize getFrameSize() const
  207076. {
  207077. return windowBorder;
  207078. }
  207079. bool setAlwaysOnTop (bool alwaysOnTop)
  207080. {
  207081. const bool oldDeactivate = shouldDeactivateTitleBar;
  207082. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207083. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207084. 0, 0, 0, 0,
  207085. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207086. shouldDeactivateTitleBar = oldDeactivate;
  207087. if (shadower != 0)
  207088. shadower->componentBroughtToFront (*component);
  207089. return true;
  207090. }
  207091. void toFront (bool makeActive)
  207092. {
  207093. setMinimised (false);
  207094. const bool oldDeactivate = shouldDeactivateTitleBar;
  207095. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207096. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207097. shouldDeactivateTitleBar = oldDeactivate;
  207098. if (! makeActive)
  207099. {
  207100. // in this case a broughttofront call won't have occured, so do it now..
  207101. handleBroughtToFront();
  207102. }
  207103. }
  207104. void toBehind (ComponentPeer* other)
  207105. {
  207106. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207107. jassert (otherPeer != 0); // wrong type of window?
  207108. if (otherPeer != 0)
  207109. {
  207110. setMinimised (false);
  207111. // must be careful not to try to put a topmost window behind a normal one, or win32
  207112. // promotes the normal one to be topmost!
  207113. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207114. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207115. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207116. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207117. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207118. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207119. }
  207120. }
  207121. bool isFocused() const
  207122. {
  207123. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207124. }
  207125. void grabFocus()
  207126. {
  207127. const bool oldDeactivate = shouldDeactivateTitleBar;
  207128. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207129. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207130. shouldDeactivateTitleBar = oldDeactivate;
  207131. }
  207132. void textInputRequired (const Point<int>&)
  207133. {
  207134. if (! hasCreatedCaret)
  207135. {
  207136. hasCreatedCaret = true;
  207137. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207138. }
  207139. ShowCaret (hwnd);
  207140. SetCaretPos (0, 0);
  207141. }
  207142. void repaint (const Rectangle<int>& area)
  207143. {
  207144. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207145. InvalidateRect (hwnd, &r, FALSE);
  207146. }
  207147. void performAnyPendingRepaintsNow()
  207148. {
  207149. MSG m;
  207150. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207151. DispatchMessage (&m);
  207152. }
  207153. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207154. {
  207155. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207156. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207157. return 0;
  207158. }
  207159. void setTaskBarIcon (const Image& image)
  207160. {
  207161. if (image.isValid())
  207162. {
  207163. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  207164. if (taskBarIcon == 0)
  207165. {
  207166. taskBarIcon = new NOTIFYICONDATA();
  207167. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207168. taskBarIcon->hWnd = (HWND) hwnd;
  207169. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207170. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207171. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207172. taskBarIcon->hIcon = hicon;
  207173. taskBarIcon->szTip[0] = 0;
  207174. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207175. }
  207176. else
  207177. {
  207178. HICON oldIcon = taskBarIcon->hIcon;
  207179. taskBarIcon->hIcon = hicon;
  207180. taskBarIcon->uFlags = NIF_ICON;
  207181. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207182. DestroyIcon (oldIcon);
  207183. }
  207184. DestroyIcon (hicon);
  207185. }
  207186. else if (taskBarIcon != 0)
  207187. {
  207188. taskBarIcon->uFlags = 0;
  207189. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207190. DestroyIcon (taskBarIcon->hIcon);
  207191. taskBarIcon = 0;
  207192. }
  207193. }
  207194. void setTaskBarIconToolTip (const String& toolTip) const
  207195. {
  207196. if (taskBarIcon != 0)
  207197. {
  207198. taskBarIcon->uFlags = NIF_TIP;
  207199. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207200. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207201. }
  207202. }
  207203. bool isInside (HWND h) const
  207204. {
  207205. return GetAncestor (hwnd, GA_ROOT) == h;
  207206. }
  207207. static void updateKeyModifiers() throw()
  207208. {
  207209. int keyMods = 0;
  207210. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207211. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207212. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207213. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207214. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207215. }
  207216. static void updateModifiersFromWParam (const WPARAM wParam)
  207217. {
  207218. int mouseMods = 0;
  207219. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207220. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207221. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207222. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207223. updateKeyModifiers();
  207224. }
  207225. static int64 getMouseEventTime()
  207226. {
  207227. static int64 eventTimeOffset = 0;
  207228. static DWORD lastMessageTime = 0;
  207229. const DWORD thisMessageTime = GetMessageTime();
  207230. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207231. {
  207232. lastMessageTime = thisMessageTime;
  207233. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207234. }
  207235. return eventTimeOffset + thisMessageTime;
  207236. }
  207237. juce_UseDebuggingNewOperator
  207238. bool dontRepaint;
  207239. static ModifierKeys currentModifiers;
  207240. static ModifierKeys modifiersAtLastCallback;
  207241. private:
  207242. HWND hwnd, parentToAddTo;
  207243. ScopedPointer<DropShadower> shadower;
  207244. RenderingEngineType currentRenderingEngine;
  207245. #if JUCE_DIRECT2D
  207246. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207247. #endif
  207248. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207249. BorderSize windowBorder;
  207250. HICON currentWindowIcon;
  207251. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207252. IDropTarget* dropTarget;
  207253. class TemporaryImage : public Timer
  207254. {
  207255. public:
  207256. TemporaryImage() {}
  207257. ~TemporaryImage() {}
  207258. const Image& getImage (const bool transparent, const int w, const int h)
  207259. {
  207260. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207261. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207262. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207263. startTimer (3000);
  207264. return image;
  207265. }
  207266. void timerCallback()
  207267. {
  207268. stopTimer();
  207269. image = Image::null;
  207270. }
  207271. private:
  207272. Image image;
  207273. TemporaryImage (const TemporaryImage&);
  207274. TemporaryImage& operator= (const TemporaryImage&);
  207275. };
  207276. TemporaryImage offscreenImageGenerator;
  207277. class WindowClassHolder : public DeletedAtShutdown
  207278. {
  207279. public:
  207280. WindowClassHolder()
  207281. : windowClassName ("JUCE_")
  207282. {
  207283. // this name has to be different for each app/dll instance because otherwise
  207284. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207285. // window class).
  207286. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207287. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207288. TCHAR moduleFile [1024];
  207289. moduleFile[0] = 0;
  207290. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207291. WORD iconNum = 0;
  207292. WNDCLASSEX wcex;
  207293. wcex.cbSize = sizeof (wcex);
  207294. wcex.style = CS_OWNDC;
  207295. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207296. wcex.lpszClassName = windowClassName;
  207297. wcex.cbClsExtra = 0;
  207298. wcex.cbWndExtra = 32;
  207299. wcex.hInstance = moduleHandle;
  207300. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207301. iconNum = 1;
  207302. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207303. wcex.hCursor = 0;
  207304. wcex.hbrBackground = 0;
  207305. wcex.lpszMenuName = 0;
  207306. RegisterClassEx (&wcex);
  207307. }
  207308. ~WindowClassHolder()
  207309. {
  207310. if (ComponentPeer::getNumPeers() == 0)
  207311. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207312. clearSingletonInstance();
  207313. }
  207314. String windowClassName;
  207315. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207316. };
  207317. static void* createWindowCallback (void* userData)
  207318. {
  207319. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207320. return 0;
  207321. }
  207322. void createWindow()
  207323. {
  207324. DWORD exstyle = WS_EX_ACCEPTFILES;
  207325. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207326. if (hasTitleBar())
  207327. {
  207328. type |= WS_OVERLAPPED;
  207329. if ((styleFlags & windowHasCloseButton) != 0)
  207330. {
  207331. type |= WS_SYSMENU;
  207332. }
  207333. else
  207334. {
  207335. // annoyingly, windows won't let you have a min/max button without a close button
  207336. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207337. }
  207338. if ((styleFlags & windowIsResizable) != 0)
  207339. type |= WS_THICKFRAME;
  207340. }
  207341. else if (parentToAddTo != 0)
  207342. {
  207343. type |= WS_CHILD;
  207344. }
  207345. else
  207346. {
  207347. type |= WS_POPUP | WS_SYSMENU;
  207348. }
  207349. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207350. exstyle |= WS_EX_TOOLWINDOW;
  207351. else
  207352. exstyle |= WS_EX_APPWINDOW;
  207353. if ((styleFlags & windowHasMinimiseButton) != 0)
  207354. type |= WS_MINIMIZEBOX;
  207355. if ((styleFlags & windowHasMaximiseButton) != 0)
  207356. type |= WS_MAXIMIZEBOX;
  207357. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207358. exstyle |= WS_EX_TRANSPARENT;
  207359. if ((styleFlags & windowIsSemiTransparent) != 0
  207360. && Desktop::canUseSemiTransparentWindows())
  207361. exstyle |= WS_EX_LAYERED;
  207362. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207363. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207364. #if JUCE_DIRECT2D
  207365. updateDirect2DContext();
  207366. #endif
  207367. if (hwnd != 0)
  207368. {
  207369. SetWindowLongPtr (hwnd, 0, 0);
  207370. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207371. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207372. if (dropTarget == 0)
  207373. dropTarget = new JuceDropTarget (this);
  207374. RegisterDragDrop (hwnd, dropTarget);
  207375. updateBorderSize();
  207376. // Calling this function here is (for some reason) necessary to make Windows
  207377. // correctly enable the menu items that we specify in the wm_initmenu message.
  207378. GetSystemMenu (hwnd, false);
  207379. }
  207380. else
  207381. {
  207382. jassertfalse;
  207383. }
  207384. }
  207385. static void* destroyWindowCallback (void* handle)
  207386. {
  207387. RevokeDragDrop ((HWND) handle);
  207388. DestroyWindow ((HWND) handle);
  207389. return 0;
  207390. }
  207391. static void* toFrontCallback1 (void* h)
  207392. {
  207393. SetForegroundWindow ((HWND) h);
  207394. return 0;
  207395. }
  207396. static void* toFrontCallback2 (void* h)
  207397. {
  207398. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207399. return 0;
  207400. }
  207401. static void* setFocusCallback (void* h)
  207402. {
  207403. SetFocus ((HWND) h);
  207404. return 0;
  207405. }
  207406. static void* getFocusCallback (void*)
  207407. {
  207408. return GetFocus();
  207409. }
  207410. void offsetWithinParent (int& x, int& y) const
  207411. {
  207412. if (isTransparent())
  207413. {
  207414. HWND parentHwnd = GetParent (hwnd);
  207415. if (parentHwnd != 0)
  207416. {
  207417. RECT parentRect;
  207418. GetWindowRect (parentHwnd, &parentRect);
  207419. x += parentRect.left;
  207420. y += parentRect.top;
  207421. }
  207422. }
  207423. }
  207424. bool isTransparent() const
  207425. {
  207426. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207427. }
  207428. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207429. void setIcon (const Image& newIcon)
  207430. {
  207431. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207432. if (hicon != 0)
  207433. {
  207434. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207435. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207436. if (currentWindowIcon != 0)
  207437. DestroyIcon (currentWindowIcon);
  207438. currentWindowIcon = hicon;
  207439. }
  207440. }
  207441. void handlePaintMessage()
  207442. {
  207443. #if JUCE_DIRECT2D
  207444. if (direct2DContext != 0)
  207445. {
  207446. RECT r;
  207447. if (GetUpdateRect (hwnd, &r, false))
  207448. {
  207449. direct2DContext->start();
  207450. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207451. handlePaint (*direct2DContext);
  207452. direct2DContext->end();
  207453. }
  207454. }
  207455. else
  207456. #endif
  207457. {
  207458. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207459. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207460. PAINTSTRUCT paintStruct;
  207461. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207462. // message and become re-entrant, but that's OK
  207463. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207464. // corrupt the image it's using to paint into, so do a check here.
  207465. static bool reentrant = false;
  207466. if (reentrant)
  207467. {
  207468. DeleteObject (rgn);
  207469. EndPaint (hwnd, &paintStruct);
  207470. return;
  207471. }
  207472. reentrant = true;
  207473. // this is the rectangle to update..
  207474. int x = paintStruct.rcPaint.left;
  207475. int y = paintStruct.rcPaint.top;
  207476. int w = paintStruct.rcPaint.right - x;
  207477. int h = paintStruct.rcPaint.bottom - y;
  207478. const bool transparent = isTransparent();
  207479. if (transparent)
  207480. {
  207481. // it's not possible to have a transparent window with a title bar at the moment!
  207482. jassert (! hasTitleBar());
  207483. RECT r;
  207484. GetWindowRect (hwnd, &r);
  207485. x = y = 0;
  207486. w = r.right - r.left;
  207487. h = r.bottom - r.top;
  207488. }
  207489. if (w > 0 && h > 0)
  207490. {
  207491. clearMaskedRegion();
  207492. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207493. RectangleList contextClip;
  207494. const Rectangle<int> clipBounds (0, 0, w, h);
  207495. bool needToPaintAll = true;
  207496. if (regionType == COMPLEXREGION && ! transparent)
  207497. {
  207498. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207499. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207500. DeleteObject (clipRgn);
  207501. char rgnData [8192];
  207502. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207503. if (res > 0 && res <= sizeof (rgnData))
  207504. {
  207505. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207506. if (hdr->iType == RDH_RECTANGLES
  207507. && hdr->rcBound.right - hdr->rcBound.left >= w
  207508. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207509. {
  207510. needToPaintAll = false;
  207511. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207512. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207513. while (--num >= 0)
  207514. {
  207515. if (rects->right <= x + w && rects->bottom <= y + h)
  207516. {
  207517. // (need to move this one pixel to the left because of a win32 bug)
  207518. const int cx = jmax (x, (int) rects->left - 1);
  207519. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207520. .getIntersection (clipBounds));
  207521. }
  207522. else
  207523. {
  207524. needToPaintAll = true;
  207525. break;
  207526. }
  207527. ++rects;
  207528. }
  207529. }
  207530. }
  207531. }
  207532. if (needToPaintAll)
  207533. {
  207534. contextClip.clear();
  207535. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207536. }
  207537. if (transparent)
  207538. {
  207539. RectangleList::Iterator i (contextClip);
  207540. while (i.next())
  207541. offscreenImage.clear (*i.getRectangle());
  207542. }
  207543. // if the component's not opaque, this won't draw properly unless the platform can support this
  207544. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207545. updateCurrentModifiers();
  207546. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207547. handlePaint (context);
  207548. if (! dontRepaint)
  207549. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207550. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207551. }
  207552. DeleteObject (rgn);
  207553. EndPaint (hwnd, &paintStruct);
  207554. reentrant = false;
  207555. }
  207556. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207557. _fpreset(); // because some graphics cards can unmask FP exceptions
  207558. #endif
  207559. lastPaintTime = Time::getMillisecondCounter();
  207560. }
  207561. void doMouseEvent (const Point<int>& position)
  207562. {
  207563. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207564. }
  207565. const StringArray getAvailableRenderingEngines()
  207566. {
  207567. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207568. #if JUCE_DIRECT2D
  207569. // xxx is this correct? Seems to enable it on Vista too??
  207570. OSVERSIONINFO info;
  207571. zerostruct (info);
  207572. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207573. GetVersionEx (&info);
  207574. if (info.dwMajorVersion >= 6)
  207575. s.add ("Direct2D");
  207576. #endif
  207577. return s;
  207578. }
  207579. int getCurrentRenderingEngine() throw()
  207580. {
  207581. return currentRenderingEngine;
  207582. }
  207583. #if JUCE_DIRECT2D
  207584. void updateDirect2DContext()
  207585. {
  207586. if (currentRenderingEngine != direct2DRenderingEngine)
  207587. direct2DContext = 0;
  207588. else if (direct2DContext == 0)
  207589. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207590. }
  207591. #endif
  207592. void setCurrentRenderingEngine (int index)
  207593. {
  207594. (void) index;
  207595. #if JUCE_DIRECT2D
  207596. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207597. updateDirect2DContext();
  207598. repaint (component->getLocalBounds());
  207599. #endif
  207600. }
  207601. void doMouseMove (const Point<int>& position)
  207602. {
  207603. if (! isMouseOver)
  207604. {
  207605. isMouseOver = true;
  207606. updateKeyModifiers();
  207607. TRACKMOUSEEVENT tme;
  207608. tme.cbSize = sizeof (tme);
  207609. tme.dwFlags = TME_LEAVE;
  207610. tme.hwndTrack = hwnd;
  207611. tme.dwHoverTime = 0;
  207612. if (! TrackMouseEvent (&tme))
  207613. jassertfalse;
  207614. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207615. }
  207616. else if (! isDragging)
  207617. {
  207618. if (! contains (position, false))
  207619. return;
  207620. }
  207621. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207622. static uint32 lastMouseTime = 0;
  207623. const uint32 now = Time::getMillisecondCounter();
  207624. const int maxMouseMovesPerSecond = 60;
  207625. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207626. {
  207627. lastMouseTime = now;
  207628. doMouseEvent (position);
  207629. }
  207630. }
  207631. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207632. {
  207633. if (GetCapture() != hwnd)
  207634. SetCapture (hwnd);
  207635. doMouseMove (position);
  207636. updateModifiersFromWParam (wParam);
  207637. isDragging = true;
  207638. doMouseEvent (position);
  207639. }
  207640. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207641. {
  207642. updateModifiersFromWParam (wParam);
  207643. isDragging = false;
  207644. // release the mouse capture if the user has released all buttons
  207645. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207646. ReleaseCapture();
  207647. doMouseEvent (position);
  207648. }
  207649. void doCaptureChanged()
  207650. {
  207651. if (isDragging)
  207652. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207653. }
  207654. void doMouseExit()
  207655. {
  207656. isMouseOver = false;
  207657. doMouseEvent (getCurrentMousePos());
  207658. }
  207659. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207660. {
  207661. updateKeyModifiers();
  207662. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207663. handleMouseWheel (0, position, getMouseEventTime(),
  207664. isVertical ? 0.0f : amount,
  207665. isVertical ? amount : 0.0f);
  207666. }
  207667. void sendModifierKeyChangeIfNeeded()
  207668. {
  207669. if (modifiersAtLastCallback != currentModifiers)
  207670. {
  207671. modifiersAtLastCallback = currentModifiers;
  207672. handleModifierKeysChange();
  207673. }
  207674. }
  207675. bool doKeyUp (const WPARAM key)
  207676. {
  207677. updateKeyModifiers();
  207678. switch (key)
  207679. {
  207680. case VK_SHIFT:
  207681. case VK_CONTROL:
  207682. case VK_MENU:
  207683. case VK_CAPITAL:
  207684. case VK_LWIN:
  207685. case VK_RWIN:
  207686. case VK_APPS:
  207687. case VK_NUMLOCK:
  207688. case VK_SCROLL:
  207689. case VK_LSHIFT:
  207690. case VK_RSHIFT:
  207691. case VK_LCONTROL:
  207692. case VK_LMENU:
  207693. case VK_RCONTROL:
  207694. case VK_RMENU:
  207695. sendModifierKeyChangeIfNeeded();
  207696. }
  207697. return handleKeyUpOrDown (false)
  207698. || Component::getCurrentlyModalComponent() != 0;
  207699. }
  207700. bool doKeyDown (const WPARAM key)
  207701. {
  207702. updateKeyModifiers();
  207703. bool used = false;
  207704. switch (key)
  207705. {
  207706. case VK_SHIFT:
  207707. case VK_LSHIFT:
  207708. case VK_RSHIFT:
  207709. case VK_CONTROL:
  207710. case VK_LCONTROL:
  207711. case VK_RCONTROL:
  207712. case VK_MENU:
  207713. case VK_LMENU:
  207714. case VK_RMENU:
  207715. case VK_LWIN:
  207716. case VK_RWIN:
  207717. case VK_CAPITAL:
  207718. case VK_NUMLOCK:
  207719. case VK_SCROLL:
  207720. case VK_APPS:
  207721. sendModifierKeyChangeIfNeeded();
  207722. break;
  207723. case VK_LEFT:
  207724. case VK_RIGHT:
  207725. case VK_UP:
  207726. case VK_DOWN:
  207727. case VK_PRIOR:
  207728. case VK_NEXT:
  207729. case VK_HOME:
  207730. case VK_END:
  207731. case VK_DELETE:
  207732. case VK_INSERT:
  207733. case VK_F1:
  207734. case VK_F2:
  207735. case VK_F3:
  207736. case VK_F4:
  207737. case VK_F5:
  207738. case VK_F6:
  207739. case VK_F7:
  207740. case VK_F8:
  207741. case VK_F9:
  207742. case VK_F10:
  207743. case VK_F11:
  207744. case VK_F12:
  207745. case VK_F13:
  207746. case VK_F14:
  207747. case VK_F15:
  207748. case VK_F16:
  207749. used = handleKeyUpOrDown (true);
  207750. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207751. break;
  207752. case VK_ADD:
  207753. case VK_SUBTRACT:
  207754. case VK_MULTIPLY:
  207755. case VK_DIVIDE:
  207756. case VK_SEPARATOR:
  207757. case VK_DECIMAL:
  207758. used = handleKeyUpOrDown (true);
  207759. break;
  207760. default:
  207761. used = handleKeyUpOrDown (true);
  207762. {
  207763. MSG msg;
  207764. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207765. {
  207766. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207767. // manually generate the key-press event that matches this key-down.
  207768. const UINT keyChar = MapVirtualKey (key, 2);
  207769. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207770. }
  207771. }
  207772. break;
  207773. }
  207774. if (Component::getCurrentlyModalComponent() != 0)
  207775. used = true;
  207776. return used;
  207777. }
  207778. bool doKeyChar (int key, const LPARAM flags)
  207779. {
  207780. updateKeyModifiers();
  207781. juce_wchar textChar = (juce_wchar) key;
  207782. const int virtualScanCode = (flags >> 16) & 0xff;
  207783. if (key >= '0' && key <= '9')
  207784. {
  207785. switch (virtualScanCode) // check for a numeric keypad scan-code
  207786. {
  207787. case 0x52:
  207788. case 0x4f:
  207789. case 0x50:
  207790. case 0x51:
  207791. case 0x4b:
  207792. case 0x4c:
  207793. case 0x4d:
  207794. case 0x47:
  207795. case 0x48:
  207796. case 0x49:
  207797. key = (key - '0') + KeyPress::numberPad0;
  207798. break;
  207799. default:
  207800. break;
  207801. }
  207802. }
  207803. else
  207804. {
  207805. // convert the scan code to an unmodified character code..
  207806. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207807. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207808. keyChar = LOWORD (keyChar);
  207809. if (keyChar != 0)
  207810. key = (int) keyChar;
  207811. // avoid sending junk text characters for some control-key combinations
  207812. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207813. textChar = 0;
  207814. }
  207815. return handleKeyPress (key, textChar);
  207816. }
  207817. bool doAppCommand (const LPARAM lParam)
  207818. {
  207819. int key = 0;
  207820. switch (GET_APPCOMMAND_LPARAM (lParam))
  207821. {
  207822. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207823. key = KeyPress::playKey;
  207824. break;
  207825. case APPCOMMAND_MEDIA_STOP:
  207826. key = KeyPress::stopKey;
  207827. break;
  207828. case APPCOMMAND_MEDIA_NEXTTRACK:
  207829. key = KeyPress::fastForwardKey;
  207830. break;
  207831. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207832. key = KeyPress::rewindKey;
  207833. break;
  207834. }
  207835. if (key != 0)
  207836. {
  207837. updateKeyModifiers();
  207838. if (hwnd == GetActiveWindow())
  207839. {
  207840. handleKeyPress (key, 0);
  207841. return true;
  207842. }
  207843. }
  207844. return false;
  207845. }
  207846. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207847. {
  207848. public:
  207849. JuceDropTarget (Win32ComponentPeer* const owner_)
  207850. : owner (owner_)
  207851. {
  207852. }
  207853. ~JuceDropTarget() {}
  207854. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207855. {
  207856. updateFileList (pDataObject);
  207857. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207858. *pdwEffect = DROPEFFECT_COPY;
  207859. return S_OK;
  207860. }
  207861. HRESULT __stdcall DragLeave()
  207862. {
  207863. owner->handleFileDragExit (files);
  207864. return S_OK;
  207865. }
  207866. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207867. {
  207868. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207869. *pdwEffect = DROPEFFECT_COPY;
  207870. return S_OK;
  207871. }
  207872. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207873. {
  207874. updateFileList (pDataObject);
  207875. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207876. *pdwEffect = DROPEFFECT_COPY;
  207877. return S_OK;
  207878. }
  207879. private:
  207880. Win32ComponentPeer* const owner;
  207881. StringArray files;
  207882. void updateFileList (IDataObject* const pDataObject)
  207883. {
  207884. files.clear();
  207885. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207886. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207887. if (pDataObject->GetData (&format, &medium) == S_OK)
  207888. {
  207889. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207890. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207891. unsigned int i = 0;
  207892. if (pDropFiles->fWide)
  207893. {
  207894. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207895. for (;;)
  207896. {
  207897. unsigned int len = 0;
  207898. while (i + len < totalLen && fname [i + len] != 0)
  207899. ++len;
  207900. if (len == 0)
  207901. break;
  207902. files.add (String (fname + i, len));
  207903. i += len + 1;
  207904. }
  207905. }
  207906. else
  207907. {
  207908. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207909. for (;;)
  207910. {
  207911. unsigned int len = 0;
  207912. while (i + len < totalLen && fname [i + len] != 0)
  207913. ++len;
  207914. if (len == 0)
  207915. break;
  207916. files.add (String (fname + i, len));
  207917. i += len + 1;
  207918. }
  207919. }
  207920. GlobalUnlock (medium.hGlobal);
  207921. }
  207922. }
  207923. JuceDropTarget (const JuceDropTarget&);
  207924. JuceDropTarget& operator= (const JuceDropTarget&);
  207925. };
  207926. void doSettingChange()
  207927. {
  207928. Desktop::getInstance().refreshMonitorSizes();
  207929. if (fullScreen && ! isMinimised())
  207930. {
  207931. const Rectangle<int> r (component->getParentMonitorArea());
  207932. SetWindowPos (hwnd, 0,
  207933. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207934. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207935. }
  207936. }
  207937. public:
  207938. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207939. {
  207940. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207941. if (peer != 0)
  207942. return peer->peerWindowProc (h, message, wParam, lParam);
  207943. return DefWindowProcW (h, message, wParam, lParam);
  207944. }
  207945. private:
  207946. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207947. {
  207948. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207949. }
  207950. const Point<int> getCurrentMousePos() throw()
  207951. {
  207952. RECT wr;
  207953. GetWindowRect (hwnd, &wr);
  207954. const DWORD mp = GetMessagePos();
  207955. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207956. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207957. }
  207958. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207959. {
  207960. if (isValidPeer (this))
  207961. {
  207962. switch (message)
  207963. {
  207964. case WM_NCHITTEST:
  207965. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207966. return HTTRANSPARENT;
  207967. if (hasTitleBar())
  207968. break;
  207969. return HTCLIENT;
  207970. case WM_PAINT:
  207971. handlePaintMessage();
  207972. return 0;
  207973. case WM_NCPAINT:
  207974. if (wParam != 1)
  207975. handlePaintMessage();
  207976. if (hasTitleBar())
  207977. break;
  207978. return 0;
  207979. case WM_ERASEBKGND:
  207980. case WM_NCCALCSIZE:
  207981. if (hasTitleBar())
  207982. break;
  207983. return 1;
  207984. case WM_MOUSEMOVE:
  207985. doMouseMove (getPointFromLParam (lParam));
  207986. return 0;
  207987. case WM_MOUSELEAVE:
  207988. doMouseExit();
  207989. return 0;
  207990. case WM_LBUTTONDOWN:
  207991. case WM_MBUTTONDOWN:
  207992. case WM_RBUTTONDOWN:
  207993. doMouseDown (getPointFromLParam (lParam), wParam);
  207994. return 0;
  207995. case WM_LBUTTONUP:
  207996. case WM_MBUTTONUP:
  207997. case WM_RBUTTONUP:
  207998. doMouseUp (getPointFromLParam (lParam), wParam);
  207999. return 0;
  208000. case WM_CAPTURECHANGED:
  208001. doCaptureChanged();
  208002. return 0;
  208003. case WM_NCMOUSEMOVE:
  208004. if (hasTitleBar())
  208005. break;
  208006. return 0;
  208007. case 0x020A: /* WM_MOUSEWHEEL */
  208008. doMouseWheel (getCurrentMousePos(), wParam, true);
  208009. return 0;
  208010. case 0x020E: /* WM_MOUSEHWHEEL */
  208011. doMouseWheel (getCurrentMousePos(), wParam, false);
  208012. return 0;
  208013. case WM_WINDOWPOSCHANGING:
  208014. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  208015. {
  208016. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  208017. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  208018. {
  208019. if (constrainer != 0)
  208020. {
  208021. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  208022. component->getY() - windowBorder.getTop(),
  208023. component->getWidth() + windowBorder.getLeftAndRight(),
  208024. component->getHeight() + windowBorder.getTopAndBottom());
  208025. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  208026. constrainer->checkBounds (pos, current,
  208027. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208028. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  208029. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  208030. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  208031. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  208032. wp->x = pos.getX();
  208033. wp->y = pos.getY();
  208034. wp->cx = pos.getWidth();
  208035. wp->cy = pos.getHeight();
  208036. }
  208037. }
  208038. }
  208039. return 0;
  208040. case WM_WINDOWPOSCHANGED:
  208041. handleMovedOrResized();
  208042. if (dontRepaint)
  208043. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208044. return 0;
  208045. case WM_KEYDOWN:
  208046. case WM_SYSKEYDOWN:
  208047. if (doKeyDown (wParam))
  208048. return 0;
  208049. break;
  208050. case WM_KEYUP:
  208051. case WM_SYSKEYUP:
  208052. if (doKeyUp (wParam))
  208053. return 0;
  208054. break;
  208055. case WM_CHAR:
  208056. if (doKeyChar ((int) wParam, lParam))
  208057. return 0;
  208058. break;
  208059. case WM_APPCOMMAND:
  208060. if (doAppCommand (lParam))
  208061. return TRUE;
  208062. break;
  208063. case WM_SETFOCUS:
  208064. updateKeyModifiers();
  208065. handleFocusGain();
  208066. break;
  208067. case WM_KILLFOCUS:
  208068. if (hasCreatedCaret)
  208069. {
  208070. hasCreatedCaret = false;
  208071. DestroyCaret();
  208072. }
  208073. handleFocusLoss();
  208074. break;
  208075. case WM_ACTIVATEAPP:
  208076. // Windows does weird things to process priority when you swap apps,
  208077. // so this forces an update when the app is brought to the front
  208078. if (wParam != FALSE)
  208079. juce_repeatLastProcessPriority();
  208080. else
  208081. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208082. juce_CheckCurrentlyFocusedTopLevelWindow();
  208083. modifiersAtLastCallback = -1;
  208084. return 0;
  208085. case WM_ACTIVATE:
  208086. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208087. {
  208088. modifiersAtLastCallback = -1;
  208089. updateKeyModifiers();
  208090. if (isMinimised())
  208091. {
  208092. component->repaint();
  208093. handleMovedOrResized();
  208094. if (! ComponentPeer::isValidPeer (this))
  208095. return 0;
  208096. }
  208097. if (LOWORD (wParam) == WA_CLICKACTIVE
  208098. && component->isCurrentlyBlockedByAnotherModalComponent())
  208099. {
  208100. const Point<int> mousePos (component->getMouseXYRelative());
  208101. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  208102. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208103. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208104. return 0;
  208105. }
  208106. handleBroughtToFront();
  208107. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208108. Component::getCurrentlyModalComponent()->toFront (true);
  208109. return 0;
  208110. }
  208111. break;
  208112. case WM_NCACTIVATE:
  208113. // while a temporary window is being shown, prevent Windows from deactivating the
  208114. // title bars of our main windows.
  208115. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208116. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208117. break;
  208118. case WM_MOUSEACTIVATE:
  208119. if (! component->getMouseClickGrabsKeyboardFocus())
  208120. return MA_NOACTIVATE;
  208121. break;
  208122. case WM_SHOWWINDOW:
  208123. if (wParam != 0)
  208124. handleBroughtToFront();
  208125. break;
  208126. case WM_CLOSE:
  208127. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208128. handleUserClosingWindow();
  208129. return 0;
  208130. case WM_QUERYENDSESSION:
  208131. if (JUCEApplication::getInstance() != 0)
  208132. {
  208133. JUCEApplication::getInstance()->systemRequestedQuit();
  208134. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208135. }
  208136. return TRUE;
  208137. case WM_TRAYNOTIFY:
  208138. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208139. {
  208140. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  208141. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208142. {
  208143. Component* const current = Component::getCurrentlyModalComponent();
  208144. if (current != 0)
  208145. current->inputAttemptWhenModal();
  208146. }
  208147. }
  208148. else
  208149. {
  208150. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  208151. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  208152. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  208153. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  208154. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  208155. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208156. eventMods = eventMods.withoutMouseButtons();
  208157. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  208158. Point<int>(), eventMods, component, component, getMouseEventTime(),
  208159. Point<int>(), getMouseEventTime(), 1, false);
  208160. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  208161. {
  208162. SetFocus (hwnd);
  208163. SetForegroundWindow (hwnd);
  208164. component->mouseDown (e);
  208165. }
  208166. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208167. {
  208168. component->mouseUp (e);
  208169. }
  208170. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208171. {
  208172. component->mouseDoubleClick (e);
  208173. }
  208174. else if (lParam == WM_MOUSEMOVE)
  208175. {
  208176. component->mouseMove (e);
  208177. }
  208178. }
  208179. break;
  208180. case WM_SYNCPAINT:
  208181. return 0;
  208182. case WM_PALETTECHANGED:
  208183. InvalidateRect (h, 0, 0);
  208184. break;
  208185. case WM_DISPLAYCHANGE:
  208186. InvalidateRect (h, 0, 0);
  208187. createPaletteIfNeeded = true;
  208188. // intentional fall-through...
  208189. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208190. doSettingChange();
  208191. break;
  208192. case WM_INITMENU:
  208193. if (! hasTitleBar())
  208194. {
  208195. if (isFullScreen())
  208196. {
  208197. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208198. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208199. }
  208200. else if (! isMinimised())
  208201. {
  208202. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208203. }
  208204. }
  208205. break;
  208206. case WM_SYSCOMMAND:
  208207. switch (wParam & 0xfff0)
  208208. {
  208209. case SC_CLOSE:
  208210. if (sendInputAttemptWhenModalMessage())
  208211. return 0;
  208212. if (hasTitleBar())
  208213. {
  208214. PostMessage (h, WM_CLOSE, 0, 0);
  208215. return 0;
  208216. }
  208217. break;
  208218. case SC_KEYMENU:
  208219. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  208220. // obscure situations that can arise if a modal loop is started from an alt-key
  208221. // keypress).
  208222. if (hasTitleBar() && h == GetCapture())
  208223. ReleaseCapture();
  208224. break;
  208225. case SC_MAXIMIZE:
  208226. if (sendInputAttemptWhenModalMessage())
  208227. return 0;
  208228. setFullScreen (true);
  208229. return 0;
  208230. case SC_MINIMIZE:
  208231. if (sendInputAttemptWhenModalMessage())
  208232. return 0;
  208233. if (! hasTitleBar())
  208234. {
  208235. setMinimised (true);
  208236. return 0;
  208237. }
  208238. break;
  208239. case SC_RESTORE:
  208240. if (sendInputAttemptWhenModalMessage())
  208241. return 0;
  208242. if (hasTitleBar())
  208243. {
  208244. if (isFullScreen())
  208245. {
  208246. setFullScreen (false);
  208247. return 0;
  208248. }
  208249. }
  208250. else
  208251. {
  208252. if (isMinimised())
  208253. setMinimised (false);
  208254. else if (isFullScreen())
  208255. setFullScreen (false);
  208256. return 0;
  208257. }
  208258. break;
  208259. }
  208260. break;
  208261. case WM_NCLBUTTONDOWN:
  208262. case WM_NCRBUTTONDOWN:
  208263. case WM_NCMBUTTONDOWN:
  208264. sendInputAttemptWhenModalMessage();
  208265. break;
  208266. //case WM_IME_STARTCOMPOSITION;
  208267. // return 0;
  208268. case WM_GETDLGCODE:
  208269. return DLGC_WANTALLKEYS;
  208270. default:
  208271. break;
  208272. }
  208273. }
  208274. return DefWindowProcW (h, message, wParam, lParam);
  208275. }
  208276. bool sendInputAttemptWhenModalMessage()
  208277. {
  208278. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208279. {
  208280. Component* const current = Component::getCurrentlyModalComponent();
  208281. if (current != 0)
  208282. current->inputAttemptWhenModal();
  208283. return true;
  208284. }
  208285. return false;
  208286. }
  208287. Win32ComponentPeer (const Win32ComponentPeer&);
  208288. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208289. };
  208290. ModifierKeys Win32ComponentPeer::currentModifiers;
  208291. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208292. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208293. {
  208294. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208295. }
  208296. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208297. void ModifierKeys::updateCurrentModifiers() throw()
  208298. {
  208299. currentModifiers = Win32ComponentPeer::currentModifiers;
  208300. }
  208301. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208302. {
  208303. Win32ComponentPeer::updateKeyModifiers();
  208304. int keyMods = 0;
  208305. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  208306. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  208307. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  208308. Win32ComponentPeer::currentModifiers
  208309. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  208310. return Win32ComponentPeer::currentModifiers;
  208311. }
  208312. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208313. {
  208314. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208315. if (wp != 0)
  208316. wp->setTaskBarIcon (newImage);
  208317. }
  208318. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208319. {
  208320. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208321. if (wp != 0)
  208322. wp->setTaskBarIconToolTip (tooltip);
  208323. }
  208324. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208325. {
  208326. DWORD val = GetWindowLong (h, styleType);
  208327. if (bitIsSet)
  208328. val |= feature;
  208329. else
  208330. val &= ~feature;
  208331. SetWindowLongPtr (h, styleType, val);
  208332. SetWindowPos (h, 0, 0, 0, 0, 0,
  208333. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208334. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208335. }
  208336. bool Process::isForegroundProcess()
  208337. {
  208338. HWND fg = GetForegroundWindow();
  208339. if (fg == 0)
  208340. return true;
  208341. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208342. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208343. // have to see if any of our windows are children of the foreground window
  208344. fg = GetAncestor (fg, GA_ROOT);
  208345. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208346. {
  208347. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208348. if (wp != 0 && wp->isInside (fg))
  208349. return true;
  208350. }
  208351. return false;
  208352. }
  208353. bool AlertWindow::showNativeDialogBox (const String& title,
  208354. const String& bodyText,
  208355. bool isOkCancel)
  208356. {
  208357. return MessageBox (0, bodyText, title,
  208358. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208359. : MB_OK)) == IDOK;
  208360. }
  208361. void Desktop::createMouseInputSources()
  208362. {
  208363. mouseSources.add (new MouseInputSource (0, true));
  208364. }
  208365. const Point<int> Desktop::getMousePosition()
  208366. {
  208367. POINT mousePos;
  208368. GetCursorPos (&mousePos);
  208369. return Point<int> (mousePos.x, mousePos.y);
  208370. }
  208371. void Desktop::setMousePosition (const Point<int>& newPosition)
  208372. {
  208373. SetCursorPos (newPosition.getX(), newPosition.getY());
  208374. }
  208375. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208376. {
  208377. return createSoftwareImage (format, width, height, clearImage);
  208378. }
  208379. class ScreenSaverDefeater : public Timer,
  208380. public DeletedAtShutdown
  208381. {
  208382. public:
  208383. ScreenSaverDefeater()
  208384. {
  208385. startTimer (10000);
  208386. timerCallback();
  208387. }
  208388. ~ScreenSaverDefeater() {}
  208389. void timerCallback()
  208390. {
  208391. if (Process::isForegroundProcess())
  208392. {
  208393. // simulate a shift key getting pressed..
  208394. INPUT input[2];
  208395. input[0].type = INPUT_KEYBOARD;
  208396. input[0].ki.wVk = VK_SHIFT;
  208397. input[0].ki.dwFlags = 0;
  208398. input[0].ki.dwExtraInfo = 0;
  208399. input[1].type = INPUT_KEYBOARD;
  208400. input[1].ki.wVk = VK_SHIFT;
  208401. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208402. input[1].ki.dwExtraInfo = 0;
  208403. SendInput (2, input, sizeof (INPUT));
  208404. }
  208405. }
  208406. };
  208407. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208408. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208409. {
  208410. if (isEnabled)
  208411. deleteAndZero (screenSaverDefeater);
  208412. else if (screenSaverDefeater == 0)
  208413. screenSaverDefeater = new ScreenSaverDefeater();
  208414. }
  208415. bool Desktop::isScreenSaverEnabled()
  208416. {
  208417. return screenSaverDefeater == 0;
  208418. }
  208419. /* (The code below is the "correct" way to disable the screen saver, but it
  208420. completely fails on winXP when the saver is password-protected...)
  208421. static bool juce_screenSaverEnabled = true;
  208422. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208423. {
  208424. juce_screenSaverEnabled = isEnabled;
  208425. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208426. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208427. }
  208428. bool Desktop::isScreenSaverEnabled() throw()
  208429. {
  208430. return juce_screenSaverEnabled;
  208431. }
  208432. */
  208433. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208434. {
  208435. if (enableOrDisable)
  208436. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208437. }
  208438. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208439. {
  208440. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208441. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208442. return TRUE;
  208443. }
  208444. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208445. {
  208446. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208447. // make sure the first in the list is the main monitor
  208448. for (int i = 1; i < monitorCoords.size(); ++i)
  208449. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208450. monitorCoords.swap (i, 0);
  208451. if (monitorCoords.size() == 0)
  208452. {
  208453. RECT r;
  208454. GetWindowRect (GetDesktopWindow(), &r);
  208455. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208456. }
  208457. if (clipToWorkArea)
  208458. {
  208459. // clip the main monitor to the active non-taskbar area
  208460. RECT r;
  208461. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208462. Rectangle<int>& screen = monitorCoords.getReference (0);
  208463. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208464. jmax (screen.getY(), (int) r.top));
  208465. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208466. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208467. }
  208468. }
  208469. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  208470. {
  208471. Image im;
  208472. if (bitmap != 0)
  208473. {
  208474. BITMAP bm;
  208475. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208476. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208477. {
  208478. HDC tempDC = GetDC (0);
  208479. HDC dc = CreateCompatibleDC (tempDC);
  208480. ReleaseDC (0, tempDC);
  208481. SelectObject (dc, bitmap);
  208482. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208483. Image::BitmapData imageData (im, true);
  208484. for (int y = bm.bmHeight; --y >= 0;)
  208485. {
  208486. for (int x = bm.bmWidth; --x >= 0;)
  208487. {
  208488. COLORREF col = GetPixel (dc, x, y);
  208489. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  208490. (uint8) GetGValue (col),
  208491. (uint8) GetBValue (col)));
  208492. }
  208493. }
  208494. DeleteDC (dc);
  208495. }
  208496. }
  208497. return im;
  208498. }
  208499. static const Image createImageFromHICON (HICON icon)
  208500. {
  208501. ICONINFO info;
  208502. if (GetIconInfo (icon, &info))
  208503. {
  208504. Image mask (createImageFromHBITMAP (info.hbmMask));
  208505. Image image (createImageFromHBITMAP (info.hbmColor));
  208506. if (mask.isValid() && image.isValid())
  208507. {
  208508. for (int y = image.getHeight(); --y >= 0;)
  208509. {
  208510. for (int x = image.getWidth(); --x >= 0;)
  208511. {
  208512. const float brightness = mask.getPixelAt (x, y).getBrightness();
  208513. if (brightness > 0.0f)
  208514. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  208515. }
  208516. }
  208517. return image;
  208518. }
  208519. }
  208520. return Image::null;
  208521. }
  208522. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  208523. {
  208524. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208525. Image bitmap (nativeBitmap);
  208526. {
  208527. Graphics g (bitmap);
  208528. g.drawImageAt (image, 0, 0);
  208529. }
  208530. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208531. ICONINFO info;
  208532. info.fIcon = isIcon;
  208533. info.xHotspot = hotspotX;
  208534. info.yHotspot = hotspotY;
  208535. info.hbmMask = mask;
  208536. info.hbmColor = nativeBitmap->hBitmap;
  208537. HICON hi = CreateIconIndirect (&info);
  208538. DeleteObject (mask);
  208539. return hi;
  208540. }
  208541. const Image juce_createIconForFile (const File& file)
  208542. {
  208543. Image image;
  208544. WCHAR filename [1024];
  208545. file.getFullPathName().copyToUnicode (filename, 1023);
  208546. WORD iconNum = 0;
  208547. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208548. filename, &iconNum);
  208549. if (icon != 0)
  208550. {
  208551. image = createImageFromHICON (icon);
  208552. DestroyIcon (icon);
  208553. }
  208554. return image;
  208555. }
  208556. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208557. {
  208558. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208559. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208560. Image im (image);
  208561. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208562. {
  208563. im = im.rescaled (maxW, maxH);
  208564. hotspotX = (hotspotX * maxW) / image.getWidth();
  208565. hotspotY = (hotspotY * maxH) / image.getHeight();
  208566. }
  208567. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208568. }
  208569. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208570. {
  208571. if (cursorHandle != 0 && ! isStandard)
  208572. DestroyCursor ((HCURSOR) cursorHandle);
  208573. }
  208574. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208575. {
  208576. LPCTSTR cursorName = IDC_ARROW;
  208577. switch (type)
  208578. {
  208579. case NormalCursor: break;
  208580. case NoCursor: return 0;
  208581. case WaitCursor: cursorName = IDC_WAIT; break;
  208582. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208583. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208584. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208585. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208586. case LeftRightResizeCursor:
  208587. case LeftEdgeResizeCursor:
  208588. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208589. case UpDownResizeCursor:
  208590. case TopEdgeResizeCursor:
  208591. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208592. case TopLeftCornerResizeCursor:
  208593. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208594. case TopRightCornerResizeCursor:
  208595. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208596. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208597. case DraggingHandCursor:
  208598. {
  208599. static void* dragHandCursor = 0;
  208600. if (dragHandCursor == 0)
  208601. {
  208602. static const unsigned char dragHandData[] =
  208603. { 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,
  208604. 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,
  208605. 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 };
  208606. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208607. }
  208608. return dragHandCursor;
  208609. }
  208610. default:
  208611. jassertfalse; break;
  208612. }
  208613. HCURSOR cursorH = LoadCursor (0, cursorName);
  208614. if (cursorH == 0)
  208615. cursorH = LoadCursor (0, IDC_ARROW);
  208616. return cursorH;
  208617. }
  208618. void MouseCursor::showInWindow (ComponentPeer*) const
  208619. {
  208620. SetCursor ((HCURSOR) getHandle());
  208621. }
  208622. void MouseCursor::showInAllWindows() const
  208623. {
  208624. showInWindow (0);
  208625. }
  208626. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208627. {
  208628. public:
  208629. JuceDropSource() {}
  208630. ~JuceDropSource() {}
  208631. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208632. {
  208633. if (escapePressed)
  208634. return DRAGDROP_S_CANCEL;
  208635. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208636. return DRAGDROP_S_DROP;
  208637. return S_OK;
  208638. }
  208639. HRESULT __stdcall GiveFeedback (DWORD)
  208640. {
  208641. return DRAGDROP_S_USEDEFAULTCURSORS;
  208642. }
  208643. };
  208644. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208645. {
  208646. public:
  208647. JuceEnumFormatEtc (const FORMATETC* const format_)
  208648. : format (format_),
  208649. index (0)
  208650. {
  208651. }
  208652. ~JuceEnumFormatEtc() {}
  208653. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208654. {
  208655. if (result == 0)
  208656. return E_POINTER;
  208657. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208658. newOne->index = index;
  208659. *result = newOne;
  208660. return S_OK;
  208661. }
  208662. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208663. {
  208664. if (pceltFetched != 0)
  208665. *pceltFetched = 0;
  208666. else if (celt != 1)
  208667. return S_FALSE;
  208668. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208669. {
  208670. copyFormatEtc (lpFormatEtc [0], *format);
  208671. ++index;
  208672. if (pceltFetched != 0)
  208673. *pceltFetched = 1;
  208674. return S_OK;
  208675. }
  208676. return S_FALSE;
  208677. }
  208678. HRESULT __stdcall Skip (ULONG celt)
  208679. {
  208680. if (index + (int) celt >= 1)
  208681. return S_FALSE;
  208682. index += celt;
  208683. return S_OK;
  208684. }
  208685. HRESULT __stdcall Reset()
  208686. {
  208687. index = 0;
  208688. return S_OK;
  208689. }
  208690. private:
  208691. const FORMATETC* const format;
  208692. int index;
  208693. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208694. {
  208695. dest = source;
  208696. if (source.ptd != 0)
  208697. {
  208698. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208699. *(dest.ptd) = *(source.ptd);
  208700. }
  208701. }
  208702. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208703. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208704. };
  208705. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208706. {
  208707. public:
  208708. JuceDataObject (JuceDropSource* const dropSource_,
  208709. const FORMATETC* const format_,
  208710. const STGMEDIUM* const medium_)
  208711. : dropSource (dropSource_),
  208712. format (format_),
  208713. medium (medium_)
  208714. {
  208715. }
  208716. virtual ~JuceDataObject()
  208717. {
  208718. jassert (refCount == 0);
  208719. }
  208720. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  208721. {
  208722. if ((pFormatEtc->tymed & format->tymed) != 0
  208723. && pFormatEtc->cfFormat == format->cfFormat
  208724. && pFormatEtc->dwAspect == format->dwAspect)
  208725. {
  208726. pMedium->tymed = format->tymed;
  208727. pMedium->pUnkForRelease = 0;
  208728. if (format->tymed == TYMED_HGLOBAL)
  208729. {
  208730. const SIZE_T len = GlobalSize (medium->hGlobal);
  208731. void* const src = GlobalLock (medium->hGlobal);
  208732. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208733. memcpy (dst, src, len);
  208734. GlobalUnlock (medium->hGlobal);
  208735. pMedium->hGlobal = dst;
  208736. return S_OK;
  208737. }
  208738. }
  208739. return DV_E_FORMATETC;
  208740. }
  208741. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  208742. {
  208743. if (f == 0)
  208744. return E_INVALIDARG;
  208745. if (f->tymed == format->tymed
  208746. && f->cfFormat == format->cfFormat
  208747. && f->dwAspect == format->dwAspect)
  208748. return S_OK;
  208749. return DV_E_FORMATETC;
  208750. }
  208751. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  208752. {
  208753. pFormatEtcOut->ptd = 0;
  208754. return E_NOTIMPL;
  208755. }
  208756. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  208757. {
  208758. if (result == 0)
  208759. return E_POINTER;
  208760. if (direction == DATADIR_GET)
  208761. {
  208762. *result = new JuceEnumFormatEtc (format);
  208763. return S_OK;
  208764. }
  208765. *result = 0;
  208766. return E_NOTIMPL;
  208767. }
  208768. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  208769. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  208770. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  208771. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208772. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  208773. private:
  208774. JuceDropSource* const dropSource;
  208775. const FORMATETC* const format;
  208776. const STGMEDIUM* const medium;
  208777. JuceDataObject (const JuceDataObject&);
  208778. JuceDataObject& operator= (const JuceDataObject&);
  208779. };
  208780. static HDROP createHDrop (const StringArray& fileNames)
  208781. {
  208782. int totalChars = 0;
  208783. for (int i = fileNames.size(); --i >= 0;)
  208784. totalChars += fileNames[i].length() + 1;
  208785. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208786. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208787. if (hDrop != 0)
  208788. {
  208789. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208790. pDropFiles->pFiles = sizeof (DROPFILES);
  208791. pDropFiles->fWide = true;
  208792. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208793. for (int i = 0; i < fileNames.size(); ++i)
  208794. {
  208795. fileNames[i].copyToUnicode (fname, 2048);
  208796. fname += fileNames[i].length() + 1;
  208797. }
  208798. *fname = 0;
  208799. GlobalUnlock (hDrop);
  208800. }
  208801. return hDrop;
  208802. }
  208803. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208804. {
  208805. JuceDropSource* const source = new JuceDropSource();
  208806. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208807. DWORD effect;
  208808. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208809. data->Release();
  208810. source->Release();
  208811. return res == DRAGDROP_S_DROP;
  208812. }
  208813. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208814. {
  208815. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208816. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208817. medium.hGlobal = createHDrop (files);
  208818. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208819. : DROPEFFECT_COPY);
  208820. }
  208821. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208822. {
  208823. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208824. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208825. const int numChars = text.length();
  208826. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208827. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208828. text.copyToUnicode (data, numChars + 1);
  208829. format.cfFormat = CF_UNICODETEXT;
  208830. GlobalUnlock (medium.hGlobal);
  208831. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208832. }
  208833. #endif
  208834. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208835. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208836. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208837. // compiled on its own).
  208838. #if JUCE_INCLUDED_FILE
  208839. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  208840. namespace FileChooserHelpers
  208841. {
  208842. static const void* defaultDirPath = 0;
  208843. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  208844. static Component* currentExtraFileWin = 0;
  208845. static bool areThereAnyAlwaysOnTopWindows()
  208846. {
  208847. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208848. {
  208849. Component* c = Desktop::getInstance().getComponent (i);
  208850. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208851. return true;
  208852. }
  208853. return false;
  208854. }
  208855. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  208856. {
  208857. if (msg == BFFM_INITIALIZED)
  208858. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  208859. else if (msg == BFFM_VALIDATEFAILEDW)
  208860. returnedString = (LPCWSTR) lParam;
  208861. else if (msg == BFFM_VALIDATEFAILEDA)
  208862. returnedString = (const char*) lParam;
  208863. return 0;
  208864. }
  208865. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208866. {
  208867. if (currentExtraFileWin != 0)
  208868. {
  208869. if (uiMsg == WM_INITDIALOG)
  208870. {
  208871. HWND dialogH = GetParent (hdlg);
  208872. jassert (dialogH != 0);
  208873. if (dialogH == 0)
  208874. dialogH = hdlg;
  208875. RECT r, cr;
  208876. GetWindowRect (dialogH, &r);
  208877. GetClientRect (dialogH, &cr);
  208878. SetWindowPos (dialogH, 0,
  208879. r.left, r.top,
  208880. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  208881. jmax (150, (int) (r.bottom - r.top)),
  208882. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208883. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  208884. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  208885. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  208886. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  208887. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  208888. }
  208889. else if (uiMsg == WM_NOTIFY)
  208890. {
  208891. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208892. if (ofn->hdr.code == CDN_SELCHANGE)
  208893. {
  208894. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  208895. if (comp != 0)
  208896. {
  208897. TCHAR path [MAX_PATH * 2];
  208898. path[0] = 0;
  208899. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208900. const String fn ((const WCHAR*) path);
  208901. comp->selectedFileChanged (File (fn));
  208902. }
  208903. }
  208904. }
  208905. }
  208906. return 0;
  208907. }
  208908. class FPComponentHolder : public Component
  208909. {
  208910. public:
  208911. FPComponentHolder()
  208912. {
  208913. setVisible (true);
  208914. setOpaque (true);
  208915. }
  208916. ~FPComponentHolder()
  208917. {
  208918. }
  208919. void paint (Graphics& g)
  208920. {
  208921. g.fillAll (Colours::lightgrey);
  208922. }
  208923. private:
  208924. FPComponentHolder (const FPComponentHolder&);
  208925. FPComponentHolder& operator= (const FPComponentHolder&);
  208926. };
  208927. }
  208928. void FileChooser::showPlatformDialog (Array<File>& results,
  208929. const String& title,
  208930. const File& currentFileOrDirectory,
  208931. const String& filter,
  208932. bool selectsDirectory,
  208933. bool /*selectsFiles*/,
  208934. bool isSaveDialogue,
  208935. bool warnAboutOverwritingExistingFiles,
  208936. bool selectMultipleFiles,
  208937. FilePreviewComponent* extraInfoComponent)
  208938. {
  208939. using namespace FileChooserHelpers;
  208940. const int numCharsAvailable = 32768;
  208941. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  208942. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  208943. int fnameIdx = 0;
  208944. JUCE_TRY
  208945. {
  208946. // use a modal window as the parent for this dialog box
  208947. // to block input from other app windows
  208948. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208949. Component w (String::empty);
  208950. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208951. mainMon.getY() + mainMon.getHeight() / 4,
  208952. 0, 0);
  208953. w.setOpaque (true);
  208954. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208955. w.addToDesktop (0);
  208956. if (extraInfoComponent == 0)
  208957. w.enterModalState();
  208958. String initialDir;
  208959. if (currentFileOrDirectory.isDirectory())
  208960. {
  208961. initialDir = currentFileOrDirectory.getFullPathName();
  208962. }
  208963. else
  208964. {
  208965. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  208966. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208967. }
  208968. if (currentExtraFileWin->isValidComponent())
  208969. {
  208970. jassertfalse;
  208971. return;
  208972. }
  208973. if (selectsDirectory)
  208974. {
  208975. LPITEMIDLIST list = 0;
  208976. filenameSpace.fillWith (0);
  208977. {
  208978. BROWSEINFO bi;
  208979. zerostruct (bi);
  208980. bi.hwndOwner = (HWND) w.getWindowHandle();
  208981. bi.pszDisplayName = fname;
  208982. bi.lpszTitle = title;
  208983. bi.lpfn = browseCallbackProc;
  208984. #ifdef BIF_USENEWUI
  208985. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208986. #else
  208987. bi.ulFlags = 0x50;
  208988. #endif
  208989. defaultDirPath = (const WCHAR*) initialDir;
  208990. list = SHBrowseForFolder (&bi);
  208991. if (! SHGetPathFromIDListW (list, fname))
  208992. {
  208993. fname[0] = 0;
  208994. returnedString = String::empty;
  208995. }
  208996. }
  208997. LPMALLOC al;
  208998. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208999. al->Free (list);
  209000. defaultDirPath = 0;
  209001. if (returnedString.isNotEmpty())
  209002. {
  209003. const String stringFName (fname);
  209004. results.add (File (stringFName).getSiblingFile (returnedString));
  209005. returnedString = String::empty;
  209006. return;
  209007. }
  209008. }
  209009. else
  209010. {
  209011. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209012. if (warnAboutOverwritingExistingFiles)
  209013. flags |= OFN_OVERWRITEPROMPT;
  209014. if (selectMultipleFiles)
  209015. flags |= OFN_ALLOWMULTISELECT;
  209016. if (extraInfoComponent != 0)
  209017. {
  209018. flags |= OFN_ENABLEHOOK;
  209019. currentExtraFileWin = new FPComponentHolder();
  209020. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  209021. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  209022. extraInfoComponent->getHeight());
  209023. currentExtraFileWin->addToDesktop (0);
  209024. currentExtraFileWin->enterModalState();
  209025. }
  209026. {
  209027. WCHAR filters [1024];
  209028. zeromem (filters, sizeof (filters));
  209029. filter.copyToUnicode (filters, 1024);
  209030. filter.copyToUnicode (filters + filter.length() + 1,
  209031. 1022 - filter.length());
  209032. OPENFILENAMEW of;
  209033. zerostruct (of);
  209034. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209035. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209036. #else
  209037. of.lStructSize = sizeof (of);
  209038. #endif
  209039. of.hwndOwner = (HWND) w.getWindowHandle();
  209040. of.lpstrFilter = filters;
  209041. of.nFilterIndex = 1;
  209042. of.lpstrFile = fname;
  209043. of.nMaxFile = numCharsAvailable;
  209044. of.lpstrInitialDir = initialDir;
  209045. of.lpstrTitle = title;
  209046. of.Flags = flags;
  209047. if (extraInfoComponent != 0)
  209048. of.lpfnHook = &openCallback;
  209049. if (isSaveDialogue)
  209050. {
  209051. if (! GetSaveFileName (&of))
  209052. fname[0] = 0;
  209053. else
  209054. fnameIdx = of.nFileOffset;
  209055. }
  209056. else
  209057. {
  209058. if (! GetOpenFileName (&of))
  209059. fname[0] = 0;
  209060. else
  209061. fnameIdx = of.nFileOffset;
  209062. }
  209063. }
  209064. }
  209065. }
  209066. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  209067. catch (...)
  209068. {
  209069. fname[0] = 0;
  209070. }
  209071. #endif
  209072. deleteAndZero (currentExtraFileWin);
  209073. const WCHAR* const files = fname;
  209074. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  209075. {
  209076. const WCHAR* filename = files + fnameIdx;
  209077. while (*filename != 0)
  209078. {
  209079. const String filepath (String (files) + "\\" + String (filename));
  209080. results.add (File (filepath));
  209081. filename += CharacterFunctions::length (filename) + 1;
  209082. }
  209083. }
  209084. else if (files[0] != 0)
  209085. {
  209086. results.add (File (files));
  209087. }
  209088. }
  209089. #endif
  209090. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209091. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209092. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209093. // compiled on its own).
  209094. #if JUCE_INCLUDED_FILE
  209095. void SystemClipboard::copyTextToClipboard (const String& text)
  209096. {
  209097. if (OpenClipboard (0) != 0)
  209098. {
  209099. if (EmptyClipboard() != 0)
  209100. {
  209101. const int len = text.length();
  209102. if (len > 0)
  209103. {
  209104. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209105. (len + 1) * sizeof (wchar_t));
  209106. if (bufH != 0)
  209107. {
  209108. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209109. text.copyToUnicode (data, len);
  209110. GlobalUnlock (bufH);
  209111. SetClipboardData (CF_UNICODETEXT, bufH);
  209112. }
  209113. }
  209114. }
  209115. CloseClipboard();
  209116. }
  209117. }
  209118. const String SystemClipboard::getTextFromClipboard()
  209119. {
  209120. String result;
  209121. if (OpenClipboard (0) != 0)
  209122. {
  209123. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209124. if (bufH != 0)
  209125. {
  209126. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209127. if (data != 0)
  209128. {
  209129. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209130. GlobalUnlock (bufH);
  209131. }
  209132. }
  209133. CloseClipboard();
  209134. }
  209135. return result;
  209136. }
  209137. #endif
  209138. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209139. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209140. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209141. // compiled on its own).
  209142. #if JUCE_INCLUDED_FILE
  209143. namespace ActiveXHelpers
  209144. {
  209145. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209146. {
  209147. public:
  209148. JuceIStorage() {}
  209149. ~JuceIStorage() {}
  209150. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209151. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209152. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209153. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209154. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209155. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209156. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209157. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209158. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209159. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209160. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209161. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209162. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209163. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209164. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209165. juce_UseDebuggingNewOperator
  209166. };
  209167. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209168. {
  209169. HWND window;
  209170. public:
  209171. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209172. ~JuceOleInPlaceFrame() {}
  209173. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209174. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209175. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209176. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209177. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209178. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209179. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209180. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209181. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209182. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209183. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209184. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209185. juce_UseDebuggingNewOperator
  209186. };
  209187. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209188. {
  209189. HWND window;
  209190. JuceOleInPlaceFrame* frame;
  209191. public:
  209192. JuceIOleInPlaceSite (HWND window_)
  209193. : window (window_),
  209194. frame (new JuceOleInPlaceFrame (window))
  209195. {}
  209196. ~JuceIOleInPlaceSite()
  209197. {
  209198. frame->Release();
  209199. }
  209200. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209201. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209202. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209203. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209204. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209205. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209206. {
  209207. *lplpFrame = frame;
  209208. *lplpDoc = 0;
  209209. lpFrameInfo->fMDIApp = FALSE;
  209210. lpFrameInfo->hwndFrame = window;
  209211. lpFrameInfo->haccel = 0;
  209212. lpFrameInfo->cAccelEntries = 0;
  209213. return S_OK;
  209214. }
  209215. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209216. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209217. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209218. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209219. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209220. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209221. juce_UseDebuggingNewOperator
  209222. };
  209223. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209224. {
  209225. JuceIOleInPlaceSite* inplaceSite;
  209226. public:
  209227. JuceIOleClientSite (HWND window)
  209228. : inplaceSite (new JuceIOleInPlaceSite (window))
  209229. {}
  209230. ~JuceIOleClientSite()
  209231. {
  209232. inplaceSite->Release();
  209233. }
  209234. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  209235. {
  209236. if (type == IID_IOleInPlaceSite)
  209237. {
  209238. inplaceSite->AddRef();
  209239. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209240. return S_OK;
  209241. }
  209242. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209243. }
  209244. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209245. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209246. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209247. HRESULT __stdcall ShowObject() { return S_OK; }
  209248. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209249. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209250. juce_UseDebuggingNewOperator
  209251. };
  209252. static Array<ActiveXControlComponent*> activeXComps;
  209253. static HWND getHWND (const ActiveXControlComponent* const component)
  209254. {
  209255. HWND hwnd = 0;
  209256. const IID iid = IID_IOleWindow;
  209257. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209258. if (window != 0)
  209259. {
  209260. window->GetWindow (&hwnd);
  209261. window->Release();
  209262. }
  209263. return hwnd;
  209264. }
  209265. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209266. {
  209267. RECT activeXRect, peerRect;
  209268. GetWindowRect (hwnd, &activeXRect);
  209269. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209270. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209271. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209272. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209273. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209274. switch (message)
  209275. {
  209276. case WM_MOUSEMOVE:
  209277. case WM_LBUTTONDOWN:
  209278. case WM_MBUTTONDOWN:
  209279. case WM_RBUTTONDOWN:
  209280. case WM_LBUTTONUP:
  209281. case WM_MBUTTONUP:
  209282. case WM_RBUTTONUP:
  209283. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209284. break;
  209285. default:
  209286. break;
  209287. }
  209288. }
  209289. }
  209290. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209291. {
  209292. ActiveXControlComponent* const owner;
  209293. bool wasShowing;
  209294. public:
  209295. HWND controlHWND;
  209296. IStorage* storage;
  209297. IOleClientSite* clientSite;
  209298. IOleObject* control;
  209299. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  209300. : ComponentMovementWatcher (owner_),
  209301. owner (owner_),
  209302. wasShowing (owner_ != 0 && owner_->isShowing()),
  209303. controlHWND (0),
  209304. storage (new ActiveXHelpers::JuceIStorage()),
  209305. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209306. control (0)
  209307. {
  209308. }
  209309. ~Pimpl()
  209310. {
  209311. if (control != 0)
  209312. {
  209313. control->Close (OLECLOSE_NOSAVE);
  209314. control->Release();
  209315. }
  209316. clientSite->Release();
  209317. storage->Release();
  209318. }
  209319. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209320. {
  209321. Component* const topComp = owner->getTopLevelComponent();
  209322. if (topComp->getPeer() != 0)
  209323. {
  209324. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  209325. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  209326. }
  209327. }
  209328. void componentPeerChanged()
  209329. {
  209330. const bool isShowingNow = owner->isShowing();
  209331. if (wasShowing != isShowingNow)
  209332. {
  209333. wasShowing = isShowingNow;
  209334. owner->setControlVisible (isShowingNow);
  209335. }
  209336. componentMovedOrResized (true, true);
  209337. }
  209338. void componentVisibilityChanged (Component&)
  209339. {
  209340. componentPeerChanged();
  209341. }
  209342. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209343. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209344. {
  209345. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209346. {
  209347. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209348. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209349. {
  209350. switch (message)
  209351. {
  209352. case WM_MOUSEMOVE:
  209353. case WM_LBUTTONDOWN:
  209354. case WM_MBUTTONDOWN:
  209355. case WM_RBUTTONDOWN:
  209356. case WM_LBUTTONUP:
  209357. case WM_MBUTTONUP:
  209358. case WM_RBUTTONUP:
  209359. case WM_LBUTTONDBLCLK:
  209360. case WM_MBUTTONDBLCLK:
  209361. case WM_RBUTTONDBLCLK:
  209362. if (ax->isShowing())
  209363. {
  209364. ComponentPeer* const peer = ax->getPeer();
  209365. if (peer != 0)
  209366. {
  209367. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209368. if (! ax->areMouseEventsAllowed())
  209369. return 0;
  209370. }
  209371. }
  209372. break;
  209373. default:
  209374. break;
  209375. }
  209376. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209377. }
  209378. }
  209379. return DefWindowProc (hwnd, message, wParam, lParam);
  209380. }
  209381. };
  209382. ActiveXControlComponent::ActiveXControlComponent()
  209383. : originalWndProc (0),
  209384. mouseEventsAllowed (true)
  209385. {
  209386. ActiveXHelpers::activeXComps.add (this);
  209387. }
  209388. ActiveXControlComponent::~ActiveXControlComponent()
  209389. {
  209390. deleteControl();
  209391. ActiveXHelpers::activeXComps.removeValue (this);
  209392. }
  209393. void ActiveXControlComponent::paint (Graphics& g)
  209394. {
  209395. if (control == 0)
  209396. g.fillAll (Colours::lightgrey);
  209397. }
  209398. bool ActiveXControlComponent::createControl (const void* controlIID)
  209399. {
  209400. deleteControl();
  209401. ComponentPeer* const peer = getPeer();
  209402. // the component must have already been added to a real window when you call this!
  209403. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209404. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209405. {
  209406. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209407. HWND hwnd = (HWND) peer->getNativeHandle();
  209408. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  209409. HRESULT hr;
  209410. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209411. newControl->clientSite, newControl->storage,
  209412. (void**) &(newControl->control))) == S_OK)
  209413. {
  209414. newControl->control->SetHostNames (L"Juce", 0);
  209415. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209416. {
  209417. RECT rect;
  209418. rect.left = pos.getX();
  209419. rect.top = pos.getY();
  209420. rect.right = pos.getX() + getWidth();
  209421. rect.bottom = pos.getY() + getHeight();
  209422. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209423. {
  209424. control = newControl;
  209425. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209426. control->controlHWND = ActiveXHelpers::getHWND (this);
  209427. if (control->controlHWND != 0)
  209428. {
  209429. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209430. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209431. }
  209432. return true;
  209433. }
  209434. }
  209435. }
  209436. }
  209437. return false;
  209438. }
  209439. void ActiveXControlComponent::deleteControl()
  209440. {
  209441. control = 0;
  209442. originalWndProc = 0;
  209443. }
  209444. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209445. {
  209446. void* result = 0;
  209447. if (control != 0 && control->control != 0
  209448. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209449. return result;
  209450. return 0;
  209451. }
  209452. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209453. {
  209454. if (control->controlHWND != 0)
  209455. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209456. }
  209457. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209458. {
  209459. if (control->controlHWND != 0)
  209460. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209461. }
  209462. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209463. {
  209464. mouseEventsAllowed = eventsCanReachControl;
  209465. }
  209466. #endif
  209467. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209468. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209469. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209470. // compiled on its own).
  209471. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209472. using namespace QTOLibrary;
  209473. using namespace QTOControlLib;
  209474. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209475. static bool isQTAvailable = false;
  209476. class QuickTimeMovieComponent::Pimpl
  209477. {
  209478. public:
  209479. Pimpl() : dataHandle (0)
  209480. {
  209481. }
  209482. ~Pimpl()
  209483. {
  209484. clearHandle();
  209485. }
  209486. void clearHandle()
  209487. {
  209488. if (dataHandle != 0)
  209489. {
  209490. DisposeHandle (dataHandle);
  209491. dataHandle = 0;
  209492. }
  209493. }
  209494. IQTControlPtr qtControl;
  209495. IQTMoviePtr qtMovie;
  209496. Handle dataHandle;
  209497. };
  209498. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209499. : movieLoaded (false),
  209500. controllerVisible (true)
  209501. {
  209502. pimpl = new Pimpl();
  209503. setMouseEventsAllowed (false);
  209504. }
  209505. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209506. {
  209507. closeMovie();
  209508. pimpl->qtControl = 0;
  209509. deleteControl();
  209510. pimpl = 0;
  209511. }
  209512. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209513. {
  209514. if (! isQTAvailable)
  209515. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209516. return isQTAvailable;
  209517. }
  209518. void QuickTimeMovieComponent::createControlIfNeeded()
  209519. {
  209520. if (isShowing() && ! isControlCreated())
  209521. {
  209522. const IID qtIID = __uuidof (QTControl);
  209523. if (createControl (&qtIID))
  209524. {
  209525. const IID qtInterfaceIID = __uuidof (IQTControl);
  209526. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209527. if (pimpl->qtControl != 0)
  209528. {
  209529. pimpl->qtControl->Release(); // it has one ref too many at this point
  209530. pimpl->qtControl->QuickTimeInitialize();
  209531. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209532. if (movieFile != File::nonexistent)
  209533. loadMovie (movieFile, controllerVisible);
  209534. }
  209535. }
  209536. }
  209537. }
  209538. bool QuickTimeMovieComponent::isControlCreated() const
  209539. {
  209540. return isControlOpen();
  209541. }
  209542. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209543. const bool isControllerVisible)
  209544. {
  209545. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209546. movieFile = File::nonexistent;
  209547. movieLoaded = false;
  209548. pimpl->qtMovie = 0;
  209549. controllerVisible = isControllerVisible;
  209550. createControlIfNeeded();
  209551. if (isControlCreated())
  209552. {
  209553. if (pimpl->qtControl != 0)
  209554. {
  209555. pimpl->qtControl->Put_MovieHandle (0);
  209556. pimpl->clearHandle();
  209557. Movie movie;
  209558. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209559. {
  209560. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209561. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209562. if (pimpl->qtMovie != 0)
  209563. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209564. : qtMovieControllerTypeNone);
  209565. }
  209566. if (movie == 0)
  209567. pimpl->clearHandle();
  209568. }
  209569. movieLoaded = (pimpl->qtMovie != 0);
  209570. }
  209571. else
  209572. {
  209573. // You're trying to open a movie when the control hasn't yet been created, probably because
  209574. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209575. jassertfalse;
  209576. }
  209577. return movieLoaded;
  209578. }
  209579. void QuickTimeMovieComponent::closeMovie()
  209580. {
  209581. stop();
  209582. movieFile = File::nonexistent;
  209583. movieLoaded = false;
  209584. pimpl->qtMovie = 0;
  209585. if (pimpl->qtControl != 0)
  209586. pimpl->qtControl->Put_MovieHandle (0);
  209587. pimpl->clearHandle();
  209588. }
  209589. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209590. {
  209591. return movieFile;
  209592. }
  209593. bool QuickTimeMovieComponent::isMovieOpen() const
  209594. {
  209595. return movieLoaded;
  209596. }
  209597. double QuickTimeMovieComponent::getMovieDuration() const
  209598. {
  209599. if (pimpl->qtMovie != 0)
  209600. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209601. return 0.0;
  209602. }
  209603. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209604. {
  209605. if (pimpl->qtMovie != 0)
  209606. {
  209607. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209608. width = r.right - r.left;
  209609. height = r.bottom - r.top;
  209610. }
  209611. else
  209612. {
  209613. width = height = 0;
  209614. }
  209615. }
  209616. void QuickTimeMovieComponent::play()
  209617. {
  209618. if (pimpl->qtMovie != 0)
  209619. pimpl->qtMovie->Play();
  209620. }
  209621. void QuickTimeMovieComponent::stop()
  209622. {
  209623. if (pimpl->qtMovie != 0)
  209624. pimpl->qtMovie->Stop();
  209625. }
  209626. bool QuickTimeMovieComponent::isPlaying() const
  209627. {
  209628. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209629. }
  209630. void QuickTimeMovieComponent::setPosition (const double seconds)
  209631. {
  209632. if (pimpl->qtMovie != 0)
  209633. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209634. }
  209635. double QuickTimeMovieComponent::getPosition() const
  209636. {
  209637. if (pimpl->qtMovie != 0)
  209638. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209639. return 0.0;
  209640. }
  209641. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209642. {
  209643. if (pimpl->qtMovie != 0)
  209644. pimpl->qtMovie->PutRate (newSpeed);
  209645. }
  209646. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209647. {
  209648. if (pimpl->qtMovie != 0)
  209649. {
  209650. pimpl->qtMovie->PutAudioVolume (newVolume);
  209651. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209652. }
  209653. }
  209654. float QuickTimeMovieComponent::getMovieVolume() const
  209655. {
  209656. if (pimpl->qtMovie != 0)
  209657. return pimpl->qtMovie->GetAudioVolume();
  209658. return 0.0f;
  209659. }
  209660. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209661. {
  209662. if (pimpl->qtMovie != 0)
  209663. pimpl->qtMovie->PutLoop (shouldLoop);
  209664. }
  209665. bool QuickTimeMovieComponent::isLooping() const
  209666. {
  209667. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209668. }
  209669. bool QuickTimeMovieComponent::isControllerVisible() const
  209670. {
  209671. return controllerVisible;
  209672. }
  209673. void QuickTimeMovieComponent::parentHierarchyChanged()
  209674. {
  209675. createControlIfNeeded();
  209676. QTCompBaseClass::parentHierarchyChanged();
  209677. }
  209678. void QuickTimeMovieComponent::visibilityChanged()
  209679. {
  209680. createControlIfNeeded();
  209681. QTCompBaseClass::visibilityChanged();
  209682. }
  209683. void QuickTimeMovieComponent::paint (Graphics& g)
  209684. {
  209685. if (! isControlCreated())
  209686. g.fillAll (Colours::black);
  209687. }
  209688. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209689. {
  209690. Handle dataRef = 0;
  209691. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209692. if (err == noErr)
  209693. {
  209694. Str255 suffix;
  209695. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209696. StringPtr name = suffix;
  209697. err = PtrAndHand (name, dataRef, name[0] + 1);
  209698. if (err == noErr)
  209699. {
  209700. long atoms[3];
  209701. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209702. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209703. atoms[2] = EndianU32_NtoB (MovieFileType);
  209704. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209705. if (err == noErr)
  209706. return dataRef;
  209707. }
  209708. DisposeHandle (dataRef);
  209709. }
  209710. return 0;
  209711. }
  209712. static CFStringRef juceStringToCFString (const String& s)
  209713. {
  209714. const int len = s.length();
  209715. const juce_wchar* const t = s;
  209716. HeapBlock <UniChar> temp (len + 2);
  209717. for (int i = 0; i <= len; ++i)
  209718. temp[i] = t[i];
  209719. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209720. }
  209721. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209722. {
  209723. Boolean trueBool = true;
  209724. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209725. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209726. props[prop].propValueSize = sizeof (trueBool);
  209727. props[prop].propValueAddress = &trueBool;
  209728. ++prop;
  209729. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209730. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209731. props[prop].propValueSize = sizeof (trueBool);
  209732. props[prop].propValueAddress = &trueBool;
  209733. ++prop;
  209734. Boolean isActive = true;
  209735. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209736. props[prop].propID = kQTNewMoviePropertyID_Active;
  209737. props[prop].propValueSize = sizeof (isActive);
  209738. props[prop].propValueAddress = &isActive;
  209739. ++prop;
  209740. MacSetPort (0);
  209741. jassert (prop <= 5);
  209742. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209743. return err == noErr;
  209744. }
  209745. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209746. {
  209747. if (input == 0)
  209748. return false;
  209749. dataHandle = 0;
  209750. bool ok = false;
  209751. QTNewMoviePropertyElement props[5];
  209752. zeromem (props, sizeof (props));
  209753. int prop = 0;
  209754. DataReferenceRecord dr;
  209755. props[prop].propClass = kQTPropertyClass_DataLocation;
  209756. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209757. props[prop].propValueSize = sizeof (dr);
  209758. props[prop].propValueAddress = &dr;
  209759. ++prop;
  209760. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209761. if (fin != 0)
  209762. {
  209763. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209764. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209765. &dr.dataRef, &dr.dataRefType);
  209766. ok = openMovie (props, prop, movie);
  209767. DisposeHandle (dr.dataRef);
  209768. CFRelease (filePath);
  209769. }
  209770. else
  209771. {
  209772. // sanity-check because this currently needs to load the whole stream into memory..
  209773. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209774. dataHandle = NewHandle ((Size) input->getTotalLength());
  209775. HLock (dataHandle);
  209776. // read the entire stream into memory - this is a pain, but can't get it to work
  209777. // properly using a custom callback to supply the data.
  209778. input->read (*dataHandle, (int) input->getTotalLength());
  209779. HUnlock (dataHandle);
  209780. // different types to get QT to try. (We should really be a bit smarter here by
  209781. // working out in advance which one the stream contains, rather than just trying
  209782. // each one)
  209783. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209784. "\04.avi", "\04.m4a" };
  209785. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209786. {
  209787. /* // this fails for some bizarre reason - it can be bodged to work with
  209788. // movies, but can't seem to do it for other file types..
  209789. QTNewMovieUserProcRecord procInfo;
  209790. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209791. procInfo.getMovieUserProcRefcon = this;
  209792. procInfo.defaultDataRef.dataRef = dataRef;
  209793. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209794. props[prop].propClass = kQTPropertyClass_DataLocation;
  209795. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209796. props[prop].propValueSize = sizeof (procInfo);
  209797. props[prop].propValueAddress = (void*) &procInfo;
  209798. ++prop; */
  209799. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209800. dr.dataRefType = HandleDataHandlerSubType;
  209801. ok = openMovie (props, prop, movie);
  209802. DisposeHandle (dr.dataRef);
  209803. }
  209804. }
  209805. return ok;
  209806. }
  209807. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209808. const bool isControllerVisible)
  209809. {
  209810. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209811. movieFile = movieFile_;
  209812. return ok;
  209813. }
  209814. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209815. const bool isControllerVisible)
  209816. {
  209817. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209818. }
  209819. void QuickTimeMovieComponent::goToStart()
  209820. {
  209821. setPosition (0.0);
  209822. }
  209823. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209824. const RectanglePlacement& placement)
  209825. {
  209826. int normalWidth, normalHeight;
  209827. getMovieNormalSize (normalWidth, normalHeight);
  209828. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209829. {
  209830. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209831. placement.applyTo (x, y, w, h,
  209832. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209833. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209834. if (w > 0 && h > 0)
  209835. {
  209836. setBounds (roundToInt (x), roundToInt (y),
  209837. roundToInt (w), roundToInt (h));
  209838. }
  209839. }
  209840. else
  209841. {
  209842. setBounds (spaceToFitWithin);
  209843. }
  209844. }
  209845. #endif
  209846. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209847. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209848. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209849. // compiled on its own).
  209850. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209851. class WebBrowserComponentInternal : public ActiveXControlComponent
  209852. {
  209853. public:
  209854. WebBrowserComponentInternal()
  209855. : browser (0),
  209856. connectionPoint (0),
  209857. adviseCookie (0)
  209858. {
  209859. }
  209860. ~WebBrowserComponentInternal()
  209861. {
  209862. if (connectionPoint != 0)
  209863. connectionPoint->Unadvise (adviseCookie);
  209864. if (browser != 0)
  209865. browser->Release();
  209866. }
  209867. void createBrowser()
  209868. {
  209869. createControl (&CLSID_WebBrowser);
  209870. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209871. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209872. if (connectionPointContainer != 0)
  209873. {
  209874. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209875. &connectionPoint);
  209876. if (connectionPoint != 0)
  209877. {
  209878. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209879. jassert (owner != 0);
  209880. EventHandler* handler = new EventHandler (owner);
  209881. connectionPoint->Advise (handler, &adviseCookie);
  209882. handler->Release();
  209883. }
  209884. }
  209885. }
  209886. void goToURL (const String& url,
  209887. const StringArray* headers,
  209888. const MemoryBlock* postData)
  209889. {
  209890. if (browser != 0)
  209891. {
  209892. LPSAFEARRAY sa = 0;
  209893. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209894. VariantInit (&flags);
  209895. VariantInit (&frame);
  209896. VariantInit (&postDataVar);
  209897. VariantInit (&headersVar);
  209898. if (headers != 0)
  209899. {
  209900. V_VT (&headersVar) = VT_BSTR;
  209901. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209902. }
  209903. if (postData != 0 && postData->getSize() > 0)
  209904. {
  209905. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209906. if (sa != 0)
  209907. {
  209908. void* data = 0;
  209909. SafeArrayAccessData (sa, &data);
  209910. jassert (data != 0);
  209911. if (data != 0)
  209912. {
  209913. postData->copyTo (data, 0, postData->getSize());
  209914. SafeArrayUnaccessData (sa);
  209915. VARIANT postDataVar2;
  209916. VariantInit (&postDataVar2);
  209917. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209918. V_ARRAY (&postDataVar2) = sa;
  209919. postDataVar = postDataVar2;
  209920. }
  209921. }
  209922. }
  209923. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209924. &flags, &frame,
  209925. &postDataVar, &headersVar);
  209926. if (sa != 0)
  209927. SafeArrayDestroy (sa);
  209928. VariantClear (&flags);
  209929. VariantClear (&frame);
  209930. VariantClear (&postDataVar);
  209931. VariantClear (&headersVar);
  209932. }
  209933. }
  209934. IWebBrowser2* browser;
  209935. juce_UseDebuggingNewOperator
  209936. private:
  209937. IConnectionPoint* connectionPoint;
  209938. DWORD adviseCookie;
  209939. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209940. public ComponentMovementWatcher
  209941. {
  209942. public:
  209943. EventHandler (WebBrowserComponent* owner_)
  209944. : ComponentMovementWatcher (owner_),
  209945. owner (owner_)
  209946. {
  209947. }
  209948. ~EventHandler()
  209949. {
  209950. }
  209951. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  209952. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  209953. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  209954. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  209955. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  209956. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  209957. UINT __RPC_FAR* /*puArgErr*/)
  209958. {
  209959. switch (dispIdMember)
  209960. {
  209961. case DISPID_BEFORENAVIGATE2:
  209962. {
  209963. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209964. String url;
  209965. if ((vurl->vt & VT_BYREF) != 0)
  209966. url = *vurl->pbstrVal;
  209967. else
  209968. url = vurl->bstrVal;
  209969. *pDispParams->rgvarg->pboolVal
  209970. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209971. : VARIANT_TRUE;
  209972. return S_OK;
  209973. }
  209974. default:
  209975. break;
  209976. }
  209977. return E_NOTIMPL;
  209978. }
  209979. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209980. void componentPeerChanged() {}
  209981. void componentVisibilityChanged (Component&)
  209982. {
  209983. owner->visibilityChanged();
  209984. }
  209985. juce_UseDebuggingNewOperator
  209986. private:
  209987. WebBrowserComponent* const owner;
  209988. EventHandler (const EventHandler&);
  209989. EventHandler& operator= (const EventHandler&);
  209990. };
  209991. };
  209992. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209993. : browser (0),
  209994. blankPageShown (false),
  209995. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209996. {
  209997. setOpaque (true);
  209998. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209999. }
  210000. WebBrowserComponent::~WebBrowserComponent()
  210001. {
  210002. delete browser;
  210003. }
  210004. void WebBrowserComponent::goToURL (const String& url,
  210005. const StringArray* headers,
  210006. const MemoryBlock* postData)
  210007. {
  210008. lastURL = url;
  210009. lastHeaders.clear();
  210010. if (headers != 0)
  210011. lastHeaders = *headers;
  210012. lastPostData.setSize (0);
  210013. if (postData != 0)
  210014. lastPostData = *postData;
  210015. blankPageShown = false;
  210016. browser->goToURL (url, headers, postData);
  210017. }
  210018. void WebBrowserComponent::stop()
  210019. {
  210020. if (browser->browser != 0)
  210021. browser->browser->Stop();
  210022. }
  210023. void WebBrowserComponent::goBack()
  210024. {
  210025. lastURL = String::empty;
  210026. blankPageShown = false;
  210027. if (browser->browser != 0)
  210028. browser->browser->GoBack();
  210029. }
  210030. void WebBrowserComponent::goForward()
  210031. {
  210032. lastURL = String::empty;
  210033. if (browser->browser != 0)
  210034. browser->browser->GoForward();
  210035. }
  210036. void WebBrowserComponent::refresh()
  210037. {
  210038. if (browser->browser != 0)
  210039. browser->browser->Refresh();
  210040. }
  210041. void WebBrowserComponent::paint (Graphics& g)
  210042. {
  210043. if (browser->browser == 0)
  210044. g.fillAll (Colours::white);
  210045. }
  210046. void WebBrowserComponent::checkWindowAssociation()
  210047. {
  210048. if (isShowing())
  210049. {
  210050. if (browser->browser == 0 && getPeer() != 0)
  210051. {
  210052. browser->createBrowser();
  210053. reloadLastURL();
  210054. }
  210055. else
  210056. {
  210057. if (blankPageShown)
  210058. goBack();
  210059. }
  210060. }
  210061. else
  210062. {
  210063. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210064. {
  210065. // when the component becomes invisible, some stuff like flash
  210066. // carries on playing audio, so we need to force it onto a blank
  210067. // page to avoid this..
  210068. blankPageShown = true;
  210069. browser->goToURL ("about:blank", 0, 0);
  210070. }
  210071. }
  210072. }
  210073. void WebBrowserComponent::reloadLastURL()
  210074. {
  210075. if (lastURL.isNotEmpty())
  210076. {
  210077. goToURL (lastURL, &lastHeaders, &lastPostData);
  210078. lastURL = String::empty;
  210079. }
  210080. }
  210081. void WebBrowserComponent::parentHierarchyChanged()
  210082. {
  210083. checkWindowAssociation();
  210084. }
  210085. void WebBrowserComponent::resized()
  210086. {
  210087. browser->setSize (getWidth(), getHeight());
  210088. }
  210089. void WebBrowserComponent::visibilityChanged()
  210090. {
  210091. checkWindowAssociation();
  210092. }
  210093. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210094. {
  210095. return true;
  210096. }
  210097. #endif
  210098. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210099. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210100. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210101. // compiled on its own).
  210102. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210103. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210104. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210105. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210106. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210107. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210108. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210109. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210110. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210111. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210112. #define WGL_ACCELERATION_ARB 0x2003
  210113. #define WGL_SWAP_METHOD_ARB 0x2007
  210114. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210115. #define WGL_PIXEL_TYPE_ARB 0x2013
  210116. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210117. #define WGL_COLOR_BITS_ARB 0x2014
  210118. #define WGL_RED_BITS_ARB 0x2015
  210119. #define WGL_GREEN_BITS_ARB 0x2017
  210120. #define WGL_BLUE_BITS_ARB 0x2019
  210121. #define WGL_ALPHA_BITS_ARB 0x201B
  210122. #define WGL_DEPTH_BITS_ARB 0x2022
  210123. #define WGL_STENCIL_BITS_ARB 0x2023
  210124. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210125. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210126. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210127. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210128. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210129. #define WGL_STEREO_ARB 0x2012
  210130. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210131. #define WGL_SAMPLES_ARB 0x2042
  210132. #define WGL_TYPE_RGBA_ARB 0x202B
  210133. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210134. {
  210135. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210136. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210137. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210138. else
  210139. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210140. }
  210141. class WindowedGLContext : public OpenGLContext
  210142. {
  210143. public:
  210144. WindowedGLContext (Component* const component_,
  210145. HGLRC contextToShareWith,
  210146. const OpenGLPixelFormat& pixelFormat)
  210147. : renderContext (0),
  210148. dc (0),
  210149. component (component_)
  210150. {
  210151. jassert (component != 0);
  210152. createNativeWindow();
  210153. // Use a default pixel format that should be supported everywhere
  210154. PIXELFORMATDESCRIPTOR pfd;
  210155. zerostruct (pfd);
  210156. pfd.nSize = sizeof (pfd);
  210157. pfd.nVersion = 1;
  210158. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210159. pfd.iPixelType = PFD_TYPE_RGBA;
  210160. pfd.cColorBits = 24;
  210161. pfd.cDepthBits = 16;
  210162. const int format = ChoosePixelFormat (dc, &pfd);
  210163. if (format != 0)
  210164. SetPixelFormat (dc, format, &pfd);
  210165. renderContext = wglCreateContext (dc);
  210166. makeActive();
  210167. setPixelFormat (pixelFormat);
  210168. if (contextToShareWith != 0 && renderContext != 0)
  210169. wglShareLists (contextToShareWith, renderContext);
  210170. }
  210171. ~WindowedGLContext()
  210172. {
  210173. deleteContext();
  210174. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210175. nativeWindow = 0;
  210176. }
  210177. void deleteContext()
  210178. {
  210179. makeInactive();
  210180. if (renderContext != 0)
  210181. {
  210182. wglDeleteContext (renderContext);
  210183. renderContext = 0;
  210184. }
  210185. }
  210186. bool makeActive() const throw()
  210187. {
  210188. jassert (renderContext != 0);
  210189. return wglMakeCurrent (dc, renderContext) != 0;
  210190. }
  210191. bool makeInactive() const throw()
  210192. {
  210193. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210194. }
  210195. bool isActive() const throw()
  210196. {
  210197. return wglGetCurrentContext() == renderContext;
  210198. }
  210199. const OpenGLPixelFormat getPixelFormat() const
  210200. {
  210201. OpenGLPixelFormat pf;
  210202. makeActive();
  210203. StringArray availableExtensions;
  210204. getWglExtensions (dc, availableExtensions);
  210205. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210206. return pf;
  210207. }
  210208. void* getRawContext() const throw()
  210209. {
  210210. return renderContext;
  210211. }
  210212. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210213. {
  210214. makeActive();
  210215. PIXELFORMATDESCRIPTOR pfd;
  210216. zerostruct (pfd);
  210217. pfd.nSize = sizeof (pfd);
  210218. pfd.nVersion = 1;
  210219. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210220. pfd.iPixelType = PFD_TYPE_RGBA;
  210221. pfd.iLayerType = PFD_MAIN_PLANE;
  210222. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210223. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210224. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210225. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210226. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210227. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210228. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210229. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210230. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210231. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210232. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210233. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210234. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210235. int format = 0;
  210236. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210237. StringArray availableExtensions;
  210238. getWglExtensions (dc, availableExtensions);
  210239. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210240. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210241. {
  210242. int attributes[64];
  210243. int n = 0;
  210244. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210245. attributes[n++] = GL_TRUE;
  210246. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210247. attributes[n++] = GL_TRUE;
  210248. attributes[n++] = WGL_ACCELERATION_ARB;
  210249. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210250. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210251. attributes[n++] = GL_TRUE;
  210252. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210253. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210254. attributes[n++] = WGL_COLOR_BITS_ARB;
  210255. attributes[n++] = pfd.cColorBits;
  210256. attributes[n++] = WGL_RED_BITS_ARB;
  210257. attributes[n++] = pixelFormat.redBits;
  210258. attributes[n++] = WGL_GREEN_BITS_ARB;
  210259. attributes[n++] = pixelFormat.greenBits;
  210260. attributes[n++] = WGL_BLUE_BITS_ARB;
  210261. attributes[n++] = pixelFormat.blueBits;
  210262. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210263. attributes[n++] = pixelFormat.alphaBits;
  210264. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210265. attributes[n++] = pixelFormat.depthBufferBits;
  210266. if (pixelFormat.stencilBufferBits > 0)
  210267. {
  210268. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210269. attributes[n++] = pixelFormat.stencilBufferBits;
  210270. }
  210271. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210272. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210273. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210274. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210275. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210276. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210277. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210278. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210279. if (availableExtensions.contains ("WGL_ARB_multisample")
  210280. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210281. {
  210282. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210283. attributes[n++] = 1;
  210284. attributes[n++] = WGL_SAMPLES_ARB;
  210285. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210286. }
  210287. attributes[n++] = 0;
  210288. UINT formatsCount;
  210289. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210290. (void) ok;
  210291. jassert (ok);
  210292. }
  210293. else
  210294. {
  210295. format = ChoosePixelFormat (dc, &pfd);
  210296. }
  210297. if (format != 0)
  210298. {
  210299. makeInactive();
  210300. // win32 can't change the pixel format of a window, so need to delete the
  210301. // old one and create a new one..
  210302. jassert (nativeWindow != 0);
  210303. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210304. nativeWindow = 0;
  210305. createNativeWindow();
  210306. if (SetPixelFormat (dc, format, &pfd))
  210307. {
  210308. wglDeleteContext (renderContext);
  210309. renderContext = wglCreateContext (dc);
  210310. jassert (renderContext != 0);
  210311. return renderContext != 0;
  210312. }
  210313. }
  210314. return false;
  210315. }
  210316. void updateWindowPosition (int x, int y, int w, int h, int)
  210317. {
  210318. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210319. x, y, w, h,
  210320. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210321. }
  210322. void repaint()
  210323. {
  210324. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210325. }
  210326. void swapBuffers()
  210327. {
  210328. SwapBuffers (dc);
  210329. }
  210330. bool setSwapInterval (int numFramesPerSwap)
  210331. {
  210332. makeActive();
  210333. StringArray availableExtensions;
  210334. getWglExtensions (dc, availableExtensions);
  210335. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210336. return availableExtensions.contains ("WGL_EXT_swap_control")
  210337. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210338. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210339. }
  210340. int getSwapInterval() const
  210341. {
  210342. makeActive();
  210343. StringArray availableExtensions;
  210344. getWglExtensions (dc, availableExtensions);
  210345. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210346. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210347. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210348. return wglGetSwapIntervalEXT();
  210349. return 0;
  210350. }
  210351. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210352. {
  210353. jassert (isActive());
  210354. StringArray availableExtensions;
  210355. getWglExtensions (dc, availableExtensions);
  210356. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210357. int numTypes = 0;
  210358. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210359. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210360. {
  210361. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210362. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210363. jassertfalse;
  210364. }
  210365. else
  210366. {
  210367. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210368. }
  210369. OpenGLPixelFormat pf;
  210370. for (int i = 0; i < numTypes; ++i)
  210371. {
  210372. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210373. {
  210374. bool alreadyListed = false;
  210375. for (int j = results.size(); --j >= 0;)
  210376. if (pf == *results.getUnchecked(j))
  210377. alreadyListed = true;
  210378. if (! alreadyListed)
  210379. results.add (new OpenGLPixelFormat (pf));
  210380. }
  210381. }
  210382. }
  210383. void* getNativeWindowHandle() const
  210384. {
  210385. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210386. }
  210387. juce_UseDebuggingNewOperator
  210388. HGLRC renderContext;
  210389. private:
  210390. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210391. Component* const component;
  210392. HDC dc;
  210393. void createNativeWindow()
  210394. {
  210395. nativeWindow = new Win32ComponentPeer (component, 0, 0);
  210396. nativeWindow->dontRepaint = true;
  210397. nativeWindow->setVisible (true);
  210398. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  210399. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210400. if (peer != 0)
  210401. {
  210402. SetParent (hwnd, (HWND) peer->getNativeHandle());
  210403. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  210404. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  210405. }
  210406. dc = GetDC (hwnd);
  210407. }
  210408. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210409. OpenGLPixelFormat& result,
  210410. const StringArray& availableExtensions) const throw()
  210411. {
  210412. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210413. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210414. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210415. {
  210416. int attributes[32];
  210417. int numAttributes = 0;
  210418. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210419. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210420. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210421. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210422. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210423. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210424. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210425. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210426. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210427. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210428. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210429. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210430. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210431. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210432. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210433. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210434. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210435. int values[32];
  210436. zeromem (values, sizeof (values));
  210437. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210438. {
  210439. int n = 0;
  210440. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210441. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210442. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210443. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210444. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210445. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210446. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210447. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210448. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210449. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210450. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210451. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210452. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210453. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210454. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210455. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210456. return isValidFormat;
  210457. }
  210458. else
  210459. {
  210460. jassertfalse;
  210461. }
  210462. }
  210463. else
  210464. {
  210465. PIXELFORMATDESCRIPTOR pfd;
  210466. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210467. {
  210468. result.redBits = pfd.cRedBits;
  210469. result.greenBits = pfd.cGreenBits;
  210470. result.blueBits = pfd.cBlueBits;
  210471. result.alphaBits = pfd.cAlphaBits;
  210472. result.depthBufferBits = pfd.cDepthBits;
  210473. result.stencilBufferBits = pfd.cStencilBits;
  210474. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210475. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210476. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210477. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210478. result.fullSceneAntiAliasingNumSamples = 0;
  210479. return true;
  210480. }
  210481. else
  210482. {
  210483. jassertfalse;
  210484. }
  210485. }
  210486. return false;
  210487. }
  210488. WindowedGLContext (const WindowedGLContext&);
  210489. WindowedGLContext& operator= (const WindowedGLContext&);
  210490. };
  210491. OpenGLContext* OpenGLComponent::createContext()
  210492. {
  210493. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210494. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210495. preferredPixelFormat));
  210496. return (c->renderContext != 0) ? c.release() : 0;
  210497. }
  210498. void* OpenGLComponent::getNativeWindowHandle() const
  210499. {
  210500. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210501. }
  210502. void juce_glViewport (const int w, const int h)
  210503. {
  210504. glViewport (0, 0, w, h);
  210505. }
  210506. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210507. OwnedArray <OpenGLPixelFormat>& results)
  210508. {
  210509. Component tempComp;
  210510. {
  210511. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210512. wc.makeActive();
  210513. wc.findAlternativeOpenGLPixelFormats (results);
  210514. }
  210515. }
  210516. #endif
  210517. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210518. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210519. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210520. // compiled on its own).
  210521. #if JUCE_INCLUDED_FILE
  210522. #if JUCE_USE_CDREADER
  210523. namespace CDReaderHelpers
  210524. {
  210525. //***************************************************************************
  210526. // %%% TARGET STATUS VALUES %%%
  210527. //***************************************************************************
  210528. #define STATUS_GOOD 0x00 // Status Good
  210529. #define STATUS_CHKCOND 0x02 // Check Condition
  210530. #define STATUS_CONDMET 0x04 // Condition Met
  210531. #define STATUS_BUSY 0x08 // Busy
  210532. #define STATUS_INTERM 0x10 // Intermediate
  210533. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210534. #define STATUS_RESCONF 0x18 // Reservation conflict
  210535. #define STATUS_COMTERM 0x22 // Command Terminated
  210536. #define STATUS_QFULL 0x28 // Queue full
  210537. //***************************************************************************
  210538. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210539. //***************************************************************************
  210540. #define MAXLUN 7 // Maximum Logical Unit Id
  210541. #define MAXTARG 7 // Maximum Target Id
  210542. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210543. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210544. //***************************************************************************
  210545. // %%% Commands for all Device Types %%%
  210546. //***************************************************************************
  210547. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210548. #define SCSI_COMPARE 0x39 // Compare (O)
  210549. #define SCSI_COPY 0x18 // Copy (O)
  210550. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210551. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210552. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210553. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210554. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210555. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210556. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210557. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210558. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210559. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210560. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210561. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210562. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210563. //***************************************************************************
  210564. // %%% Commands Unique to Direct Access Devices %%%
  210565. //***************************************************************************
  210566. #define SCSI_COMPARE 0x39 // Compare (O)
  210567. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210568. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210569. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210570. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210571. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210572. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210573. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210574. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210575. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210576. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210577. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210578. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210579. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210580. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210581. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210582. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210583. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210584. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210585. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210586. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210587. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210588. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210589. #define SCSI_VERIFY 0x2F // Verify (O)
  210590. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210591. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210592. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210593. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210594. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210595. //***************************************************************************
  210596. // %%% Commands Unique to Sequential Access Devices %%%
  210597. //***************************************************************************
  210598. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210599. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210600. #define SCSI_LOCATE 0x2B // Locate (O)
  210601. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210602. #define SCSI_READ_POS 0x34 // Read Position (O)
  210603. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210604. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210605. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210606. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210607. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210608. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210609. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210610. //***************************************************************************
  210611. // %%% Commands Unique to Printer Devices %%%
  210612. //***************************************************************************
  210613. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210614. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210615. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210616. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210617. //***************************************************************************
  210618. // %%% Commands Unique to Processor Devices %%%
  210619. //***************************************************************************
  210620. #define SCSI_RECEIVE 0x08 // Receive (O)
  210621. #define SCSI_SEND 0x0A // Send (O)
  210622. //***************************************************************************
  210623. // %%% Commands Unique to Write-Once Devices %%%
  210624. //***************************************************************************
  210625. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210626. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210627. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210628. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210629. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210630. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210631. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210632. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210633. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210634. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210635. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210636. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210637. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210638. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210639. //***************************************************************************
  210640. // %%% Commands Unique to CD-ROM Devices %%%
  210641. //***************************************************************************
  210642. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210643. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210644. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210645. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210646. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210647. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210648. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210649. #define SCSI_READHEADER 0x44 // Read Header (O)
  210650. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210651. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210652. //***************************************************************************
  210653. // %%% Commands Unique to Scanner Devices %%%
  210654. //***************************************************************************
  210655. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210656. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210657. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210658. #define SCSI_SCAN 0x1B // Scan (O)
  210659. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210660. //***************************************************************************
  210661. // %%% Commands Unique to Optical Memory Devices %%%
  210662. //***************************************************************************
  210663. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210664. //***************************************************************************
  210665. // %%% Commands Unique to Medium Changer Devices %%%
  210666. //***************************************************************************
  210667. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210668. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210669. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210670. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210671. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210672. //***************************************************************************
  210673. // %%% Commands Unique to Communication Devices %%%
  210674. //***************************************************************************
  210675. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210676. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210677. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210678. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210679. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210680. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210681. //***************************************************************************
  210682. // %%% Request Sense Data Format %%%
  210683. //***************************************************************************
  210684. typedef struct {
  210685. BYTE ErrorCode; // Error Code (70H or 71H)
  210686. BYTE SegmentNum; // Number of current segment descriptor
  210687. BYTE SenseKey; // Sense Key(See bit definitions too)
  210688. BYTE InfoByte0; // Information MSB
  210689. BYTE InfoByte1; // Information MID
  210690. BYTE InfoByte2; // Information MID
  210691. BYTE InfoByte3; // Information LSB
  210692. BYTE AddSenLen; // Additional Sense Length
  210693. BYTE ComSpecInf0; // Command Specific Information MSB
  210694. BYTE ComSpecInf1; // Command Specific Information MID
  210695. BYTE ComSpecInf2; // Command Specific Information MID
  210696. BYTE ComSpecInf3; // Command Specific Information LSB
  210697. BYTE AddSenseCode; // Additional Sense Code
  210698. BYTE AddSenQual; // Additional Sense Code Qualifier
  210699. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210700. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210701. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210702. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210703. BYTE AddSenseBytes; // Additional Sense Bytes
  210704. } SENSE_DATA_FMT;
  210705. //***************************************************************************
  210706. // %%% REQUEST SENSE ERROR CODE %%%
  210707. //***************************************************************************
  210708. #define SERROR_CURRENT 0x70 // Current Errors
  210709. #define SERROR_DEFERED 0x71 // Deferred Errors
  210710. //***************************************************************************
  210711. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210712. //***************************************************************************
  210713. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210714. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210715. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210716. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210717. //***************************************************************************
  210718. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210719. //***************************************************************************
  210720. #define KEY_NOSENSE 0x00 // No Sense
  210721. #define KEY_RECERROR 0x01 // Recovered Error
  210722. #define KEY_NOTREADY 0x02 // Not Ready
  210723. #define KEY_MEDIUMERR 0x03 // Medium Error
  210724. #define KEY_HARDERROR 0x04 // Hardware Error
  210725. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210726. #define KEY_UNITATT 0x06 // Unit Attention
  210727. #define KEY_DATAPROT 0x07 // Data Protect
  210728. #define KEY_BLANKCHK 0x08 // Blank Check
  210729. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210730. #define KEY_COPYABORT 0x0A // Copy Abort
  210731. #define KEY_EQUAL 0x0C // Equal (Search)
  210732. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210733. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210734. #define KEY_RESERVED 0x0F // Reserved
  210735. //***************************************************************************
  210736. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210737. //***************************************************************************
  210738. #define DTYPE_DASD 0x00 // Disk Device
  210739. #define DTYPE_SEQD 0x01 // Tape Device
  210740. #define DTYPE_PRNT 0x02 // Printer
  210741. #define DTYPE_PROC 0x03 // Processor
  210742. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210743. #define DTYPE_CROM 0x05 // CD-ROM device
  210744. #define DTYPE_SCAN 0x06 // Scanner device
  210745. #define DTYPE_OPTI 0x07 // Optical memory device
  210746. #define DTYPE_JUKE 0x08 // Medium Changer device
  210747. #define DTYPE_COMM 0x09 // Communications device
  210748. #define DTYPE_RESL 0x0A // Reserved (low)
  210749. #define DTYPE_RESH 0x1E // Reserved (high)
  210750. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210751. //***************************************************************************
  210752. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210753. //***************************************************************************
  210754. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210755. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210756. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210757. #define ANSI_RESLO 0x3 // Reserved (low)
  210758. #define ANSI_RESHI 0x7 // Reserved (high)
  210759. typedef struct
  210760. {
  210761. USHORT Length;
  210762. UCHAR ScsiStatus;
  210763. UCHAR PathId;
  210764. UCHAR TargetId;
  210765. UCHAR Lun;
  210766. UCHAR CdbLength;
  210767. UCHAR SenseInfoLength;
  210768. UCHAR DataIn;
  210769. ULONG DataTransferLength;
  210770. ULONG TimeOutValue;
  210771. ULONG DataBufferOffset;
  210772. ULONG SenseInfoOffset;
  210773. UCHAR Cdb[16];
  210774. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210775. typedef struct
  210776. {
  210777. USHORT Length;
  210778. UCHAR ScsiStatus;
  210779. UCHAR PathId;
  210780. UCHAR TargetId;
  210781. UCHAR Lun;
  210782. UCHAR CdbLength;
  210783. UCHAR SenseInfoLength;
  210784. UCHAR DataIn;
  210785. ULONG DataTransferLength;
  210786. ULONG TimeOutValue;
  210787. PVOID DataBuffer;
  210788. ULONG SenseInfoOffset;
  210789. UCHAR Cdb[16];
  210790. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210791. typedef struct
  210792. {
  210793. SCSI_PASS_THROUGH_DIRECT spt;
  210794. ULONG Filler;
  210795. UCHAR ucSenseBuf[32];
  210796. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210797. typedef struct
  210798. {
  210799. ULONG Length;
  210800. UCHAR PortNumber;
  210801. UCHAR PathId;
  210802. UCHAR TargetId;
  210803. UCHAR Lun;
  210804. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210805. #define METHOD_BUFFERED 0
  210806. #define METHOD_IN_DIRECT 1
  210807. #define METHOD_OUT_DIRECT 2
  210808. #define METHOD_NEITHER 3
  210809. #define FILE_ANY_ACCESS 0
  210810. #ifndef FILE_READ_ACCESS
  210811. #define FILE_READ_ACCESS (0x0001)
  210812. #endif
  210813. #ifndef FILE_WRITE_ACCESS
  210814. #define FILE_WRITE_ACCESS (0x0002)
  210815. #endif
  210816. #define IOCTL_SCSI_BASE 0x00000004
  210817. #define SCSI_IOCTL_DATA_OUT 0
  210818. #define SCSI_IOCTL_DATA_IN 1
  210819. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210820. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210821. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210822. )
  210823. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210824. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210825. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210826. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210827. #define SENSE_LEN 14
  210828. #define SRB_DIR_SCSI 0x00
  210829. #define SRB_POSTING 0x01
  210830. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210831. #define SRB_DIR_IN 0x08
  210832. #define SRB_DIR_OUT 0x10
  210833. #define SRB_EVENT_NOTIFY 0x40
  210834. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210835. #define MAX_SRB_TIMEOUT 1080001u
  210836. #define DEFAULT_SRB_TIMEOUT 1080001u
  210837. #define SC_HA_INQUIRY 0x00
  210838. #define SC_GET_DEV_TYPE 0x01
  210839. #define SC_EXEC_SCSI_CMD 0x02
  210840. #define SC_ABORT_SRB 0x03
  210841. #define SC_RESET_DEV 0x04
  210842. #define SC_SET_HA_PARMS 0x05
  210843. #define SC_GET_DISK_INFO 0x06
  210844. #define SC_RESCAN_SCSI_BUS 0x07
  210845. #define SC_GETSET_TIMEOUTS 0x08
  210846. #define SS_PENDING 0x00
  210847. #define SS_COMP 0x01
  210848. #define SS_ABORTED 0x02
  210849. #define SS_ABORT_FAIL 0x03
  210850. #define SS_ERR 0x04
  210851. #define SS_INVALID_CMD 0x80
  210852. #define SS_INVALID_HA 0x81
  210853. #define SS_NO_DEVICE 0x82
  210854. #define SS_INVALID_SRB 0xE0
  210855. #define SS_OLD_MANAGER 0xE1
  210856. #define SS_BUFFER_ALIGN 0xE1
  210857. #define SS_ILLEGAL_MODE 0xE2
  210858. #define SS_NO_ASPI 0xE3
  210859. #define SS_FAILED_INIT 0xE4
  210860. #define SS_ASPI_IS_BUSY 0xE5
  210861. #define SS_BUFFER_TO_BIG 0xE6
  210862. #define SS_BUFFER_TOO_BIG 0xE6
  210863. #define SS_MISMATCHED_COMPONENTS 0xE7
  210864. #define SS_NO_ADAPTERS 0xE8
  210865. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210866. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210867. #define SS_BAD_INSTALL 0xEB
  210868. #define HASTAT_OK 0x00
  210869. #define HASTAT_SEL_TO 0x11
  210870. #define HASTAT_DO_DU 0x12
  210871. #define HASTAT_BUS_FREE 0x13
  210872. #define HASTAT_PHASE_ERR 0x14
  210873. #define HASTAT_TIMEOUT 0x09
  210874. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210875. #define HASTAT_MESSAGE_REJECT 0x0D
  210876. #define HASTAT_BUS_RESET 0x0E
  210877. #define HASTAT_PARITY_ERROR 0x0F
  210878. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210879. #define PACKED
  210880. #pragma pack(1)
  210881. typedef struct
  210882. {
  210883. BYTE SRB_Cmd;
  210884. BYTE SRB_Status;
  210885. BYTE SRB_HaID;
  210886. BYTE SRB_Flags;
  210887. DWORD SRB_Hdr_Rsvd;
  210888. BYTE HA_Count;
  210889. BYTE HA_SCSI_ID;
  210890. BYTE HA_ManagerId[16];
  210891. BYTE HA_Identifier[16];
  210892. BYTE HA_Unique[16];
  210893. WORD HA_Rsvd1;
  210894. BYTE pad[20];
  210895. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210896. typedef struct
  210897. {
  210898. BYTE SRB_Cmd;
  210899. BYTE SRB_Status;
  210900. BYTE SRB_HaID;
  210901. BYTE SRB_Flags;
  210902. DWORD SRB_Hdr_Rsvd;
  210903. BYTE SRB_Target;
  210904. BYTE SRB_Lun;
  210905. BYTE SRB_DeviceType;
  210906. BYTE SRB_Rsvd1;
  210907. BYTE pad[68];
  210908. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210909. typedef struct
  210910. {
  210911. BYTE SRB_Cmd;
  210912. BYTE SRB_Status;
  210913. BYTE SRB_HaID;
  210914. BYTE SRB_Flags;
  210915. DWORD SRB_Hdr_Rsvd;
  210916. BYTE SRB_Target;
  210917. BYTE SRB_Lun;
  210918. WORD SRB_Rsvd1;
  210919. DWORD SRB_BufLen;
  210920. BYTE FAR *SRB_BufPointer;
  210921. BYTE SRB_SenseLen;
  210922. BYTE SRB_CDBLen;
  210923. BYTE SRB_HaStat;
  210924. BYTE SRB_TargStat;
  210925. VOID FAR *SRB_PostProc;
  210926. BYTE SRB_Rsvd2[20];
  210927. BYTE CDBByte[16];
  210928. BYTE SenseArea[SENSE_LEN+2];
  210929. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210930. typedef struct
  210931. {
  210932. BYTE SRB_Cmd;
  210933. BYTE SRB_Status;
  210934. BYTE SRB_HaId;
  210935. BYTE SRB_Flags;
  210936. DWORD SRB_Hdr_Rsvd;
  210937. } PACKED SRB, *PSRB, FAR *LPSRB;
  210938. #pragma pack()
  210939. struct CDDeviceInfo
  210940. {
  210941. char vendor[9];
  210942. char productId[17];
  210943. char rev[5];
  210944. char vendorSpec[21];
  210945. BYTE ha;
  210946. BYTE tgt;
  210947. BYTE lun;
  210948. char scsiDriveLetter; // will be 0 if not using scsi
  210949. };
  210950. class CDReadBuffer
  210951. {
  210952. public:
  210953. int startFrame;
  210954. int numFrames;
  210955. int dataStartOffset;
  210956. int dataLength;
  210957. int bufferSize;
  210958. HeapBlock<BYTE> buffer;
  210959. int index;
  210960. bool wantsIndex;
  210961. CDReadBuffer (const int numberOfFrames)
  210962. : startFrame (0),
  210963. numFrames (0),
  210964. dataStartOffset (0),
  210965. dataLength (0),
  210966. bufferSize (2352 * numberOfFrames),
  210967. buffer (bufferSize),
  210968. index (0),
  210969. wantsIndex (false)
  210970. {
  210971. }
  210972. bool isZero() const throw()
  210973. {
  210974. BYTE* p = buffer + dataStartOffset;
  210975. for (int i = dataLength; --i >= 0;)
  210976. if (*p++ != 0)
  210977. return false;
  210978. return true;
  210979. }
  210980. };
  210981. class CDDeviceHandle;
  210982. class CDController
  210983. {
  210984. public:
  210985. CDController();
  210986. virtual ~CDController();
  210987. virtual bool read (CDReadBuffer* t) = 0;
  210988. virtual void shutDown();
  210989. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210990. int getLastIndex();
  210991. public:
  210992. bool initialised;
  210993. CDDeviceHandle* deviceInfo;
  210994. int framesToCheck, framesOverlap;
  210995. void prepare (SRB_ExecSCSICmd& s);
  210996. void perform (SRB_ExecSCSICmd& s);
  210997. void setPaused (bool paused);
  210998. };
  210999. #pragma pack(1)
  211000. struct TOCTRACK
  211001. {
  211002. BYTE rsvd;
  211003. BYTE ADR;
  211004. BYTE trackNumber;
  211005. BYTE rsvd2;
  211006. BYTE addr[4];
  211007. };
  211008. struct TOC
  211009. {
  211010. WORD tocLen;
  211011. BYTE firstTrack;
  211012. BYTE lastTrack;
  211013. TOCTRACK tracks[100];
  211014. };
  211015. #pragma pack()
  211016. enum
  211017. {
  211018. READTYPE_ANY = 0,
  211019. READTYPE_ATAPI1 = 1,
  211020. READTYPE_ATAPI2 = 2,
  211021. READTYPE_READ6 = 3,
  211022. READTYPE_READ10 = 4,
  211023. READTYPE_READ_D8 = 5,
  211024. READTYPE_READ_D4 = 6,
  211025. READTYPE_READ_D4_1 = 7,
  211026. READTYPE_READ10_2 = 8
  211027. };
  211028. class CDDeviceHandle
  211029. {
  211030. public:
  211031. CDDeviceHandle (const CDDeviceInfo* const device)
  211032. : scsiHandle (0),
  211033. readType (READTYPE_ANY),
  211034. controller (0)
  211035. {
  211036. memcpy (&info, device, sizeof (info));
  211037. }
  211038. ~CDDeviceHandle()
  211039. {
  211040. if (controller != 0)
  211041. {
  211042. controller->shutDown();
  211043. controller = 0;
  211044. }
  211045. if (scsiHandle != 0)
  211046. CloseHandle (scsiHandle);
  211047. }
  211048. bool readTOC (TOC* lpToc);
  211049. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  211050. void openDrawer (bool shouldBeOpen);
  211051. CDDeviceInfo info;
  211052. HANDLE scsiHandle;
  211053. BYTE readType;
  211054. private:
  211055. ScopedPointer<CDController> controller;
  211056. bool testController (const int readType,
  211057. CDController* const newController,
  211058. CDReadBuffer* const bufferToUse);
  211059. };
  211060. DWORD (*fGetASPI32SupportInfo)(void);
  211061. DWORD (*fSendASPI32Command)(LPSRB);
  211062. static HINSTANCE winAspiLib = 0;
  211063. static bool usingScsi = false;
  211064. static bool initialised = false;
  211065. static bool InitialiseCDRipper()
  211066. {
  211067. if (! initialised)
  211068. {
  211069. initialised = true;
  211070. OSVERSIONINFO info;
  211071. info.dwOSVersionInfoSize = sizeof (info);
  211072. GetVersionEx (&info);
  211073. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  211074. if (! usingScsi)
  211075. {
  211076. fGetASPI32SupportInfo = 0;
  211077. fSendASPI32Command = 0;
  211078. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  211079. if (winAspiLib != 0)
  211080. {
  211081. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  211082. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  211083. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  211084. return false;
  211085. }
  211086. else
  211087. {
  211088. usingScsi = true;
  211089. }
  211090. }
  211091. }
  211092. return true;
  211093. }
  211094. static void DeinitialiseCDRipper()
  211095. {
  211096. if (winAspiLib != 0)
  211097. {
  211098. fGetASPI32SupportInfo = 0;
  211099. fSendASPI32Command = 0;
  211100. FreeLibrary (winAspiLib);
  211101. winAspiLib = 0;
  211102. }
  211103. initialised = false;
  211104. }
  211105. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  211106. {
  211107. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  211108. OSVERSIONINFO info;
  211109. info.dwOSVersionInfoSize = sizeof (info);
  211110. GetVersionEx (&info);
  211111. DWORD flags = GENERIC_READ;
  211112. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  211113. flags = GENERIC_READ | GENERIC_WRITE;
  211114. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211115. if (h == INVALID_HANDLE_VALUE)
  211116. {
  211117. flags ^= GENERIC_WRITE;
  211118. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211119. }
  211120. return h;
  211121. }
  211122. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  211123. const char driveLetter,
  211124. HANDLE& deviceHandle,
  211125. const bool retryOnFailure = true)
  211126. {
  211127. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  211128. zerostruct (s);
  211129. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  211130. s.spt.CdbLength = srb->SRB_CDBLen;
  211131. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  211132. ? SCSI_IOCTL_DATA_IN
  211133. : ((srb->SRB_Flags & SRB_DIR_OUT)
  211134. ? SCSI_IOCTL_DATA_OUT
  211135. : SCSI_IOCTL_DATA_UNSPECIFIED));
  211136. s.spt.DataTransferLength = srb->SRB_BufLen;
  211137. s.spt.TimeOutValue = 5;
  211138. s.spt.DataBuffer = srb->SRB_BufPointer;
  211139. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211140. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  211141. srb->SRB_Status = SS_ERR;
  211142. srb->SRB_TargStat = 0x0004;
  211143. DWORD bytesReturned = 0;
  211144. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211145. &s, sizeof (s),
  211146. &s, sizeof (s),
  211147. &bytesReturned, 0) != 0)
  211148. {
  211149. srb->SRB_Status = SS_COMP;
  211150. }
  211151. else if (retryOnFailure)
  211152. {
  211153. const DWORD error = GetLastError();
  211154. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211155. {
  211156. if (error != ERROR_INVALID_HANDLE)
  211157. CloseHandle (deviceHandle);
  211158. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211159. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211160. }
  211161. }
  211162. return srb->SRB_Status;
  211163. }
  211164. // Controller types..
  211165. class ControllerType1 : public CDController
  211166. {
  211167. public:
  211168. ControllerType1() {}
  211169. ~ControllerType1() {}
  211170. bool read (CDReadBuffer* rb)
  211171. {
  211172. if (rb->numFrames * 2352 > rb->bufferSize)
  211173. return false;
  211174. SRB_ExecSCSICmd s;
  211175. prepare (s);
  211176. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211177. s.SRB_BufLen = rb->bufferSize;
  211178. s.SRB_BufPointer = rb->buffer;
  211179. s.SRB_CDBLen = 12;
  211180. s.CDBByte[0] = 0xBE;
  211181. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211182. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211183. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211184. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211185. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211186. perform (s);
  211187. if (s.SRB_Status != SS_COMP)
  211188. return false;
  211189. rb->dataLength = rb->numFrames * 2352;
  211190. rb->dataStartOffset = 0;
  211191. return true;
  211192. }
  211193. };
  211194. class ControllerType2 : public CDController
  211195. {
  211196. public:
  211197. ControllerType2() {}
  211198. ~ControllerType2() {}
  211199. void shutDown()
  211200. {
  211201. if (initialised)
  211202. {
  211203. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211204. SRB_ExecSCSICmd s;
  211205. prepare (s);
  211206. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211207. s.SRB_BufLen = 0x0C;
  211208. s.SRB_BufPointer = bufPointer;
  211209. s.SRB_CDBLen = 6;
  211210. s.CDBByte[0] = 0x15;
  211211. s.CDBByte[4] = 0x0C;
  211212. perform (s);
  211213. }
  211214. }
  211215. bool init()
  211216. {
  211217. SRB_ExecSCSICmd s;
  211218. s.SRB_Status = SS_ERR;
  211219. if (deviceInfo->readType == READTYPE_READ10_2)
  211220. {
  211221. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211222. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211223. for (int i = 0; i < 2; ++i)
  211224. {
  211225. prepare (s);
  211226. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211227. s.SRB_BufLen = 0x14;
  211228. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211229. s.SRB_CDBLen = 6;
  211230. s.CDBByte[0] = 0x15;
  211231. s.CDBByte[1] = 0x10;
  211232. s.CDBByte[4] = 0x14;
  211233. perform (s);
  211234. if (s.SRB_Status != SS_COMP)
  211235. return false;
  211236. }
  211237. }
  211238. else
  211239. {
  211240. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211241. prepare (s);
  211242. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211243. s.SRB_BufLen = 0x0C;
  211244. s.SRB_BufPointer = bufPointer;
  211245. s.SRB_CDBLen = 6;
  211246. s.CDBByte[0] = 0x15;
  211247. s.CDBByte[4] = 0x0C;
  211248. perform (s);
  211249. }
  211250. return s.SRB_Status == SS_COMP;
  211251. }
  211252. bool read (CDReadBuffer* rb)
  211253. {
  211254. if (rb->numFrames * 2352 > rb->bufferSize)
  211255. return false;
  211256. if (!initialised)
  211257. {
  211258. initialised = init();
  211259. if (!initialised)
  211260. return false;
  211261. }
  211262. SRB_ExecSCSICmd s;
  211263. prepare (s);
  211264. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211265. s.SRB_BufLen = rb->bufferSize;
  211266. s.SRB_BufPointer = rb->buffer;
  211267. s.SRB_CDBLen = 10;
  211268. s.CDBByte[0] = 0x28;
  211269. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211270. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211271. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211272. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211273. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211274. perform (s);
  211275. if (s.SRB_Status != SS_COMP)
  211276. return false;
  211277. rb->dataLength = rb->numFrames * 2352;
  211278. rb->dataStartOffset = 0;
  211279. return true;
  211280. }
  211281. };
  211282. class ControllerType3 : public CDController
  211283. {
  211284. public:
  211285. ControllerType3() {}
  211286. ~ControllerType3() {}
  211287. bool read (CDReadBuffer* rb)
  211288. {
  211289. if (rb->numFrames * 2352 > rb->bufferSize)
  211290. return false;
  211291. if (!initialised)
  211292. {
  211293. setPaused (false);
  211294. initialised = true;
  211295. }
  211296. SRB_ExecSCSICmd s;
  211297. prepare (s);
  211298. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211299. s.SRB_BufLen = rb->numFrames * 2352;
  211300. s.SRB_BufPointer = rb->buffer;
  211301. s.SRB_CDBLen = 12;
  211302. s.CDBByte[0] = 0xD8;
  211303. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211304. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211305. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211306. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211307. perform (s);
  211308. if (s.SRB_Status != SS_COMP)
  211309. return false;
  211310. rb->dataLength = rb->numFrames * 2352;
  211311. rb->dataStartOffset = 0;
  211312. return true;
  211313. }
  211314. };
  211315. class ControllerType4 : public CDController
  211316. {
  211317. public:
  211318. ControllerType4() {}
  211319. ~ControllerType4() {}
  211320. bool selectD4Mode()
  211321. {
  211322. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211323. SRB_ExecSCSICmd s;
  211324. prepare (s);
  211325. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211326. s.SRB_CDBLen = 6;
  211327. s.SRB_BufLen = 12;
  211328. s.SRB_BufPointer = bufPointer;
  211329. s.CDBByte[0] = 0x15;
  211330. s.CDBByte[1] = 0x10;
  211331. s.CDBByte[4] = 0x08;
  211332. perform (s);
  211333. return s.SRB_Status == SS_COMP;
  211334. }
  211335. bool read (CDReadBuffer* rb)
  211336. {
  211337. if (rb->numFrames * 2352 > rb->bufferSize)
  211338. return false;
  211339. if (!initialised)
  211340. {
  211341. setPaused (true);
  211342. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211343. selectD4Mode();
  211344. initialised = true;
  211345. }
  211346. SRB_ExecSCSICmd s;
  211347. prepare (s);
  211348. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211349. s.SRB_BufLen = rb->bufferSize;
  211350. s.SRB_BufPointer = rb->buffer;
  211351. s.SRB_CDBLen = 10;
  211352. s.CDBByte[0] = 0xD4;
  211353. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211354. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211355. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211356. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211357. perform (s);
  211358. if (s.SRB_Status != SS_COMP)
  211359. return false;
  211360. rb->dataLength = rb->numFrames * 2352;
  211361. rb->dataStartOffset = 0;
  211362. return true;
  211363. }
  211364. };
  211365. CDController::CDController() : initialised (false)
  211366. {
  211367. }
  211368. CDController::~CDController()
  211369. {
  211370. }
  211371. void CDController::prepare (SRB_ExecSCSICmd& s)
  211372. {
  211373. zerostruct (s);
  211374. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211375. s.SRB_HaID = deviceInfo->info.ha;
  211376. s.SRB_Target = deviceInfo->info.tgt;
  211377. s.SRB_Lun = deviceInfo->info.lun;
  211378. s.SRB_SenseLen = SENSE_LEN;
  211379. }
  211380. void CDController::perform (SRB_ExecSCSICmd& s)
  211381. {
  211382. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211383. s.SRB_PostProc = event;
  211384. ResetEvent (event);
  211385. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211386. deviceInfo->info.scsiDriveLetter,
  211387. deviceInfo->scsiHandle)
  211388. : fSendASPI32Command ((LPSRB)&s);
  211389. if (status == SS_PENDING)
  211390. WaitForSingleObject (event, 4000);
  211391. CloseHandle (event);
  211392. }
  211393. void CDController::setPaused (bool paused)
  211394. {
  211395. SRB_ExecSCSICmd s;
  211396. prepare (s);
  211397. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211398. s.SRB_CDBLen = 10;
  211399. s.CDBByte[0] = 0x4B;
  211400. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211401. perform (s);
  211402. }
  211403. void CDController::shutDown()
  211404. {
  211405. }
  211406. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211407. {
  211408. if (overlapBuffer != 0)
  211409. {
  211410. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211411. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211412. if (doJitter
  211413. && overlapBuffer->startFrame > 0
  211414. && overlapBuffer->numFrames > 0
  211415. && overlapBuffer->dataLength > 0)
  211416. {
  211417. const int numFrames = rb->numFrames;
  211418. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211419. {
  211420. rb->startFrame -= framesOverlap;
  211421. if (framesToCheck < framesOverlap
  211422. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211423. rb->numFrames += framesOverlap;
  211424. }
  211425. else
  211426. {
  211427. overlapBuffer->dataLength = 0;
  211428. overlapBuffer->startFrame = 0;
  211429. overlapBuffer->numFrames = 0;
  211430. }
  211431. }
  211432. if (! read (rb))
  211433. return false;
  211434. if (doJitter)
  211435. {
  211436. const int checkLen = framesToCheck * 2352;
  211437. const int maxToCheck = rb->dataLength - checkLen;
  211438. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211439. return true;
  211440. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211441. bool found = false;
  211442. for (int i = 0; i < maxToCheck; ++i)
  211443. {
  211444. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211445. {
  211446. i += checkLen;
  211447. rb->dataStartOffset = i;
  211448. rb->dataLength -= i;
  211449. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211450. found = true;
  211451. break;
  211452. }
  211453. }
  211454. rb->numFrames = rb->dataLength / 2352;
  211455. rb->dataLength = 2352 * rb->numFrames;
  211456. if (!found)
  211457. return false;
  211458. }
  211459. if (canDoJitter)
  211460. {
  211461. memcpy (overlapBuffer->buffer,
  211462. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211463. 2352 * framesToCheck);
  211464. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211465. overlapBuffer->numFrames = framesToCheck;
  211466. overlapBuffer->dataLength = 2352 * framesToCheck;
  211467. overlapBuffer->dataStartOffset = 0;
  211468. }
  211469. else
  211470. {
  211471. overlapBuffer->startFrame = 0;
  211472. overlapBuffer->numFrames = 0;
  211473. overlapBuffer->dataLength = 0;
  211474. }
  211475. return true;
  211476. }
  211477. else
  211478. {
  211479. return read (rb);
  211480. }
  211481. }
  211482. int CDController::getLastIndex()
  211483. {
  211484. char qdata[100];
  211485. SRB_ExecSCSICmd s;
  211486. prepare (s);
  211487. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211488. s.SRB_BufLen = sizeof (qdata);
  211489. s.SRB_BufPointer = (BYTE*)qdata;
  211490. s.SRB_CDBLen = 12;
  211491. s.CDBByte[0] = 0x42;
  211492. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211493. s.CDBByte[2] = 64;
  211494. s.CDBByte[3] = 1; // get current position
  211495. s.CDBByte[7] = 0;
  211496. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211497. perform (s);
  211498. if (s.SRB_Status == SS_COMP)
  211499. return qdata[7];
  211500. return 0;
  211501. }
  211502. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211503. {
  211504. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211505. SRB_ExecSCSICmd s;
  211506. zerostruct (s);
  211507. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211508. s.SRB_HaID = info.ha;
  211509. s.SRB_Target = info.tgt;
  211510. s.SRB_Lun = info.lun;
  211511. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211512. s.SRB_BufLen = 0x324;
  211513. s.SRB_BufPointer = (BYTE*)lpToc;
  211514. s.SRB_SenseLen = 0x0E;
  211515. s.SRB_CDBLen = 0x0A;
  211516. s.SRB_PostProc = event;
  211517. s.CDBByte[0] = 0x43;
  211518. s.CDBByte[1] = 0x00;
  211519. s.CDBByte[7] = 0x03;
  211520. s.CDBByte[8] = 0x24;
  211521. ResetEvent (event);
  211522. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211523. : fSendASPI32Command ((LPSRB)&s);
  211524. if (status == SS_PENDING)
  211525. WaitForSingleObject (event, 4000);
  211526. CloseHandle (event);
  211527. return (s.SRB_Status == SS_COMP);
  211528. }
  211529. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211530. CDReadBuffer* const overlapBuffer)
  211531. {
  211532. if (controller == 0)
  211533. {
  211534. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211535. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211536. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211537. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211538. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211539. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211540. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211541. }
  211542. buffer->index = 0;
  211543. if ((controller != 0)
  211544. && controller->readAudio (buffer, overlapBuffer))
  211545. {
  211546. if (buffer->wantsIndex)
  211547. buffer->index = controller->getLastIndex();
  211548. return true;
  211549. }
  211550. return false;
  211551. }
  211552. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211553. {
  211554. if (shouldBeOpen)
  211555. {
  211556. if (controller != 0)
  211557. {
  211558. controller->shutDown();
  211559. controller = 0;
  211560. }
  211561. if (scsiHandle != 0)
  211562. {
  211563. CloseHandle (scsiHandle);
  211564. scsiHandle = 0;
  211565. }
  211566. }
  211567. SRB_ExecSCSICmd s;
  211568. zerostruct (s);
  211569. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211570. s.SRB_HaID = info.ha;
  211571. s.SRB_Target = info.tgt;
  211572. s.SRB_Lun = info.lun;
  211573. s.SRB_SenseLen = SENSE_LEN;
  211574. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211575. s.SRB_BufLen = 0;
  211576. s.SRB_BufPointer = 0;
  211577. s.SRB_CDBLen = 12;
  211578. s.CDBByte[0] = 0x1b;
  211579. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211580. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211581. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211582. s.SRB_PostProc = event;
  211583. ResetEvent (event);
  211584. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211585. : fSendASPI32Command ((LPSRB)&s);
  211586. if (status == SS_PENDING)
  211587. WaitForSingleObject (event, 4000);
  211588. CloseHandle (event);
  211589. }
  211590. bool CDDeviceHandle::testController (const int type,
  211591. CDController* const newController,
  211592. CDReadBuffer* const rb)
  211593. {
  211594. controller = newController;
  211595. readType = (BYTE)type;
  211596. controller->deviceInfo = this;
  211597. controller->framesToCheck = 1;
  211598. controller->framesOverlap = 3;
  211599. bool passed = false;
  211600. memset (rb->buffer, 0xcd, rb->bufferSize);
  211601. if (controller->read (rb))
  211602. {
  211603. passed = true;
  211604. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211605. int wrong = 0;
  211606. for (int i = rb->dataLength / 4; --i >= 0;)
  211607. {
  211608. if (*p++ == (int) 0xcdcdcdcd)
  211609. {
  211610. if (++wrong == 4)
  211611. {
  211612. passed = false;
  211613. break;
  211614. }
  211615. }
  211616. else
  211617. {
  211618. wrong = 0;
  211619. }
  211620. }
  211621. }
  211622. if (! passed)
  211623. {
  211624. controller->shutDown();
  211625. controller = 0;
  211626. }
  211627. return passed;
  211628. }
  211629. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211630. {
  211631. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211632. const int bufSize = 128;
  211633. BYTE buffer[bufSize];
  211634. zeromem (buffer, bufSize);
  211635. SRB_ExecSCSICmd s;
  211636. zerostruct (s);
  211637. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211638. s.SRB_HaID = ha;
  211639. s.SRB_Target = tgt;
  211640. s.SRB_Lun = lun;
  211641. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211642. s.SRB_BufLen = bufSize;
  211643. s.SRB_BufPointer = buffer;
  211644. s.SRB_SenseLen = SENSE_LEN;
  211645. s.SRB_CDBLen = 6;
  211646. s.SRB_PostProc = event;
  211647. s.CDBByte[0] = SCSI_INQUIRY;
  211648. s.CDBByte[4] = 100;
  211649. ResetEvent (event);
  211650. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211651. WaitForSingleObject (event, 4000);
  211652. CloseHandle (event);
  211653. if (s.SRB_Status == SS_COMP)
  211654. {
  211655. memcpy (dev->vendor, &buffer[8], 8);
  211656. memcpy (dev->productId, &buffer[16], 16);
  211657. memcpy (dev->rev, &buffer[32], 4);
  211658. memcpy (dev->vendorSpec, &buffer[36], 20);
  211659. }
  211660. }
  211661. static int FindCDDevices (CDDeviceInfo* const list,
  211662. int maxItems)
  211663. {
  211664. int count = 0;
  211665. if (usingScsi)
  211666. {
  211667. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211668. {
  211669. TCHAR drivePath[8];
  211670. drivePath[0] = driveLetter;
  211671. drivePath[1] = ':';
  211672. drivePath[2] = '\\';
  211673. drivePath[3] = 0;
  211674. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211675. {
  211676. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211677. if (h != INVALID_HANDLE_VALUE)
  211678. {
  211679. BYTE buffer[100], passThroughStruct[1024];
  211680. zeromem (buffer, sizeof (buffer));
  211681. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211682. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211683. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211684. p->spt.CdbLength = 6;
  211685. p->spt.SenseInfoLength = 24;
  211686. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211687. p->spt.DataTransferLength = 100;
  211688. p->spt.TimeOutValue = 2;
  211689. p->spt.DataBuffer = buffer;
  211690. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211691. p->spt.Cdb[0] = 0x12;
  211692. p->spt.Cdb[4] = 100;
  211693. DWORD bytesReturned = 0;
  211694. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211695. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211696. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211697. &bytesReturned, 0) != 0)
  211698. {
  211699. zeromem (&list[count], sizeof (CDDeviceInfo));
  211700. list[count].scsiDriveLetter = driveLetter;
  211701. memcpy (list[count].vendor, &buffer[8], 8);
  211702. memcpy (list[count].productId, &buffer[16], 16);
  211703. memcpy (list[count].rev, &buffer[32], 4);
  211704. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211705. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211706. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211707. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211708. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211709. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211710. &bytesReturned, 0) != 0)
  211711. {
  211712. list[count].ha = scsiAddr->PortNumber;
  211713. list[count].tgt = scsiAddr->TargetId;
  211714. list[count].lun = scsiAddr->Lun;
  211715. ++count;
  211716. }
  211717. }
  211718. CloseHandle (h);
  211719. }
  211720. }
  211721. }
  211722. }
  211723. else
  211724. {
  211725. const DWORD d = fGetASPI32SupportInfo();
  211726. BYTE status = HIBYTE (LOWORD (d));
  211727. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211728. return 0;
  211729. const int numAdapters = LOBYTE (LOWORD (d));
  211730. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211731. {
  211732. SRB_HAInquiry s;
  211733. zerostruct (s);
  211734. s.SRB_Cmd = SC_HA_INQUIRY;
  211735. s.SRB_HaID = ha;
  211736. fSendASPI32Command ((LPSRB)&s);
  211737. if (s.SRB_Status == SS_COMP)
  211738. {
  211739. maxItems = (int)s.HA_Unique[3];
  211740. if (maxItems == 0)
  211741. maxItems = 8;
  211742. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211743. {
  211744. for (BYTE lun = 0; lun < 8; ++lun)
  211745. {
  211746. SRB_GDEVBlock sb;
  211747. zerostruct (sb);
  211748. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211749. sb.SRB_HaID = ha;
  211750. sb.SRB_Target = tgt;
  211751. sb.SRB_Lun = lun;
  211752. fSendASPI32Command ((LPSRB) &sb);
  211753. if (sb.SRB_Status == SS_COMP
  211754. && sb.SRB_DeviceType == DTYPE_CROM)
  211755. {
  211756. zeromem (&list[count], sizeof (CDDeviceInfo));
  211757. list[count].ha = ha;
  211758. list[count].tgt = tgt;
  211759. list[count].lun = lun;
  211760. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211761. ++count;
  211762. }
  211763. }
  211764. }
  211765. }
  211766. }
  211767. }
  211768. return count;
  211769. }
  211770. static int ripperUsers = 0;
  211771. static bool initialisedOk = false;
  211772. class DeinitialiseTimer : private Timer,
  211773. private DeletedAtShutdown
  211774. {
  211775. DeinitialiseTimer (const DeinitialiseTimer&);
  211776. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211777. public:
  211778. DeinitialiseTimer()
  211779. {
  211780. startTimer (4000);
  211781. }
  211782. ~DeinitialiseTimer()
  211783. {
  211784. if (--ripperUsers == 0)
  211785. DeinitialiseCDRipper();
  211786. }
  211787. void timerCallback()
  211788. {
  211789. delete this;
  211790. }
  211791. juce_UseDebuggingNewOperator
  211792. };
  211793. static void incUserCount()
  211794. {
  211795. if (ripperUsers++ == 0)
  211796. initialisedOk = InitialiseCDRipper();
  211797. }
  211798. static void decUserCount()
  211799. {
  211800. new DeinitialiseTimer();
  211801. }
  211802. struct CDDeviceWrapper
  211803. {
  211804. ScopedPointer<CDDeviceHandle> cdH;
  211805. ScopedPointer<CDReadBuffer> overlapBuffer;
  211806. bool jitter;
  211807. };
  211808. static int getAddressOf (const TOCTRACK* const t)
  211809. {
  211810. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211811. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211812. }
  211813. static const int samplesPerFrame = 44100 / 75;
  211814. static const int bytesPerFrame = samplesPerFrame * 4;
  211815. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211816. {
  211817. SRB_GDEVBlock s;
  211818. zerostruct (s);
  211819. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211820. s.SRB_HaID = device->ha;
  211821. s.SRB_Target = device->tgt;
  211822. s.SRB_Lun = device->lun;
  211823. if (usingScsi)
  211824. {
  211825. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211826. if (h != INVALID_HANDLE_VALUE)
  211827. {
  211828. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211829. cdh->scsiHandle = h;
  211830. return cdh;
  211831. }
  211832. }
  211833. else
  211834. {
  211835. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211836. && s.SRB_DeviceType == DTYPE_CROM)
  211837. {
  211838. return new CDDeviceHandle (device);
  211839. }
  211840. }
  211841. return 0;
  211842. }
  211843. }
  211844. const StringArray AudioCDReader::getAvailableCDNames()
  211845. {
  211846. using namespace CDReaderHelpers;
  211847. StringArray results;
  211848. incUserCount();
  211849. if (initialisedOk)
  211850. {
  211851. CDDeviceInfo list[8];
  211852. const int num = FindCDDevices (list, 8);
  211853. decUserCount();
  211854. for (int i = 0; i < num; ++i)
  211855. {
  211856. String s;
  211857. if (list[i].scsiDriveLetter > 0)
  211858. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211859. s << String (list[i].vendor).trim()
  211860. << ' ' << String (list[i].productId).trim()
  211861. << ' ' << String (list[i].rev).trim();
  211862. results.add (s);
  211863. }
  211864. }
  211865. return results;
  211866. }
  211867. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211868. {
  211869. using namespace CDReaderHelpers;
  211870. incUserCount();
  211871. if (initialisedOk)
  211872. {
  211873. CDDeviceInfo list[8];
  211874. const int num = FindCDDevices (list, 8);
  211875. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211876. {
  211877. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211878. if (handle != 0)
  211879. {
  211880. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211881. d->cdH = handle;
  211882. d->overlapBuffer = new CDReadBuffer(3);
  211883. return new AudioCDReader (d);
  211884. }
  211885. }
  211886. }
  211887. decUserCount();
  211888. return 0;
  211889. }
  211890. AudioCDReader::AudioCDReader (void* handle_)
  211891. : AudioFormatReader (0, "CD Audio"),
  211892. handle (handle_),
  211893. indexingEnabled (false),
  211894. lastIndex (0),
  211895. firstFrameInBuffer (0),
  211896. samplesInBuffer (0)
  211897. {
  211898. using namespace CDReaderHelpers;
  211899. jassert (handle_ != 0);
  211900. refreshTrackLengths();
  211901. sampleRate = 44100.0;
  211902. bitsPerSample = 16;
  211903. numChannels = 2;
  211904. usesFloatingPointData = false;
  211905. buffer.setSize (4 * bytesPerFrame, true);
  211906. }
  211907. AudioCDReader::~AudioCDReader()
  211908. {
  211909. using namespace CDReaderHelpers;
  211910. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211911. delete device;
  211912. decUserCount();
  211913. }
  211914. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211915. int64 startSampleInFile, int numSamples)
  211916. {
  211917. using namespace CDReaderHelpers;
  211918. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211919. bool ok = true;
  211920. while (numSamples > 0)
  211921. {
  211922. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211923. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211924. if (startSampleInFile >= bufferStartSample
  211925. && startSampleInFile < bufferEndSample)
  211926. {
  211927. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211928. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211929. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211930. const short* src = (const short*) buffer.getData();
  211931. src += 2 * (startSampleInFile - bufferStartSample);
  211932. for (int i = 0; i < toDo; ++i)
  211933. {
  211934. l[i] = src [i << 1] << 16;
  211935. if (r != 0)
  211936. r[i] = src [(i << 1) + 1] << 16;
  211937. }
  211938. startOffsetInDestBuffer += toDo;
  211939. startSampleInFile += toDo;
  211940. numSamples -= toDo;
  211941. }
  211942. else
  211943. {
  211944. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211945. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211946. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211947. {
  211948. device->overlapBuffer->dataLength = 0;
  211949. device->overlapBuffer->startFrame = 0;
  211950. device->overlapBuffer->numFrames = 0;
  211951. device->jitter = false;
  211952. }
  211953. firstFrameInBuffer = frameNeeded;
  211954. lastIndex = 0;
  211955. CDReadBuffer readBuffer (framesInBuffer + 4);
  211956. readBuffer.wantsIndex = indexingEnabled;
  211957. int i;
  211958. for (i = 5; --i >= 0;)
  211959. {
  211960. readBuffer.startFrame = frameNeeded;
  211961. readBuffer.numFrames = framesInBuffer;
  211962. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211963. break;
  211964. else
  211965. device->overlapBuffer->dataLength = 0;
  211966. }
  211967. if (i >= 0)
  211968. {
  211969. memcpy ((char*) buffer.getData(),
  211970. readBuffer.buffer + readBuffer.dataStartOffset,
  211971. readBuffer.dataLength);
  211972. samplesInBuffer = readBuffer.dataLength >> 2;
  211973. lastIndex = readBuffer.index;
  211974. }
  211975. else
  211976. {
  211977. int* l = destSamples[0] + startOffsetInDestBuffer;
  211978. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211979. while (--numSamples >= 0)
  211980. {
  211981. *l++ = 0;
  211982. if (r != 0)
  211983. *r++ = 0;
  211984. }
  211985. // sometimes the read fails for just the very last couple of blocks, so
  211986. // we'll ignore and errors in the last half-second of the disk..
  211987. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211988. break;
  211989. }
  211990. }
  211991. }
  211992. return ok;
  211993. }
  211994. bool AudioCDReader::isCDStillPresent() const
  211995. {
  211996. using namespace CDReaderHelpers;
  211997. TOC toc;
  211998. zerostruct (toc);
  211999. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  212000. }
  212001. void AudioCDReader::refreshTrackLengths()
  212002. {
  212003. using namespace CDReaderHelpers;
  212004. trackStartSamples.clear();
  212005. zeromem (audioTracks, sizeof (audioTracks));
  212006. TOC toc;
  212007. zerostruct (toc);
  212008. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  212009. {
  212010. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  212011. for (int i = 0; i <= numTracks; ++i)
  212012. {
  212013. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  212014. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  212015. }
  212016. }
  212017. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  212018. }
  212019. bool AudioCDReader::isTrackAudio (int trackNum) const
  212020. {
  212021. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  212022. }
  212023. void AudioCDReader::enableIndexScanning (bool b)
  212024. {
  212025. indexingEnabled = b;
  212026. }
  212027. int AudioCDReader::getLastIndex() const
  212028. {
  212029. return lastIndex;
  212030. }
  212031. const int framesPerIndexRead = 4;
  212032. int AudioCDReader::getIndexAt (int samplePos)
  212033. {
  212034. using namespace CDReaderHelpers;
  212035. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212036. const int frameNeeded = samplePos / samplesPerFrame;
  212037. device->overlapBuffer->dataLength = 0;
  212038. device->overlapBuffer->startFrame = 0;
  212039. device->overlapBuffer->numFrames = 0;
  212040. device->jitter = false;
  212041. firstFrameInBuffer = 0;
  212042. lastIndex = 0;
  212043. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  212044. readBuffer.wantsIndex = true;
  212045. int i;
  212046. for (i = 5; --i >= 0;)
  212047. {
  212048. readBuffer.startFrame = frameNeeded;
  212049. readBuffer.numFrames = framesPerIndexRead;
  212050. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212051. break;
  212052. }
  212053. if (i >= 0)
  212054. return readBuffer.index;
  212055. return -1;
  212056. }
  212057. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  212058. {
  212059. using namespace CDReaderHelpers;
  212060. Array <int> indexes;
  212061. const int trackStart = getPositionOfTrackStart (trackNumber);
  212062. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  212063. bool needToScan = true;
  212064. if (trackEnd - trackStart > 20 * 44100)
  212065. {
  212066. // check the end of the track for indexes before scanning the whole thing
  212067. needToScan = false;
  212068. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  212069. bool seenAnIndex = false;
  212070. while (pos <= trackEnd - samplesPerFrame)
  212071. {
  212072. const int index = getIndexAt (pos);
  212073. if (index == 0)
  212074. {
  212075. // lead-out, so skip back a bit if we've not found any indexes yet..
  212076. if (seenAnIndex)
  212077. break;
  212078. pos -= 44100 * 5;
  212079. if (pos < trackStart)
  212080. break;
  212081. }
  212082. else
  212083. {
  212084. if (index > 0)
  212085. seenAnIndex = true;
  212086. if (index > 1)
  212087. {
  212088. needToScan = true;
  212089. break;
  212090. }
  212091. pos += samplesPerFrame * framesPerIndexRead;
  212092. }
  212093. }
  212094. }
  212095. if (needToScan)
  212096. {
  212097. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212098. int pos = trackStart;
  212099. int last = -1;
  212100. while (pos < trackEnd - samplesPerFrame * 10)
  212101. {
  212102. const int frameNeeded = pos / samplesPerFrame;
  212103. device->overlapBuffer->dataLength = 0;
  212104. device->overlapBuffer->startFrame = 0;
  212105. device->overlapBuffer->numFrames = 0;
  212106. device->jitter = false;
  212107. firstFrameInBuffer = 0;
  212108. CDReadBuffer readBuffer (4);
  212109. readBuffer.wantsIndex = true;
  212110. int i;
  212111. for (i = 5; --i >= 0;)
  212112. {
  212113. readBuffer.startFrame = frameNeeded;
  212114. readBuffer.numFrames = framesPerIndexRead;
  212115. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212116. break;
  212117. }
  212118. if (i < 0)
  212119. break;
  212120. if (readBuffer.index > last && readBuffer.index > 1)
  212121. {
  212122. last = readBuffer.index;
  212123. indexes.add (pos);
  212124. }
  212125. pos += samplesPerFrame * framesPerIndexRead;
  212126. }
  212127. indexes.removeValue (trackStart);
  212128. }
  212129. return indexes;
  212130. }
  212131. void AudioCDReader::ejectDisk()
  212132. {
  212133. using namespace CDReaderHelpers;
  212134. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  212135. }
  212136. #endif
  212137. #if JUCE_USE_CDBURNER
  212138. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  212139. {
  212140. CoInitialize (0);
  212141. IDiscMaster* dm;
  212142. IDiscRecorder* result = 0;
  212143. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212144. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212145. IID_IDiscMaster,
  212146. (void**) &dm)))
  212147. {
  212148. if (SUCCEEDED (dm->Open()))
  212149. {
  212150. IEnumDiscRecorders* drEnum = 0;
  212151. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212152. {
  212153. IDiscRecorder* dr = 0;
  212154. DWORD dummy;
  212155. int index = 0;
  212156. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212157. {
  212158. if (indexToOpen == index)
  212159. {
  212160. result = dr;
  212161. break;
  212162. }
  212163. else if (list != 0)
  212164. {
  212165. BSTR path;
  212166. if (SUCCEEDED (dr->GetPath (&path)))
  212167. list->add ((const WCHAR*) path);
  212168. }
  212169. ++index;
  212170. dr->Release();
  212171. }
  212172. drEnum->Release();
  212173. }
  212174. if (master == 0)
  212175. dm->Close();
  212176. }
  212177. if (master != 0)
  212178. *master = dm;
  212179. else
  212180. dm->Release();
  212181. }
  212182. return result;
  212183. }
  212184. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212185. public Timer
  212186. {
  212187. public:
  212188. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212189. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212190. listener (0), progress (0), shouldCancel (false)
  212191. {
  212192. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212193. jassert (SUCCEEDED (hr));
  212194. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212195. //jassert (SUCCEEDED (hr));
  212196. lastState = getDiskState();
  212197. startTimer (2000);
  212198. }
  212199. ~Pimpl() {}
  212200. void releaseObjects()
  212201. {
  212202. discRecorder->Close();
  212203. if (redbook != 0)
  212204. redbook->Release();
  212205. discRecorder->Release();
  212206. discMaster->Release();
  212207. Release();
  212208. }
  212209. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212210. {
  212211. if (listener != 0 && ! shouldCancel)
  212212. shouldCancel = listener->audioCDBurnProgress (progress);
  212213. *pbCancel = shouldCancel;
  212214. return S_OK;
  212215. }
  212216. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212217. {
  212218. progress = nCompleted / (float) nTotal;
  212219. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212220. return E_NOTIMPL;
  212221. }
  212222. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212223. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212224. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212225. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212226. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212227. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212228. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212229. class ScopedDiscOpener
  212230. {
  212231. public:
  212232. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212233. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212234. private:
  212235. Pimpl& pimpl;
  212236. ScopedDiscOpener (const ScopedDiscOpener&);
  212237. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212238. };
  212239. DiskState getDiskState()
  212240. {
  212241. const ScopedDiscOpener opener (*this);
  212242. long type, flags;
  212243. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212244. if (FAILED (hr))
  212245. return unknown;
  212246. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212247. return writableDiskPresent;
  212248. if (type == 0)
  212249. return noDisc;
  212250. else
  212251. return readOnlyDiskPresent;
  212252. }
  212253. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212254. {
  212255. ComSmartPtr<IPropertyStorage> prop;
  212256. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  212257. return defaultReturn;
  212258. PROPSPEC iPropSpec;
  212259. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212260. iPropSpec.lpwstr = name;
  212261. PROPVARIANT iPropVariant;
  212262. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212263. ? defaultReturn : (int) iPropVariant.lVal;
  212264. }
  212265. bool setIntProperty (const LPOLESTR name, const int value) const
  212266. {
  212267. ComSmartPtr<IPropertyStorage> prop;
  212268. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  212269. return false;
  212270. PROPSPEC iPropSpec;
  212271. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212272. iPropSpec.lpwstr = name;
  212273. PROPVARIANT iPropVariant;
  212274. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212275. return false;
  212276. iPropVariant.lVal = (long) value;
  212277. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212278. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212279. }
  212280. void timerCallback()
  212281. {
  212282. const DiskState state = getDiskState();
  212283. if (state != lastState)
  212284. {
  212285. lastState = state;
  212286. owner.sendChangeMessage (&owner);
  212287. }
  212288. }
  212289. AudioCDBurner& owner;
  212290. DiskState lastState;
  212291. IDiscMaster* discMaster;
  212292. IDiscRecorder* discRecorder;
  212293. IRedbookDiscMaster* redbook;
  212294. AudioCDBurner::BurnProgressListener* listener;
  212295. float progress;
  212296. bool shouldCancel;
  212297. };
  212298. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212299. {
  212300. IDiscMaster* discMaster = 0;
  212301. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  212302. if (discRecorder != 0)
  212303. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212304. }
  212305. AudioCDBurner::~AudioCDBurner()
  212306. {
  212307. if (pimpl != 0)
  212308. pimpl.release()->releaseObjects();
  212309. }
  212310. const StringArray AudioCDBurner::findAvailableDevices()
  212311. {
  212312. StringArray devs;
  212313. enumCDBurners (&devs, -1, 0);
  212314. return devs;
  212315. }
  212316. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212317. {
  212318. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212319. if (b->pimpl == 0)
  212320. b = 0;
  212321. return b.release();
  212322. }
  212323. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212324. {
  212325. return pimpl->getDiskState();
  212326. }
  212327. bool AudioCDBurner::isDiskPresent() const
  212328. {
  212329. return getDiskState() == writableDiskPresent;
  212330. }
  212331. bool AudioCDBurner::openTray()
  212332. {
  212333. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212334. return SUCCEEDED (pimpl->discRecorder->Eject());
  212335. }
  212336. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212337. {
  212338. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212339. DiskState oldState = getDiskState();
  212340. DiskState newState = oldState;
  212341. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212342. {
  212343. newState = getDiskState();
  212344. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212345. }
  212346. return newState;
  212347. }
  212348. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212349. {
  212350. Array<int> results;
  212351. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212352. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212353. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212354. if (speeds[i] <= maxSpeed)
  212355. results.add (speeds[i]);
  212356. results.addIfNotAlreadyThere (maxSpeed);
  212357. return results;
  212358. }
  212359. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212360. {
  212361. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212362. return false;
  212363. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212364. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212365. }
  212366. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212367. {
  212368. long blocksFree = 0;
  212369. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212370. return blocksFree;
  212371. }
  212372. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212373. bool performFakeBurnForTesting, int writeSpeed)
  212374. {
  212375. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212376. pimpl->listener = listener;
  212377. pimpl->progress = 0;
  212378. pimpl->shouldCancel = false;
  212379. UINT_PTR cookie;
  212380. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212381. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212382. ejectDiscAfterwards);
  212383. String error;
  212384. if (hr != S_OK)
  212385. {
  212386. const char* e = "Couldn't open or write to the CD device";
  212387. if (hr == IMAPI_E_USERABORT)
  212388. e = "User cancelled the write operation";
  212389. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212390. e = "No Disk present";
  212391. error = e;
  212392. }
  212393. pimpl->discMaster->ProgressUnadvise (cookie);
  212394. pimpl->listener = 0;
  212395. return error;
  212396. }
  212397. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212398. {
  212399. if (audioSource == 0)
  212400. return false;
  212401. ScopedPointer<AudioSource> source (audioSource);
  212402. long bytesPerBlock;
  212403. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212404. const int samplesPerBlock = bytesPerBlock / 4;
  212405. bool ok = true;
  212406. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212407. HeapBlock <byte> buffer (bytesPerBlock);
  212408. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212409. int samplesDone = 0;
  212410. source->prepareToPlay (samplesPerBlock, 44100.0);
  212411. while (ok)
  212412. {
  212413. {
  212414. AudioSourceChannelInfo info;
  212415. info.buffer = &sourceBuffer;
  212416. info.numSamples = samplesPerBlock;
  212417. info.startSample = 0;
  212418. sourceBuffer.clear();
  212419. source->getNextAudioBlock (info);
  212420. }
  212421. zeromem (buffer, bytesPerBlock);
  212422. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  212423. buffer, samplesPerBlock, 4);
  212424. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  212425. buffer + 2, samplesPerBlock, 4);
  212426. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212427. if (FAILED (hr))
  212428. ok = false;
  212429. samplesDone += samplesPerBlock;
  212430. if (samplesDone >= numSamples)
  212431. break;
  212432. }
  212433. hr = pimpl->redbook->CloseAudioTrack();
  212434. return ok && hr == S_OK;
  212435. }
  212436. #endif
  212437. #endif
  212438. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212439. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212440. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212441. // compiled on its own).
  212442. #if JUCE_INCLUDED_FILE
  212443. class MidiInThread : public Thread
  212444. {
  212445. public:
  212446. MidiInThread (MidiInput* const input_,
  212447. MidiInputCallback* const callback_)
  212448. : Thread ("Juce Midi"),
  212449. deviceHandle (0),
  212450. input (input_),
  212451. callback (callback_),
  212452. isStarted (false),
  212453. startTime (0)
  212454. {
  212455. pending.ensureSize ((int) defaultBufferSize);
  212456. for (int i = (int) numInHeaders; --i >= 0;)
  212457. {
  212458. zeromem (&hdr[i], sizeof (MIDIHDR));
  212459. hdr[i].lpData = inData[i];
  212460. hdr[i].dwBufferLength = (int) inBufferSize;
  212461. }
  212462. };
  212463. ~MidiInThread()
  212464. {
  212465. stop();
  212466. if (deviceHandle != 0)
  212467. {
  212468. int count = 5;
  212469. while (--count >= 0)
  212470. {
  212471. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212472. break;
  212473. Sleep (20);
  212474. }
  212475. }
  212476. }
  212477. void handle (const uint32 message, const uint32 timeStamp)
  212478. {
  212479. const int byte = message & 0xff;
  212480. if (byte < 0x80)
  212481. return;
  212482. const int time = timeStampToMs (timeStamp);
  212483. {
  212484. const ScopedLock sl (lock);
  212485. pending.addEvent (&message, 3, time);
  212486. }
  212487. notify();
  212488. }
  212489. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212490. {
  212491. const int time = timeStampToMs (timeStamp);
  212492. const int num = hdr->dwBytesRecorded;
  212493. if (num > 0)
  212494. {
  212495. {
  212496. const ScopedLock sl (lock);
  212497. pending.addEvent (hdr->lpData, num, time);
  212498. }
  212499. notify();
  212500. }
  212501. }
  212502. void writeBlock (const int i)
  212503. {
  212504. hdr[i].dwBytesRecorded = 0;
  212505. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr[i], sizeof (MIDIHDR));
  212506. jassert (res == MMSYSERR_NOERROR);
  212507. res = midiInAddBuffer (deviceHandle, &hdr[i], sizeof (MIDIHDR));
  212508. jassert (res == MMSYSERR_NOERROR);
  212509. }
  212510. void run()
  212511. {
  212512. MidiBuffer newEvents;
  212513. newEvents.ensureSize ((int) defaultBufferSize);
  212514. while (! threadShouldExit())
  212515. {
  212516. for (int i = 0; i < (int) numInHeaders; ++i)
  212517. {
  212518. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212519. {
  212520. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr[i], sizeof (MIDIHDR));
  212521. (void) res;
  212522. jassert (res == MMSYSERR_NOERROR);
  212523. writeBlock (i);
  212524. }
  212525. }
  212526. newEvents.clear(); // (resets it without freeing allocated storage)
  212527. {
  212528. const ScopedLock sl (lock);
  212529. newEvents.swapWith (pending);
  212530. }
  212531. //xxx needs to figure out if blocks are broken up or not
  212532. if (newEvents.isEmpty())
  212533. {
  212534. wait (500);
  212535. }
  212536. else
  212537. {
  212538. MidiMessage message (0xf4, 0.0);
  212539. int time;
  212540. for (MidiBuffer::Iterator i (newEvents); i.getNextEvent (message, time);)
  212541. {
  212542. message.setTimeStamp (time * 0.001);
  212543. callback->handleIncomingMidiMessage (input, message);
  212544. }
  212545. }
  212546. }
  212547. }
  212548. void start()
  212549. {
  212550. jassert (deviceHandle != 0);
  212551. if (deviceHandle != 0 && ! isStarted)
  212552. {
  212553. stop();
  212554. activeMidiThreads.addIfNotAlreadyThere (this);
  212555. int i;
  212556. for (i = 0; i < (int) numInHeaders; ++i)
  212557. writeBlock (i);
  212558. startTime = Time::getMillisecondCounter();
  212559. MMRESULT res = midiInStart (deviceHandle);
  212560. jassert (res == MMSYSERR_NOERROR);
  212561. if (res == MMSYSERR_NOERROR)
  212562. {
  212563. isStarted = true;
  212564. pending.clear();
  212565. startThread (6);
  212566. }
  212567. }
  212568. }
  212569. void stop()
  212570. {
  212571. if (isStarted)
  212572. {
  212573. stopThread (5000);
  212574. midiInReset (deviceHandle);
  212575. midiInStop (deviceHandle);
  212576. activeMidiThreads.removeValue (this);
  212577. { const ScopedLock sl (lock); }
  212578. for (int i = (int) numInHeaders; --i >= 0;)
  212579. {
  212580. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212581. {
  212582. int c = 10;
  212583. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  212584. Sleep (20);
  212585. jassert (c >= 0);
  212586. }
  212587. }
  212588. isStarted = false;
  212589. pending.clear();
  212590. }
  212591. }
  212592. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212593. {
  212594. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  212595. if (thread != 0 && activeMidiThreads.contains (thread))
  212596. {
  212597. if (uMsg == MIM_DATA)
  212598. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  212599. else if (uMsg == MIM_LONGDATA)
  212600. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212601. }
  212602. }
  212603. juce_UseDebuggingNewOperator
  212604. HMIDIIN deviceHandle;
  212605. private:
  212606. static Array <void*, CriticalSection> activeMidiThreads;
  212607. MidiInput* input;
  212608. MidiInputCallback* callback;
  212609. bool isStarted;
  212610. uint32 startTime;
  212611. CriticalSection lock;
  212612. enum { defaultBufferSize = 8192,
  212613. numInHeaders = 32,
  212614. inBufferSize = 256 };
  212615. MIDIHDR hdr [(int) numInHeaders];
  212616. char inData [(int) numInHeaders] [(int) inBufferSize];
  212617. MidiBuffer pending;
  212618. int timeStampToMs (uint32 timeStamp)
  212619. {
  212620. timeStamp += startTime;
  212621. const uint32 now = Time::getMillisecondCounter();
  212622. if (timeStamp > now)
  212623. {
  212624. if (timeStamp > now + 2)
  212625. --startTime;
  212626. timeStamp = now;
  212627. }
  212628. return (int) timeStamp;
  212629. }
  212630. MidiInThread (const MidiInThread&);
  212631. MidiInThread& operator= (const MidiInThread&);
  212632. };
  212633. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  212634. const StringArray MidiInput::getDevices()
  212635. {
  212636. StringArray s;
  212637. const int num = midiInGetNumDevs();
  212638. for (int i = 0; i < num; ++i)
  212639. {
  212640. MIDIINCAPS mc;
  212641. zerostruct (mc);
  212642. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212643. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212644. }
  212645. return s;
  212646. }
  212647. int MidiInput::getDefaultDeviceIndex()
  212648. {
  212649. return 0;
  212650. }
  212651. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212652. {
  212653. if (callback == 0)
  212654. return 0;
  212655. UINT deviceId = MIDI_MAPPER;
  212656. int n = 0;
  212657. String name;
  212658. const int num = midiInGetNumDevs();
  212659. for (int i = 0; i < num; ++i)
  212660. {
  212661. MIDIINCAPS mc;
  212662. zerostruct (mc);
  212663. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212664. {
  212665. if (index == n)
  212666. {
  212667. deviceId = i;
  212668. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212669. break;
  212670. }
  212671. ++n;
  212672. }
  212673. }
  212674. ScopedPointer <MidiInput> in (new MidiInput (name));
  212675. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  212676. HMIDIIN h;
  212677. HRESULT err = midiInOpen (&h, deviceId,
  212678. (DWORD_PTR) &MidiInThread::midiInCallback,
  212679. (DWORD_PTR) (MidiInThread*) thread,
  212680. CALLBACK_FUNCTION);
  212681. if (err == MMSYSERR_NOERROR)
  212682. {
  212683. thread->deviceHandle = h;
  212684. in->internal = thread.release();
  212685. return in.release();
  212686. }
  212687. return 0;
  212688. }
  212689. MidiInput::MidiInput (const String& name_)
  212690. : name (name_),
  212691. internal (0)
  212692. {
  212693. }
  212694. MidiInput::~MidiInput()
  212695. {
  212696. delete static_cast <MidiInThread*> (internal);
  212697. }
  212698. void MidiInput::start()
  212699. {
  212700. static_cast <MidiInThread*> (internal)->start();
  212701. }
  212702. void MidiInput::stop()
  212703. {
  212704. static_cast <MidiInThread*> (internal)->stop();
  212705. }
  212706. struct MidiOutHandle
  212707. {
  212708. int refCount;
  212709. UINT deviceId;
  212710. HMIDIOUT handle;
  212711. static Array<MidiOutHandle*> activeHandles;
  212712. juce_UseDebuggingNewOperator
  212713. };
  212714. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212715. const StringArray MidiOutput::getDevices()
  212716. {
  212717. StringArray s;
  212718. const int num = midiOutGetNumDevs();
  212719. for (int i = 0; i < num; ++i)
  212720. {
  212721. MIDIOUTCAPS mc;
  212722. zerostruct (mc);
  212723. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212724. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212725. }
  212726. return s;
  212727. }
  212728. int MidiOutput::getDefaultDeviceIndex()
  212729. {
  212730. const int num = midiOutGetNumDevs();
  212731. int n = 0;
  212732. for (int i = 0; i < num; ++i)
  212733. {
  212734. MIDIOUTCAPS mc;
  212735. zerostruct (mc);
  212736. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212737. {
  212738. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212739. return n;
  212740. ++n;
  212741. }
  212742. }
  212743. return 0;
  212744. }
  212745. MidiOutput* MidiOutput::openDevice (int index)
  212746. {
  212747. UINT deviceId = MIDI_MAPPER;
  212748. const int num = midiOutGetNumDevs();
  212749. int i, n = 0;
  212750. for (i = 0; i < num; ++i)
  212751. {
  212752. MIDIOUTCAPS mc;
  212753. zerostruct (mc);
  212754. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212755. {
  212756. // use the microsoft sw synth as a default - best not to allow deviceId
  212757. // to be MIDI_MAPPER, or else device sharing breaks
  212758. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212759. deviceId = i;
  212760. if (index == n)
  212761. {
  212762. deviceId = i;
  212763. break;
  212764. }
  212765. ++n;
  212766. }
  212767. }
  212768. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212769. {
  212770. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212771. if (han != 0 && han->deviceId == deviceId)
  212772. {
  212773. han->refCount++;
  212774. MidiOutput* const out = new MidiOutput();
  212775. out->internal = han;
  212776. return out;
  212777. }
  212778. }
  212779. for (i = 4; --i >= 0;)
  212780. {
  212781. HMIDIOUT h = 0;
  212782. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212783. if (res == MMSYSERR_NOERROR)
  212784. {
  212785. MidiOutHandle* const han = new MidiOutHandle();
  212786. han->deviceId = deviceId;
  212787. han->refCount = 1;
  212788. han->handle = h;
  212789. MidiOutHandle::activeHandles.add (han);
  212790. MidiOutput* const out = new MidiOutput();
  212791. out->internal = han;
  212792. return out;
  212793. }
  212794. else if (res == MMSYSERR_ALLOCATED)
  212795. {
  212796. Sleep (100);
  212797. }
  212798. else
  212799. {
  212800. break;
  212801. }
  212802. }
  212803. return 0;
  212804. }
  212805. MidiOutput::~MidiOutput()
  212806. {
  212807. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212808. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212809. {
  212810. midiOutClose (h->handle);
  212811. MidiOutHandle::activeHandles.removeValue (h);
  212812. delete h;
  212813. }
  212814. }
  212815. void MidiOutput::reset()
  212816. {
  212817. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212818. midiOutReset (h->handle);
  212819. }
  212820. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212821. {
  212822. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212823. DWORD n;
  212824. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212825. {
  212826. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212827. rightVol = nn[0] / (float) 0xffff;
  212828. leftVol = nn[1] / (float) 0xffff;
  212829. return true;
  212830. }
  212831. else
  212832. {
  212833. rightVol = leftVol = 1.0f;
  212834. return false;
  212835. }
  212836. }
  212837. void MidiOutput::setVolume (float leftVol, float rightVol)
  212838. {
  212839. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212840. DWORD n;
  212841. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212842. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212843. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212844. midiOutSetVolume (handle->handle, n);
  212845. }
  212846. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212847. {
  212848. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212849. if (message.getRawDataSize() > 3
  212850. || message.isSysEx())
  212851. {
  212852. MIDIHDR h;
  212853. zerostruct (h);
  212854. h.lpData = (char*) message.getRawData();
  212855. h.dwBufferLength = message.getRawDataSize();
  212856. h.dwBytesRecorded = message.getRawDataSize();
  212857. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212858. {
  212859. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212860. if (res == MMSYSERR_NOERROR)
  212861. {
  212862. while ((h.dwFlags & MHDR_DONE) == 0)
  212863. Sleep (1);
  212864. int count = 500; // 1 sec timeout
  212865. while (--count >= 0)
  212866. {
  212867. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212868. if (res == MIDIERR_STILLPLAYING)
  212869. Sleep (2);
  212870. else
  212871. break;
  212872. }
  212873. }
  212874. }
  212875. }
  212876. else
  212877. {
  212878. midiOutShortMsg (handle->handle,
  212879. *(unsigned int*) message.getRawData());
  212880. }
  212881. }
  212882. #endif
  212883. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212884. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212885. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212886. // compiled on its own).
  212887. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212888. #undef WINDOWS
  212889. // #define ASIO_DEBUGGING 1
  212890. #if ASIO_DEBUGGING
  212891. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212892. #else
  212893. #define log(a) {}
  212894. #endif
  212895. #if ASIO_DEBUGGING
  212896. static void logError (const String& context, long error)
  212897. {
  212898. String err ("unknown error");
  212899. if (error == ASE_NotPresent) err = "Not Present";
  212900. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212901. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212902. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212903. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212904. else if (error == ASE_NoClock) err = "No Clock";
  212905. else if (error == ASE_NoMemory) err = "Out of memory";
  212906. log ("!!error: " + context + " - " + err);
  212907. }
  212908. #else
  212909. #define logError(a, b) {}
  212910. #endif
  212911. class ASIOAudioIODevice;
  212912. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212913. static const int maxASIOChannels = 160;
  212914. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212915. private Timer
  212916. {
  212917. public:
  212918. Component ourWindow;
  212919. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212920. const String& optionalDllForDirectLoading_)
  212921. : AudioIODevice (name_, "ASIO"),
  212922. asioObject (0),
  212923. classId (classId_),
  212924. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212925. currentBitDepth (16),
  212926. currentSampleRate (0),
  212927. isOpen_ (false),
  212928. isStarted (false),
  212929. postOutput (true),
  212930. insideControlPanelModalLoop (false),
  212931. shouldUsePreferredSize (false)
  212932. {
  212933. name = name_;
  212934. ourWindow.addToDesktop (0);
  212935. windowHandle = ourWindow.getWindowHandle();
  212936. jassert (currentASIODev [slotNumber] == 0);
  212937. currentASIODev [slotNumber] = this;
  212938. openDevice();
  212939. }
  212940. ~ASIOAudioIODevice()
  212941. {
  212942. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212943. if (currentASIODev[i] == this)
  212944. currentASIODev[i] = 0;
  212945. close();
  212946. log ("ASIO - exiting");
  212947. removeCurrentDriver();
  212948. }
  212949. void updateSampleRates()
  212950. {
  212951. // find a list of sample rates..
  212952. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212953. sampleRates.clear();
  212954. if (asioObject != 0)
  212955. {
  212956. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212957. {
  212958. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212959. if (err == 0)
  212960. {
  212961. sampleRates.add ((int) possibleSampleRates[index]);
  212962. log ("rate: " + String ((int) possibleSampleRates[index]));
  212963. }
  212964. else if (err != ASE_NoClock)
  212965. {
  212966. logError ("CanSampleRate", err);
  212967. }
  212968. }
  212969. if (sampleRates.size() == 0)
  212970. {
  212971. double cr = 0;
  212972. const long err = asioObject->getSampleRate (&cr);
  212973. log ("No sample rates supported - current rate: " + String ((int) cr));
  212974. if (err == 0)
  212975. sampleRates.add ((int) cr);
  212976. }
  212977. }
  212978. }
  212979. const StringArray getOutputChannelNames()
  212980. {
  212981. return outputChannelNames;
  212982. }
  212983. const StringArray getInputChannelNames()
  212984. {
  212985. return inputChannelNames;
  212986. }
  212987. int getNumSampleRates()
  212988. {
  212989. return sampleRates.size();
  212990. }
  212991. double getSampleRate (int index)
  212992. {
  212993. return sampleRates [index];
  212994. }
  212995. int getNumBufferSizesAvailable()
  212996. {
  212997. return bufferSizes.size();
  212998. }
  212999. int getBufferSizeSamples (int index)
  213000. {
  213001. return bufferSizes [index];
  213002. }
  213003. int getDefaultBufferSize()
  213004. {
  213005. return preferredSize;
  213006. }
  213007. const String open (const BigInteger& inputChannels,
  213008. const BigInteger& outputChannels,
  213009. double sr,
  213010. int bufferSizeSamples)
  213011. {
  213012. close();
  213013. currentCallback = 0;
  213014. if (bufferSizeSamples <= 0)
  213015. shouldUsePreferredSize = true;
  213016. if (asioObject == 0 || ! isASIOOpen)
  213017. {
  213018. log ("Warning: device not open");
  213019. const String err (openDevice());
  213020. if (asioObject == 0 || ! isASIOOpen)
  213021. return err;
  213022. }
  213023. isStarted = false;
  213024. bufferIndex = -1;
  213025. long err = 0;
  213026. long newPreferredSize = 0;
  213027. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  213028. minSize = 0;
  213029. maxSize = 0;
  213030. newPreferredSize = 0;
  213031. granularity = 0;
  213032. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  213033. {
  213034. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  213035. shouldUsePreferredSize = true;
  213036. preferredSize = newPreferredSize;
  213037. }
  213038. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  213039. // dynamic changes to the buffer size...
  213040. shouldUsePreferredSize = shouldUsePreferredSize
  213041. || getName().containsIgnoreCase ("Digidesign");
  213042. if (shouldUsePreferredSize)
  213043. {
  213044. log ("Using preferred size for buffer..");
  213045. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213046. {
  213047. bufferSizeSamples = preferredSize;
  213048. }
  213049. else
  213050. {
  213051. bufferSizeSamples = 1024;
  213052. logError ("GetBufferSize1", err);
  213053. }
  213054. shouldUsePreferredSize = false;
  213055. }
  213056. int sampleRate = roundDoubleToInt (sr);
  213057. currentSampleRate = sampleRate;
  213058. currentBlockSizeSamples = bufferSizeSamples;
  213059. currentChansOut.clear();
  213060. currentChansIn.clear();
  213061. zeromem (inBuffers, sizeof (inBuffers));
  213062. zeromem (outBuffers, sizeof (outBuffers));
  213063. updateSampleRates();
  213064. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  213065. sampleRate = sampleRates[0];
  213066. jassert (sampleRate != 0);
  213067. if (sampleRate == 0)
  213068. sampleRate = 44100;
  213069. long numSources = 32;
  213070. ASIOClockSource clocks[32];
  213071. zeromem (clocks, sizeof (clocks));
  213072. asioObject->getClockSources (clocks, &numSources);
  213073. bool isSourceSet = false;
  213074. // careful not to remove this loop because it does more than just logging!
  213075. int i;
  213076. for (i = 0; i < numSources; ++i)
  213077. {
  213078. String s ("clock: ");
  213079. s += clocks[i].name;
  213080. if (clocks[i].isCurrentSource)
  213081. {
  213082. isSourceSet = true;
  213083. s << " (cur)";
  213084. }
  213085. log (s);
  213086. }
  213087. if (numSources > 1 && ! isSourceSet)
  213088. {
  213089. log ("setting clock source");
  213090. asioObject->setClockSource (clocks[0].index);
  213091. Thread::sleep (20);
  213092. }
  213093. else
  213094. {
  213095. if (numSources == 0)
  213096. {
  213097. log ("ASIO - no clock sources!");
  213098. }
  213099. }
  213100. double cr = 0;
  213101. err = asioObject->getSampleRate (&cr);
  213102. if (err == 0)
  213103. {
  213104. currentSampleRate = cr;
  213105. }
  213106. else
  213107. {
  213108. logError ("GetSampleRate", err);
  213109. currentSampleRate = 0;
  213110. }
  213111. error = String::empty;
  213112. needToReset = false;
  213113. isReSync = false;
  213114. err = 0;
  213115. bool buffersCreated = false;
  213116. if (currentSampleRate != sampleRate)
  213117. {
  213118. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  213119. err = asioObject->setSampleRate (sampleRate);
  213120. if (err == ASE_NoClock && numSources > 0)
  213121. {
  213122. log ("trying to set a clock source..");
  213123. Thread::sleep (10);
  213124. err = asioObject->setClockSource (clocks[0].index);
  213125. if (err != 0)
  213126. {
  213127. logError ("SetClock", err);
  213128. }
  213129. Thread::sleep (10);
  213130. err = asioObject->setSampleRate (sampleRate);
  213131. }
  213132. }
  213133. if (err == 0)
  213134. {
  213135. currentSampleRate = sampleRate;
  213136. if (needToReset)
  213137. {
  213138. if (isReSync)
  213139. {
  213140. log ("Resync request");
  213141. }
  213142. log ("! Resetting ASIO after sample rate change");
  213143. removeCurrentDriver();
  213144. loadDriver();
  213145. const String error (initDriver());
  213146. if (error.isNotEmpty())
  213147. {
  213148. log ("ASIOInit: " + error);
  213149. }
  213150. needToReset = false;
  213151. isReSync = false;
  213152. }
  213153. numActiveInputChans = 0;
  213154. numActiveOutputChans = 0;
  213155. ASIOBufferInfo* info = bufferInfos;
  213156. int i;
  213157. for (i = 0; i < totalNumInputChans; ++i)
  213158. {
  213159. if (inputChannels[i])
  213160. {
  213161. currentChansIn.setBit (i);
  213162. info->isInput = 1;
  213163. info->channelNum = i;
  213164. info->buffers[0] = info->buffers[1] = 0;
  213165. ++info;
  213166. ++numActiveInputChans;
  213167. }
  213168. }
  213169. for (i = 0; i < totalNumOutputChans; ++i)
  213170. {
  213171. if (outputChannels[i])
  213172. {
  213173. currentChansOut.setBit (i);
  213174. info->isInput = 0;
  213175. info->channelNum = i;
  213176. info->buffers[0] = info->buffers[1] = 0;
  213177. ++info;
  213178. ++numActiveOutputChans;
  213179. }
  213180. }
  213181. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213182. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213183. if (currentASIODev[0] == this)
  213184. {
  213185. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213186. callbacks.asioMessage = &asioMessagesCallback0;
  213187. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213188. }
  213189. else if (currentASIODev[1] == this)
  213190. {
  213191. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213192. callbacks.asioMessage = &asioMessagesCallback1;
  213193. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213194. }
  213195. else if (currentASIODev[2] == this)
  213196. {
  213197. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213198. callbacks.asioMessage = &asioMessagesCallback2;
  213199. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213200. }
  213201. else
  213202. {
  213203. jassertfalse;
  213204. }
  213205. log ("disposing buffers");
  213206. err = asioObject->disposeBuffers();
  213207. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213208. err = asioObject->createBuffers (bufferInfos,
  213209. totalBuffers,
  213210. currentBlockSizeSamples,
  213211. &callbacks);
  213212. if (err != 0)
  213213. {
  213214. currentBlockSizeSamples = preferredSize;
  213215. logError ("create buffers 2", err);
  213216. asioObject->disposeBuffers();
  213217. err = asioObject->createBuffers (bufferInfos,
  213218. totalBuffers,
  213219. currentBlockSizeSamples,
  213220. &callbacks);
  213221. }
  213222. if (err == 0)
  213223. {
  213224. buffersCreated = true;
  213225. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213226. int n = 0;
  213227. Array <int> types;
  213228. currentBitDepth = 16;
  213229. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213230. {
  213231. if (inputChannels[i])
  213232. {
  213233. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213234. ASIOChannelInfo channelInfo;
  213235. zerostruct (channelInfo);
  213236. channelInfo.channel = i;
  213237. channelInfo.isInput = 1;
  213238. asioObject->getChannelInfo (&channelInfo);
  213239. types.addIfNotAlreadyThere (channelInfo.type);
  213240. typeToFormatParameters (channelInfo.type,
  213241. inputChannelBitDepths[n],
  213242. inputChannelBytesPerSample[n],
  213243. inputChannelIsFloat[n],
  213244. inputChannelLittleEndian[n]);
  213245. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213246. ++n;
  213247. }
  213248. }
  213249. jassert (numActiveInputChans == n);
  213250. n = 0;
  213251. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213252. {
  213253. if (outputChannels[i])
  213254. {
  213255. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213256. ASIOChannelInfo channelInfo;
  213257. zerostruct (channelInfo);
  213258. channelInfo.channel = i;
  213259. channelInfo.isInput = 0;
  213260. asioObject->getChannelInfo (&channelInfo);
  213261. types.addIfNotAlreadyThere (channelInfo.type);
  213262. typeToFormatParameters (channelInfo.type,
  213263. outputChannelBitDepths[n],
  213264. outputChannelBytesPerSample[n],
  213265. outputChannelIsFloat[n],
  213266. outputChannelLittleEndian[n]);
  213267. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213268. ++n;
  213269. }
  213270. }
  213271. jassert (numActiveOutputChans == n);
  213272. for (i = types.size(); --i >= 0;)
  213273. {
  213274. log ("channel format: " + String (types[i]));
  213275. }
  213276. jassert (n <= totalBuffers);
  213277. for (i = 0; i < numActiveOutputChans; ++i)
  213278. {
  213279. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213280. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213281. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213282. {
  213283. log ("!! Null buffers");
  213284. }
  213285. else
  213286. {
  213287. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213288. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213289. }
  213290. }
  213291. inputLatency = outputLatency = 0;
  213292. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213293. {
  213294. log ("ASIO - no latencies");
  213295. }
  213296. else
  213297. {
  213298. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213299. }
  213300. isOpen_ = true;
  213301. log ("starting ASIO");
  213302. calledback = false;
  213303. err = asioObject->start();
  213304. if (err != 0)
  213305. {
  213306. isOpen_ = false;
  213307. log ("ASIO - stop on failure");
  213308. Thread::sleep (10);
  213309. asioObject->stop();
  213310. error = "Can't start device";
  213311. Thread::sleep (10);
  213312. }
  213313. else
  213314. {
  213315. int count = 300;
  213316. while (--count > 0 && ! calledback)
  213317. Thread::sleep (10);
  213318. isStarted = true;
  213319. if (! calledback)
  213320. {
  213321. error = "Device didn't start correctly";
  213322. log ("ASIO didn't callback - stopping..");
  213323. asioObject->stop();
  213324. }
  213325. }
  213326. }
  213327. else
  213328. {
  213329. error = "Can't create i/o buffers";
  213330. }
  213331. }
  213332. else
  213333. {
  213334. error = "Can't set sample rate: ";
  213335. error << sampleRate;
  213336. }
  213337. if (error.isNotEmpty())
  213338. {
  213339. logError (error, err);
  213340. if (asioObject != 0 && buffersCreated)
  213341. asioObject->disposeBuffers();
  213342. Thread::sleep (20);
  213343. isStarted = false;
  213344. isOpen_ = false;
  213345. const String errorCopy (error);
  213346. close(); // (this resets the error string)
  213347. error = errorCopy;
  213348. }
  213349. needToReset = false;
  213350. isReSync = false;
  213351. return error;
  213352. }
  213353. void close()
  213354. {
  213355. error = String::empty;
  213356. stopTimer();
  213357. stop();
  213358. if (isASIOOpen && isOpen_)
  213359. {
  213360. const ScopedLock sl (callbackLock);
  213361. isOpen_ = false;
  213362. isStarted = false;
  213363. needToReset = false;
  213364. isReSync = false;
  213365. log ("ASIO - stopping");
  213366. if (asioObject != 0)
  213367. {
  213368. Thread::sleep (20);
  213369. asioObject->stop();
  213370. Thread::sleep (10);
  213371. asioObject->disposeBuffers();
  213372. }
  213373. Thread::sleep (10);
  213374. }
  213375. }
  213376. bool isOpen()
  213377. {
  213378. return isOpen_ || insideControlPanelModalLoop;
  213379. }
  213380. int getCurrentBufferSizeSamples()
  213381. {
  213382. return currentBlockSizeSamples;
  213383. }
  213384. double getCurrentSampleRate()
  213385. {
  213386. return currentSampleRate;
  213387. }
  213388. const BigInteger getActiveOutputChannels() const
  213389. {
  213390. return currentChansOut;
  213391. }
  213392. const BigInteger getActiveInputChannels() const
  213393. {
  213394. return currentChansIn;
  213395. }
  213396. int getCurrentBitDepth()
  213397. {
  213398. return currentBitDepth;
  213399. }
  213400. int getOutputLatencyInSamples()
  213401. {
  213402. return outputLatency + currentBlockSizeSamples / 4;
  213403. }
  213404. int getInputLatencyInSamples()
  213405. {
  213406. return inputLatency + currentBlockSizeSamples / 4;
  213407. }
  213408. void start (AudioIODeviceCallback* callback)
  213409. {
  213410. if (callback != 0)
  213411. {
  213412. callback->audioDeviceAboutToStart (this);
  213413. const ScopedLock sl (callbackLock);
  213414. currentCallback = callback;
  213415. }
  213416. }
  213417. void stop()
  213418. {
  213419. AudioIODeviceCallback* const lastCallback = currentCallback;
  213420. {
  213421. const ScopedLock sl (callbackLock);
  213422. currentCallback = 0;
  213423. }
  213424. if (lastCallback != 0)
  213425. lastCallback->audioDeviceStopped();
  213426. }
  213427. bool isPlaying()
  213428. {
  213429. return isASIOOpen && (currentCallback != 0);
  213430. }
  213431. const String getLastError()
  213432. {
  213433. return error;
  213434. }
  213435. bool hasControlPanel() const
  213436. {
  213437. return true;
  213438. }
  213439. bool showControlPanel()
  213440. {
  213441. log ("ASIO - showing control panel");
  213442. Component modalWindow (String::empty);
  213443. modalWindow.setOpaque (true);
  213444. modalWindow.addToDesktop (0);
  213445. modalWindow.enterModalState();
  213446. bool done = false;
  213447. JUCE_TRY
  213448. {
  213449. // are there are devices that need to be closed before showing their control panel?
  213450. // close();
  213451. insideControlPanelModalLoop = true;
  213452. const uint32 started = Time::getMillisecondCounter();
  213453. if (asioObject != 0)
  213454. {
  213455. asioObject->controlPanel();
  213456. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213457. log ("spent: " + String (spent));
  213458. if (spent > 300)
  213459. {
  213460. shouldUsePreferredSize = true;
  213461. done = true;
  213462. }
  213463. }
  213464. }
  213465. JUCE_CATCH_ALL
  213466. insideControlPanelModalLoop = false;
  213467. return done;
  213468. }
  213469. void resetRequest() throw()
  213470. {
  213471. needToReset = true;
  213472. }
  213473. void resyncRequest() throw()
  213474. {
  213475. needToReset = true;
  213476. isReSync = true;
  213477. }
  213478. void timerCallback()
  213479. {
  213480. if (! insideControlPanelModalLoop)
  213481. {
  213482. stopTimer();
  213483. // used to cause a reset
  213484. log ("! ASIO restart request!");
  213485. if (isOpen_)
  213486. {
  213487. AudioIODeviceCallback* const oldCallback = currentCallback;
  213488. close();
  213489. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213490. currentSampleRate, currentBlockSizeSamples);
  213491. if (oldCallback != 0)
  213492. start (oldCallback);
  213493. }
  213494. }
  213495. else
  213496. {
  213497. startTimer (100);
  213498. }
  213499. }
  213500. juce_UseDebuggingNewOperator
  213501. private:
  213502. IASIO* volatile asioObject;
  213503. ASIOCallbacks callbacks;
  213504. void* windowHandle;
  213505. CLSID classId;
  213506. const String optionalDllForDirectLoading;
  213507. String error;
  213508. long totalNumInputChans, totalNumOutputChans;
  213509. StringArray inputChannelNames, outputChannelNames;
  213510. Array<int> sampleRates, bufferSizes;
  213511. long inputLatency, outputLatency;
  213512. long minSize, maxSize, preferredSize, granularity;
  213513. int volatile currentBlockSizeSamples;
  213514. int volatile currentBitDepth;
  213515. double volatile currentSampleRate;
  213516. BigInteger currentChansOut, currentChansIn;
  213517. AudioIODeviceCallback* volatile currentCallback;
  213518. CriticalSection callbackLock;
  213519. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213520. float* inBuffers [maxASIOChannels];
  213521. float* outBuffers [maxASIOChannels];
  213522. int inputChannelBitDepths [maxASIOChannels];
  213523. int outputChannelBitDepths [maxASIOChannels];
  213524. int inputChannelBytesPerSample [maxASIOChannels];
  213525. int outputChannelBytesPerSample [maxASIOChannels];
  213526. bool inputChannelIsFloat [maxASIOChannels];
  213527. bool outputChannelIsFloat [maxASIOChannels];
  213528. bool inputChannelLittleEndian [maxASIOChannels];
  213529. bool outputChannelLittleEndian [maxASIOChannels];
  213530. WaitableEvent event1;
  213531. HeapBlock <float> tempBuffer;
  213532. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213533. bool isOpen_, isStarted;
  213534. bool volatile isASIOOpen;
  213535. bool volatile calledback;
  213536. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213537. bool volatile insideControlPanelModalLoop;
  213538. bool volatile shouldUsePreferredSize;
  213539. void removeCurrentDriver()
  213540. {
  213541. if (asioObject != 0)
  213542. {
  213543. asioObject->Release();
  213544. asioObject = 0;
  213545. }
  213546. }
  213547. bool loadDriver()
  213548. {
  213549. removeCurrentDriver();
  213550. JUCE_TRY
  213551. {
  213552. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213553. classId, (void**) &asioObject) == S_OK)
  213554. {
  213555. return true;
  213556. }
  213557. // If a class isn't registered but we have a path for it, we can fallback to
  213558. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213559. if (optionalDllForDirectLoading.isNotEmpty())
  213560. {
  213561. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213562. if (h != 0)
  213563. {
  213564. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213565. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213566. if (dllGetClassObject != 0)
  213567. {
  213568. IClassFactory* classFactory = 0;
  213569. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213570. if (classFactory != 0)
  213571. {
  213572. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213573. classFactory->Release();
  213574. }
  213575. return asioObject != 0;
  213576. }
  213577. }
  213578. }
  213579. }
  213580. JUCE_CATCH_ALL
  213581. asioObject = 0;
  213582. return false;
  213583. }
  213584. const String initDriver()
  213585. {
  213586. if (asioObject != 0)
  213587. {
  213588. char buffer [256];
  213589. zeromem (buffer, sizeof (buffer));
  213590. if (! asioObject->init (windowHandle))
  213591. {
  213592. asioObject->getErrorMessage (buffer);
  213593. return String (buffer, sizeof (buffer) - 1);
  213594. }
  213595. // just in case any daft drivers expect this to be called..
  213596. asioObject->getDriverName (buffer);
  213597. return String::empty;
  213598. }
  213599. return "No Driver";
  213600. }
  213601. const String openDevice()
  213602. {
  213603. // use this in case the driver starts opening dialog boxes..
  213604. Component modalWindow (String::empty);
  213605. modalWindow.setOpaque (true);
  213606. modalWindow.addToDesktop (0);
  213607. modalWindow.enterModalState();
  213608. // open the device and get its info..
  213609. log ("opening ASIO device: " + getName());
  213610. needToReset = false;
  213611. isReSync = false;
  213612. outputChannelNames.clear();
  213613. inputChannelNames.clear();
  213614. bufferSizes.clear();
  213615. sampleRates.clear();
  213616. isASIOOpen = false;
  213617. isOpen_ = false;
  213618. totalNumInputChans = 0;
  213619. totalNumOutputChans = 0;
  213620. numActiveInputChans = 0;
  213621. numActiveOutputChans = 0;
  213622. currentCallback = 0;
  213623. error = String::empty;
  213624. if (getName().isEmpty())
  213625. return error;
  213626. long err = 0;
  213627. if (loadDriver())
  213628. {
  213629. if ((error = initDriver()).isEmpty())
  213630. {
  213631. numActiveInputChans = 0;
  213632. numActiveOutputChans = 0;
  213633. totalNumInputChans = 0;
  213634. totalNumOutputChans = 0;
  213635. if (asioObject != 0
  213636. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213637. {
  213638. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213639. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213640. {
  213641. // find a list of buffer sizes..
  213642. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213643. if (granularity >= 0)
  213644. {
  213645. granularity = jmax (1, (int) granularity);
  213646. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213647. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213648. }
  213649. else if (granularity < 0)
  213650. {
  213651. for (int i = 0; i < 18; ++i)
  213652. {
  213653. const int s = (1 << i);
  213654. if (s >= minSize && s <= maxSize)
  213655. bufferSizes.add (s);
  213656. }
  213657. }
  213658. if (! bufferSizes.contains (preferredSize))
  213659. bufferSizes.insert (0, preferredSize);
  213660. double currentRate = 0;
  213661. asioObject->getSampleRate (&currentRate);
  213662. if (currentRate <= 0.0 || currentRate > 192001.0)
  213663. {
  213664. log ("setting sample rate");
  213665. err = asioObject->setSampleRate (44100.0);
  213666. if (err != 0)
  213667. {
  213668. logError ("setting sample rate", err);
  213669. }
  213670. asioObject->getSampleRate (&currentRate);
  213671. }
  213672. currentSampleRate = currentRate;
  213673. postOutput = (asioObject->outputReady() == 0);
  213674. if (postOutput)
  213675. {
  213676. log ("ASIO outputReady = ok");
  213677. }
  213678. updateSampleRates();
  213679. // ..because cubase does it at this point
  213680. inputLatency = outputLatency = 0;
  213681. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213682. {
  213683. log ("ASIO - no latencies");
  213684. }
  213685. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213686. // create some dummy buffers now.. because cubase does..
  213687. numActiveInputChans = 0;
  213688. numActiveOutputChans = 0;
  213689. ASIOBufferInfo* info = bufferInfos;
  213690. int i, numChans = 0;
  213691. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213692. {
  213693. info->isInput = 1;
  213694. info->channelNum = i;
  213695. info->buffers[0] = info->buffers[1] = 0;
  213696. ++info;
  213697. ++numChans;
  213698. }
  213699. const int outputBufferIndex = numChans;
  213700. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213701. {
  213702. info->isInput = 0;
  213703. info->channelNum = i;
  213704. info->buffers[0] = info->buffers[1] = 0;
  213705. ++info;
  213706. ++numChans;
  213707. }
  213708. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213709. if (currentASIODev[0] == this)
  213710. {
  213711. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213712. callbacks.asioMessage = &asioMessagesCallback0;
  213713. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213714. }
  213715. else if (currentASIODev[1] == this)
  213716. {
  213717. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213718. callbacks.asioMessage = &asioMessagesCallback1;
  213719. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213720. }
  213721. else if (currentASIODev[2] == this)
  213722. {
  213723. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213724. callbacks.asioMessage = &asioMessagesCallback2;
  213725. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213726. }
  213727. else
  213728. {
  213729. jassertfalse;
  213730. }
  213731. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213732. if (preferredSize > 0)
  213733. {
  213734. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213735. if (err != 0)
  213736. {
  213737. logError ("dummy buffers", err);
  213738. }
  213739. }
  213740. long newInps = 0, newOuts = 0;
  213741. asioObject->getChannels (&newInps, &newOuts);
  213742. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213743. {
  213744. totalNumInputChans = newInps;
  213745. totalNumOutputChans = newOuts;
  213746. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213747. }
  213748. updateSampleRates();
  213749. ASIOChannelInfo channelInfo;
  213750. channelInfo.type = 0;
  213751. for (i = 0; i < totalNumInputChans; ++i)
  213752. {
  213753. zerostruct (channelInfo);
  213754. channelInfo.channel = i;
  213755. channelInfo.isInput = 1;
  213756. asioObject->getChannelInfo (&channelInfo);
  213757. inputChannelNames.add (String (channelInfo.name));
  213758. }
  213759. for (i = 0; i < totalNumOutputChans; ++i)
  213760. {
  213761. zerostruct (channelInfo);
  213762. channelInfo.channel = i;
  213763. channelInfo.isInput = 0;
  213764. asioObject->getChannelInfo (&channelInfo);
  213765. outputChannelNames.add (String (channelInfo.name));
  213766. typeToFormatParameters (channelInfo.type,
  213767. outputChannelBitDepths[i],
  213768. outputChannelBytesPerSample[i],
  213769. outputChannelIsFloat[i],
  213770. outputChannelLittleEndian[i]);
  213771. if (i < 2)
  213772. {
  213773. // clear the channels that are used with the dummy stuff
  213774. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213775. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213776. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213777. }
  213778. }
  213779. outputChannelNames.trim();
  213780. inputChannelNames.trim();
  213781. outputChannelNames.appendNumbersToDuplicates (false, true);
  213782. inputChannelNames.appendNumbersToDuplicates (false, true);
  213783. // start and stop because cubase does it..
  213784. asioObject->getLatencies (&inputLatency, &outputLatency);
  213785. if ((err = asioObject->start()) != 0)
  213786. {
  213787. // ignore an error here, as it might start later after setting other stuff up
  213788. logError ("ASIO start", err);
  213789. }
  213790. Thread::sleep (100);
  213791. asioObject->stop();
  213792. }
  213793. else
  213794. {
  213795. error = "Can't detect buffer sizes";
  213796. }
  213797. }
  213798. else
  213799. {
  213800. error = "Can't detect asio channels";
  213801. }
  213802. }
  213803. }
  213804. else
  213805. {
  213806. error = "No such device";
  213807. }
  213808. if (error.isNotEmpty())
  213809. {
  213810. logError (error, err);
  213811. if (asioObject != 0)
  213812. asioObject->disposeBuffers();
  213813. removeCurrentDriver();
  213814. isASIOOpen = false;
  213815. }
  213816. else
  213817. {
  213818. isASIOOpen = true;
  213819. log ("ASIO device open");
  213820. }
  213821. isOpen_ = false;
  213822. needToReset = false;
  213823. isReSync = false;
  213824. return error;
  213825. }
  213826. void callback (const long index)
  213827. {
  213828. if (isStarted)
  213829. {
  213830. bufferIndex = index;
  213831. processBuffer();
  213832. }
  213833. else
  213834. {
  213835. if (postOutput && (asioObject != 0))
  213836. asioObject->outputReady();
  213837. }
  213838. calledback = true;
  213839. }
  213840. void processBuffer()
  213841. {
  213842. const ASIOBufferInfo* const infos = bufferInfos;
  213843. const int bi = bufferIndex;
  213844. const ScopedLock sl (callbackLock);
  213845. if (needToReset)
  213846. {
  213847. needToReset = false;
  213848. if (isReSync)
  213849. {
  213850. log ("! ASIO resync");
  213851. isReSync = false;
  213852. }
  213853. else
  213854. {
  213855. startTimer (20);
  213856. }
  213857. }
  213858. if (bi >= 0)
  213859. {
  213860. const int samps = currentBlockSizeSamples;
  213861. if (currentCallback != 0)
  213862. {
  213863. int i;
  213864. for (i = 0; i < numActiveInputChans; ++i)
  213865. {
  213866. float* const dst = inBuffers[i];
  213867. jassert (dst != 0);
  213868. const char* const src = (const char*) (infos[i].buffers[bi]);
  213869. if (inputChannelIsFloat[i])
  213870. {
  213871. memcpy (dst, src, samps * sizeof (float));
  213872. }
  213873. else
  213874. {
  213875. jassert (dst == tempBuffer + (samps * i));
  213876. switch (inputChannelBitDepths[i])
  213877. {
  213878. case 16:
  213879. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213880. samps, inputChannelLittleEndian[i]);
  213881. break;
  213882. case 24:
  213883. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213884. samps, inputChannelLittleEndian[i]);
  213885. break;
  213886. case 32:
  213887. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213888. samps, inputChannelLittleEndian[i]);
  213889. break;
  213890. case 64:
  213891. jassertfalse;
  213892. break;
  213893. }
  213894. }
  213895. }
  213896. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  213897. numActiveInputChans,
  213898. outBuffers,
  213899. numActiveOutputChans,
  213900. samps);
  213901. for (i = 0; i < numActiveOutputChans; ++i)
  213902. {
  213903. float* const src = outBuffers[i];
  213904. jassert (src != 0);
  213905. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213906. if (outputChannelIsFloat[i])
  213907. {
  213908. memcpy (dst, src, samps * sizeof (float));
  213909. }
  213910. else
  213911. {
  213912. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213913. switch (outputChannelBitDepths[i])
  213914. {
  213915. case 16:
  213916. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213917. samps, outputChannelLittleEndian[i]);
  213918. break;
  213919. case 24:
  213920. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213921. samps, outputChannelLittleEndian[i]);
  213922. break;
  213923. case 32:
  213924. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213925. samps, outputChannelLittleEndian[i]);
  213926. break;
  213927. case 64:
  213928. jassertfalse;
  213929. break;
  213930. }
  213931. }
  213932. }
  213933. }
  213934. else
  213935. {
  213936. for (int i = 0; i < numActiveOutputChans; ++i)
  213937. {
  213938. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213939. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213940. }
  213941. }
  213942. }
  213943. if (postOutput)
  213944. asioObject->outputReady();
  213945. }
  213946. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213947. {
  213948. if (currentASIODev[0] != 0)
  213949. currentASIODev[0]->callback (index);
  213950. return 0;
  213951. }
  213952. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213953. {
  213954. if (currentASIODev[1] != 0)
  213955. currentASIODev[1]->callback (index);
  213956. return 0;
  213957. }
  213958. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213959. {
  213960. if (currentASIODev[2] != 0)
  213961. currentASIODev[2]->callback (index);
  213962. return 0;
  213963. }
  213964. static void bufferSwitchCallback0 (long index, long)
  213965. {
  213966. if (currentASIODev[0] != 0)
  213967. currentASIODev[0]->callback (index);
  213968. }
  213969. static void bufferSwitchCallback1 (long index, long)
  213970. {
  213971. if (currentASIODev[1] != 0)
  213972. currentASIODev[1]->callback (index);
  213973. }
  213974. static void bufferSwitchCallback2 (long index, long)
  213975. {
  213976. if (currentASIODev[2] != 0)
  213977. currentASIODev[2]->callback (index);
  213978. }
  213979. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  213980. {
  213981. return asioMessagesCallback (selector, value, 0);
  213982. }
  213983. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  213984. {
  213985. return asioMessagesCallback (selector, value, 1);
  213986. }
  213987. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  213988. {
  213989. return asioMessagesCallback (selector, value, 2);
  213990. }
  213991. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  213992. {
  213993. switch (selector)
  213994. {
  213995. case kAsioSelectorSupported:
  213996. if (value == kAsioResetRequest
  213997. || value == kAsioEngineVersion
  213998. || value == kAsioResyncRequest
  213999. || value == kAsioLatenciesChanged
  214000. || value == kAsioSupportsInputMonitor)
  214001. return 1;
  214002. break;
  214003. case kAsioBufferSizeChange:
  214004. break;
  214005. case kAsioResetRequest:
  214006. if (currentASIODev[deviceIndex] != 0)
  214007. currentASIODev[deviceIndex]->resetRequest();
  214008. return 1;
  214009. case kAsioResyncRequest:
  214010. if (currentASIODev[deviceIndex] != 0)
  214011. currentASIODev[deviceIndex]->resyncRequest();
  214012. return 1;
  214013. case kAsioLatenciesChanged:
  214014. return 1;
  214015. case kAsioEngineVersion:
  214016. return 2;
  214017. case kAsioSupportsTimeInfo:
  214018. case kAsioSupportsTimeCode:
  214019. return 0;
  214020. }
  214021. return 0;
  214022. }
  214023. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  214024. {
  214025. }
  214026. static void convertInt16ToFloat (const char* src,
  214027. float* dest,
  214028. const int srcStrideBytes,
  214029. int numSamples,
  214030. const bool littleEndian) throw()
  214031. {
  214032. const double g = 1.0 / 32768.0;
  214033. if (littleEndian)
  214034. {
  214035. while (--numSamples >= 0)
  214036. {
  214037. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  214038. src += srcStrideBytes;
  214039. }
  214040. }
  214041. else
  214042. {
  214043. while (--numSamples >= 0)
  214044. {
  214045. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  214046. src += srcStrideBytes;
  214047. }
  214048. }
  214049. }
  214050. static void convertFloatToInt16 (const float* src,
  214051. char* dest,
  214052. const int dstStrideBytes,
  214053. int numSamples,
  214054. const bool littleEndian) throw()
  214055. {
  214056. const double maxVal = (double) 0x7fff;
  214057. if (littleEndian)
  214058. {
  214059. while (--numSamples >= 0)
  214060. {
  214061. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214062. dest += dstStrideBytes;
  214063. }
  214064. }
  214065. else
  214066. {
  214067. while (--numSamples >= 0)
  214068. {
  214069. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214070. dest += dstStrideBytes;
  214071. }
  214072. }
  214073. }
  214074. static void convertInt24ToFloat (const char* src,
  214075. float* dest,
  214076. const int srcStrideBytes,
  214077. int numSamples,
  214078. const bool littleEndian) throw()
  214079. {
  214080. const double g = 1.0 / 0x7fffff;
  214081. if (littleEndian)
  214082. {
  214083. while (--numSamples >= 0)
  214084. {
  214085. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  214086. src += srcStrideBytes;
  214087. }
  214088. }
  214089. else
  214090. {
  214091. while (--numSamples >= 0)
  214092. {
  214093. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  214094. src += srcStrideBytes;
  214095. }
  214096. }
  214097. }
  214098. static void convertFloatToInt24 (const float* src,
  214099. char* dest,
  214100. const int dstStrideBytes,
  214101. int numSamples,
  214102. const bool littleEndian) throw()
  214103. {
  214104. const double maxVal = (double) 0x7fffff;
  214105. if (littleEndian)
  214106. {
  214107. while (--numSamples >= 0)
  214108. {
  214109. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214110. dest += dstStrideBytes;
  214111. }
  214112. }
  214113. else
  214114. {
  214115. while (--numSamples >= 0)
  214116. {
  214117. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214118. dest += dstStrideBytes;
  214119. }
  214120. }
  214121. }
  214122. static void convertInt32ToFloat (const char* src,
  214123. float* dest,
  214124. const int srcStrideBytes,
  214125. int numSamples,
  214126. const bool littleEndian) throw()
  214127. {
  214128. const double g = 1.0 / 0x7fffffff;
  214129. if (littleEndian)
  214130. {
  214131. while (--numSamples >= 0)
  214132. {
  214133. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  214134. src += srcStrideBytes;
  214135. }
  214136. }
  214137. else
  214138. {
  214139. while (--numSamples >= 0)
  214140. {
  214141. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  214142. src += srcStrideBytes;
  214143. }
  214144. }
  214145. }
  214146. static void convertFloatToInt32 (const float* src,
  214147. char* dest,
  214148. const int dstStrideBytes,
  214149. int numSamples,
  214150. const bool littleEndian) throw()
  214151. {
  214152. const double maxVal = (double) 0x7fffffff;
  214153. if (littleEndian)
  214154. {
  214155. while (--numSamples >= 0)
  214156. {
  214157. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214158. dest += dstStrideBytes;
  214159. }
  214160. }
  214161. else
  214162. {
  214163. while (--numSamples >= 0)
  214164. {
  214165. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214166. dest += dstStrideBytes;
  214167. }
  214168. }
  214169. }
  214170. static void typeToFormatParameters (const long type,
  214171. int& bitDepth,
  214172. int& byteStride,
  214173. bool& formatIsFloat,
  214174. bool& littleEndian) throw()
  214175. {
  214176. bitDepth = 0;
  214177. littleEndian = false;
  214178. formatIsFloat = false;
  214179. switch (type)
  214180. {
  214181. case ASIOSTInt16MSB:
  214182. case ASIOSTInt16LSB:
  214183. case ASIOSTInt32MSB16:
  214184. case ASIOSTInt32LSB16:
  214185. bitDepth = 16; break;
  214186. case ASIOSTFloat32MSB:
  214187. case ASIOSTFloat32LSB:
  214188. formatIsFloat = true;
  214189. bitDepth = 32; break;
  214190. case ASIOSTInt32MSB:
  214191. case ASIOSTInt32LSB:
  214192. bitDepth = 32; break;
  214193. case ASIOSTInt24MSB:
  214194. case ASIOSTInt24LSB:
  214195. case ASIOSTInt32MSB24:
  214196. case ASIOSTInt32LSB24:
  214197. case ASIOSTInt32MSB18:
  214198. case ASIOSTInt32MSB20:
  214199. case ASIOSTInt32LSB18:
  214200. case ASIOSTInt32LSB20:
  214201. bitDepth = 24; break;
  214202. case ASIOSTFloat64MSB:
  214203. case ASIOSTFloat64LSB:
  214204. default:
  214205. bitDepth = 64;
  214206. break;
  214207. }
  214208. switch (type)
  214209. {
  214210. case ASIOSTInt16MSB:
  214211. case ASIOSTInt32MSB16:
  214212. case ASIOSTFloat32MSB:
  214213. case ASIOSTFloat64MSB:
  214214. case ASIOSTInt32MSB:
  214215. case ASIOSTInt32MSB18:
  214216. case ASIOSTInt32MSB20:
  214217. case ASIOSTInt32MSB24:
  214218. case ASIOSTInt24MSB:
  214219. littleEndian = false; break;
  214220. case ASIOSTInt16LSB:
  214221. case ASIOSTInt32LSB16:
  214222. case ASIOSTFloat32LSB:
  214223. case ASIOSTFloat64LSB:
  214224. case ASIOSTInt32LSB:
  214225. case ASIOSTInt32LSB18:
  214226. case ASIOSTInt32LSB20:
  214227. case ASIOSTInt32LSB24:
  214228. case ASIOSTInt24LSB:
  214229. littleEndian = true; break;
  214230. default:
  214231. break;
  214232. }
  214233. switch (type)
  214234. {
  214235. case ASIOSTInt16LSB:
  214236. case ASIOSTInt16MSB:
  214237. byteStride = 2; break;
  214238. case ASIOSTInt24LSB:
  214239. case ASIOSTInt24MSB:
  214240. byteStride = 3; break;
  214241. case ASIOSTInt32MSB16:
  214242. case ASIOSTInt32LSB16:
  214243. case ASIOSTInt32MSB:
  214244. case ASIOSTInt32MSB18:
  214245. case ASIOSTInt32MSB20:
  214246. case ASIOSTInt32MSB24:
  214247. case ASIOSTInt32LSB:
  214248. case ASIOSTInt32LSB18:
  214249. case ASIOSTInt32LSB20:
  214250. case ASIOSTInt32LSB24:
  214251. case ASIOSTFloat32LSB:
  214252. case ASIOSTFloat32MSB:
  214253. byteStride = 4; break;
  214254. case ASIOSTFloat64MSB:
  214255. case ASIOSTFloat64LSB:
  214256. byteStride = 8; break;
  214257. default:
  214258. break;
  214259. }
  214260. }
  214261. };
  214262. class ASIOAudioIODeviceType : public AudioIODeviceType
  214263. {
  214264. public:
  214265. ASIOAudioIODeviceType()
  214266. : AudioIODeviceType ("ASIO"),
  214267. hasScanned (false)
  214268. {
  214269. CoInitialize (0);
  214270. }
  214271. ~ASIOAudioIODeviceType()
  214272. {
  214273. }
  214274. void scanForDevices()
  214275. {
  214276. hasScanned = true;
  214277. deviceNames.clear();
  214278. classIds.clear();
  214279. HKEY hk = 0;
  214280. int index = 0;
  214281. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214282. {
  214283. for (;;)
  214284. {
  214285. char name [256];
  214286. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214287. {
  214288. addDriverInfo (name, hk);
  214289. }
  214290. else
  214291. {
  214292. break;
  214293. }
  214294. }
  214295. RegCloseKey (hk);
  214296. }
  214297. }
  214298. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214299. {
  214300. jassert (hasScanned); // need to call scanForDevices() before doing this
  214301. return deviceNames;
  214302. }
  214303. int getDefaultDeviceIndex (bool) const
  214304. {
  214305. jassert (hasScanned); // need to call scanForDevices() before doing this
  214306. for (int i = deviceNames.size(); --i >= 0;)
  214307. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214308. return i; // asio4all is a safe choice for a default..
  214309. #if JUCE_DEBUG
  214310. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214311. return 1; // (the digi m-box driver crashes the app when you run
  214312. // it in the debugger, which can be a bit annoying)
  214313. #endif
  214314. return 0;
  214315. }
  214316. static int findFreeSlot()
  214317. {
  214318. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214319. if (currentASIODev[i] == 0)
  214320. return i;
  214321. jassertfalse; // unfortunately you can only have a finite number
  214322. // of ASIO devices open at the same time..
  214323. return -1;
  214324. }
  214325. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214326. {
  214327. jassert (hasScanned); // need to call scanForDevices() before doing this
  214328. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214329. }
  214330. bool hasSeparateInputsAndOutputs() const { return false; }
  214331. AudioIODevice* createDevice (const String& outputDeviceName,
  214332. const String& inputDeviceName)
  214333. {
  214334. // ASIO can't open two different devices for input and output - they must be the same one.
  214335. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214336. jassert (hasScanned); // need to call scanForDevices() before doing this
  214337. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214338. : inputDeviceName);
  214339. if (index >= 0)
  214340. {
  214341. const int freeSlot = findFreeSlot();
  214342. if (freeSlot >= 0)
  214343. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214344. }
  214345. return 0;
  214346. }
  214347. juce_UseDebuggingNewOperator
  214348. private:
  214349. StringArray deviceNames;
  214350. OwnedArray <CLSID> classIds;
  214351. bool hasScanned;
  214352. static bool checkClassIsOk (const String& classId)
  214353. {
  214354. HKEY hk = 0;
  214355. bool ok = false;
  214356. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214357. {
  214358. int index = 0;
  214359. for (;;)
  214360. {
  214361. WCHAR buf [512];
  214362. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214363. {
  214364. if (classId.equalsIgnoreCase (buf))
  214365. {
  214366. HKEY subKey, pathKey;
  214367. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214368. {
  214369. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214370. {
  214371. WCHAR pathName [1024];
  214372. DWORD dtype = REG_SZ;
  214373. DWORD dsize = sizeof (pathName);
  214374. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214375. ok = File (pathName).exists();
  214376. RegCloseKey (pathKey);
  214377. }
  214378. RegCloseKey (subKey);
  214379. }
  214380. break;
  214381. }
  214382. }
  214383. else
  214384. {
  214385. break;
  214386. }
  214387. }
  214388. RegCloseKey (hk);
  214389. }
  214390. return ok;
  214391. }
  214392. void addDriverInfo (const String& keyName, HKEY hk)
  214393. {
  214394. HKEY subKey;
  214395. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214396. {
  214397. WCHAR buf [256];
  214398. zerostruct (buf);
  214399. DWORD dtype = REG_SZ;
  214400. DWORD dsize = sizeof (buf);
  214401. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214402. {
  214403. if (dsize > 0 && checkClassIsOk (buf))
  214404. {
  214405. CLSID classId;
  214406. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214407. {
  214408. dtype = REG_SZ;
  214409. dsize = sizeof (buf);
  214410. String deviceName;
  214411. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214412. deviceName = buf;
  214413. else
  214414. deviceName = keyName;
  214415. log ("found " + deviceName);
  214416. deviceNames.add (deviceName);
  214417. classIds.add (new CLSID (classId));
  214418. }
  214419. }
  214420. RegCloseKey (subKey);
  214421. }
  214422. }
  214423. }
  214424. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214425. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214426. };
  214427. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214428. {
  214429. return new ASIOAudioIODeviceType();
  214430. }
  214431. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214432. void* guid,
  214433. const String& optionalDllForDirectLoading)
  214434. {
  214435. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214436. if (freeSlot < 0)
  214437. return 0;
  214438. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214439. }
  214440. #undef log
  214441. #endif
  214442. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214443. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214444. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214445. // compiled on its own).
  214446. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214447. END_JUCE_NAMESPACE
  214448. extern "C"
  214449. {
  214450. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214451. typedef struct typeDSBUFFERDESC
  214452. {
  214453. DWORD dwSize;
  214454. DWORD dwFlags;
  214455. DWORD dwBufferBytes;
  214456. DWORD dwReserved;
  214457. LPWAVEFORMATEX lpwfxFormat;
  214458. GUID guid3DAlgorithm;
  214459. } DSBUFFERDESC;
  214460. struct IDirectSoundBuffer;
  214461. #undef INTERFACE
  214462. #define INTERFACE IDirectSound
  214463. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214464. {
  214465. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214466. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214467. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214468. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214469. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214470. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214471. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214472. STDMETHOD(Compact) (THIS) PURE;
  214473. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214474. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214475. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214476. };
  214477. #undef INTERFACE
  214478. #define INTERFACE IDirectSoundBuffer
  214479. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214480. {
  214481. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214482. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214483. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214484. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214485. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214486. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214487. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214488. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214489. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214490. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214491. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214492. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214493. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214494. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214495. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214496. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214497. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214498. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214499. STDMETHOD(Stop) (THIS) PURE;
  214500. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214501. STDMETHOD(Restore) (THIS) PURE;
  214502. };
  214503. typedef struct typeDSCBUFFERDESC
  214504. {
  214505. DWORD dwSize;
  214506. DWORD dwFlags;
  214507. DWORD dwBufferBytes;
  214508. DWORD dwReserved;
  214509. LPWAVEFORMATEX lpwfxFormat;
  214510. } DSCBUFFERDESC;
  214511. struct IDirectSoundCaptureBuffer;
  214512. #undef INTERFACE
  214513. #define INTERFACE IDirectSoundCapture
  214514. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214515. {
  214516. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214517. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214518. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214519. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214520. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214521. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214522. };
  214523. #undef INTERFACE
  214524. #define INTERFACE IDirectSoundCaptureBuffer
  214525. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214526. {
  214527. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214528. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214529. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214530. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214531. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214532. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214533. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214534. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214535. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214536. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214537. STDMETHOD(Stop) (THIS) PURE;
  214538. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214539. };
  214540. };
  214541. BEGIN_JUCE_NAMESPACE
  214542. static const String getDSErrorMessage (HRESULT hr)
  214543. {
  214544. const char* result = 0;
  214545. switch (hr)
  214546. {
  214547. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214548. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214549. case E_INVALIDARG: result = "Invalid parameter"; break;
  214550. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214551. case E_FAIL: result = "Generic error"; break;
  214552. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214553. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214554. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214555. case E_NOTIMPL: result = "Unsupported function"; break;
  214556. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214557. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214558. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214559. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214560. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214561. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214562. case E_NOINTERFACE: result = "No interface"; break;
  214563. case S_OK: result = "No error"; break;
  214564. default: return "Unknown error: " + String ((int) hr);
  214565. }
  214566. return result;
  214567. }
  214568. #define DS_DEBUGGING 1
  214569. #ifdef DS_DEBUGGING
  214570. #define CATCH JUCE_CATCH_EXCEPTION
  214571. #undef log
  214572. #define log(a) Logger::writeToLog(a);
  214573. #undef logError
  214574. #define logError(a) logDSError(a, __LINE__);
  214575. static void logDSError (HRESULT hr, int lineNum)
  214576. {
  214577. if (hr != S_OK)
  214578. {
  214579. String error ("DS error at line ");
  214580. error << lineNum << " - " << getDSErrorMessage (hr);
  214581. log (error);
  214582. }
  214583. }
  214584. #else
  214585. #define CATCH JUCE_CATCH_ALL
  214586. #define log(a)
  214587. #define logError(a)
  214588. #endif
  214589. #define DSOUND_FUNCTION(functionName, params) \
  214590. typedef HRESULT (WINAPI *type##functionName) params; \
  214591. static type##functionName ds##functionName = 0;
  214592. #define DSOUND_FUNCTION_LOAD(functionName) \
  214593. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214594. jassert (ds##functionName != 0);
  214595. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214596. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214597. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214598. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214599. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214600. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214601. static void initialiseDSoundFunctions()
  214602. {
  214603. if (dsDirectSoundCreate == 0)
  214604. {
  214605. HMODULE h = LoadLibraryA ("dsound.dll");
  214606. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214607. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214608. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214609. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214610. }
  214611. }
  214612. class DSoundInternalOutChannel
  214613. {
  214614. String name;
  214615. LPGUID guid;
  214616. int sampleRate, bufferSizeSamples;
  214617. float* leftBuffer;
  214618. float* rightBuffer;
  214619. IDirectSound* pDirectSound;
  214620. IDirectSoundBuffer* pOutputBuffer;
  214621. DWORD writeOffset;
  214622. int totalBytesPerBuffer;
  214623. int bytesPerBuffer;
  214624. unsigned int lastPlayCursor;
  214625. public:
  214626. int bitDepth;
  214627. bool doneFlag;
  214628. DSoundInternalOutChannel (const String& name_,
  214629. LPGUID guid_,
  214630. int rate,
  214631. int bufferSize,
  214632. float* left,
  214633. float* right)
  214634. : name (name_),
  214635. guid (guid_),
  214636. sampleRate (rate),
  214637. bufferSizeSamples (bufferSize),
  214638. leftBuffer (left),
  214639. rightBuffer (right),
  214640. pDirectSound (0),
  214641. pOutputBuffer (0),
  214642. bitDepth (16)
  214643. {
  214644. }
  214645. ~DSoundInternalOutChannel()
  214646. {
  214647. close();
  214648. }
  214649. void close()
  214650. {
  214651. HRESULT hr;
  214652. if (pOutputBuffer != 0)
  214653. {
  214654. JUCE_TRY
  214655. {
  214656. log ("closing dsound out: " + name);
  214657. hr = pOutputBuffer->Stop();
  214658. logError (hr);
  214659. }
  214660. CATCH
  214661. JUCE_TRY
  214662. {
  214663. hr = pOutputBuffer->Release();
  214664. logError (hr);
  214665. }
  214666. CATCH
  214667. pOutputBuffer = 0;
  214668. }
  214669. if (pDirectSound != 0)
  214670. {
  214671. JUCE_TRY
  214672. {
  214673. hr = pDirectSound->Release();
  214674. logError (hr);
  214675. }
  214676. CATCH
  214677. pDirectSound = 0;
  214678. }
  214679. }
  214680. const String open()
  214681. {
  214682. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214683. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214684. pDirectSound = 0;
  214685. pOutputBuffer = 0;
  214686. writeOffset = 0;
  214687. String error;
  214688. HRESULT hr = E_NOINTERFACE;
  214689. if (dsDirectSoundCreate != 0)
  214690. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214691. if (hr == S_OK)
  214692. {
  214693. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214694. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214695. const int numChannels = 2;
  214696. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214697. logError (hr);
  214698. if (hr == S_OK)
  214699. {
  214700. IDirectSoundBuffer* pPrimaryBuffer;
  214701. DSBUFFERDESC primaryDesc;
  214702. zerostruct (primaryDesc);
  214703. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214704. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214705. primaryDesc.dwBufferBytes = 0;
  214706. primaryDesc.lpwfxFormat = 0;
  214707. log ("opening dsound out step 2");
  214708. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214709. logError (hr);
  214710. if (hr == S_OK)
  214711. {
  214712. WAVEFORMATEX wfFormat;
  214713. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214714. wfFormat.nChannels = (unsigned short) numChannels;
  214715. wfFormat.nSamplesPerSec = sampleRate;
  214716. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214717. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214718. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214719. wfFormat.cbSize = 0;
  214720. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214721. logError (hr);
  214722. if (hr == S_OK)
  214723. {
  214724. DSBUFFERDESC secondaryDesc;
  214725. zerostruct (secondaryDesc);
  214726. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214727. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214728. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214729. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214730. secondaryDesc.lpwfxFormat = &wfFormat;
  214731. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214732. logError (hr);
  214733. if (hr == S_OK)
  214734. {
  214735. log ("opening dsound out step 3");
  214736. DWORD dwDataLen;
  214737. unsigned char* pDSBuffData;
  214738. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214739. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214740. logError (hr);
  214741. if (hr == S_OK)
  214742. {
  214743. zeromem (pDSBuffData, dwDataLen);
  214744. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214745. if (hr == S_OK)
  214746. {
  214747. hr = pOutputBuffer->SetCurrentPosition (0);
  214748. if (hr == S_OK)
  214749. {
  214750. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214751. if (hr == S_OK)
  214752. return String::empty;
  214753. }
  214754. }
  214755. }
  214756. }
  214757. }
  214758. }
  214759. }
  214760. }
  214761. error = getDSErrorMessage (hr);
  214762. close();
  214763. return error;
  214764. }
  214765. void synchronisePosition()
  214766. {
  214767. if (pOutputBuffer != 0)
  214768. {
  214769. DWORD playCursor;
  214770. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214771. }
  214772. }
  214773. bool service()
  214774. {
  214775. if (pOutputBuffer == 0)
  214776. return true;
  214777. DWORD playCursor, writeCursor;
  214778. for (;;)
  214779. {
  214780. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214781. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214782. {
  214783. pOutputBuffer->Restore();
  214784. continue;
  214785. }
  214786. if (hr == S_OK)
  214787. break;
  214788. logError (hr);
  214789. jassertfalse;
  214790. return true;
  214791. }
  214792. int playWriteGap = writeCursor - playCursor;
  214793. if (playWriteGap < 0)
  214794. playWriteGap += totalBytesPerBuffer;
  214795. int bytesEmpty = playCursor - writeOffset;
  214796. if (bytesEmpty < 0)
  214797. bytesEmpty += totalBytesPerBuffer;
  214798. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214799. {
  214800. writeOffset = writeCursor;
  214801. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214802. }
  214803. if (bytesEmpty >= bytesPerBuffer)
  214804. {
  214805. void* lpbuf1 = 0;
  214806. void* lpbuf2 = 0;
  214807. DWORD dwSize1 = 0;
  214808. DWORD dwSize2 = 0;
  214809. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214810. bytesPerBuffer,
  214811. &lpbuf1, &dwSize1,
  214812. &lpbuf2, &dwSize2, 0);
  214813. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214814. {
  214815. pOutputBuffer->Restore();
  214816. hr = pOutputBuffer->Lock (writeOffset,
  214817. bytesPerBuffer,
  214818. &lpbuf1, &dwSize1,
  214819. &lpbuf2, &dwSize2, 0);
  214820. }
  214821. if (hr == S_OK)
  214822. {
  214823. if (bitDepth == 16)
  214824. {
  214825. const float gainL = 32767.0f;
  214826. const float gainR = 32767.0f;
  214827. int* dest = static_cast<int*> (lpbuf1);
  214828. const float* left = leftBuffer;
  214829. const float* right = rightBuffer;
  214830. int samples1 = dwSize1 >> 2;
  214831. int samples2 = dwSize2 >> 2;
  214832. if (left == 0)
  214833. {
  214834. while (--samples1 >= 0)
  214835. {
  214836. int r = roundToInt (gainR * *right++);
  214837. if (r < -32768)
  214838. r = -32768;
  214839. else if (r > 32767)
  214840. r = 32767;
  214841. *dest++ = (r << 16);
  214842. }
  214843. dest = static_cast<int*> (lpbuf2);
  214844. while (--samples2 >= 0)
  214845. {
  214846. int r = roundToInt (gainR * *right++);
  214847. if (r < -32768)
  214848. r = -32768;
  214849. else if (r > 32767)
  214850. r = 32767;
  214851. *dest++ = (r << 16);
  214852. }
  214853. }
  214854. else if (right == 0)
  214855. {
  214856. while (--samples1 >= 0)
  214857. {
  214858. int l = roundToInt (gainL * *left++);
  214859. if (l < -32768)
  214860. l = -32768;
  214861. else if (l > 32767)
  214862. l = 32767;
  214863. l &= 0xffff;
  214864. *dest++ = l;
  214865. }
  214866. dest = static_cast<int*> (lpbuf2);
  214867. while (--samples2 >= 0)
  214868. {
  214869. int l = roundToInt (gainL * *left++);
  214870. if (l < -32768)
  214871. l = -32768;
  214872. else if (l > 32767)
  214873. l = 32767;
  214874. l &= 0xffff;
  214875. *dest++ = l;
  214876. }
  214877. }
  214878. else
  214879. {
  214880. while (--samples1 >= 0)
  214881. {
  214882. int l = roundToInt (gainL * *left++);
  214883. if (l < -32768)
  214884. l = -32768;
  214885. else if (l > 32767)
  214886. l = 32767;
  214887. l &= 0xffff;
  214888. int r = roundToInt (gainR * *right++);
  214889. if (r < -32768)
  214890. r = -32768;
  214891. else if (r > 32767)
  214892. r = 32767;
  214893. *dest++ = (r << 16) | l;
  214894. }
  214895. dest = static_cast<int*> (lpbuf2);
  214896. while (--samples2 >= 0)
  214897. {
  214898. int l = roundToInt (gainL * *left++);
  214899. if (l < -32768)
  214900. l = -32768;
  214901. else if (l > 32767)
  214902. l = 32767;
  214903. l &= 0xffff;
  214904. int r = roundToInt (gainR * *right++);
  214905. if (r < -32768)
  214906. r = -32768;
  214907. else if (r > 32767)
  214908. r = 32767;
  214909. *dest++ = (r << 16) | l;
  214910. }
  214911. }
  214912. }
  214913. else
  214914. {
  214915. jassertfalse;
  214916. }
  214917. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214918. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214919. }
  214920. else
  214921. {
  214922. jassertfalse;
  214923. logError (hr);
  214924. }
  214925. bytesEmpty -= bytesPerBuffer;
  214926. return true;
  214927. }
  214928. else
  214929. {
  214930. return false;
  214931. }
  214932. }
  214933. };
  214934. struct DSoundInternalInChannel
  214935. {
  214936. String name;
  214937. LPGUID guid;
  214938. int sampleRate, bufferSizeSamples;
  214939. float* leftBuffer;
  214940. float* rightBuffer;
  214941. IDirectSound* pDirectSound;
  214942. IDirectSoundCapture* pDirectSoundCapture;
  214943. IDirectSoundCaptureBuffer* pInputBuffer;
  214944. public:
  214945. unsigned int readOffset;
  214946. int bytesPerBuffer, totalBytesPerBuffer;
  214947. int bitDepth;
  214948. bool doneFlag;
  214949. DSoundInternalInChannel (const String& name_,
  214950. LPGUID guid_,
  214951. int rate,
  214952. int bufferSize,
  214953. float* left,
  214954. float* right)
  214955. : name (name_),
  214956. guid (guid_),
  214957. sampleRate (rate),
  214958. bufferSizeSamples (bufferSize),
  214959. leftBuffer (left),
  214960. rightBuffer (right),
  214961. pDirectSound (0),
  214962. pDirectSoundCapture (0),
  214963. pInputBuffer (0),
  214964. bitDepth (16)
  214965. {
  214966. }
  214967. ~DSoundInternalInChannel()
  214968. {
  214969. close();
  214970. }
  214971. void close()
  214972. {
  214973. HRESULT hr;
  214974. if (pInputBuffer != 0)
  214975. {
  214976. JUCE_TRY
  214977. {
  214978. log ("closing dsound in: " + name);
  214979. hr = pInputBuffer->Stop();
  214980. logError (hr);
  214981. }
  214982. CATCH
  214983. JUCE_TRY
  214984. {
  214985. hr = pInputBuffer->Release();
  214986. logError (hr);
  214987. }
  214988. CATCH
  214989. pInputBuffer = 0;
  214990. }
  214991. if (pDirectSoundCapture != 0)
  214992. {
  214993. JUCE_TRY
  214994. {
  214995. hr = pDirectSoundCapture->Release();
  214996. logError (hr);
  214997. }
  214998. CATCH
  214999. pDirectSoundCapture = 0;
  215000. }
  215001. if (pDirectSound != 0)
  215002. {
  215003. JUCE_TRY
  215004. {
  215005. hr = pDirectSound->Release();
  215006. logError (hr);
  215007. }
  215008. CATCH
  215009. pDirectSound = 0;
  215010. }
  215011. }
  215012. const String open()
  215013. {
  215014. log ("opening dsound in device: " + name
  215015. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  215016. pDirectSound = 0;
  215017. pDirectSoundCapture = 0;
  215018. pInputBuffer = 0;
  215019. readOffset = 0;
  215020. totalBytesPerBuffer = 0;
  215021. String error;
  215022. HRESULT hr = E_NOINTERFACE;
  215023. if (dsDirectSoundCaptureCreate != 0)
  215024. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  215025. logError (hr);
  215026. if (hr == S_OK)
  215027. {
  215028. const int numChannels = 2;
  215029. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  215030. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  215031. WAVEFORMATEX wfFormat;
  215032. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  215033. wfFormat.nChannels = (unsigned short)numChannels;
  215034. wfFormat.nSamplesPerSec = sampleRate;
  215035. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  215036. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  215037. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  215038. wfFormat.cbSize = 0;
  215039. DSCBUFFERDESC captureDesc;
  215040. zerostruct (captureDesc);
  215041. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  215042. captureDesc.dwFlags = 0;
  215043. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  215044. captureDesc.lpwfxFormat = &wfFormat;
  215045. log ("opening dsound in step 2");
  215046. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  215047. logError (hr);
  215048. if (hr == S_OK)
  215049. {
  215050. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  215051. logError (hr);
  215052. if (hr == S_OK)
  215053. return String::empty;
  215054. }
  215055. }
  215056. error = getDSErrorMessage (hr);
  215057. close();
  215058. return error;
  215059. }
  215060. void synchronisePosition()
  215061. {
  215062. if (pInputBuffer != 0)
  215063. {
  215064. DWORD capturePos;
  215065. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  215066. }
  215067. }
  215068. bool service()
  215069. {
  215070. if (pInputBuffer == 0)
  215071. return true;
  215072. DWORD capturePos, readPos;
  215073. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  215074. logError (hr);
  215075. if (hr != S_OK)
  215076. return true;
  215077. int bytesFilled = readPos - readOffset;
  215078. if (bytesFilled < 0)
  215079. bytesFilled += totalBytesPerBuffer;
  215080. if (bytesFilled >= bytesPerBuffer)
  215081. {
  215082. LPBYTE lpbuf1 = 0;
  215083. LPBYTE lpbuf2 = 0;
  215084. DWORD dwsize1 = 0;
  215085. DWORD dwsize2 = 0;
  215086. HRESULT hr = pInputBuffer->Lock (readOffset,
  215087. bytesPerBuffer,
  215088. (void**) &lpbuf1, &dwsize1,
  215089. (void**) &lpbuf2, &dwsize2, 0);
  215090. if (hr == S_OK)
  215091. {
  215092. if (bitDepth == 16)
  215093. {
  215094. const float g = 1.0f / 32768.0f;
  215095. float* destL = leftBuffer;
  215096. float* destR = rightBuffer;
  215097. int samples1 = dwsize1 >> 2;
  215098. int samples2 = dwsize2 >> 2;
  215099. const short* src = (const short*)lpbuf1;
  215100. if (destL == 0)
  215101. {
  215102. while (--samples1 >= 0)
  215103. {
  215104. ++src;
  215105. *destR++ = *src++ * g;
  215106. }
  215107. src = (const short*)lpbuf2;
  215108. while (--samples2 >= 0)
  215109. {
  215110. ++src;
  215111. *destR++ = *src++ * g;
  215112. }
  215113. }
  215114. else if (destR == 0)
  215115. {
  215116. while (--samples1 >= 0)
  215117. {
  215118. *destL++ = *src++ * g;
  215119. ++src;
  215120. }
  215121. src = (const short*)lpbuf2;
  215122. while (--samples2 >= 0)
  215123. {
  215124. *destL++ = *src++ * g;
  215125. ++src;
  215126. }
  215127. }
  215128. else
  215129. {
  215130. while (--samples1 >= 0)
  215131. {
  215132. *destL++ = *src++ * g;
  215133. *destR++ = *src++ * g;
  215134. }
  215135. src = (const short*)lpbuf2;
  215136. while (--samples2 >= 0)
  215137. {
  215138. *destL++ = *src++ * g;
  215139. *destR++ = *src++ * g;
  215140. }
  215141. }
  215142. }
  215143. else
  215144. {
  215145. jassertfalse;
  215146. }
  215147. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  215148. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  215149. }
  215150. else
  215151. {
  215152. logError (hr);
  215153. jassertfalse;
  215154. }
  215155. bytesFilled -= bytesPerBuffer;
  215156. return true;
  215157. }
  215158. else
  215159. {
  215160. return false;
  215161. }
  215162. }
  215163. };
  215164. class DSoundAudioIODevice : public AudioIODevice,
  215165. public Thread
  215166. {
  215167. public:
  215168. DSoundAudioIODevice (const String& deviceName,
  215169. const int outputDeviceIndex_,
  215170. const int inputDeviceIndex_)
  215171. : AudioIODevice (deviceName, "DirectSound"),
  215172. Thread ("Juce DSound"),
  215173. isOpen_ (false),
  215174. isStarted (false),
  215175. outputDeviceIndex (outputDeviceIndex_),
  215176. inputDeviceIndex (inputDeviceIndex_),
  215177. totalSamplesOut (0),
  215178. sampleRate (0.0),
  215179. inputBuffers (1, 1),
  215180. outputBuffers (1, 1),
  215181. callback (0),
  215182. bufferSizeSamples (0)
  215183. {
  215184. if (outputDeviceIndex_ >= 0)
  215185. {
  215186. outChannels.add (TRANS("Left"));
  215187. outChannels.add (TRANS("Right"));
  215188. }
  215189. if (inputDeviceIndex_ >= 0)
  215190. {
  215191. inChannels.add (TRANS("Left"));
  215192. inChannels.add (TRANS("Right"));
  215193. }
  215194. }
  215195. ~DSoundAudioIODevice()
  215196. {
  215197. close();
  215198. }
  215199. const StringArray getOutputChannelNames()
  215200. {
  215201. return outChannels;
  215202. }
  215203. const StringArray getInputChannelNames()
  215204. {
  215205. return inChannels;
  215206. }
  215207. int getNumSampleRates()
  215208. {
  215209. return 4;
  215210. }
  215211. double getSampleRate (int index)
  215212. {
  215213. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215214. return samps [jlimit (0, 3, index)];
  215215. }
  215216. int getNumBufferSizesAvailable()
  215217. {
  215218. return 50;
  215219. }
  215220. int getBufferSizeSamples (int index)
  215221. {
  215222. int n = 64;
  215223. for (int i = 0; i < index; ++i)
  215224. n += (n < 512) ? 32
  215225. : ((n < 1024) ? 64
  215226. : ((n < 2048) ? 128 : 256));
  215227. return n;
  215228. }
  215229. int getDefaultBufferSize()
  215230. {
  215231. return 2560;
  215232. }
  215233. const String open (const BigInteger& inputChannels,
  215234. const BigInteger& outputChannels,
  215235. double sampleRate,
  215236. int bufferSizeSamples)
  215237. {
  215238. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215239. isOpen_ = lastError.isEmpty();
  215240. return lastError;
  215241. }
  215242. void close()
  215243. {
  215244. stop();
  215245. if (isOpen_)
  215246. {
  215247. closeDevice();
  215248. isOpen_ = false;
  215249. }
  215250. }
  215251. bool isOpen()
  215252. {
  215253. return isOpen_ && isThreadRunning();
  215254. }
  215255. int getCurrentBufferSizeSamples()
  215256. {
  215257. return bufferSizeSamples;
  215258. }
  215259. double getCurrentSampleRate()
  215260. {
  215261. return sampleRate;
  215262. }
  215263. int getCurrentBitDepth()
  215264. {
  215265. int i, bits = 256;
  215266. for (i = inChans.size(); --i >= 0;)
  215267. bits = jmin (bits, inChans[i]->bitDepth);
  215268. for (i = outChans.size(); --i >= 0;)
  215269. bits = jmin (bits, outChans[i]->bitDepth);
  215270. if (bits > 32)
  215271. bits = 16;
  215272. return bits;
  215273. }
  215274. const BigInteger getActiveOutputChannels() const
  215275. {
  215276. return enabledOutputs;
  215277. }
  215278. const BigInteger getActiveInputChannels() const
  215279. {
  215280. return enabledInputs;
  215281. }
  215282. int getOutputLatencyInSamples()
  215283. {
  215284. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215285. }
  215286. int getInputLatencyInSamples()
  215287. {
  215288. return getOutputLatencyInSamples();
  215289. }
  215290. void start (AudioIODeviceCallback* call)
  215291. {
  215292. if (isOpen_ && call != 0 && ! isStarted)
  215293. {
  215294. if (! isThreadRunning())
  215295. {
  215296. // something gone wrong and the thread's stopped..
  215297. isOpen_ = false;
  215298. return;
  215299. }
  215300. call->audioDeviceAboutToStart (this);
  215301. const ScopedLock sl (startStopLock);
  215302. callback = call;
  215303. isStarted = true;
  215304. }
  215305. }
  215306. void stop()
  215307. {
  215308. if (isStarted)
  215309. {
  215310. AudioIODeviceCallback* const callbackLocal = callback;
  215311. {
  215312. const ScopedLock sl (startStopLock);
  215313. isStarted = false;
  215314. }
  215315. if (callbackLocal != 0)
  215316. callbackLocal->audioDeviceStopped();
  215317. }
  215318. }
  215319. bool isPlaying()
  215320. {
  215321. return isStarted && isOpen_ && isThreadRunning();
  215322. }
  215323. const String getLastError()
  215324. {
  215325. return lastError;
  215326. }
  215327. juce_UseDebuggingNewOperator
  215328. StringArray inChannels, outChannels;
  215329. int outputDeviceIndex, inputDeviceIndex;
  215330. private:
  215331. bool isOpen_;
  215332. bool isStarted;
  215333. String lastError;
  215334. OwnedArray <DSoundInternalInChannel> inChans;
  215335. OwnedArray <DSoundInternalOutChannel> outChans;
  215336. WaitableEvent startEvent;
  215337. int bufferSizeSamples;
  215338. int volatile totalSamplesOut;
  215339. int64 volatile lastBlockTime;
  215340. double sampleRate;
  215341. BigInteger enabledInputs, enabledOutputs;
  215342. AudioSampleBuffer inputBuffers, outputBuffers;
  215343. AudioIODeviceCallback* callback;
  215344. CriticalSection startStopLock;
  215345. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215346. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215347. const String openDevice (const BigInteger& inputChannels,
  215348. const BigInteger& outputChannels,
  215349. double sampleRate_,
  215350. int bufferSizeSamples_);
  215351. void closeDevice()
  215352. {
  215353. isStarted = false;
  215354. stopThread (5000);
  215355. inChans.clear();
  215356. outChans.clear();
  215357. inputBuffers.setSize (1, 1);
  215358. outputBuffers.setSize (1, 1);
  215359. }
  215360. void resync()
  215361. {
  215362. if (! threadShouldExit())
  215363. {
  215364. sleep (5);
  215365. int i;
  215366. for (i = 0; i < outChans.size(); ++i)
  215367. outChans.getUnchecked(i)->synchronisePosition();
  215368. for (i = 0; i < inChans.size(); ++i)
  215369. inChans.getUnchecked(i)->synchronisePosition();
  215370. }
  215371. }
  215372. public:
  215373. void run()
  215374. {
  215375. while (! threadShouldExit())
  215376. {
  215377. if (wait (100))
  215378. break;
  215379. }
  215380. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215381. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215382. while (! threadShouldExit())
  215383. {
  215384. int numToDo = 0;
  215385. uint32 startTime = Time::getMillisecondCounter();
  215386. int i;
  215387. for (i = inChans.size(); --i >= 0;)
  215388. {
  215389. inChans.getUnchecked(i)->doneFlag = false;
  215390. ++numToDo;
  215391. }
  215392. for (i = outChans.size(); --i >= 0;)
  215393. {
  215394. outChans.getUnchecked(i)->doneFlag = false;
  215395. ++numToDo;
  215396. }
  215397. if (numToDo > 0)
  215398. {
  215399. const int maxCount = 3;
  215400. int count = maxCount;
  215401. for (;;)
  215402. {
  215403. for (i = inChans.size(); --i >= 0;)
  215404. {
  215405. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215406. if ((! in->doneFlag) && in->service())
  215407. {
  215408. in->doneFlag = true;
  215409. --numToDo;
  215410. }
  215411. }
  215412. for (i = outChans.size(); --i >= 0;)
  215413. {
  215414. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215415. if ((! out->doneFlag) && out->service())
  215416. {
  215417. out->doneFlag = true;
  215418. --numToDo;
  215419. }
  215420. }
  215421. if (numToDo <= 0)
  215422. break;
  215423. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215424. {
  215425. resync();
  215426. break;
  215427. }
  215428. if (--count <= 0)
  215429. {
  215430. Sleep (1);
  215431. count = maxCount;
  215432. }
  215433. if (threadShouldExit())
  215434. return;
  215435. }
  215436. }
  215437. else
  215438. {
  215439. sleep (1);
  215440. }
  215441. const ScopedLock sl (startStopLock);
  215442. if (isStarted)
  215443. {
  215444. JUCE_TRY
  215445. {
  215446. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215447. inputBuffers.getNumChannels(),
  215448. outputBuffers.getArrayOfChannels(),
  215449. outputBuffers.getNumChannels(),
  215450. bufferSizeSamples);
  215451. }
  215452. JUCE_CATCH_EXCEPTION
  215453. totalSamplesOut += bufferSizeSamples;
  215454. }
  215455. else
  215456. {
  215457. outputBuffers.clear();
  215458. totalSamplesOut = 0;
  215459. sleep (1);
  215460. }
  215461. }
  215462. }
  215463. };
  215464. class DSoundAudioIODeviceType : public AudioIODeviceType
  215465. {
  215466. public:
  215467. DSoundAudioIODeviceType()
  215468. : AudioIODeviceType ("DirectSound"),
  215469. hasScanned (false)
  215470. {
  215471. initialiseDSoundFunctions();
  215472. }
  215473. ~DSoundAudioIODeviceType()
  215474. {
  215475. }
  215476. void scanForDevices()
  215477. {
  215478. hasScanned = true;
  215479. outputDeviceNames.clear();
  215480. outputGuids.clear();
  215481. inputDeviceNames.clear();
  215482. inputGuids.clear();
  215483. if (dsDirectSoundEnumerateW != 0)
  215484. {
  215485. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215486. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215487. }
  215488. }
  215489. const StringArray getDeviceNames (bool wantInputNames) const
  215490. {
  215491. jassert (hasScanned); // need to call scanForDevices() before doing this
  215492. return wantInputNames ? inputDeviceNames
  215493. : outputDeviceNames;
  215494. }
  215495. int getDefaultDeviceIndex (bool /*forInput*/) const
  215496. {
  215497. jassert (hasScanned); // need to call scanForDevices() before doing this
  215498. return 0;
  215499. }
  215500. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215501. {
  215502. jassert (hasScanned); // need to call scanForDevices() before doing this
  215503. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215504. if (d == 0)
  215505. return -1;
  215506. return asInput ? d->inputDeviceIndex
  215507. : d->outputDeviceIndex;
  215508. }
  215509. bool hasSeparateInputsAndOutputs() const { return true; }
  215510. AudioIODevice* createDevice (const String& outputDeviceName,
  215511. const String& inputDeviceName)
  215512. {
  215513. jassert (hasScanned); // need to call scanForDevices() before doing this
  215514. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215515. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215516. if (outputIndex >= 0 || inputIndex >= 0)
  215517. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215518. : inputDeviceName,
  215519. outputIndex, inputIndex);
  215520. return 0;
  215521. }
  215522. juce_UseDebuggingNewOperator
  215523. StringArray outputDeviceNames;
  215524. OwnedArray <GUID> outputGuids;
  215525. StringArray inputDeviceNames;
  215526. OwnedArray <GUID> inputGuids;
  215527. private:
  215528. bool hasScanned;
  215529. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215530. {
  215531. desc = desc.trim();
  215532. if (desc.isNotEmpty())
  215533. {
  215534. const String origDesc (desc);
  215535. int n = 2;
  215536. while (outputDeviceNames.contains (desc))
  215537. desc = origDesc + " (" + String (n++) + ")";
  215538. outputDeviceNames.add (desc);
  215539. if (lpGUID != 0)
  215540. outputGuids.add (new GUID (*lpGUID));
  215541. else
  215542. outputGuids.add (0);
  215543. }
  215544. return TRUE;
  215545. }
  215546. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215547. {
  215548. return ((DSoundAudioIODeviceType*) object)
  215549. ->outputEnumProc (lpGUID, String (description));
  215550. }
  215551. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215552. {
  215553. return ((DSoundAudioIODeviceType*) object)
  215554. ->outputEnumProc (lpGUID, String (description));
  215555. }
  215556. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215557. {
  215558. desc = desc.trim();
  215559. if (desc.isNotEmpty())
  215560. {
  215561. const String origDesc (desc);
  215562. int n = 2;
  215563. while (inputDeviceNames.contains (desc))
  215564. desc = origDesc + " (" + String (n++) + ")";
  215565. inputDeviceNames.add (desc);
  215566. if (lpGUID != 0)
  215567. inputGuids.add (new GUID (*lpGUID));
  215568. else
  215569. inputGuids.add (0);
  215570. }
  215571. return TRUE;
  215572. }
  215573. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215574. {
  215575. return ((DSoundAudioIODeviceType*) object)
  215576. ->inputEnumProc (lpGUID, String (description));
  215577. }
  215578. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215579. {
  215580. return ((DSoundAudioIODeviceType*) object)
  215581. ->inputEnumProc (lpGUID, String (description));
  215582. }
  215583. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215584. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215585. };
  215586. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215587. const BigInteger& outputChannels,
  215588. double sampleRate_,
  215589. int bufferSizeSamples_)
  215590. {
  215591. closeDevice();
  215592. totalSamplesOut = 0;
  215593. sampleRate = sampleRate_;
  215594. if (bufferSizeSamples_ <= 0)
  215595. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215596. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215597. DSoundAudioIODeviceType dlh;
  215598. dlh.scanForDevices();
  215599. enabledInputs = inputChannels;
  215600. enabledInputs.setRange (inChannels.size(),
  215601. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215602. false);
  215603. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215604. inputBuffers.clear();
  215605. int i, numIns = 0;
  215606. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215607. {
  215608. float* left = 0;
  215609. if (enabledInputs[i])
  215610. left = inputBuffers.getSampleData (numIns++);
  215611. float* right = 0;
  215612. if (enabledInputs[i + 1])
  215613. right = inputBuffers.getSampleData (numIns++);
  215614. if (left != 0 || right != 0)
  215615. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215616. dlh.inputGuids [inputDeviceIndex],
  215617. (int) sampleRate, bufferSizeSamples,
  215618. left, right));
  215619. }
  215620. enabledOutputs = outputChannels;
  215621. enabledOutputs.setRange (outChannels.size(),
  215622. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215623. false);
  215624. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215625. outputBuffers.clear();
  215626. int numOuts = 0;
  215627. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215628. {
  215629. float* left = 0;
  215630. if (enabledOutputs[i])
  215631. left = outputBuffers.getSampleData (numOuts++);
  215632. float* right = 0;
  215633. if (enabledOutputs[i + 1])
  215634. right = outputBuffers.getSampleData (numOuts++);
  215635. if (left != 0 || right != 0)
  215636. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215637. dlh.outputGuids [outputDeviceIndex],
  215638. (int) sampleRate, bufferSizeSamples,
  215639. left, right));
  215640. }
  215641. String error;
  215642. // boost our priority while opening the devices to try to get better sync between them
  215643. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215644. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215645. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215646. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215647. for (i = 0; i < outChans.size(); ++i)
  215648. {
  215649. error = outChans[i]->open();
  215650. if (error.isNotEmpty())
  215651. {
  215652. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215653. break;
  215654. }
  215655. }
  215656. if (error.isEmpty())
  215657. {
  215658. for (i = 0; i < inChans.size(); ++i)
  215659. {
  215660. error = inChans[i]->open();
  215661. if (error.isNotEmpty())
  215662. {
  215663. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215664. break;
  215665. }
  215666. }
  215667. }
  215668. if (error.isEmpty())
  215669. {
  215670. totalSamplesOut = 0;
  215671. for (i = 0; i < outChans.size(); ++i)
  215672. outChans.getUnchecked(i)->synchronisePosition();
  215673. for (i = 0; i < inChans.size(); ++i)
  215674. inChans.getUnchecked(i)->synchronisePosition();
  215675. startThread (9);
  215676. sleep (10);
  215677. notify();
  215678. }
  215679. else
  215680. {
  215681. log (error);
  215682. }
  215683. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215684. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215685. return error;
  215686. }
  215687. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215688. {
  215689. return new DSoundAudioIODeviceType();
  215690. }
  215691. #undef log
  215692. #endif
  215693. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215694. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215695. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215696. // compiled on its own).
  215697. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215698. #if 1
  215699. const String getAudioErrorDesc (HRESULT hr)
  215700. {
  215701. const char* e = 0;
  215702. switch (hr)
  215703. {
  215704. case E_POINTER: e = "E_POINTER"; break;
  215705. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  215706. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  215707. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215708. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215709. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215710. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  215711. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215712. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  215713. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215714. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  215715. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  215716. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215717. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215718. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215719. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215720. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215721. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215722. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215723. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215724. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215725. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215726. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215727. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  215728. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215729. default: return String::toHexString ((int) hr);
  215730. }
  215731. return e;
  215732. }
  215733. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  215734. #define OK(a) wasapi_checkResult(a)
  215735. static bool wasapi_checkResult (HRESULT hr)
  215736. {
  215737. logFailure (hr);
  215738. return SUCCEEDED (hr);
  215739. }
  215740. #else
  215741. #define logFailure(hr) {}
  215742. #define OK(a) SUCCEEDED(a)
  215743. #endif
  215744. static const String wasapi_getDeviceID (IMMDevice* const device)
  215745. {
  215746. String s;
  215747. WCHAR* deviceId = 0;
  215748. if (OK (device->GetId (&deviceId)))
  215749. {
  215750. s = String (deviceId);
  215751. CoTaskMemFree (deviceId);
  215752. }
  215753. return s;
  215754. }
  215755. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  215756. {
  215757. EDataFlow flow = eRender;
  215758. ComSmartPtr <IMMEndpoint> endPoint;
  215759. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  215760. (void) OK (endPoint->GetDataFlow (&flow));
  215761. return flow;
  215762. }
  215763. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215764. {
  215765. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215766. }
  215767. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215768. {
  215769. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215770. : sizeof (WAVEFORMATEX));
  215771. }
  215772. class WASAPIDeviceBase
  215773. {
  215774. public:
  215775. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215776. : device (device_),
  215777. sampleRate (0),
  215778. numChannels (0),
  215779. actualNumChannels (0),
  215780. defaultSampleRate (0),
  215781. minBufferSize (0),
  215782. defaultBufferSize (0),
  215783. latencySamples (0),
  215784. useExclusiveMode (useExclusiveMode_)
  215785. {
  215786. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215787. ComSmartPtr <IAudioClient> tempClient (createClient());
  215788. if (tempClient == 0)
  215789. return;
  215790. REFERENCE_TIME defaultPeriod, minPeriod;
  215791. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215792. return;
  215793. WAVEFORMATEX* mixFormat = 0;
  215794. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  215795. return;
  215796. WAVEFORMATEXTENSIBLE format;
  215797. wasapi_copyWavFormat (format, mixFormat);
  215798. CoTaskMemFree (mixFormat);
  215799. actualNumChannels = numChannels = format.Format.nChannels;
  215800. defaultSampleRate = format.Format.nSamplesPerSec;
  215801. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  215802. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  215803. rates.addUsingDefaultSort (defaultSampleRate);
  215804. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215805. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215806. {
  215807. if (ratesToTest[i] == defaultSampleRate)
  215808. continue;
  215809. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215810. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215811. (WAVEFORMATEX*) &format, 0)))
  215812. if (! rates.contains (ratesToTest[i]))
  215813. rates.addUsingDefaultSort (ratesToTest[i]);
  215814. }
  215815. }
  215816. ~WASAPIDeviceBase()
  215817. {
  215818. device = 0;
  215819. CloseHandle (clientEvent);
  215820. }
  215821. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215822. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215823. {
  215824. sampleRate = newSampleRate;
  215825. channels = newChannels;
  215826. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215827. numChannels = channels.getHighestBit() + 1;
  215828. if (numChannels == 0)
  215829. return true;
  215830. client = createClient();
  215831. if (client != 0
  215832. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215833. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215834. {
  215835. channelMaps.clear();
  215836. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215837. if (channels[i])
  215838. channelMaps.add (i);
  215839. REFERENCE_TIME latency;
  215840. if (OK (client->GetStreamLatency (&latency)))
  215841. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  215842. (void) OK (client->GetBufferSize (&actualBufferSize));
  215843. return OK (client->SetEventHandle (clientEvent));
  215844. }
  215845. return false;
  215846. }
  215847. void closeClient()
  215848. {
  215849. if (client != 0)
  215850. client->Stop();
  215851. client = 0;
  215852. ResetEvent (clientEvent);
  215853. }
  215854. ComSmartPtr <IMMDevice> device;
  215855. ComSmartPtr <IAudioClient> client;
  215856. double sampleRate, defaultSampleRate;
  215857. int numChannels, actualNumChannels;
  215858. int minBufferSize, defaultBufferSize, latencySamples;
  215859. const bool useExclusiveMode;
  215860. Array <double> rates;
  215861. HANDLE clientEvent;
  215862. BigInteger channels;
  215863. AudioDataConverters::DataFormat dataFormat;
  215864. Array <int> channelMaps;
  215865. UINT32 actualBufferSize;
  215866. int bytesPerSample;
  215867. private:
  215868. const ComSmartPtr <IAudioClient> createClient()
  215869. {
  215870. ComSmartPtr <IAudioClient> client;
  215871. if (device != 0)
  215872. {
  215873. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  215874. logFailure (hr);
  215875. }
  215876. return client;
  215877. }
  215878. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215879. {
  215880. WAVEFORMATEXTENSIBLE format;
  215881. zerostruct (format);
  215882. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215883. {
  215884. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215885. }
  215886. else
  215887. {
  215888. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215889. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215890. }
  215891. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215892. format.Format.nChannels = (WORD) numChannels;
  215893. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215894. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215895. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215896. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215897. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215898. switch (numChannels)
  215899. {
  215900. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215901. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215902. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215903. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215904. 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;
  215905. default: break;
  215906. }
  215907. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215908. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215909. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215910. logFailure (hr);
  215911. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215912. {
  215913. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215914. hr = S_OK;
  215915. }
  215916. CoTaskMemFree (nearestFormat);
  215917. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215918. if (useExclusiveMode)
  215919. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215920. GUID session;
  215921. if (hr == S_OK
  215922. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215923. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215924. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215925. {
  215926. actualNumChannels = format.Format.nChannels;
  215927. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215928. bytesPerSample = format.Format.wBitsPerSample / 8;
  215929. dataFormat = isFloat ? AudioDataConverters::float32LE
  215930. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  215931. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  215932. : AudioDataConverters::int16LE)));
  215933. return true;
  215934. }
  215935. return false;
  215936. }
  215937. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215938. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215939. };
  215940. class WASAPIInputDevice : public WASAPIDeviceBase
  215941. {
  215942. public:
  215943. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215944. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215945. reservoir (1, 1)
  215946. {
  215947. }
  215948. ~WASAPIInputDevice()
  215949. {
  215950. close();
  215951. }
  215952. bool open (const double newSampleRate, const BigInteger& newChannels)
  215953. {
  215954. reservoirSize = 0;
  215955. reservoirCapacity = 16384;
  215956. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215957. return openClient (newSampleRate, newChannels)
  215958. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  215959. }
  215960. void close()
  215961. {
  215962. closeClient();
  215963. captureClient = 0;
  215964. reservoir.setSize (0);
  215965. }
  215966. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215967. {
  215968. if (numChannels <= 0)
  215969. return;
  215970. int offset = 0;
  215971. while (bufferSize > 0)
  215972. {
  215973. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215974. {
  215975. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215976. for (int i = 0; i < numDestBuffers; ++i)
  215977. {
  215978. float* const dest = destBuffers[i] + offset;
  215979. const int srcChan = channelMaps.getUnchecked(i);
  215980. switch (dataFormat)
  215981. {
  215982. case AudioDataConverters::float32LE:
  215983. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215984. break;
  215985. case AudioDataConverters::int32LE:
  215986. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215987. break;
  215988. case AudioDataConverters::int24LE:
  215989. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  215990. break;
  215991. case AudioDataConverters::int16LE:
  215992. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  215993. break;
  215994. default: jassertfalse; break;
  215995. }
  215996. }
  215997. bufferSize -= samplesToDo;
  215998. offset += samplesToDo;
  215999. reservoirSize -= samplesToDo;
  216000. }
  216001. else
  216002. {
  216003. UINT32 packetLength = 0;
  216004. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  216005. break;
  216006. if (packetLength == 0)
  216007. {
  216008. if (thread.threadShouldExit())
  216009. break;
  216010. Thread::sleep (1);
  216011. continue;
  216012. }
  216013. uint8* inputData = 0;
  216014. UINT32 numSamplesAvailable;
  216015. DWORD flags;
  216016. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  216017. {
  216018. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  216019. for (int i = 0; i < numDestBuffers; ++i)
  216020. {
  216021. float* const dest = destBuffers[i] + offset;
  216022. const int srcChan = channelMaps.getUnchecked(i);
  216023. switch (dataFormat)
  216024. {
  216025. case AudioDataConverters::float32LE:
  216026. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  216027. break;
  216028. case AudioDataConverters::int32LE:
  216029. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  216030. break;
  216031. case AudioDataConverters::int24LE:
  216032. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  216033. break;
  216034. case AudioDataConverters::int16LE:
  216035. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  216036. break;
  216037. default: jassertfalse; break;
  216038. }
  216039. }
  216040. bufferSize -= samplesToDo;
  216041. offset += samplesToDo;
  216042. if (samplesToDo < (int) numSamplesAvailable)
  216043. {
  216044. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  216045. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  216046. bytesPerSample * actualNumChannels * reservoirSize);
  216047. }
  216048. captureClient->ReleaseBuffer (numSamplesAvailable);
  216049. }
  216050. }
  216051. }
  216052. }
  216053. ComSmartPtr <IAudioCaptureClient> captureClient;
  216054. MemoryBlock reservoir;
  216055. int reservoirSize, reservoirCapacity;
  216056. private:
  216057. WASAPIInputDevice (const WASAPIInputDevice&);
  216058. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  216059. };
  216060. class WASAPIOutputDevice : public WASAPIDeviceBase
  216061. {
  216062. public:
  216063. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  216064. : WASAPIDeviceBase (device_, useExclusiveMode_)
  216065. {
  216066. }
  216067. ~WASAPIOutputDevice()
  216068. {
  216069. close();
  216070. }
  216071. bool open (const double newSampleRate, const BigInteger& newChannels)
  216072. {
  216073. return openClient (newSampleRate, newChannels)
  216074. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  216075. }
  216076. void close()
  216077. {
  216078. closeClient();
  216079. renderClient = 0;
  216080. }
  216081. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  216082. {
  216083. if (numChannels <= 0)
  216084. return;
  216085. int offset = 0;
  216086. while (bufferSize > 0)
  216087. {
  216088. UINT32 padding = 0;
  216089. if (! OK (client->GetCurrentPadding (&padding)))
  216090. return;
  216091. int samplesToDo = useExclusiveMode ? bufferSize
  216092. : jmin ((int) (actualBufferSize - padding), bufferSize);
  216093. if (samplesToDo <= 0)
  216094. {
  216095. if (thread.threadShouldExit())
  216096. break;
  216097. Thread::sleep (0);
  216098. continue;
  216099. }
  216100. uint8* outputData = 0;
  216101. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  216102. {
  216103. for (int i = 0; i < numSrcBuffers; ++i)
  216104. {
  216105. const float* const source = srcBuffers[i] + offset;
  216106. const int destChan = channelMaps.getUnchecked(i);
  216107. switch (dataFormat)
  216108. {
  216109. case AudioDataConverters::float32LE:
  216110. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  216111. break;
  216112. case AudioDataConverters::int32LE:
  216113. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  216114. break;
  216115. case AudioDataConverters::int24LE:
  216116. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  216117. break;
  216118. case AudioDataConverters::int16LE:
  216119. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  216120. break;
  216121. default: jassertfalse; break;
  216122. }
  216123. }
  216124. renderClient->ReleaseBuffer (samplesToDo, 0);
  216125. offset += samplesToDo;
  216126. bufferSize -= samplesToDo;
  216127. }
  216128. }
  216129. }
  216130. ComSmartPtr <IAudioRenderClient> renderClient;
  216131. private:
  216132. WASAPIOutputDevice (const WASAPIOutputDevice&);
  216133. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  216134. };
  216135. class WASAPIAudioIODevice : public AudioIODevice,
  216136. public Thread
  216137. {
  216138. public:
  216139. WASAPIAudioIODevice (const String& deviceName,
  216140. const String& outputDeviceId_,
  216141. const String& inputDeviceId_,
  216142. const bool useExclusiveMode_)
  216143. : AudioIODevice (deviceName, "Windows Audio"),
  216144. Thread ("Juce WASAPI"),
  216145. isOpen_ (false),
  216146. isStarted (false),
  216147. outputDeviceId (outputDeviceId_),
  216148. inputDeviceId (inputDeviceId_),
  216149. useExclusiveMode (useExclusiveMode_),
  216150. currentBufferSizeSamples (0),
  216151. currentSampleRate (0),
  216152. callback (0)
  216153. {
  216154. }
  216155. ~WASAPIAudioIODevice()
  216156. {
  216157. close();
  216158. }
  216159. bool initialise()
  216160. {
  216161. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  216162. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  216163. latencyIn = latencyOut = 0;
  216164. Array <double> ratesIn, ratesOut;
  216165. if (createDevices())
  216166. {
  216167. jassert (inputDevice != 0 || outputDevice != 0);
  216168. if (inputDevice != 0 && outputDevice != 0)
  216169. {
  216170. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  216171. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  216172. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  216173. sampleRates = inputDevice->rates;
  216174. sampleRates.removeValuesNotIn (outputDevice->rates);
  216175. }
  216176. else
  216177. {
  216178. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  216179. : static_cast<WASAPIDeviceBase*> (outputDevice);
  216180. defaultSampleRate = d->defaultSampleRate;
  216181. minBufferSize = d->minBufferSize;
  216182. defaultBufferSize = d->defaultBufferSize;
  216183. sampleRates = d->rates;
  216184. }
  216185. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  216186. if (minBufferSize != defaultBufferSize)
  216187. bufferSizes.addUsingDefaultSort (minBufferSize);
  216188. int n = 64;
  216189. for (int i = 0; i < 40; ++i)
  216190. {
  216191. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  216192. bufferSizes.addUsingDefaultSort (n);
  216193. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  216194. }
  216195. return true;
  216196. }
  216197. return false;
  216198. }
  216199. const StringArray getOutputChannelNames()
  216200. {
  216201. StringArray outChannels;
  216202. if (outputDevice != 0)
  216203. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  216204. outChannels.add ("Output channel " + String (i));
  216205. return outChannels;
  216206. }
  216207. const StringArray getInputChannelNames()
  216208. {
  216209. StringArray inChannels;
  216210. if (inputDevice != 0)
  216211. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216212. inChannels.add ("Input channel " + String (i));
  216213. return inChannels;
  216214. }
  216215. int getNumSampleRates() { return sampleRates.size(); }
  216216. double getSampleRate (int index) { return sampleRates [index]; }
  216217. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216218. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216219. int getDefaultBufferSize() { return defaultBufferSize; }
  216220. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216221. double getCurrentSampleRate() { return currentSampleRate; }
  216222. int getCurrentBitDepth() { return 32; }
  216223. int getOutputLatencyInSamples() { return latencyOut; }
  216224. int getInputLatencyInSamples() { return latencyIn; }
  216225. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216226. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216227. const String getLastError() { return lastError; }
  216228. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216229. double sampleRate, int bufferSizeSamples)
  216230. {
  216231. close();
  216232. lastError = String::empty;
  216233. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216234. {
  216235. lastError = "The input and output devices don't share a common sample rate!";
  216236. return lastError;
  216237. }
  216238. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216239. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216240. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216241. {
  216242. lastError = "Couldn't open the input device!";
  216243. return lastError;
  216244. }
  216245. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216246. {
  216247. close();
  216248. lastError = "Couldn't open the output device!";
  216249. return lastError;
  216250. }
  216251. if (inputDevice != 0)
  216252. ResetEvent (inputDevice->clientEvent);
  216253. if (outputDevice != 0)
  216254. ResetEvent (outputDevice->clientEvent);
  216255. startThread (8);
  216256. Thread::sleep (5);
  216257. if (inputDevice != 0 && inputDevice->client != 0)
  216258. {
  216259. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216260. HRESULT hr = inputDevice->client->Start();
  216261. logFailure (hr); //xxx handle this
  216262. }
  216263. if (outputDevice != 0 && outputDevice->client != 0)
  216264. {
  216265. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216266. HRESULT hr = outputDevice->client->Start();
  216267. logFailure (hr); //xxx handle this
  216268. }
  216269. isOpen_ = true;
  216270. return lastError;
  216271. }
  216272. void close()
  216273. {
  216274. stop();
  216275. if (inputDevice != 0)
  216276. SetEvent (inputDevice->clientEvent);
  216277. if (outputDevice != 0)
  216278. SetEvent (outputDevice->clientEvent);
  216279. stopThread (5000);
  216280. if (inputDevice != 0)
  216281. inputDevice->close();
  216282. if (outputDevice != 0)
  216283. outputDevice->close();
  216284. isOpen_ = false;
  216285. }
  216286. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216287. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216288. void start (AudioIODeviceCallback* call)
  216289. {
  216290. if (isOpen_ && call != 0 && ! isStarted)
  216291. {
  216292. if (! isThreadRunning())
  216293. {
  216294. // something's gone wrong and the thread's stopped..
  216295. isOpen_ = false;
  216296. return;
  216297. }
  216298. call->audioDeviceAboutToStart (this);
  216299. const ScopedLock sl (startStopLock);
  216300. callback = call;
  216301. isStarted = true;
  216302. }
  216303. }
  216304. void stop()
  216305. {
  216306. if (isStarted)
  216307. {
  216308. AudioIODeviceCallback* const callbackLocal = callback;
  216309. {
  216310. const ScopedLock sl (startStopLock);
  216311. isStarted = false;
  216312. }
  216313. if (callbackLocal != 0)
  216314. callbackLocal->audioDeviceStopped();
  216315. }
  216316. }
  216317. void setMMThreadPriority()
  216318. {
  216319. DynamicLibraryLoader dll ("avrt.dll");
  216320. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216321. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216322. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216323. {
  216324. DWORD dummy = 0;
  216325. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216326. if (h != 0)
  216327. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216328. }
  216329. }
  216330. void run()
  216331. {
  216332. setMMThreadPriority();
  216333. const int bufferSize = currentBufferSizeSamples;
  216334. HANDLE events[2];
  216335. int numEvents = 0;
  216336. if (inputDevice != 0)
  216337. events [numEvents++] = inputDevice->clientEvent;
  216338. if (outputDevice != 0)
  216339. events [numEvents++] = outputDevice->clientEvent;
  216340. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216341. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216342. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216343. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216344. float** const inputBuffers = ins.getArrayOfChannels();
  216345. float** const outputBuffers = outs.getArrayOfChannels();
  216346. ins.clear();
  216347. while (! threadShouldExit())
  216348. {
  216349. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216350. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216351. if (result == WAIT_TIMEOUT)
  216352. continue;
  216353. if (threadShouldExit())
  216354. break;
  216355. if (inputDevice != 0)
  216356. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216357. // Make the callback..
  216358. {
  216359. const ScopedLock sl (startStopLock);
  216360. if (isStarted)
  216361. {
  216362. JUCE_TRY
  216363. {
  216364. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216365. numInputBuffers,
  216366. outputBuffers,
  216367. numOutputBuffers,
  216368. bufferSize);
  216369. }
  216370. JUCE_CATCH_EXCEPTION
  216371. }
  216372. else
  216373. {
  216374. outs.clear();
  216375. }
  216376. }
  216377. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216378. continue;
  216379. if (outputDevice != 0)
  216380. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216381. }
  216382. }
  216383. juce_UseDebuggingNewOperator
  216384. String outputDeviceId, inputDeviceId;
  216385. String lastError;
  216386. private:
  216387. // Device stats...
  216388. ScopedPointer<WASAPIInputDevice> inputDevice;
  216389. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216390. const bool useExclusiveMode;
  216391. double defaultSampleRate;
  216392. int minBufferSize, defaultBufferSize;
  216393. int latencyIn, latencyOut;
  216394. Array <double> sampleRates;
  216395. Array <int> bufferSizes;
  216396. // Active state...
  216397. bool isOpen_, isStarted;
  216398. int currentBufferSizeSamples;
  216399. double currentSampleRate;
  216400. AudioIODeviceCallback* callback;
  216401. CriticalSection startStopLock;
  216402. bool createDevices()
  216403. {
  216404. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216405. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216406. return false;
  216407. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216408. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  216409. return false;
  216410. UINT32 numDevices = 0;
  216411. if (! OK (deviceCollection->GetCount (&numDevices)))
  216412. return false;
  216413. for (UINT32 i = 0; i < numDevices; ++i)
  216414. {
  216415. ComSmartPtr <IMMDevice> device;
  216416. if (! OK (deviceCollection->Item (i, &device)))
  216417. continue;
  216418. const String deviceId (wasapi_getDeviceID (device));
  216419. if (deviceId.isEmpty())
  216420. continue;
  216421. const EDataFlow flow = wasapi_getDataFlow (device);
  216422. if (deviceId == inputDeviceId && flow == eCapture)
  216423. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216424. else if (deviceId == outputDeviceId && flow == eRender)
  216425. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216426. }
  216427. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216428. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216429. }
  216430. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216431. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216432. };
  216433. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216434. {
  216435. public:
  216436. WASAPIAudioIODeviceType()
  216437. : AudioIODeviceType ("Windows Audio"),
  216438. hasScanned (false)
  216439. {
  216440. }
  216441. ~WASAPIAudioIODeviceType()
  216442. {
  216443. }
  216444. void scanForDevices()
  216445. {
  216446. hasScanned = true;
  216447. outputDeviceNames.clear();
  216448. inputDeviceNames.clear();
  216449. outputDeviceIds.clear();
  216450. inputDeviceIds.clear();
  216451. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216452. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216453. return;
  216454. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216455. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216456. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216457. UINT32 numDevices = 0;
  216458. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  216459. && OK (deviceCollection->GetCount (&numDevices))))
  216460. return;
  216461. for (UINT32 i = 0; i < numDevices; ++i)
  216462. {
  216463. ComSmartPtr <IMMDevice> device;
  216464. if (! OK (deviceCollection->Item (i, &device)))
  216465. continue;
  216466. const String deviceId (wasapi_getDeviceID (device));
  216467. DWORD state = 0;
  216468. if (! OK (device->GetState (&state)))
  216469. continue;
  216470. if (state != DEVICE_STATE_ACTIVE)
  216471. continue;
  216472. String name;
  216473. {
  216474. ComSmartPtr <IPropertyStore> properties;
  216475. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  216476. continue;
  216477. PROPVARIANT value;
  216478. PropVariantInit (&value);
  216479. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216480. name = value.pwszVal;
  216481. PropVariantClear (&value);
  216482. }
  216483. const EDataFlow flow = wasapi_getDataFlow (device);
  216484. if (flow == eRender)
  216485. {
  216486. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216487. outputDeviceIds.insert (index, deviceId);
  216488. outputDeviceNames.insert (index, name);
  216489. }
  216490. else if (flow == eCapture)
  216491. {
  216492. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216493. inputDeviceIds.insert (index, deviceId);
  216494. inputDeviceNames.insert (index, name);
  216495. }
  216496. }
  216497. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216498. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216499. }
  216500. const StringArray getDeviceNames (bool wantInputNames) const
  216501. {
  216502. jassert (hasScanned); // need to call scanForDevices() before doing this
  216503. return wantInputNames ? inputDeviceNames
  216504. : outputDeviceNames;
  216505. }
  216506. int getDefaultDeviceIndex (bool /*forInput*/) const
  216507. {
  216508. jassert (hasScanned); // need to call scanForDevices() before doing this
  216509. return 0;
  216510. }
  216511. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216512. {
  216513. jassert (hasScanned); // need to call scanForDevices() before doing this
  216514. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216515. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216516. : outputDeviceIds.indexOf (d->outputDeviceId));
  216517. }
  216518. bool hasSeparateInputsAndOutputs() const { return true; }
  216519. AudioIODevice* createDevice (const String& outputDeviceName,
  216520. const String& inputDeviceName)
  216521. {
  216522. jassert (hasScanned); // need to call scanForDevices() before doing this
  216523. const bool useExclusiveMode = false;
  216524. ScopedPointer<WASAPIAudioIODevice> device;
  216525. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216526. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216527. if (outputIndex >= 0 || inputIndex >= 0)
  216528. {
  216529. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216530. : inputDeviceName,
  216531. outputDeviceIds [outputIndex],
  216532. inputDeviceIds [inputIndex],
  216533. useExclusiveMode);
  216534. if (! device->initialise())
  216535. device = 0;
  216536. }
  216537. return device.release();
  216538. }
  216539. juce_UseDebuggingNewOperator
  216540. StringArray outputDeviceNames, outputDeviceIds;
  216541. StringArray inputDeviceNames, inputDeviceIds;
  216542. private:
  216543. bool hasScanned;
  216544. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216545. {
  216546. String s;
  216547. IMMDevice* dev = 0;
  216548. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216549. eMultimedia, &dev)))
  216550. {
  216551. WCHAR* deviceId = 0;
  216552. if (OK (dev->GetId (&deviceId)))
  216553. {
  216554. s = String (deviceId);
  216555. CoTaskMemFree (deviceId);
  216556. }
  216557. dev->Release();
  216558. }
  216559. return s;
  216560. }
  216561. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216562. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216563. };
  216564. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216565. {
  216566. return new WASAPIAudioIODeviceType();
  216567. }
  216568. #undef logFailure
  216569. #undef OK
  216570. #endif
  216571. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216572. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216573. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216574. // compiled on its own).
  216575. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216576. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216577. {
  216578. public:
  216579. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216580. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216581. const ComSmartPtr <IBaseFilter>& filter_,
  216582. int minWidth, int minHeight,
  216583. int maxWidth, int maxHeight)
  216584. : owner (owner_),
  216585. captureGraphBuilder (captureGraphBuilder_),
  216586. filter (filter_),
  216587. ok (false),
  216588. imageNeedsFlipping (false),
  216589. width (0),
  216590. height (0),
  216591. activeUsers (0),
  216592. recordNextFrameTime (false)
  216593. {
  216594. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216595. if (FAILED (hr))
  216596. return;
  216597. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216598. if (FAILED (hr))
  216599. return;
  216600. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  216601. if (FAILED (hr))
  216602. return;
  216603. {
  216604. ComSmartPtr <IAMStreamConfig> streamConfig;
  216605. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216606. IID_IAMStreamConfig, (void**) &streamConfig);
  216607. if (streamConfig != 0)
  216608. {
  216609. getVideoSizes (streamConfig);
  216610. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216611. return;
  216612. }
  216613. }
  216614. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216615. if (FAILED (hr))
  216616. return;
  216617. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216618. if (FAILED (hr))
  216619. return;
  216620. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216621. if (FAILED (hr))
  216622. return;
  216623. if (! connectFilters (filter, smartTee))
  216624. return;
  216625. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216626. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216627. if (FAILED (hr))
  216628. return;
  216629. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  216630. if (FAILED (hr))
  216631. return;
  216632. AM_MEDIA_TYPE mt;
  216633. zerostruct (mt);
  216634. mt.majortype = MEDIATYPE_Video;
  216635. mt.subtype = MEDIASUBTYPE_RGB24;
  216636. mt.formattype = FORMAT_VideoInfo;
  216637. sampleGrabber->SetMediaType (&mt);
  216638. callback = new GrabberCallback (*this);
  216639. sampleGrabber->SetCallback (callback, 1);
  216640. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216641. if (FAILED (hr))
  216642. return;
  216643. ComSmartPtr <IPin> grabberInputPin;
  216644. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  216645. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  216646. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  216647. return;
  216648. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216649. if (FAILED (hr))
  216650. return;
  216651. zerostruct (mt);
  216652. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216653. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216654. width = pVih->bmiHeader.biWidth;
  216655. height = pVih->bmiHeader.biHeight;
  216656. ComSmartPtr <IBaseFilter> nullFilter;
  216657. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216658. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216659. if (connectFilters (sampleGrabberBase, nullFilter)
  216660. && addGraphToRot())
  216661. {
  216662. activeImage = Image (Image::RGB, width, height, true);
  216663. loadingImage = Image (Image::RGB, width, height, true);
  216664. ok = true;
  216665. }
  216666. }
  216667. ~DShowCameraDeviceInteral()
  216668. {
  216669. if (mediaControl != 0)
  216670. mediaControl->Stop();
  216671. removeGraphFromRot();
  216672. for (int i = viewerComps.size(); --i >= 0;)
  216673. viewerComps.getUnchecked(i)->ownerDeleted();
  216674. callback = 0;
  216675. graphBuilder = 0;
  216676. sampleGrabber = 0;
  216677. mediaControl = 0;
  216678. filter = 0;
  216679. captureGraphBuilder = 0;
  216680. smartTee = 0;
  216681. smartTeePreviewOutputPin = 0;
  216682. smartTeeCaptureOutputPin = 0;
  216683. asfWriter = 0;
  216684. }
  216685. void addUser()
  216686. {
  216687. if (ok && activeUsers++ == 0)
  216688. mediaControl->Run();
  216689. }
  216690. void removeUser()
  216691. {
  216692. if (ok && --activeUsers == 0)
  216693. mediaControl->Stop();
  216694. }
  216695. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216696. {
  216697. if (recordNextFrameTime)
  216698. {
  216699. const double defaultCameraLatency = 0.1;
  216700. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216701. recordNextFrameTime = false;
  216702. ComSmartPtr <IPin> pin;
  216703. if (getPin (filter, PINDIR_OUTPUT, &pin))
  216704. {
  216705. ComSmartPtr <IAMPushSource> pushSource;
  216706. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  216707. if (pushSource != 0)
  216708. {
  216709. REFERENCE_TIME latency = 0;
  216710. hr = pushSource->GetLatency (&latency);
  216711. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216712. }
  216713. }
  216714. }
  216715. {
  216716. const int lineStride = width * 3;
  216717. const ScopedLock sl (imageSwapLock);
  216718. {
  216719. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216720. for (int i = 0; i < height; ++i)
  216721. memcpy (destData.getLinePointer ((height - 1) - i),
  216722. buffer + lineStride * i,
  216723. lineStride);
  216724. }
  216725. imageNeedsFlipping = true;
  216726. }
  216727. if (listeners.size() > 0)
  216728. callListeners (loadingImage);
  216729. sendChangeMessage (this);
  216730. }
  216731. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216732. {
  216733. if (imageNeedsFlipping)
  216734. {
  216735. const ScopedLock sl (imageSwapLock);
  216736. swapVariables (loadingImage, activeImage);
  216737. imageNeedsFlipping = false;
  216738. }
  216739. RectanglePlacement rp (RectanglePlacement::centred);
  216740. double dx = 0, dy = 0, dw = width, dh = height;
  216741. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216742. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216743. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216744. g.saveState();
  216745. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216746. g.fillAll (Colours::black);
  216747. g.restoreState();
  216748. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216749. }
  216750. bool createFileCaptureFilter (const File& file)
  216751. {
  216752. removeFileCaptureFilter();
  216753. file.deleteFile();
  216754. mediaControl->Stop();
  216755. firstRecordedTime = Time();
  216756. recordNextFrameTime = true;
  216757. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216758. if (SUCCEEDED (hr))
  216759. {
  216760. ComSmartPtr <IFileSinkFilter> fileSink;
  216761. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  216762. if (SUCCEEDED (hr))
  216763. {
  216764. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216765. if (SUCCEEDED (hr))
  216766. {
  216767. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216768. if (SUCCEEDED (hr))
  216769. {
  216770. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216771. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  216772. asfConfig->SetIndexMode (true);
  216773. ComSmartPtr <IWMProfileManager> profileManager;
  216774. hr = WMCreateProfileManager (&profileManager);
  216775. // This gibberish is the DirectShow profile for a video-only wmv file.
  216776. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  216777. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216778. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216779. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  216780. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  216781. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216782. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  216783. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  216784. prof = prof.replace ("$WIDTH", String (width))
  216785. .replace ("$HEIGHT", String (height));
  216786. ComSmartPtr <IWMProfile> currentProfile;
  216787. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  216788. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216789. if (SUCCEEDED (hr))
  216790. {
  216791. ComSmartPtr <IPin> asfWriterInputPin;
  216792. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  216793. {
  216794. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216795. if (SUCCEEDED (hr)
  216796. && ok && activeUsers > 0
  216797. && SUCCEEDED (mediaControl->Run()))
  216798. {
  216799. return true;
  216800. }
  216801. }
  216802. }
  216803. }
  216804. }
  216805. }
  216806. }
  216807. removeFileCaptureFilter();
  216808. if (ok && activeUsers > 0)
  216809. mediaControl->Run();
  216810. return false;
  216811. }
  216812. void removeFileCaptureFilter()
  216813. {
  216814. mediaControl->Stop();
  216815. if (asfWriter != 0)
  216816. {
  216817. graphBuilder->RemoveFilter (asfWriter);
  216818. asfWriter = 0;
  216819. }
  216820. if (ok && activeUsers > 0)
  216821. mediaControl->Run();
  216822. }
  216823. void addListener (CameraDevice::Listener* listenerToAdd)
  216824. {
  216825. const ScopedLock sl (listenerLock);
  216826. if (listeners.size() == 0)
  216827. addUser();
  216828. listeners.addIfNotAlreadyThere (listenerToAdd);
  216829. }
  216830. void removeListener (CameraDevice::Listener* listenerToRemove)
  216831. {
  216832. const ScopedLock sl (listenerLock);
  216833. listeners.removeValue (listenerToRemove);
  216834. if (listeners.size() == 0)
  216835. removeUser();
  216836. }
  216837. void callListeners (const Image& image)
  216838. {
  216839. const ScopedLock sl (listenerLock);
  216840. for (int i = listeners.size(); --i >= 0;)
  216841. {
  216842. CameraDevice::Listener* const l = listeners[i];
  216843. if (l != 0)
  216844. l->imageReceived (image);
  216845. }
  216846. }
  216847. class DShowCaptureViewerComp : public Component,
  216848. public ChangeListener
  216849. {
  216850. public:
  216851. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216852. : owner (owner_)
  216853. {
  216854. setOpaque (true);
  216855. owner->addChangeListener (this);
  216856. owner->addUser();
  216857. owner->viewerComps.add (this);
  216858. setSize (owner_->width, owner_->height);
  216859. }
  216860. ~DShowCaptureViewerComp()
  216861. {
  216862. if (owner != 0)
  216863. {
  216864. owner->viewerComps.removeValue (this);
  216865. owner->removeUser();
  216866. owner->removeChangeListener (this);
  216867. }
  216868. }
  216869. void ownerDeleted()
  216870. {
  216871. owner = 0;
  216872. }
  216873. void paint (Graphics& g)
  216874. {
  216875. g.setColour (Colours::black);
  216876. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216877. if (owner != 0)
  216878. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216879. else
  216880. g.fillAll (Colours::black);
  216881. }
  216882. void changeListenerCallback (void*)
  216883. {
  216884. repaint();
  216885. }
  216886. private:
  216887. DShowCameraDeviceInteral* owner;
  216888. };
  216889. bool ok;
  216890. int width, height;
  216891. Time firstRecordedTime;
  216892. Array <DShowCaptureViewerComp*> viewerComps;
  216893. private:
  216894. CameraDevice* const owner;
  216895. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216896. ComSmartPtr <IBaseFilter> filter;
  216897. ComSmartPtr <IBaseFilter> smartTee;
  216898. ComSmartPtr <IGraphBuilder> graphBuilder;
  216899. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216900. ComSmartPtr <IMediaControl> mediaControl;
  216901. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216902. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216903. ComSmartPtr <IBaseFilter> asfWriter;
  216904. int activeUsers;
  216905. Array <int> widths, heights;
  216906. DWORD graphRegistrationID;
  216907. CriticalSection imageSwapLock;
  216908. bool imageNeedsFlipping;
  216909. Image loadingImage;
  216910. Image activeImage;
  216911. bool recordNextFrameTime;
  216912. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216913. {
  216914. widths.clear();
  216915. heights.clear();
  216916. int count = 0, size = 0;
  216917. streamConfig->GetNumberOfCapabilities (&count, &size);
  216918. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216919. {
  216920. for (int i = 0; i < count; ++i)
  216921. {
  216922. VIDEO_STREAM_CONFIG_CAPS scc;
  216923. AM_MEDIA_TYPE* config;
  216924. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216925. if (SUCCEEDED (hr))
  216926. {
  216927. const int w = scc.InputSize.cx;
  216928. const int h = scc.InputSize.cy;
  216929. bool duplicate = false;
  216930. for (int j = widths.size(); --j >= 0;)
  216931. {
  216932. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216933. {
  216934. duplicate = true;
  216935. break;
  216936. }
  216937. }
  216938. if (! duplicate)
  216939. {
  216940. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216941. widths.add (w);
  216942. heights.add (h);
  216943. }
  216944. deleteMediaType (config);
  216945. }
  216946. }
  216947. }
  216948. }
  216949. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216950. const int minWidth, const int minHeight,
  216951. const int maxWidth, const int maxHeight)
  216952. {
  216953. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216954. streamConfig->GetNumberOfCapabilities (&count, &size);
  216955. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216956. {
  216957. AM_MEDIA_TYPE* config;
  216958. VIDEO_STREAM_CONFIG_CAPS scc;
  216959. for (int i = 0; i < count; ++i)
  216960. {
  216961. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216962. if (SUCCEEDED (hr))
  216963. {
  216964. if (scc.InputSize.cx >= minWidth
  216965. && scc.InputSize.cy >= minHeight
  216966. && scc.InputSize.cx <= maxWidth
  216967. && scc.InputSize.cy <= maxHeight)
  216968. {
  216969. int area = scc.InputSize.cx * scc.InputSize.cy;
  216970. if (area > bestArea)
  216971. {
  216972. bestIndex = i;
  216973. bestArea = area;
  216974. }
  216975. }
  216976. deleteMediaType (config);
  216977. }
  216978. }
  216979. if (bestIndex >= 0)
  216980. {
  216981. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216982. hr = streamConfig->SetFormat (config);
  216983. deleteMediaType (config);
  216984. return SUCCEEDED (hr);
  216985. }
  216986. }
  216987. return false;
  216988. }
  216989. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  216990. {
  216991. ComSmartPtr <IEnumPins> enumerator;
  216992. ComSmartPtr <IPin> pin;
  216993. filter->EnumPins (&enumerator);
  216994. while (enumerator->Next (1, &pin, 0) == S_OK)
  216995. {
  216996. PIN_DIRECTION dir;
  216997. pin->QueryDirection (&dir);
  216998. if (wantedDirection == dir)
  216999. {
  217000. PIN_INFO info;
  217001. zerostruct (info);
  217002. pin->QueryPinInfo (&info);
  217003. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  217004. {
  217005. pin->AddRef();
  217006. *result = pin;
  217007. return true;
  217008. }
  217009. }
  217010. }
  217011. return false;
  217012. }
  217013. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  217014. {
  217015. ComSmartPtr <IPin> in, out;
  217016. return getPin (first, PINDIR_OUTPUT, &out)
  217017. && getPin (second, PINDIR_INPUT, &in)
  217018. && SUCCEEDED (graphBuilder->Connect (out, in));
  217019. }
  217020. bool addGraphToRot()
  217021. {
  217022. ComSmartPtr <IRunningObjectTable> rot;
  217023. if (FAILED (GetRunningObjectTable (0, &rot)))
  217024. return false;
  217025. ComSmartPtr <IMoniker> moniker;
  217026. WCHAR buffer[128];
  217027. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  217028. if (FAILED (hr))
  217029. return false;
  217030. graphRegistrationID = 0;
  217031. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  217032. }
  217033. void removeGraphFromRot()
  217034. {
  217035. ComSmartPtr <IRunningObjectTable> rot;
  217036. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  217037. rot->Revoke (graphRegistrationID);
  217038. }
  217039. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  217040. {
  217041. if (pmt->cbFormat != 0)
  217042. CoTaskMemFree ((PVOID) pmt->pbFormat);
  217043. if (pmt->pUnk != 0)
  217044. pmt->pUnk->Release();
  217045. CoTaskMemFree (pmt);
  217046. }
  217047. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  217048. {
  217049. public:
  217050. GrabberCallback (DShowCameraDeviceInteral& owner_)
  217051. : owner (owner_)
  217052. {
  217053. }
  217054. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  217055. {
  217056. return E_FAIL;
  217057. }
  217058. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  217059. {
  217060. owner.handleFrame (time, buffer, bufferSize);
  217061. return S_OK;
  217062. }
  217063. private:
  217064. DShowCameraDeviceInteral& owner;
  217065. GrabberCallback (const GrabberCallback&);
  217066. GrabberCallback& operator= (const GrabberCallback&);
  217067. };
  217068. ComSmartPtr <GrabberCallback> callback;
  217069. Array <CameraDevice::Listener*> listeners;
  217070. CriticalSection listenerLock;
  217071. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  217072. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  217073. };
  217074. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  217075. : name (name_)
  217076. {
  217077. isRecording = false;
  217078. }
  217079. CameraDevice::~CameraDevice()
  217080. {
  217081. stopRecording();
  217082. delete static_cast <DShowCameraDeviceInteral*> (internal);
  217083. internal = 0;
  217084. }
  217085. Component* CameraDevice::createViewerComponent()
  217086. {
  217087. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  217088. }
  217089. const String CameraDevice::getFileExtension()
  217090. {
  217091. return ".wmv";
  217092. }
  217093. void CameraDevice::startRecordingToFile (const File& file, int quality)
  217094. {
  217095. stopRecording();
  217096. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217097. d->addUser();
  217098. isRecording = d->createFileCaptureFilter (file);
  217099. }
  217100. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  217101. {
  217102. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217103. return d->firstRecordedTime;
  217104. }
  217105. void CameraDevice::stopRecording()
  217106. {
  217107. if (isRecording)
  217108. {
  217109. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217110. d->removeFileCaptureFilter();
  217111. d->removeUser();
  217112. isRecording = false;
  217113. }
  217114. }
  217115. void CameraDevice::addListener (Listener* listenerToAdd)
  217116. {
  217117. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217118. if (listenerToAdd != 0)
  217119. d->addListener (listenerToAdd);
  217120. }
  217121. void CameraDevice::removeListener (Listener* listenerToRemove)
  217122. {
  217123. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217124. if (listenerToRemove != 0)
  217125. d->removeListener (listenerToRemove);
  217126. }
  217127. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  217128. const int deviceIndexToOpen,
  217129. String& name)
  217130. {
  217131. int index = 0;
  217132. ComSmartPtr <IBaseFilter> result;
  217133. ComSmartPtr <ICreateDevEnum> pDevEnum;
  217134. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  217135. if (SUCCEEDED (hr))
  217136. {
  217137. ComSmartPtr <IEnumMoniker> enumerator;
  217138. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  217139. if (SUCCEEDED (hr) && enumerator != 0)
  217140. {
  217141. ComSmartPtr <IBaseFilter> captureFilter;
  217142. ComSmartPtr <IMoniker> moniker;
  217143. ULONG fetched;
  217144. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  217145. {
  217146. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  217147. if (SUCCEEDED (hr))
  217148. {
  217149. ComSmartPtr <IPropertyBag> propertyBag;
  217150. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  217151. if (SUCCEEDED (hr))
  217152. {
  217153. VARIANT var;
  217154. var.vt = VT_BSTR;
  217155. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  217156. propertyBag = 0;
  217157. if (SUCCEEDED (hr))
  217158. {
  217159. if (names != 0)
  217160. names->add (var.bstrVal);
  217161. if (index == deviceIndexToOpen)
  217162. {
  217163. name = var.bstrVal;
  217164. result = captureFilter;
  217165. captureFilter = 0;
  217166. break;
  217167. }
  217168. ++index;
  217169. }
  217170. moniker = 0;
  217171. }
  217172. captureFilter = 0;
  217173. }
  217174. }
  217175. }
  217176. }
  217177. return result;
  217178. }
  217179. const StringArray CameraDevice::getAvailableDevices()
  217180. {
  217181. StringArray devs;
  217182. String dummy;
  217183. enumerateCameras (&devs, -1, dummy);
  217184. return devs;
  217185. }
  217186. CameraDevice* CameraDevice::openDevice (int index,
  217187. int minWidth, int minHeight,
  217188. int maxWidth, int maxHeight)
  217189. {
  217190. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  217191. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  217192. if (SUCCEEDED (hr))
  217193. {
  217194. String name;
  217195. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  217196. if (filter != 0)
  217197. {
  217198. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  217199. DShowCameraDeviceInteral* const intern
  217200. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  217201. minWidth, minHeight, maxWidth, maxHeight);
  217202. cam->internal = intern;
  217203. if (intern->ok)
  217204. return cam.release();
  217205. }
  217206. }
  217207. return 0;
  217208. }
  217209. #endif
  217210. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  217211. #endif
  217212. // Auto-link the other win32 libs that are needed by library calls..
  217213. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217214. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217215. // Auto-links to various win32 libs that are needed by library calls..
  217216. #pragma comment(lib, "kernel32.lib")
  217217. #pragma comment(lib, "user32.lib")
  217218. #pragma comment(lib, "shell32.lib")
  217219. #pragma comment(lib, "gdi32.lib")
  217220. #pragma comment(lib, "vfw32.lib")
  217221. #pragma comment(lib, "comdlg32.lib")
  217222. #pragma comment(lib, "winmm.lib")
  217223. #pragma comment(lib, "wininet.lib")
  217224. #pragma comment(lib, "ole32.lib")
  217225. #pragma comment(lib, "oleaut32.lib")
  217226. #pragma comment(lib, "advapi32.lib")
  217227. #pragma comment(lib, "ws2_32.lib")
  217228. #pragma comment(lib, "version.lib")
  217229. #ifdef _NATIVE_WCHAR_T_DEFINED
  217230. #ifdef _DEBUG
  217231. #pragma comment(lib, "comsuppwd.lib")
  217232. #else
  217233. #pragma comment(lib, "comsuppw.lib")
  217234. #endif
  217235. #else
  217236. #ifdef _DEBUG
  217237. #pragma comment(lib, "comsuppd.lib")
  217238. #else
  217239. #pragma comment(lib, "comsupp.lib")
  217240. #endif
  217241. #endif
  217242. #if JUCE_OPENGL
  217243. #pragma comment(lib, "OpenGL32.Lib")
  217244. #pragma comment(lib, "GlU32.Lib")
  217245. #endif
  217246. #if JUCE_QUICKTIME
  217247. #pragma comment (lib, "QTMLClient.lib")
  217248. #endif
  217249. #if JUCE_USE_CAMERA
  217250. #pragma comment (lib, "Strmiids.lib")
  217251. #pragma comment (lib, "wmvcore.lib")
  217252. #endif
  217253. #if JUCE_DIRECT2D
  217254. #pragma comment (lib, "Dwrite.lib")
  217255. #pragma comment (lib, "D2d1.lib")
  217256. #endif
  217257. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217258. #endif
  217259. END_JUCE_NAMESPACE
  217260. #endif
  217261. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217262. #endif
  217263. #if JUCE_LINUX
  217264. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217265. /*
  217266. This file wraps together all the mac-specific code, so that
  217267. we can include all the native headers just once, and compile all our
  217268. platform-specific stuff in one big lump, keeping it out of the way of
  217269. the rest of the codebase.
  217270. */
  217271. #if JUCE_LINUX
  217272. BEGIN_JUCE_NAMESPACE
  217273. #define JUCE_INCLUDED_FILE 1
  217274. // Now include the actual code files..
  217275. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217276. /*
  217277. This file contains posix routines that are common to both the Linux and Mac builds.
  217278. It gets included directly in the cpp files for these platforms.
  217279. */
  217280. CriticalSection::CriticalSection() throw()
  217281. {
  217282. pthread_mutexattr_t atts;
  217283. pthread_mutexattr_init (&atts);
  217284. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217285. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217286. pthread_mutex_init (&internal, &atts);
  217287. }
  217288. CriticalSection::~CriticalSection() throw()
  217289. {
  217290. pthread_mutex_destroy (&internal);
  217291. }
  217292. void CriticalSection::enter() const throw()
  217293. {
  217294. pthread_mutex_lock (&internal);
  217295. }
  217296. bool CriticalSection::tryEnter() const throw()
  217297. {
  217298. return pthread_mutex_trylock (&internal) == 0;
  217299. }
  217300. void CriticalSection::exit() const throw()
  217301. {
  217302. pthread_mutex_unlock (&internal);
  217303. }
  217304. class WaitableEventImpl
  217305. {
  217306. public:
  217307. WaitableEventImpl (const bool manualReset_)
  217308. : triggered (false),
  217309. manualReset (manualReset_)
  217310. {
  217311. pthread_cond_init (&condition, 0);
  217312. pthread_mutexattr_t atts;
  217313. pthread_mutexattr_init (&atts);
  217314. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217315. pthread_mutex_init (&mutex, &atts);
  217316. }
  217317. ~WaitableEventImpl()
  217318. {
  217319. pthread_cond_destroy (&condition);
  217320. pthread_mutex_destroy (&mutex);
  217321. }
  217322. bool wait (const int timeOutMillisecs) throw()
  217323. {
  217324. pthread_mutex_lock (&mutex);
  217325. if (! triggered)
  217326. {
  217327. if (timeOutMillisecs < 0)
  217328. {
  217329. do
  217330. {
  217331. pthread_cond_wait (&condition, &mutex);
  217332. }
  217333. while (! triggered);
  217334. }
  217335. else
  217336. {
  217337. struct timeval now;
  217338. gettimeofday (&now, 0);
  217339. struct timespec time;
  217340. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217341. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217342. if (time.tv_nsec >= 1000000000)
  217343. {
  217344. time.tv_nsec -= 1000000000;
  217345. time.tv_sec++;
  217346. }
  217347. do
  217348. {
  217349. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217350. {
  217351. pthread_mutex_unlock (&mutex);
  217352. return false;
  217353. }
  217354. }
  217355. while (! triggered);
  217356. }
  217357. }
  217358. if (! manualReset)
  217359. triggered = false;
  217360. pthread_mutex_unlock (&mutex);
  217361. return true;
  217362. }
  217363. void signal() throw()
  217364. {
  217365. pthread_mutex_lock (&mutex);
  217366. triggered = true;
  217367. pthread_cond_broadcast (&condition);
  217368. pthread_mutex_unlock (&mutex);
  217369. }
  217370. void reset() throw()
  217371. {
  217372. pthread_mutex_lock (&mutex);
  217373. triggered = false;
  217374. pthread_mutex_unlock (&mutex);
  217375. }
  217376. private:
  217377. pthread_cond_t condition;
  217378. pthread_mutex_t mutex;
  217379. bool triggered;
  217380. const bool manualReset;
  217381. WaitableEventImpl (const WaitableEventImpl&);
  217382. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217383. };
  217384. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217385. : internal (new WaitableEventImpl (manualReset))
  217386. {
  217387. }
  217388. WaitableEvent::~WaitableEvent() throw()
  217389. {
  217390. delete static_cast <WaitableEventImpl*> (internal);
  217391. }
  217392. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217393. {
  217394. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217395. }
  217396. void WaitableEvent::signal() const throw()
  217397. {
  217398. static_cast <WaitableEventImpl*> (internal)->signal();
  217399. }
  217400. void WaitableEvent::reset() const throw()
  217401. {
  217402. static_cast <WaitableEventImpl*> (internal)->reset();
  217403. }
  217404. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217405. {
  217406. struct timespec time;
  217407. time.tv_sec = millisecs / 1000;
  217408. time.tv_nsec = (millisecs % 1000) * 1000000;
  217409. nanosleep (&time, 0);
  217410. }
  217411. const juce_wchar File::separator = '/';
  217412. const String File::separatorString ("/");
  217413. const File File::getCurrentWorkingDirectory()
  217414. {
  217415. HeapBlock<char> heapBuffer;
  217416. char localBuffer [1024];
  217417. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217418. int bufferSize = 4096;
  217419. while (cwd == 0 && errno == ERANGE)
  217420. {
  217421. heapBuffer.malloc (bufferSize);
  217422. cwd = getcwd (heapBuffer, bufferSize - 1);
  217423. bufferSize += 1024;
  217424. }
  217425. return File (String::fromUTF8 (cwd));
  217426. }
  217427. bool File::setAsCurrentWorkingDirectory() const
  217428. {
  217429. return chdir (getFullPathName().toUTF8()) == 0;
  217430. }
  217431. static bool juce_stat (const String& fileName, struct stat& info)
  217432. {
  217433. return fileName.isNotEmpty()
  217434. && (stat (fileName.toUTF8(), &info) == 0);
  217435. }
  217436. bool File::isDirectory() const
  217437. {
  217438. struct stat info;
  217439. return fullPath.isEmpty()
  217440. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217441. }
  217442. bool File::exists() const
  217443. {
  217444. return fullPath.isNotEmpty()
  217445. && access (fullPath.toUTF8(), F_OK) == 0;
  217446. }
  217447. bool File::existsAsFile() const
  217448. {
  217449. return exists() && ! isDirectory();
  217450. }
  217451. int64 File::getSize() const
  217452. {
  217453. struct stat info;
  217454. return juce_stat (fullPath, info) ? info.st_size : 0;
  217455. }
  217456. bool File::hasWriteAccess() const
  217457. {
  217458. if (exists())
  217459. return access (fullPath.toUTF8(), W_OK) == 0;
  217460. if ((! isDirectory()) && fullPath.containsChar (separator))
  217461. return getParentDirectory().hasWriteAccess();
  217462. return false;
  217463. }
  217464. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217465. {
  217466. struct stat info;
  217467. const int res = stat (fullPath.toUTF8(), &info);
  217468. if (res != 0)
  217469. return false;
  217470. info.st_mode &= 0777; // Just permissions
  217471. if (shouldBeReadOnly)
  217472. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217473. else
  217474. // Give everybody write permission?
  217475. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217476. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217477. }
  217478. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217479. {
  217480. modificationTime = 0;
  217481. accessTime = 0;
  217482. creationTime = 0;
  217483. struct stat info;
  217484. const int res = stat (fullPath.toUTF8(), &info);
  217485. if (res == 0)
  217486. {
  217487. modificationTime = (int64) info.st_mtime * 1000;
  217488. accessTime = (int64) info.st_atime * 1000;
  217489. creationTime = (int64) info.st_ctime * 1000;
  217490. }
  217491. }
  217492. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217493. {
  217494. struct utimbuf times;
  217495. times.actime = (time_t) (accessTime / 1000);
  217496. times.modtime = (time_t) (modificationTime / 1000);
  217497. return utime (fullPath.toUTF8(), &times) == 0;
  217498. }
  217499. bool File::deleteFile() const
  217500. {
  217501. if (! exists())
  217502. return true;
  217503. else if (isDirectory())
  217504. return rmdir (fullPath.toUTF8()) == 0;
  217505. else
  217506. return remove (fullPath.toUTF8()) == 0;
  217507. }
  217508. bool File::moveInternal (const File& dest) const
  217509. {
  217510. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217511. return true;
  217512. if (hasWriteAccess() && copyInternal (dest))
  217513. {
  217514. if (deleteFile())
  217515. return true;
  217516. dest.deleteFile();
  217517. }
  217518. return false;
  217519. }
  217520. void File::createDirectoryInternal (const String& fileName) const
  217521. {
  217522. mkdir (fileName.toUTF8(), 0777);
  217523. }
  217524. int64 juce_fileSetPosition (void* handle, int64 pos)
  217525. {
  217526. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217527. return pos;
  217528. return -1;
  217529. }
  217530. void FileInputStream::openHandle()
  217531. {
  217532. totalSize = file.getSize();
  217533. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217534. if (f != -1)
  217535. fileHandle = (void*) f;
  217536. }
  217537. void FileInputStream::closeHandle()
  217538. {
  217539. if (fileHandle != 0)
  217540. {
  217541. close ((int) (pointer_sized_int) fileHandle);
  217542. fileHandle = 0;
  217543. }
  217544. }
  217545. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217546. {
  217547. if (fileHandle != 0)
  217548. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217549. return 0;
  217550. }
  217551. void FileOutputStream::openHandle()
  217552. {
  217553. if (file.exists())
  217554. {
  217555. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217556. if (f != -1)
  217557. {
  217558. currentPosition = lseek (f, 0, SEEK_END);
  217559. if (currentPosition >= 0)
  217560. fileHandle = (void*) f;
  217561. else
  217562. close (f);
  217563. }
  217564. }
  217565. else
  217566. {
  217567. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217568. if (f != -1)
  217569. fileHandle = (void*) f;
  217570. }
  217571. }
  217572. void FileOutputStream::closeHandle()
  217573. {
  217574. if (fileHandle != 0)
  217575. {
  217576. close ((int) (pointer_sized_int) fileHandle);
  217577. fileHandle = 0;
  217578. }
  217579. }
  217580. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217581. {
  217582. if (fileHandle != 0)
  217583. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217584. return 0;
  217585. }
  217586. void FileOutputStream::flushInternal()
  217587. {
  217588. if (fileHandle != 0)
  217589. fsync ((int) (pointer_sized_int) fileHandle);
  217590. }
  217591. const File juce_getExecutableFile()
  217592. {
  217593. Dl_info exeInfo;
  217594. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217595. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217596. }
  217597. // if this file doesn't exist, find a parent of it that does..
  217598. static bool juce_doStatFS (File f, struct statfs& result)
  217599. {
  217600. for (int i = 5; --i >= 0;)
  217601. {
  217602. if (f.exists())
  217603. break;
  217604. f = f.getParentDirectory();
  217605. }
  217606. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217607. }
  217608. int64 File::getBytesFreeOnVolume() const
  217609. {
  217610. struct statfs buf;
  217611. if (juce_doStatFS (*this, buf))
  217612. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217613. return 0;
  217614. }
  217615. int64 File::getVolumeTotalSize() const
  217616. {
  217617. struct statfs buf;
  217618. if (juce_doStatFS (*this, buf))
  217619. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217620. return 0;
  217621. }
  217622. const String File::getVolumeLabel() const
  217623. {
  217624. #if JUCE_MAC
  217625. struct VolAttrBuf
  217626. {
  217627. u_int32_t length;
  217628. attrreference_t mountPointRef;
  217629. char mountPointSpace [MAXPATHLEN];
  217630. } attrBuf;
  217631. struct attrlist attrList;
  217632. zerostruct (attrList);
  217633. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217634. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217635. File f (*this);
  217636. for (;;)
  217637. {
  217638. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217639. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217640. (int) attrBuf.mountPointRef.attr_length);
  217641. const File parent (f.getParentDirectory());
  217642. if (f == parent)
  217643. break;
  217644. f = parent;
  217645. }
  217646. #endif
  217647. return String::empty;
  217648. }
  217649. int File::getVolumeSerialNumber() const
  217650. {
  217651. return 0; // xxx
  217652. }
  217653. void juce_runSystemCommand (const String& command)
  217654. {
  217655. int result = system (command.toUTF8());
  217656. (void) result;
  217657. }
  217658. const String juce_getOutputFromCommand (const String& command)
  217659. {
  217660. // slight bodge here, as we just pipe the output into a temp file and read it...
  217661. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217662. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217663. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217664. String result (tempFile.loadFileAsString());
  217665. tempFile.deleteFile();
  217666. return result;
  217667. }
  217668. class InterProcessLock::Pimpl
  217669. {
  217670. public:
  217671. Pimpl (const String& name, const int timeOutMillisecs)
  217672. : handle (0), refCount (1)
  217673. {
  217674. #if JUCE_MAC
  217675. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217676. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217677. #else
  217678. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217679. #endif
  217680. temp.create();
  217681. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217682. if (handle != 0)
  217683. {
  217684. struct flock fl;
  217685. zerostruct (fl);
  217686. fl.l_whence = SEEK_SET;
  217687. fl.l_type = F_WRLCK;
  217688. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217689. for (;;)
  217690. {
  217691. const int result = fcntl (handle, F_SETLK, &fl);
  217692. if (result >= 0)
  217693. return;
  217694. if (errno != EINTR)
  217695. {
  217696. if (timeOutMillisecs == 0
  217697. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217698. break;
  217699. Thread::sleep (10);
  217700. }
  217701. }
  217702. }
  217703. closeFile();
  217704. }
  217705. ~Pimpl()
  217706. {
  217707. closeFile();
  217708. }
  217709. void closeFile()
  217710. {
  217711. if (handle != 0)
  217712. {
  217713. struct flock fl;
  217714. zerostruct (fl);
  217715. fl.l_whence = SEEK_SET;
  217716. fl.l_type = F_UNLCK;
  217717. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217718. {}
  217719. close (handle);
  217720. handle = 0;
  217721. }
  217722. }
  217723. int handle, refCount;
  217724. };
  217725. InterProcessLock::InterProcessLock (const String& name_)
  217726. : name (name_)
  217727. {
  217728. }
  217729. InterProcessLock::~InterProcessLock()
  217730. {
  217731. }
  217732. bool InterProcessLock::enter (const int timeOutMillisecs)
  217733. {
  217734. const ScopedLock sl (lock);
  217735. if (pimpl == 0)
  217736. {
  217737. pimpl = new Pimpl (name, timeOutMillisecs);
  217738. if (pimpl->handle == 0)
  217739. pimpl = 0;
  217740. }
  217741. else
  217742. {
  217743. pimpl->refCount++;
  217744. }
  217745. return pimpl != 0;
  217746. }
  217747. void InterProcessLock::exit()
  217748. {
  217749. const ScopedLock sl (lock);
  217750. // Trying to release the lock too many times!
  217751. jassert (pimpl != 0);
  217752. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217753. pimpl = 0;
  217754. }
  217755. void JUCE_API juce_threadEntryPoint (void*);
  217756. void* threadEntryProc (void* userData)
  217757. {
  217758. JUCE_AUTORELEASEPOOL
  217759. juce_threadEntryPoint (userData);
  217760. return 0;
  217761. }
  217762. void* juce_createThread (void* userData)
  217763. {
  217764. pthread_t handle = 0;
  217765. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217766. {
  217767. pthread_detach (handle);
  217768. return (void*) handle;
  217769. }
  217770. return 0;
  217771. }
  217772. void juce_killThread (void* handle)
  217773. {
  217774. if (handle != 0)
  217775. pthread_cancel ((pthread_t) handle);
  217776. }
  217777. void juce_setCurrentThreadName (const String& /*name*/)
  217778. {
  217779. }
  217780. bool juce_setThreadPriority (void* handle, int priority)
  217781. {
  217782. struct sched_param param;
  217783. int policy;
  217784. priority = jlimit (0, 10, priority);
  217785. if (handle == 0)
  217786. handle = (void*) pthread_self();
  217787. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217788. return false;
  217789. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217790. const int minPriority = sched_get_priority_min (policy);
  217791. const int maxPriority = sched_get_priority_max (policy);
  217792. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217793. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217794. }
  217795. Thread::ThreadID Thread::getCurrentThreadId()
  217796. {
  217797. return (ThreadID) pthread_self();
  217798. }
  217799. void Thread::yield()
  217800. {
  217801. sched_yield();
  217802. }
  217803. /* Remove this macro if you're having problems compiling the cpu affinity
  217804. calls (the API for these has changed about quite a bit in various Linux
  217805. versions, and a lot of distros seem to ship with obsolete versions)
  217806. */
  217807. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217808. #define SUPPORT_AFFINITIES 1
  217809. #endif
  217810. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217811. {
  217812. #if SUPPORT_AFFINITIES
  217813. cpu_set_t affinity;
  217814. CPU_ZERO (&affinity);
  217815. for (int i = 0; i < 32; ++i)
  217816. if ((affinityMask & (1 << i)) != 0)
  217817. CPU_SET (i, &affinity);
  217818. /*
  217819. N.B. If this line causes a compile error, then you've probably not got the latest
  217820. version of glibc installed.
  217821. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217822. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217823. */
  217824. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217825. sched_yield();
  217826. #else
  217827. /* affinities aren't supported because either the appropriate header files weren't found,
  217828. or the SUPPORT_AFFINITIES macro was turned off
  217829. */
  217830. jassertfalse;
  217831. #endif
  217832. }
  217833. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217834. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217835. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217836. // compiled on its own).
  217837. #if JUCE_INCLUDED_FILE
  217838. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  217839. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  217840. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  217841. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  217842. bool File::copyInternal (const File& dest) const
  217843. {
  217844. FileInputStream in (*this);
  217845. if (dest.deleteFile())
  217846. {
  217847. {
  217848. FileOutputStream out (dest);
  217849. if (out.failedToOpen())
  217850. return false;
  217851. if (out.writeFromInputStream (in, -1) == getSize())
  217852. return true;
  217853. }
  217854. dest.deleteFile();
  217855. }
  217856. return false;
  217857. }
  217858. void File::findFileSystemRoots (Array<File>& destArray)
  217859. {
  217860. destArray.add (File ("/"));
  217861. }
  217862. bool File::isOnCDRomDrive() const
  217863. {
  217864. struct statfs buf;
  217865. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217866. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  217867. }
  217868. bool File::isOnHardDisk() const
  217869. {
  217870. struct statfs buf;
  217871. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217872. {
  217873. switch (buf.f_type)
  217874. {
  217875. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217876. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217877. case U_NFS_SUPER_MAGIC: // Network NFS
  217878. case U_SMB_SUPER_MAGIC: // Network Samba
  217879. return false;
  217880. default:
  217881. // Assume anything else is a hard-disk (but note it could
  217882. // be a RAM disk. There isn't a good way of determining
  217883. // this for sure)
  217884. return true;
  217885. }
  217886. }
  217887. // Assume so if this fails for some reason
  217888. return true;
  217889. }
  217890. bool File::isOnRemovableDrive() const
  217891. {
  217892. jassertfalse; // xxx not implemented for linux!
  217893. return false;
  217894. }
  217895. bool File::isHidden() const
  217896. {
  217897. return getFileName().startsWithChar ('.');
  217898. }
  217899. static const File juce_readlink (const char* const utf8, const File& defaultFile)
  217900. {
  217901. const int size = 8192;
  217902. HeapBlock<char> buffer;
  217903. buffer.malloc (size + 4);
  217904. const size_t numBytes = readlink (utf8, buffer, size);
  217905. if (numBytes > 0 && numBytes <= size)
  217906. return File (String::fromUTF8 (buffer, (int) numBytes));
  217907. return defaultFile;
  217908. }
  217909. const File File::getLinkedTarget() const
  217910. {
  217911. return juce_readlink (getFullPathName().toUTF8(), *this);
  217912. }
  217913. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217914. const File File::getSpecialLocation (const SpecialLocationType type)
  217915. {
  217916. switch (type)
  217917. {
  217918. case userHomeDirectory:
  217919. {
  217920. const char* homeDir = getenv ("HOME");
  217921. if (homeDir == 0)
  217922. {
  217923. struct passwd* const pw = getpwuid (getuid());
  217924. if (pw != 0)
  217925. homeDir = pw->pw_dir;
  217926. }
  217927. return File (String::fromUTF8 (homeDir));
  217928. }
  217929. case userDocumentsDirectory:
  217930. case userMusicDirectory:
  217931. case userMoviesDirectory:
  217932. case userApplicationDataDirectory:
  217933. return File ("~");
  217934. case userDesktopDirectory:
  217935. return File ("~/Desktop");
  217936. case commonApplicationDataDirectory:
  217937. return File ("/var");
  217938. case globalApplicationsDirectory:
  217939. return File ("/usr");
  217940. case tempDirectory:
  217941. {
  217942. File tmp ("/var/tmp");
  217943. if (! tmp.isDirectory())
  217944. {
  217945. tmp = "/tmp";
  217946. if (! tmp.isDirectory())
  217947. tmp = File::getCurrentWorkingDirectory();
  217948. }
  217949. return tmp;
  217950. }
  217951. case invokedExecutableFile:
  217952. if (juce_Argv0 != 0)
  217953. return File (String::fromUTF8 (juce_Argv0));
  217954. // deliberate fall-through...
  217955. case currentExecutableFile:
  217956. case currentApplicationFile:
  217957. return juce_getExecutableFile();
  217958. case hostApplicationPath:
  217959. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217960. default:
  217961. jassertfalse; // unknown type?
  217962. break;
  217963. }
  217964. return File::nonexistent;
  217965. }
  217966. const String File::getVersion() const
  217967. {
  217968. return String::empty; // xxx not yet implemented
  217969. }
  217970. bool File::moveToTrash() const
  217971. {
  217972. if (! exists())
  217973. return true;
  217974. File trashCan ("~/.Trash");
  217975. if (! trashCan.isDirectory())
  217976. trashCan = "~/.local/share/Trash/files";
  217977. if (! trashCan.isDirectory())
  217978. return false;
  217979. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217980. getFileExtension()));
  217981. }
  217982. class DirectoryIterator::NativeIterator::Pimpl
  217983. {
  217984. public:
  217985. Pimpl (const File& directory, const String& wildCard_)
  217986. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217987. wildCard (wildCard_),
  217988. dir (opendir (directory.getFullPathName().toUTF8()))
  217989. {
  217990. if (wildCard == "*.*")
  217991. wildCard = "*";
  217992. wildcardUTF8 = wildCard.toUTF8();
  217993. }
  217994. ~Pimpl()
  217995. {
  217996. if (dir != 0)
  217997. closedir (dir);
  217998. }
  217999. bool next (String& filenameFound,
  218000. bool* const isDir, bool* const isHidden, int64* const fileSize,
  218001. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  218002. {
  218003. if (dir == 0)
  218004. return false;
  218005. for (;;)
  218006. {
  218007. struct dirent* const de = readdir (dir);
  218008. if (de == 0)
  218009. return false;
  218010. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  218011. {
  218012. filenameFound = String::fromUTF8 (de->d_name);
  218013. const String path (parentDir + filenameFound);
  218014. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  218015. {
  218016. struct stat info;
  218017. const bool statOk = juce_stat (path, info);
  218018. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  218019. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  218020. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  218021. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  218022. }
  218023. if (isHidden != 0)
  218024. *isHidden = filenameFound.startsWithChar ('.');
  218025. if (isReadOnly != 0)
  218026. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  218027. return true;
  218028. }
  218029. }
  218030. }
  218031. private:
  218032. String parentDir, wildCard;
  218033. const char* wildcardUTF8;
  218034. DIR* dir;
  218035. Pimpl (const Pimpl&);
  218036. Pimpl& operator= (const Pimpl&);
  218037. };
  218038. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  218039. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  218040. {
  218041. }
  218042. DirectoryIterator::NativeIterator::~NativeIterator()
  218043. {
  218044. }
  218045. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  218046. bool* const isDir, bool* const isHidden, int64* const fileSize,
  218047. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  218048. {
  218049. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  218050. }
  218051. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  218052. {
  218053. String cmdString (fileName.replace (" ", "\\ ",false));
  218054. cmdString << " " << parameters;
  218055. if (URL::isProbablyAWebsiteURL (fileName)
  218056. || cmdString.startsWithIgnoreCase ("file:")
  218057. || URL::isProbablyAnEmailAddress (fileName))
  218058. {
  218059. // create a command that tries to launch a bunch of likely browsers
  218060. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  218061. StringArray cmdLines;
  218062. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  218063. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  218064. cmdString = cmdLines.joinIntoString (" || ");
  218065. }
  218066. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  218067. const int cpid = fork();
  218068. if (cpid == 0)
  218069. {
  218070. setsid();
  218071. // Child process
  218072. execve (argv[0], (char**) argv, environ);
  218073. exit (0);
  218074. }
  218075. return cpid >= 0;
  218076. }
  218077. void File::revealToUser() const
  218078. {
  218079. if (isDirectory())
  218080. startAsProcess();
  218081. else if (getParentDirectory().exists())
  218082. getParentDirectory().startAsProcess();
  218083. }
  218084. #endif
  218085. /*** End of inlined file: juce_linux_Files.cpp ***/
  218086. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  218087. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218088. // compiled on its own).
  218089. #if JUCE_INCLUDED_FILE
  218090. struct NamedPipeInternal
  218091. {
  218092. String pipeInName, pipeOutName;
  218093. int pipeIn, pipeOut;
  218094. bool volatile createdPipe, blocked, stopReadOperation;
  218095. static void signalHandler (int) {}
  218096. };
  218097. void NamedPipe::cancelPendingReads()
  218098. {
  218099. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  218100. {
  218101. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218102. intern->stopReadOperation = true;
  218103. char buffer [1] = { 0 };
  218104. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  218105. (void) bytesWritten;
  218106. int timeout = 2000;
  218107. while (intern->blocked && --timeout >= 0)
  218108. Thread::sleep (2);
  218109. intern->stopReadOperation = false;
  218110. }
  218111. }
  218112. void NamedPipe::close()
  218113. {
  218114. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218115. if (intern != 0)
  218116. {
  218117. internal = 0;
  218118. if (intern->pipeIn != -1)
  218119. ::close (intern->pipeIn);
  218120. if (intern->pipeOut != -1)
  218121. ::close (intern->pipeOut);
  218122. if (intern->createdPipe)
  218123. {
  218124. unlink (intern->pipeInName.toUTF8());
  218125. unlink (intern->pipeOutName.toUTF8());
  218126. }
  218127. delete intern;
  218128. }
  218129. }
  218130. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  218131. {
  218132. close();
  218133. NamedPipeInternal* const intern = new NamedPipeInternal();
  218134. internal = intern;
  218135. intern->createdPipe = createPipe;
  218136. intern->blocked = false;
  218137. intern->stopReadOperation = false;
  218138. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  218139. siginterrupt (SIGPIPE, 1);
  218140. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  218141. intern->pipeInName = pipePath + "_in";
  218142. intern->pipeOutName = pipePath + "_out";
  218143. intern->pipeIn = -1;
  218144. intern->pipeOut = -1;
  218145. if (createPipe)
  218146. {
  218147. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  218148. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  218149. {
  218150. delete intern;
  218151. internal = 0;
  218152. return false;
  218153. }
  218154. }
  218155. return true;
  218156. }
  218157. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  218158. {
  218159. int bytesRead = -1;
  218160. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218161. if (intern != 0)
  218162. {
  218163. intern->blocked = true;
  218164. if (intern->pipeIn == -1)
  218165. {
  218166. if (intern->createdPipe)
  218167. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  218168. else
  218169. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  218170. if (intern->pipeIn == -1)
  218171. {
  218172. intern->blocked = false;
  218173. return -1;
  218174. }
  218175. }
  218176. bytesRead = 0;
  218177. char* p = static_cast<char*> (destBuffer);
  218178. while (bytesRead < maxBytesToRead)
  218179. {
  218180. const int bytesThisTime = maxBytesToRead - bytesRead;
  218181. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  218182. if (numRead <= 0 || intern->stopReadOperation)
  218183. {
  218184. bytesRead = -1;
  218185. break;
  218186. }
  218187. bytesRead += numRead;
  218188. p += bytesRead;
  218189. }
  218190. intern->blocked = false;
  218191. }
  218192. return bytesRead;
  218193. }
  218194. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218195. {
  218196. int bytesWritten = -1;
  218197. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218198. if (intern != 0)
  218199. {
  218200. if (intern->pipeOut == -1)
  218201. {
  218202. if (intern->createdPipe)
  218203. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  218204. else
  218205. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218206. if (intern->pipeOut == -1)
  218207. {
  218208. return -1;
  218209. }
  218210. }
  218211. const char* p = static_cast<const char*> (sourceBuffer);
  218212. bytesWritten = 0;
  218213. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218214. while (bytesWritten < numBytesToWrite
  218215. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218216. {
  218217. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218218. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218219. if (numWritten <= 0)
  218220. {
  218221. bytesWritten = -1;
  218222. break;
  218223. }
  218224. bytesWritten += numWritten;
  218225. p += bytesWritten;
  218226. }
  218227. }
  218228. return bytesWritten;
  218229. }
  218230. #endif
  218231. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218232. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218233. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218234. // compiled on its own).
  218235. #if JUCE_INCLUDED_FILE
  218236. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  218237. {
  218238. int numResults = 0;
  218239. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218240. if (s != -1)
  218241. {
  218242. char buf [1024];
  218243. struct ifconf ifc;
  218244. ifc.ifc_len = sizeof (buf);
  218245. ifc.ifc_buf = buf;
  218246. ioctl (s, SIOCGIFCONF, &ifc);
  218247. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218248. {
  218249. struct ifreq ifr;
  218250. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218251. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218252. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218253. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  218254. && numResults < maxNum)
  218255. {
  218256. int64 a = 0;
  218257. for (int j = 6; --j >= 0;)
  218258. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  218259. *addresses++ = a;
  218260. ++numResults;
  218261. }
  218262. }
  218263. close (s);
  218264. }
  218265. return numResults;
  218266. }
  218267. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218268. const String& emailSubject,
  218269. const String& bodyText,
  218270. const StringArray& filesToAttach)
  218271. {
  218272. jassertfalse; // xxx todo
  218273. return false;
  218274. }
  218275. /** A HTTP input stream that uses sockets.
  218276. */
  218277. class JUCE_HTTPSocketStream
  218278. {
  218279. public:
  218280. JUCE_HTTPSocketStream()
  218281. : readPosition (0),
  218282. socketHandle (-1),
  218283. levelsOfRedirection (0),
  218284. timeoutSeconds (15)
  218285. {
  218286. }
  218287. ~JUCE_HTTPSocketStream()
  218288. {
  218289. closeSocket();
  218290. }
  218291. bool open (const String& url,
  218292. const String& headers,
  218293. const MemoryBlock& postData,
  218294. const bool isPost,
  218295. URL::OpenStreamProgressCallback* callback,
  218296. void* callbackContext,
  218297. int timeOutMs)
  218298. {
  218299. closeSocket();
  218300. uint32 timeOutTime = Time::getMillisecondCounter();
  218301. if (timeOutMs == 0)
  218302. timeOutTime += 60000;
  218303. else if (timeOutMs < 0)
  218304. timeOutTime = 0xffffffff;
  218305. else
  218306. timeOutTime += timeOutMs;
  218307. String hostName, hostPath;
  218308. int hostPort;
  218309. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218310. return false;
  218311. const struct hostent* host = 0;
  218312. int port = 0;
  218313. String proxyName, proxyPath;
  218314. int proxyPort = 0;
  218315. String proxyURL (getenv ("http_proxy"));
  218316. if (proxyURL.startsWithIgnoreCase ("http://"))
  218317. {
  218318. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218319. return false;
  218320. host = gethostbyname (proxyName.toUTF8());
  218321. port = proxyPort;
  218322. }
  218323. else
  218324. {
  218325. host = gethostbyname (hostName.toUTF8());
  218326. port = hostPort;
  218327. }
  218328. if (host == 0)
  218329. return false;
  218330. struct sockaddr_in address;
  218331. zerostruct (address);
  218332. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218333. address.sin_family = host->h_addrtype;
  218334. address.sin_port = htons (port);
  218335. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218336. if (socketHandle == -1)
  218337. return false;
  218338. int receiveBufferSize = 16384;
  218339. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218340. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218341. #if JUCE_MAC
  218342. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218343. #endif
  218344. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218345. {
  218346. closeSocket();
  218347. return false;
  218348. }
  218349. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218350. proxyName, proxyPort,
  218351. hostPath, url,
  218352. headers, postData,
  218353. isPost));
  218354. size_t totalHeaderSent = 0;
  218355. while (totalHeaderSent < requestHeader.getSize())
  218356. {
  218357. if (Time::getMillisecondCounter() > timeOutTime)
  218358. {
  218359. closeSocket();
  218360. return false;
  218361. }
  218362. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218363. if (send (socketHandle,
  218364. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218365. numToSend, 0)
  218366. != numToSend)
  218367. {
  218368. closeSocket();
  218369. return false;
  218370. }
  218371. totalHeaderSent += numToSend;
  218372. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218373. {
  218374. closeSocket();
  218375. return false;
  218376. }
  218377. }
  218378. const String responseHeader (readResponse (timeOutTime));
  218379. if (responseHeader.isNotEmpty())
  218380. {
  218381. //DBG (responseHeader);
  218382. headerLines.clear();
  218383. headerLines.addLines (responseHeader);
  218384. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218385. .substring (0, 3).getIntValue();
  218386. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218387. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218388. String location (findHeaderItem (headerLines, "Location:"));
  218389. if (statusCode >= 300 && statusCode < 400
  218390. && location.isNotEmpty())
  218391. {
  218392. if (! location.startsWithIgnoreCase ("http://"))
  218393. location = "http://" + location;
  218394. if (levelsOfRedirection++ < 3)
  218395. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218396. }
  218397. else
  218398. {
  218399. levelsOfRedirection = 0;
  218400. return true;
  218401. }
  218402. }
  218403. closeSocket();
  218404. return false;
  218405. }
  218406. int read (void* buffer, int bytesToRead)
  218407. {
  218408. fd_set readbits;
  218409. FD_ZERO (&readbits);
  218410. FD_SET (socketHandle, &readbits);
  218411. struct timeval tv;
  218412. tv.tv_sec = timeoutSeconds;
  218413. tv.tv_usec = 0;
  218414. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218415. return 0; // (timeout)
  218416. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218417. readPosition += bytesRead;
  218418. return bytesRead;
  218419. }
  218420. int readPosition;
  218421. StringArray headerLines;
  218422. juce_UseDebuggingNewOperator
  218423. private:
  218424. int socketHandle, levelsOfRedirection;
  218425. const int timeoutSeconds;
  218426. void closeSocket()
  218427. {
  218428. if (socketHandle >= 0)
  218429. close (socketHandle);
  218430. socketHandle = -1;
  218431. }
  218432. const MemoryBlock createRequestHeader (const String& hostName,
  218433. const int hostPort,
  218434. const String& proxyName,
  218435. const int proxyPort,
  218436. const String& hostPath,
  218437. const String& originalURL,
  218438. const String& headers,
  218439. const MemoryBlock& postData,
  218440. const bool isPost)
  218441. {
  218442. String header (isPost ? "POST " : "GET ");
  218443. if (proxyName.isEmpty())
  218444. {
  218445. header << hostPath << " HTTP/1.0\r\nHost: "
  218446. << hostName << ':' << hostPort;
  218447. }
  218448. else
  218449. {
  218450. header << originalURL << " HTTP/1.0\r\nHost: "
  218451. << proxyName << ':' << proxyPort;
  218452. }
  218453. header << "\r\nUser-Agent: JUCE/"
  218454. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218455. << "\r\nConnection: Close\r\nContent-Length: "
  218456. << postData.getSize() << "\r\n"
  218457. << headers << "\r\n";
  218458. MemoryBlock mb;
  218459. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218460. mb.append (postData.getData(), postData.getSize());
  218461. return mb;
  218462. }
  218463. const String readResponse (const uint32 timeOutTime)
  218464. {
  218465. int bytesRead = 0, numConsecutiveLFs = 0;
  218466. MemoryBlock buffer (1024, true);
  218467. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218468. && Time::getMillisecondCounter() <= timeOutTime)
  218469. {
  218470. fd_set readbits;
  218471. FD_ZERO (&readbits);
  218472. FD_SET (socketHandle, &readbits);
  218473. struct timeval tv;
  218474. tv.tv_sec = timeoutSeconds;
  218475. tv.tv_usec = 0;
  218476. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218477. return String::empty; // (timeout)
  218478. buffer.ensureSize (bytesRead + 8, true);
  218479. char* const dest = (char*) buffer.getData() + bytesRead;
  218480. if (recv (socketHandle, dest, 1, 0) == -1)
  218481. return String::empty;
  218482. const char lastByte = *dest;
  218483. ++bytesRead;
  218484. if (lastByte == '\n')
  218485. ++numConsecutiveLFs;
  218486. else if (lastByte != '\r')
  218487. numConsecutiveLFs = 0;
  218488. }
  218489. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218490. if (header.startsWithIgnoreCase ("HTTP/"))
  218491. return header.trimEnd();
  218492. return String::empty;
  218493. }
  218494. static bool decomposeURL (const String& url,
  218495. String& host, String& path, int& port)
  218496. {
  218497. if (! url.startsWithIgnoreCase ("http://"))
  218498. return false;
  218499. const int nextSlash = url.indexOfChar (7, '/');
  218500. int nextColon = url.indexOfChar (7, ':');
  218501. if (nextColon > nextSlash && nextSlash > 0)
  218502. nextColon = -1;
  218503. if (nextColon >= 0)
  218504. {
  218505. host = url.substring (7, nextColon);
  218506. if (nextSlash >= 0)
  218507. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218508. else
  218509. port = url.substring (nextColon + 1).getIntValue();
  218510. }
  218511. else
  218512. {
  218513. port = 80;
  218514. if (nextSlash >= 0)
  218515. host = url.substring (7, nextSlash);
  218516. else
  218517. host = url.substring (7);
  218518. }
  218519. if (nextSlash >= 0)
  218520. path = url.substring (nextSlash);
  218521. else
  218522. path = "/";
  218523. return true;
  218524. }
  218525. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218526. {
  218527. for (int i = 0; i < lines.size(); ++i)
  218528. if (lines[i].startsWithIgnoreCase (itemName))
  218529. return lines[i].substring (itemName.length()).trim();
  218530. return String::empty;
  218531. }
  218532. };
  218533. void* juce_openInternetFile (const String& url,
  218534. const String& headers,
  218535. const MemoryBlock& postData,
  218536. const bool isPost,
  218537. URL::OpenStreamProgressCallback* callback,
  218538. void* callbackContext,
  218539. int timeOutMs)
  218540. {
  218541. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218542. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218543. return s.release();
  218544. return 0;
  218545. }
  218546. void juce_closeInternetFile (void* handle)
  218547. {
  218548. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218549. }
  218550. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218551. {
  218552. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218553. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218554. }
  218555. int64 juce_getInternetFileContentLength (void* handle)
  218556. {
  218557. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218558. if (s != 0)
  218559. {
  218560. //xxx todo
  218561. jassertfalse
  218562. }
  218563. return -1;
  218564. }
  218565. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218566. {
  218567. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218568. if (s != 0)
  218569. {
  218570. for (int i = 0; i < s->headerLines.size(); ++i)
  218571. {
  218572. const String& headersEntry = s->headerLines[i];
  218573. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218574. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218575. const String previousValue (headers [key]);
  218576. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218577. }
  218578. }
  218579. }
  218580. int juce_seekInInternetFile (void* handle, int newPosition)
  218581. {
  218582. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218583. return s != 0 ? s->readPosition : 0;
  218584. }
  218585. #endif
  218586. /*** End of inlined file: juce_linux_Network.cpp ***/
  218587. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218588. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218589. // compiled on its own).
  218590. #if JUCE_INCLUDED_FILE
  218591. void Logger::outputDebugString (const String& text)
  218592. {
  218593. std::cerr << text << std::endl;
  218594. }
  218595. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218596. {
  218597. return Linux;
  218598. }
  218599. const String SystemStats::getOperatingSystemName()
  218600. {
  218601. return "Linux";
  218602. }
  218603. bool SystemStats::isOperatingSystem64Bit()
  218604. {
  218605. #if JUCE_64BIT
  218606. return true;
  218607. #else
  218608. //xxx not sure how to find this out?..
  218609. return false;
  218610. #endif
  218611. }
  218612. static const String juce_getCpuInfo (const char* const key)
  218613. {
  218614. StringArray lines;
  218615. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218616. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218617. if (lines[i].startsWithIgnoreCase (key))
  218618. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218619. return String::empty;
  218620. }
  218621. const String SystemStats::getCpuVendor()
  218622. {
  218623. return juce_getCpuInfo ("vendor_id");
  218624. }
  218625. int SystemStats::getCpuSpeedInMegaherz()
  218626. {
  218627. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  218628. }
  218629. int SystemStats::getMemorySizeInMegabytes()
  218630. {
  218631. struct sysinfo sysi;
  218632. if (sysinfo (&sysi) == 0)
  218633. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218634. return 0;
  218635. }
  218636. int SystemStats::getPageSize()
  218637. {
  218638. return sysconf (_SC_PAGESIZE);
  218639. }
  218640. const String SystemStats::getLogonName()
  218641. {
  218642. const char* user = getenv ("USER");
  218643. if (user == 0)
  218644. {
  218645. struct passwd* const pw = getpwuid (getuid());
  218646. if (pw != 0)
  218647. user = pw->pw_name;
  218648. }
  218649. return String::fromUTF8 (user);
  218650. }
  218651. const String SystemStats::getFullUserName()
  218652. {
  218653. return getLogonName();
  218654. }
  218655. void SystemStats::initialiseStats()
  218656. {
  218657. const String flags (juce_getCpuInfo ("flags"));
  218658. cpuFlags.hasMMX = flags.contains ("mmx");
  218659. cpuFlags.hasSSE = flags.contains ("sse");
  218660. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218661. cpuFlags.has3DNow = flags.contains ("3dnow");
  218662. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  218663. }
  218664. void PlatformUtilities::fpuReset()
  218665. {
  218666. }
  218667. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  218668. {
  218669. if (gettimeofday (t, 0) != 0)
  218670. return false;
  218671. static unsigned int calibrate = 0;
  218672. static bool calibrated = false;
  218673. if (! calibrated)
  218674. {
  218675. calibrated = true;
  218676. struct sysinfo sysi;
  218677. if (sysinfo (&sysi) == 0)
  218678. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218679. }
  218680. t->tv_sec -= calibrate;
  218681. return true;
  218682. }
  218683. uint32 juce_millisecondsSinceStartup() throw()
  218684. {
  218685. timeval t;
  218686. if (juce_getTimeSinceStartup (&t))
  218687. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218688. return 0;
  218689. }
  218690. int64 Time::getHighResolutionTicks() throw()
  218691. {
  218692. timeval t;
  218693. if (juce_getTimeSinceStartup (&t))
  218694. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218695. return 0;
  218696. }
  218697. int64 Time::getHighResolutionTicksPerSecond() throw()
  218698. {
  218699. return 1000000; // (microseconds)
  218700. }
  218701. double Time::getMillisecondCounterHiRes() throw()
  218702. {
  218703. return getHighResolutionTicks() * 0.001;
  218704. }
  218705. bool Time::setSystemTimeToThisTime() const
  218706. {
  218707. timeval t;
  218708. t.tv_sec = millisSinceEpoch % 1000000;
  218709. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218710. return settimeofday (&t, 0) ? false : true;
  218711. }
  218712. #endif
  218713. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218714. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218715. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218716. // compiled on its own).
  218717. #if JUCE_INCLUDED_FILE
  218718. /*
  218719. Note that a lot of methods that you'd expect to find in this file actually
  218720. live in juce_posix_SharedCode.h!
  218721. */
  218722. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218723. void Process::setPriority (ProcessPriority prior)
  218724. {
  218725. struct sched_param param;
  218726. int policy, maxp, minp;
  218727. const int p = (int) prior;
  218728. if (p <= 1)
  218729. policy = SCHED_OTHER;
  218730. else
  218731. policy = SCHED_RR;
  218732. minp = sched_get_priority_min (policy);
  218733. maxp = sched_get_priority_max (policy);
  218734. if (p < 2)
  218735. param.sched_priority = 0;
  218736. else if (p == 2 )
  218737. // Set to middle of lower realtime priority range
  218738. param.sched_priority = minp + (maxp - minp) / 4;
  218739. else
  218740. // Set to middle of higher realtime priority range
  218741. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218742. pthread_setschedparam (pthread_self(), policy, &param);
  218743. }
  218744. void Process::terminate()
  218745. {
  218746. exit (0);
  218747. }
  218748. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  218749. {
  218750. static char testResult = 0;
  218751. if (testResult == 0)
  218752. {
  218753. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218754. if (testResult >= 0)
  218755. {
  218756. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218757. testResult = 1;
  218758. }
  218759. }
  218760. return testResult < 0;
  218761. }
  218762. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218763. {
  218764. return juce_isRunningUnderDebugger();
  218765. }
  218766. void Process::raisePrivilege()
  218767. {
  218768. // If running suid root, change effective user
  218769. // to root
  218770. if (geteuid() != 0 && getuid() == 0)
  218771. {
  218772. setreuid (geteuid(), getuid());
  218773. setregid (getegid(), getgid());
  218774. }
  218775. }
  218776. void Process::lowerPrivilege()
  218777. {
  218778. // If runing suid root, change effective user
  218779. // back to real user
  218780. if (geteuid() == 0 && getuid() != 0)
  218781. {
  218782. setreuid (geteuid(), getuid());
  218783. setregid (getegid(), getgid());
  218784. }
  218785. }
  218786. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218787. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218788. {
  218789. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218790. }
  218791. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218792. {
  218793. dlclose(handle);
  218794. }
  218795. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218796. {
  218797. return dlsym (libraryHandle, procedureName.toCString());
  218798. }
  218799. #endif
  218800. #endif
  218801. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218802. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218803. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218804. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218805. // compiled on its own).
  218806. #if JUCE_INCLUDED_FILE
  218807. extern Display* display;
  218808. extern Window juce_messageWindowHandle;
  218809. namespace ClipboardHelpers
  218810. {
  218811. static String localClipboardContent;
  218812. static Atom atom_UTF8_STRING;
  218813. static Atom atom_CLIPBOARD;
  218814. static Atom atom_TARGETS;
  218815. static void initSelectionAtoms()
  218816. {
  218817. static bool isInitialised = false;
  218818. if (! isInitialised)
  218819. {
  218820. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218821. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218822. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218823. }
  218824. }
  218825. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218826. // works only for strings shorter than 1000000 bytes
  218827. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218828. {
  218829. String returnData;
  218830. char* clipData;
  218831. Atom actualType;
  218832. int actualFormat;
  218833. unsigned long numItems, bytesLeft;
  218834. if (XGetWindowProperty (display, window, prop,
  218835. 0L /* offset */, 1000000 /* length (max) */, False,
  218836. AnyPropertyType /* format */,
  218837. &actualType, &actualFormat, &numItems, &bytesLeft,
  218838. (unsigned char**) &clipData) == Success)
  218839. {
  218840. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218841. returnData = String::fromUTF8 (clipData, numItems);
  218842. else if (actualType == XA_STRING && actualFormat == 8)
  218843. returnData = String (clipData, numItems);
  218844. if (clipData != 0)
  218845. XFree (clipData);
  218846. jassert (bytesLeft == 0 || numItems == 1000000);
  218847. }
  218848. XDeleteProperty (display, window, prop);
  218849. return returnData;
  218850. }
  218851. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218852. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218853. {
  218854. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218855. // The selection owner will be asked to set the JUCE_SEL property on the
  218856. // juce_messageWindowHandle with the selection content
  218857. XConvertSelection (display, selection, requestedFormat, property_name,
  218858. juce_messageWindowHandle, CurrentTime);
  218859. int count = 50; // will wait at most for 200 ms
  218860. while (--count >= 0)
  218861. {
  218862. XEvent event;
  218863. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218864. {
  218865. if (event.xselection.property == property_name)
  218866. {
  218867. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218868. selectionContent = readWindowProperty (event.xselection.requestor,
  218869. event.xselection.property,
  218870. requestedFormat);
  218871. return true;
  218872. }
  218873. else
  218874. {
  218875. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218876. }
  218877. }
  218878. // not very elegant.. we could do a select() or something like that...
  218879. // however clipboard content requesting is inherently slow on x11, it
  218880. // often takes 50ms or more so...
  218881. Thread::sleep (4);
  218882. }
  218883. return false;
  218884. }
  218885. }
  218886. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218887. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218888. {
  218889. ClipboardHelpers::initSelectionAtoms();
  218890. // the selection content is sent to the target window as a window property
  218891. XSelectionEvent reply;
  218892. reply.type = SelectionNotify;
  218893. reply.display = evt.display;
  218894. reply.requestor = evt.requestor;
  218895. reply.selection = evt.selection;
  218896. reply.target = evt.target;
  218897. reply.property = None; // == "fail"
  218898. reply.time = evt.time;
  218899. HeapBlock <char> data;
  218900. int propertyFormat = 0, numDataItems = 0;
  218901. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218902. {
  218903. if (evt.target == XA_STRING)
  218904. {
  218905. // format data according to system locale
  218906. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218907. data.calloc (numDataItems + 1);
  218908. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218909. propertyFormat = 8; // bits/item
  218910. }
  218911. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218912. {
  218913. // translate to utf8
  218914. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218915. data.calloc (numDataItems + 1);
  218916. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218917. propertyFormat = 8; // bits/item
  218918. }
  218919. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218920. {
  218921. // another application wants to know what we are able to send
  218922. numDataItems = 2;
  218923. propertyFormat = 32; // atoms are 32-bit
  218924. data.calloc (numDataItems * 4);
  218925. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218926. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218927. atoms[1] = XA_STRING;
  218928. }
  218929. }
  218930. else
  218931. {
  218932. DBG ("requested unsupported clipboard");
  218933. }
  218934. if (data != 0)
  218935. {
  218936. const int maxReasonableSelectionSize = 1000000;
  218937. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218938. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218939. {
  218940. XChangeProperty (evt.display, evt.requestor,
  218941. evt.property, evt.target,
  218942. propertyFormat /* 8 or 32 */, PropModeReplace,
  218943. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218944. reply.property = evt.property; // " == success"
  218945. }
  218946. }
  218947. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218948. }
  218949. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218950. {
  218951. ClipboardHelpers::initSelectionAtoms();
  218952. ClipboardHelpers::localClipboardContent = clipText;
  218953. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218954. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218955. }
  218956. const String SystemClipboard::getTextFromClipboard()
  218957. {
  218958. ClipboardHelpers::initSelectionAtoms();
  218959. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218960. level" clipboard that is supposed to be filled by ctrl-C
  218961. etc). When a clipboard manager is running, the content of this
  218962. selection is preserved even when the original selection owner
  218963. exits.
  218964. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218965. filled by good old x11 apps such as xterm)
  218966. */
  218967. String content;
  218968. Atom selection = XA_PRIMARY;
  218969. Window selectionOwner = None;
  218970. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218971. {
  218972. selection = ClipboardHelpers::atom_CLIPBOARD;
  218973. selectionOwner = XGetSelectionOwner (display, selection);
  218974. }
  218975. if (selectionOwner != None)
  218976. {
  218977. if (selectionOwner == juce_messageWindowHandle)
  218978. {
  218979. content = ClipboardHelpers::localClipboardContent;
  218980. }
  218981. else
  218982. {
  218983. // first try: we want an utf8 string
  218984. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218985. if (! ok)
  218986. {
  218987. // second chance, ask for a good old locale-dependent string ..
  218988. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218989. }
  218990. }
  218991. }
  218992. return content;
  218993. }
  218994. #endif
  218995. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218996. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218997. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218998. // compiled on its own).
  218999. #if JUCE_INCLUDED_FILE
  219000. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  219001. #define JUCE_DEBUG_XERRORS 1
  219002. #endif
  219003. Display* display = 0;
  219004. Window juce_messageWindowHandle = None;
  219005. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  219006. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  219007. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  219008. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  219009. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  219010. class InternalMessageQueue
  219011. {
  219012. public:
  219013. InternalMessageQueue()
  219014. : bytesInSocket (0),
  219015. totalEventCount (0)
  219016. {
  219017. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  219018. (void) ret; jassert (ret == 0);
  219019. //setNonBlocking (fd[0]);
  219020. //setNonBlocking (fd[1]);
  219021. }
  219022. ~InternalMessageQueue()
  219023. {
  219024. close (fd[0]);
  219025. close (fd[1]);
  219026. clearSingletonInstance();
  219027. }
  219028. void postMessage (Message* msg)
  219029. {
  219030. const int maxBytesInSocketQueue = 128;
  219031. ScopedLock sl (lock);
  219032. queue.add (msg);
  219033. if (bytesInSocket < maxBytesInSocketQueue)
  219034. {
  219035. ++bytesInSocket;
  219036. ScopedUnlock ul (lock);
  219037. const unsigned char x = 0xff;
  219038. size_t bytesWritten = write (fd[0], &x, 1);
  219039. (void) bytesWritten;
  219040. }
  219041. }
  219042. bool isEmpty() const
  219043. {
  219044. ScopedLock sl (lock);
  219045. return queue.size() == 0;
  219046. }
  219047. bool dispatchNextEvent()
  219048. {
  219049. // This alternates between giving priority to XEvents or internal messages,
  219050. // to keep everything running smoothly..
  219051. if ((++totalEventCount & 1) != 0)
  219052. return dispatchNextXEvent() || dispatchNextInternalMessage();
  219053. else
  219054. return dispatchNextInternalMessage() || dispatchNextXEvent();
  219055. }
  219056. // Wait for an event (either XEvent, or an internal Message)
  219057. bool sleepUntilEvent (const int timeoutMs)
  219058. {
  219059. if (! isEmpty())
  219060. return true;
  219061. if (display != 0)
  219062. {
  219063. ScopedXLock xlock;
  219064. if (XPending (display))
  219065. return true;
  219066. }
  219067. struct timeval tv;
  219068. tv.tv_sec = 0;
  219069. tv.tv_usec = timeoutMs * 1000;
  219070. int fd0 = getWaitHandle();
  219071. int fdmax = fd0;
  219072. fd_set readset;
  219073. FD_ZERO (&readset);
  219074. FD_SET (fd0, &readset);
  219075. if (display != 0)
  219076. {
  219077. ScopedXLock xlock;
  219078. int fd1 = XConnectionNumber (display);
  219079. FD_SET (fd1, &readset);
  219080. fdmax = jmax (fd0, fd1);
  219081. }
  219082. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  219083. return (ret > 0); // ret <= 0 if error or timeout
  219084. }
  219085. struct MessageThreadFuncCall
  219086. {
  219087. enum { uniqueID = 0x73774623 };
  219088. MessageCallbackFunction* func;
  219089. void* parameter;
  219090. void* result;
  219091. CriticalSection lock;
  219092. WaitableEvent event;
  219093. };
  219094. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  219095. private:
  219096. CriticalSection lock;
  219097. OwnedArray <Message> queue;
  219098. int fd[2];
  219099. int bytesInSocket;
  219100. int totalEventCount;
  219101. int getWaitHandle() const throw() { return fd[1]; }
  219102. static bool setNonBlocking (int handle)
  219103. {
  219104. int socketFlags = fcntl (handle, F_GETFL, 0);
  219105. if (socketFlags == -1)
  219106. return false;
  219107. socketFlags |= O_NONBLOCK;
  219108. return fcntl (handle, F_SETFL, socketFlags) == 0;
  219109. }
  219110. static bool dispatchNextXEvent()
  219111. {
  219112. if (display == 0)
  219113. return false;
  219114. XEvent evt;
  219115. {
  219116. ScopedXLock xlock;
  219117. if (! XPending (display))
  219118. return false;
  219119. XNextEvent (display, &evt);
  219120. }
  219121. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  219122. juce_handleSelectionRequest (evt.xselectionrequest);
  219123. else if (evt.xany.window != juce_messageWindowHandle)
  219124. juce_windowMessageReceive (&evt);
  219125. return true;
  219126. }
  219127. Message* popNextMessage()
  219128. {
  219129. ScopedLock sl (lock);
  219130. if (bytesInSocket > 0)
  219131. {
  219132. --bytesInSocket;
  219133. ScopedUnlock ul (lock);
  219134. unsigned char x;
  219135. size_t numBytes = read (fd[1], &x, 1);
  219136. (void) numBytes;
  219137. }
  219138. return queue.removeAndReturn (0);
  219139. }
  219140. bool dispatchNextInternalMessage()
  219141. {
  219142. ScopedPointer <Message> msg (popNextMessage());
  219143. if (msg == 0)
  219144. return false;
  219145. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  219146. {
  219147. // Handle callback message
  219148. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  219149. call->result = (*(call->func)) (call->parameter);
  219150. call->event.signal();
  219151. }
  219152. else
  219153. {
  219154. // Handle "normal" messages
  219155. MessageManager::getInstance()->deliverMessage (msg.release());
  219156. }
  219157. return true;
  219158. }
  219159. };
  219160. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  219161. namespace LinuxErrorHandling
  219162. {
  219163. static bool errorOccurred = false;
  219164. static bool keyboardBreakOccurred = false;
  219165. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  219166. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  219167. // Usually happens when client-server connection is broken
  219168. static int ioErrorHandler (Display* display)
  219169. {
  219170. DBG ("ERROR: connection to X server broken.. terminating.");
  219171. if (JUCEApplication::isStandaloneApp())
  219172. MessageManager::getInstance()->stopDispatchLoop();
  219173. errorOccurred = true;
  219174. return 0;
  219175. }
  219176. // A protocol error has occurred
  219177. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  219178. {
  219179. #if JUCE_DEBUG_XERRORS
  219180. char errorStr[64] = { 0 };
  219181. char requestStr[64] = { 0 };
  219182. XGetErrorText (display, event->error_code, errorStr, 64);
  219183. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  219184. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  219185. #endif
  219186. return 0;
  219187. }
  219188. static void installXErrorHandlers()
  219189. {
  219190. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219191. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  219192. }
  219193. static void removeXErrorHandlers()
  219194. {
  219195. XSetIOErrorHandler (oldIOErrorHandler);
  219196. oldIOErrorHandler = 0;
  219197. XSetErrorHandler (oldErrorHandler);
  219198. oldErrorHandler = 0;
  219199. }
  219200. static void keyboardBreakSignalHandler (int sig)
  219201. {
  219202. if (sig == SIGINT)
  219203. keyboardBreakOccurred = true;
  219204. }
  219205. static void installKeyboardBreakHandler()
  219206. {
  219207. struct sigaction saction;
  219208. sigset_t maskSet;
  219209. sigemptyset (&maskSet);
  219210. saction.sa_handler = keyboardBreakSignalHandler;
  219211. saction.sa_mask = maskSet;
  219212. saction.sa_flags = 0;
  219213. sigaction (SIGINT, &saction, 0);
  219214. }
  219215. }
  219216. void MessageManager::doPlatformSpecificInitialisation()
  219217. {
  219218. // Initialise xlib for multiple thread support
  219219. static bool initThreadCalled = false;
  219220. if (! initThreadCalled)
  219221. {
  219222. if (! XInitThreads())
  219223. {
  219224. // This is fatal! Print error and closedown
  219225. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219226. if (JUCEApplication::isStandaloneApp())
  219227. Process::terminate();
  219228. return;
  219229. }
  219230. initThreadCalled = true;
  219231. }
  219232. LinuxErrorHandling::installXErrorHandlers();
  219233. LinuxErrorHandling::installKeyboardBreakHandler();
  219234. // Create the internal message queue
  219235. InternalMessageQueue::getInstance();
  219236. // Try to connect to a display
  219237. String displayName (getenv ("DISPLAY"));
  219238. if (displayName.isEmpty())
  219239. displayName = ":0.0";
  219240. display = XOpenDisplay (displayName.toCString());
  219241. if (display != 0) // This is not fatal! we can run headless.
  219242. {
  219243. // Create a context to store user data associated with Windows we create in WindowDriver
  219244. windowHandleXContext = XUniqueContext();
  219245. // We're only interested in client messages for this window, which are always sent
  219246. XSetWindowAttributes swa;
  219247. swa.event_mask = NoEventMask;
  219248. // Create our message window (this will never be mapped)
  219249. const int screen = DefaultScreen (display);
  219250. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219251. 0, 0, 1, 1, 0, 0, InputOnly,
  219252. DefaultVisual (display, screen),
  219253. CWEventMask, &swa);
  219254. }
  219255. }
  219256. void MessageManager::doPlatformSpecificShutdown()
  219257. {
  219258. InternalMessageQueue::deleteInstance();
  219259. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219260. {
  219261. XDestroyWindow (display, juce_messageWindowHandle);
  219262. XCloseDisplay (display);
  219263. juce_messageWindowHandle = 0;
  219264. display = 0;
  219265. LinuxErrorHandling::removeXErrorHandlers();
  219266. }
  219267. }
  219268. bool juce_postMessageToSystemQueue (Message* message)
  219269. {
  219270. if (LinuxErrorHandling::errorOccurred)
  219271. return false;
  219272. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219273. return true;
  219274. }
  219275. void MessageManager::broadcastMessage (const String& value)
  219276. {
  219277. /* TODO */
  219278. }
  219279. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219280. {
  219281. if (LinuxErrorHandling::errorOccurred)
  219282. return 0;
  219283. if (isThisTheMessageThread())
  219284. return func (parameter);
  219285. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219286. messageCallContext.func = func;
  219287. messageCallContext.parameter = parameter;
  219288. InternalMessageQueue::getInstanceWithoutCreating()
  219289. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219290. 0, 0, &messageCallContext));
  219291. // Wait for it to complete before continuing
  219292. messageCallContext.event.wait();
  219293. return messageCallContext.result;
  219294. }
  219295. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219296. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219297. {
  219298. while (! LinuxErrorHandling::errorOccurred)
  219299. {
  219300. if (LinuxErrorHandling::keyboardBreakOccurred)
  219301. {
  219302. LinuxErrorHandling::errorOccurred = true;
  219303. if (JUCEApplication::isStandaloneApp())
  219304. Process::terminate();
  219305. break;
  219306. }
  219307. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219308. return true;
  219309. if (returnIfNoPendingMessages)
  219310. break;
  219311. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219312. }
  219313. return false;
  219314. }
  219315. #endif
  219316. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219317. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219318. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219319. // compiled on its own).
  219320. #if JUCE_INCLUDED_FILE
  219321. class FreeTypeFontFace
  219322. {
  219323. public:
  219324. enum FontStyle
  219325. {
  219326. Plain = 0,
  219327. Bold = 1,
  219328. Italic = 2
  219329. };
  219330. FreeTypeFontFace (const String& familyName)
  219331. : hasSerif (false),
  219332. monospaced (false)
  219333. {
  219334. family = familyName;
  219335. }
  219336. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219337. {
  219338. if (names [(int) style].fileName.isEmpty())
  219339. {
  219340. names [(int) style].fileName = name;
  219341. names [(int) style].faceIndex = faceIndex;
  219342. }
  219343. }
  219344. const String& getFamilyName() const throw() { return family; }
  219345. const String& getFileName (const int style, int& faceIndex) const throw()
  219346. {
  219347. faceIndex = names[style].faceIndex;
  219348. return names[style].fileName;
  219349. }
  219350. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219351. bool getMonospaced() const throw() { return monospaced; }
  219352. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219353. bool getSerif() const throw() { return hasSerif; }
  219354. private:
  219355. String family;
  219356. struct FontNameIndex
  219357. {
  219358. String fileName;
  219359. int faceIndex;
  219360. };
  219361. FontNameIndex names[4];
  219362. bool hasSerif, monospaced;
  219363. };
  219364. class FreeTypeInterface : public DeletedAtShutdown
  219365. {
  219366. public:
  219367. FreeTypeInterface()
  219368. : ftLib (0),
  219369. lastFace (0),
  219370. lastBold (false),
  219371. lastItalic (false)
  219372. {
  219373. if (FT_Init_FreeType (&ftLib) != 0)
  219374. {
  219375. ftLib = 0;
  219376. DBG ("Failed to initialize FreeType");
  219377. }
  219378. StringArray fontDirs;
  219379. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219380. fontDirs.removeEmptyStrings (true);
  219381. if (fontDirs.size() == 0)
  219382. {
  219383. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219384. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219385. if (fontsInfo != 0)
  219386. {
  219387. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219388. {
  219389. fontDirs.add (e->getAllSubText().trim());
  219390. }
  219391. }
  219392. }
  219393. if (fontDirs.size() == 0)
  219394. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219395. for (int i = 0; i < fontDirs.size(); ++i)
  219396. enumerateFaces (fontDirs[i]);
  219397. }
  219398. ~FreeTypeInterface()
  219399. {
  219400. if (lastFace != 0)
  219401. FT_Done_Face (lastFace);
  219402. if (ftLib != 0)
  219403. FT_Done_FreeType (ftLib);
  219404. clearSingletonInstance();
  219405. }
  219406. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219407. {
  219408. for (int i = 0; i < faces.size(); i++)
  219409. if (faces[i]->getFamilyName() == familyName)
  219410. return faces[i];
  219411. if (! create)
  219412. return 0;
  219413. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219414. faces.add (newFace);
  219415. return newFace;
  219416. }
  219417. // Enumerate all font faces available in a given directory
  219418. void enumerateFaces (const String& path)
  219419. {
  219420. File dirPath (path);
  219421. if (path.isEmpty() || ! dirPath.isDirectory())
  219422. return;
  219423. DirectoryIterator di (dirPath, true);
  219424. while (di.next())
  219425. {
  219426. File possible (di.getFile());
  219427. if (possible.hasFileExtension ("ttf")
  219428. || possible.hasFileExtension ("pfb")
  219429. || possible.hasFileExtension ("pcf"))
  219430. {
  219431. FT_Face face;
  219432. int faceIndex = 0;
  219433. int numFaces = 0;
  219434. do
  219435. {
  219436. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219437. faceIndex, &face) == 0)
  219438. {
  219439. if (faceIndex == 0)
  219440. numFaces = face->num_faces;
  219441. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219442. {
  219443. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219444. int style = (int) FreeTypeFontFace::Plain;
  219445. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219446. style |= (int) FreeTypeFontFace::Bold;
  219447. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219448. style |= (int) FreeTypeFontFace::Italic;
  219449. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219450. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219451. // Surely there must be a better way to do this?
  219452. const String name (face->family_name);
  219453. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219454. || name.containsIgnoreCase ("Verdana")
  219455. || name.containsIgnoreCase ("Arial")));
  219456. }
  219457. FT_Done_Face (face);
  219458. }
  219459. ++faceIndex;
  219460. }
  219461. while (faceIndex < numFaces);
  219462. }
  219463. }
  219464. }
  219465. // Create a FreeType face object for a given font
  219466. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219467. {
  219468. FT_Face face = 0;
  219469. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219470. {
  219471. face = lastFace;
  219472. }
  219473. else
  219474. {
  219475. if (lastFace != 0)
  219476. {
  219477. FT_Done_Face (lastFace);
  219478. lastFace = 0;
  219479. }
  219480. lastFontName = fontName;
  219481. lastBold = bold;
  219482. lastItalic = italic;
  219483. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219484. if (ftFace != 0)
  219485. {
  219486. int style = (int) FreeTypeFontFace::Plain;
  219487. if (bold)
  219488. style |= (int) FreeTypeFontFace::Bold;
  219489. if (italic)
  219490. style |= (int) FreeTypeFontFace::Italic;
  219491. int faceIndex;
  219492. String fileName (ftFace->getFileName (style, faceIndex));
  219493. if (fileName.isEmpty())
  219494. {
  219495. style ^= (int) FreeTypeFontFace::Bold;
  219496. fileName = ftFace->getFileName (style, faceIndex);
  219497. if (fileName.isEmpty())
  219498. {
  219499. style ^= (int) FreeTypeFontFace::Bold;
  219500. style ^= (int) FreeTypeFontFace::Italic;
  219501. fileName = ftFace->getFileName (style, faceIndex);
  219502. if (! fileName.length())
  219503. {
  219504. style ^= (int) FreeTypeFontFace::Bold;
  219505. fileName = ftFace->getFileName (style, faceIndex);
  219506. }
  219507. }
  219508. }
  219509. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219510. {
  219511. face = lastFace;
  219512. // If there isn't a unicode charmap then select the first one.
  219513. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219514. FT_Set_Charmap (face, face->charmaps[0]);
  219515. }
  219516. }
  219517. }
  219518. return face;
  219519. }
  219520. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219521. {
  219522. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219523. const float height = (float) (face->ascender - face->descender);
  219524. const float scaleX = 1.0f / height;
  219525. const float scaleY = -1.0f / height;
  219526. Path destShape;
  219527. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219528. || face->glyph->format != ft_glyph_format_outline)
  219529. {
  219530. return false;
  219531. }
  219532. const FT_Outline* const outline = &face->glyph->outline;
  219533. const short* const contours = outline->contours;
  219534. const char* const tags = outline->tags;
  219535. FT_Vector* const points = outline->points;
  219536. for (int c = 0; c < outline->n_contours; c++)
  219537. {
  219538. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219539. const int endPoint = contours[c];
  219540. for (int p = startPoint; p <= endPoint; p++)
  219541. {
  219542. const float x = scaleX * points[p].x;
  219543. const float y = scaleY * points[p].y;
  219544. if (p == startPoint)
  219545. {
  219546. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219547. {
  219548. float x2 = scaleX * points [endPoint].x;
  219549. float y2 = scaleY * points [endPoint].y;
  219550. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219551. {
  219552. x2 = (x + x2) * 0.5f;
  219553. y2 = (y + y2) * 0.5f;
  219554. }
  219555. destShape.startNewSubPath (x2, y2);
  219556. }
  219557. else
  219558. {
  219559. destShape.startNewSubPath (x, y);
  219560. }
  219561. }
  219562. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219563. {
  219564. if (p != startPoint)
  219565. destShape.lineTo (x, y);
  219566. }
  219567. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219568. {
  219569. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219570. float x2 = scaleX * points [nextIndex].x;
  219571. float y2 = scaleY * points [nextIndex].y;
  219572. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219573. {
  219574. x2 = (x + x2) * 0.5f;
  219575. y2 = (y + y2) * 0.5f;
  219576. }
  219577. else
  219578. {
  219579. ++p;
  219580. }
  219581. destShape.quadraticTo (x, y, x2, y2);
  219582. }
  219583. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219584. {
  219585. if (p >= endPoint)
  219586. return false;
  219587. const int next1 = p + 1;
  219588. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219589. const float x2 = scaleX * points [next1].x;
  219590. const float y2 = scaleY * points [next1].y;
  219591. const float x3 = scaleX * points [next2].x;
  219592. const float y3 = scaleY * points [next2].y;
  219593. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219594. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219595. return false;
  219596. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219597. p += 2;
  219598. }
  219599. }
  219600. destShape.closeSubPath();
  219601. }
  219602. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219603. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219604. addKerning (face, dest, character, glyphIndex);
  219605. return true;
  219606. }
  219607. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219608. {
  219609. const float height = (float) (face->ascender - face->descender);
  219610. uint32 rightGlyphIndex;
  219611. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219612. while (rightGlyphIndex != 0)
  219613. {
  219614. FT_Vector kerning;
  219615. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219616. {
  219617. if (kerning.x != 0)
  219618. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219619. }
  219620. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219621. }
  219622. }
  219623. // Add a glyph to a font
  219624. bool addGlyphToFont (const uint32 character, const String& fontName,
  219625. bool bold, bool italic, CustomTypeface& dest)
  219626. {
  219627. FT_Face face = createFT_Face (fontName, bold, italic);
  219628. return face != 0 && addGlyph (face, dest, character);
  219629. }
  219630. void getFamilyNames (StringArray& familyNames) const
  219631. {
  219632. for (int i = 0; i < faces.size(); i++)
  219633. familyNames.add (faces[i]->getFamilyName());
  219634. }
  219635. void getMonospacedNames (StringArray& monoSpaced) const
  219636. {
  219637. for (int i = 0; i < faces.size(); i++)
  219638. if (faces[i]->getMonospaced())
  219639. monoSpaced.add (faces[i]->getFamilyName());
  219640. }
  219641. void getSerifNames (StringArray& serif) const
  219642. {
  219643. for (int i = 0; i < faces.size(); i++)
  219644. if (faces[i]->getSerif())
  219645. serif.add (faces[i]->getFamilyName());
  219646. }
  219647. void getSansSerifNames (StringArray& sansSerif) const
  219648. {
  219649. for (int i = 0; i < faces.size(); i++)
  219650. if (! faces[i]->getSerif())
  219651. sansSerif.add (faces[i]->getFamilyName());
  219652. }
  219653. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219654. private:
  219655. FT_Library ftLib;
  219656. FT_Face lastFace;
  219657. String lastFontName;
  219658. bool lastBold, lastItalic;
  219659. OwnedArray<FreeTypeFontFace> faces;
  219660. };
  219661. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219662. class FreetypeTypeface : public CustomTypeface
  219663. {
  219664. public:
  219665. FreetypeTypeface (const Font& font)
  219666. {
  219667. FT_Face face = FreeTypeInterface::getInstance()
  219668. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219669. if (face == 0)
  219670. {
  219671. #if JUCE_DEBUG
  219672. String msg ("Failed to create typeface: ");
  219673. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219674. DBG (msg);
  219675. #endif
  219676. }
  219677. else
  219678. {
  219679. setCharacteristics (font.getTypefaceName(),
  219680. face->ascender / (float) (face->ascender - face->descender),
  219681. font.isBold(), font.isItalic(),
  219682. L' ');
  219683. }
  219684. }
  219685. bool loadGlyphIfPossible (juce_wchar character)
  219686. {
  219687. return FreeTypeInterface::getInstance()
  219688. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219689. }
  219690. };
  219691. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219692. {
  219693. return new FreetypeTypeface (font);
  219694. }
  219695. const StringArray Font::findAllTypefaceNames()
  219696. {
  219697. StringArray s;
  219698. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219699. s.sort (true);
  219700. return s;
  219701. }
  219702. static const String pickBestFont (const StringArray& names,
  219703. const char* const choicesString)
  219704. {
  219705. StringArray choices;
  219706. choices.addTokens (String (choicesString), ",", String::empty);
  219707. choices.trim();
  219708. choices.removeEmptyStrings();
  219709. int i, j;
  219710. for (j = 0; j < choices.size(); ++j)
  219711. if (names.contains (choices[j], true))
  219712. return choices[j];
  219713. for (j = 0; j < choices.size(); ++j)
  219714. for (i = 0; i < names.size(); i++)
  219715. if (names[i].startsWithIgnoreCase (choices[j]))
  219716. return names[i];
  219717. for (j = 0; j < choices.size(); ++j)
  219718. for (i = 0; i < names.size(); i++)
  219719. if (names[i].containsIgnoreCase (choices[j]))
  219720. return names[i];
  219721. return names[0];
  219722. }
  219723. static const String linux_getDefaultSansSerifFontName()
  219724. {
  219725. StringArray allFonts;
  219726. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219727. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219728. }
  219729. static const String linux_getDefaultSerifFontName()
  219730. {
  219731. StringArray allFonts;
  219732. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219733. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219734. }
  219735. static const String linux_getDefaultMonospacedFontName()
  219736. {
  219737. StringArray allFonts;
  219738. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219739. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219740. }
  219741. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219742. {
  219743. defaultSans = linux_getDefaultSansSerifFontName();
  219744. defaultSerif = linux_getDefaultSerifFontName();
  219745. defaultFixed = linux_getDefaultMonospacedFontName();
  219746. }
  219747. #endif
  219748. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219749. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219750. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219751. // compiled on its own).
  219752. #if JUCE_INCLUDED_FILE
  219753. // These are defined in juce_linux_Messaging.cpp
  219754. extern Display* display;
  219755. extern XContext windowHandleXContext;
  219756. namespace Atoms
  219757. {
  219758. enum ProtocolItems
  219759. {
  219760. TAKE_FOCUS = 0,
  219761. DELETE_WINDOW = 1,
  219762. PING = 2
  219763. };
  219764. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219765. ActiveWin, Pid, WindowType, WindowState,
  219766. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219767. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219768. XdndActionDescription, XdndActionCopy,
  219769. allowedActions[5],
  219770. allowedMimeTypes[2];
  219771. const unsigned long DndVersion = 3;
  219772. static void initialiseAtoms()
  219773. {
  219774. static bool atomsInitialised = false;
  219775. if (! atomsInitialised)
  219776. {
  219777. atomsInitialised = true;
  219778. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219779. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219780. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219781. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219782. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219783. State = XInternAtom (display, "WM_STATE", True);
  219784. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219785. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219786. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219787. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219788. XdndAware = XInternAtom (display, "XdndAware", False);
  219789. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219790. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219791. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219792. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219793. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219794. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219795. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219796. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219797. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219798. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219799. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219800. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219801. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219802. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219803. allowedActions[1] = XdndActionCopy;
  219804. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219805. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219806. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219807. }
  219808. }
  219809. }
  219810. namespace Keys
  219811. {
  219812. enum MouseButtons
  219813. {
  219814. NoButton = 0,
  219815. LeftButton = 1,
  219816. MiddleButton = 2,
  219817. RightButton = 3,
  219818. WheelUp = 4,
  219819. WheelDown = 5
  219820. };
  219821. static int AltMask = 0;
  219822. static int NumLockMask = 0;
  219823. static bool numLock = false;
  219824. static bool capsLock = false;
  219825. static char keyStates [32];
  219826. static const int extendedKeyModifier = 0x10000000;
  219827. }
  219828. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219829. {
  219830. int keysym;
  219831. if (keyCode & Keys::extendedKeyModifier)
  219832. {
  219833. keysym = 0xff00 | (keyCode & 0xff);
  219834. }
  219835. else
  219836. {
  219837. keysym = keyCode;
  219838. if (keysym == (XK_Tab & 0xff)
  219839. || keysym == (XK_Return & 0xff)
  219840. || keysym == (XK_Escape & 0xff)
  219841. || keysym == (XK_BackSpace & 0xff))
  219842. {
  219843. keysym |= 0xff00;
  219844. }
  219845. }
  219846. ScopedXLock xlock;
  219847. const int keycode = XKeysymToKeycode (display, keysym);
  219848. const int keybyte = keycode >> 3;
  219849. const int keybit = (1 << (keycode & 7));
  219850. return (Keys::keyStates [keybyte] & keybit) != 0;
  219851. }
  219852. #if JUCE_USE_XSHM
  219853. namespace XSHMHelpers
  219854. {
  219855. static int trappedErrorCode = 0;
  219856. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219857. {
  219858. trappedErrorCode = err->error_code;
  219859. return 0;
  219860. }
  219861. static bool isShmAvailable() throw()
  219862. {
  219863. static bool isChecked = false;
  219864. static bool isAvailable = false;
  219865. if (! isChecked)
  219866. {
  219867. isChecked = true;
  219868. int major, minor;
  219869. Bool pixmaps;
  219870. ScopedXLock xlock;
  219871. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219872. {
  219873. trappedErrorCode = 0;
  219874. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219875. XShmSegmentInfo segmentInfo;
  219876. zerostruct (segmentInfo);
  219877. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219878. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219879. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219880. xImage->bytes_per_line * xImage->height,
  219881. IPC_CREAT | 0777)) >= 0)
  219882. {
  219883. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219884. if (segmentInfo.shmaddr != (void*) -1)
  219885. {
  219886. segmentInfo.readOnly = False;
  219887. xImage->data = segmentInfo.shmaddr;
  219888. XSync (display, False);
  219889. if (XShmAttach (display, &segmentInfo) != 0)
  219890. {
  219891. XSync (display, False);
  219892. XShmDetach (display, &segmentInfo);
  219893. isAvailable = true;
  219894. }
  219895. }
  219896. XFlush (display);
  219897. XDestroyImage (xImage);
  219898. shmdt (segmentInfo.shmaddr);
  219899. }
  219900. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219901. XSetErrorHandler (oldHandler);
  219902. if (trappedErrorCode != 0)
  219903. isAvailable = false;
  219904. }
  219905. }
  219906. return isAvailable;
  219907. }
  219908. }
  219909. #endif
  219910. #if JUCE_USE_XRENDER
  219911. namespace XRender
  219912. {
  219913. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219914. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219915. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219916. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219917. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219918. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219919. static tXRenderFindFormat xRenderFindFormat = 0;
  219920. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219921. static bool isAvailable()
  219922. {
  219923. static bool hasLoaded = false;
  219924. if (! hasLoaded)
  219925. {
  219926. ScopedXLock xlock;
  219927. hasLoaded = true;
  219928. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219929. if (h != 0)
  219930. {
  219931. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219932. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219933. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219934. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219935. }
  219936. if (xRenderQueryVersion != 0
  219937. && xRenderFindStandardFormat != 0
  219938. && xRenderFindFormat != 0
  219939. && xRenderFindVisualFormat != 0)
  219940. {
  219941. int major, minor;
  219942. if (xRenderQueryVersion (display, &major, &minor))
  219943. return true;
  219944. }
  219945. xRenderQueryVersion = 0;
  219946. }
  219947. return xRenderQueryVersion != 0;
  219948. }
  219949. static XRenderPictFormat* findPictureFormat()
  219950. {
  219951. ScopedXLock xlock;
  219952. XRenderPictFormat* pictFormat = 0;
  219953. if (isAvailable())
  219954. {
  219955. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219956. if (pictFormat == 0)
  219957. {
  219958. XRenderPictFormat desiredFormat;
  219959. desiredFormat.type = PictTypeDirect;
  219960. desiredFormat.depth = 32;
  219961. desiredFormat.direct.alphaMask = 0xff;
  219962. desiredFormat.direct.redMask = 0xff;
  219963. desiredFormat.direct.greenMask = 0xff;
  219964. desiredFormat.direct.blueMask = 0xff;
  219965. desiredFormat.direct.alpha = 24;
  219966. desiredFormat.direct.red = 16;
  219967. desiredFormat.direct.green = 8;
  219968. desiredFormat.direct.blue = 0;
  219969. pictFormat = xRenderFindFormat (display,
  219970. PictFormatType | PictFormatDepth
  219971. | PictFormatRedMask | PictFormatRed
  219972. | PictFormatGreenMask | PictFormatGreen
  219973. | PictFormatBlueMask | PictFormatBlue
  219974. | PictFormatAlphaMask | PictFormatAlpha,
  219975. &desiredFormat,
  219976. 0);
  219977. }
  219978. }
  219979. return pictFormat;
  219980. }
  219981. }
  219982. #endif
  219983. namespace Visuals
  219984. {
  219985. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219986. {
  219987. ScopedXLock xlock;
  219988. Visual* visual = 0;
  219989. int numVisuals = 0;
  219990. long desiredMask = VisualNoMask;
  219991. XVisualInfo desiredVisual;
  219992. desiredVisual.screen = DefaultScreen (display);
  219993. desiredVisual.depth = desiredDepth;
  219994. desiredMask = VisualScreenMask | VisualDepthMask;
  219995. if (desiredDepth == 32)
  219996. {
  219997. desiredVisual.c_class = TrueColor;
  219998. desiredVisual.red_mask = 0x00FF0000;
  219999. desiredVisual.green_mask = 0x0000FF00;
  220000. desiredVisual.blue_mask = 0x000000FF;
  220001. desiredVisual.bits_per_rgb = 8;
  220002. desiredMask |= VisualClassMask;
  220003. desiredMask |= VisualRedMaskMask;
  220004. desiredMask |= VisualGreenMaskMask;
  220005. desiredMask |= VisualBlueMaskMask;
  220006. desiredMask |= VisualBitsPerRGBMask;
  220007. }
  220008. XVisualInfo* xvinfos = XGetVisualInfo (display,
  220009. desiredMask,
  220010. &desiredVisual,
  220011. &numVisuals);
  220012. if (xvinfos != 0)
  220013. {
  220014. for (int i = 0; i < numVisuals; i++)
  220015. {
  220016. if (xvinfos[i].depth == desiredDepth)
  220017. {
  220018. visual = xvinfos[i].visual;
  220019. break;
  220020. }
  220021. }
  220022. XFree (xvinfos);
  220023. }
  220024. return visual;
  220025. }
  220026. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  220027. {
  220028. Visual* visual = 0;
  220029. if (desiredDepth == 32)
  220030. {
  220031. #if JUCE_USE_XSHM
  220032. if (XSHMHelpers::isShmAvailable())
  220033. {
  220034. #if JUCE_USE_XRENDER
  220035. if (XRender::isAvailable())
  220036. {
  220037. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  220038. if (pictFormat != 0)
  220039. {
  220040. int numVisuals = 0;
  220041. XVisualInfo desiredVisual;
  220042. desiredVisual.screen = DefaultScreen (display);
  220043. desiredVisual.depth = 32;
  220044. desiredVisual.bits_per_rgb = 8;
  220045. XVisualInfo* xvinfos = XGetVisualInfo (display,
  220046. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  220047. &desiredVisual, &numVisuals);
  220048. if (xvinfos != 0)
  220049. {
  220050. for (int i = 0; i < numVisuals; ++i)
  220051. {
  220052. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  220053. if (pictVisualFormat != 0
  220054. && pictVisualFormat->type == PictTypeDirect
  220055. && pictVisualFormat->direct.alphaMask)
  220056. {
  220057. visual = xvinfos[i].visual;
  220058. matchedDepth = 32;
  220059. break;
  220060. }
  220061. }
  220062. XFree (xvinfos);
  220063. }
  220064. }
  220065. }
  220066. #endif
  220067. if (visual == 0)
  220068. {
  220069. visual = findVisualWithDepth (32);
  220070. if (visual != 0)
  220071. matchedDepth = 32;
  220072. }
  220073. }
  220074. #endif
  220075. }
  220076. if (visual == 0 && desiredDepth >= 24)
  220077. {
  220078. visual = findVisualWithDepth (24);
  220079. if (visual != 0)
  220080. matchedDepth = 24;
  220081. }
  220082. if (visual == 0 && desiredDepth >= 16)
  220083. {
  220084. visual = findVisualWithDepth (16);
  220085. if (visual != 0)
  220086. matchedDepth = 16;
  220087. }
  220088. return visual;
  220089. }
  220090. }
  220091. class XBitmapImage : public Image::SharedImage
  220092. {
  220093. public:
  220094. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  220095. const bool clearImage, const int imageDepth_, Visual* visual)
  220096. : Image::SharedImage (format_, w, h),
  220097. imageDepth (imageDepth_),
  220098. gc (None)
  220099. {
  220100. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  220101. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  220102. lineStride = ((w * pixelStride + 3) & ~3);
  220103. ScopedXLock xlock;
  220104. #if JUCE_USE_XSHM
  220105. usingXShm = false;
  220106. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  220107. {
  220108. zerostruct (segmentInfo);
  220109. segmentInfo.shmid = -1;
  220110. segmentInfo.shmaddr = (char *) -1;
  220111. segmentInfo.readOnly = False;
  220112. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  220113. if (xImage != 0)
  220114. {
  220115. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  220116. xImage->bytes_per_line * xImage->height,
  220117. IPC_CREAT | 0777)) >= 0)
  220118. {
  220119. if (segmentInfo.shmid != -1)
  220120. {
  220121. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  220122. if (segmentInfo.shmaddr != (void*) -1)
  220123. {
  220124. segmentInfo.readOnly = False;
  220125. xImage->data = segmentInfo.shmaddr;
  220126. imageData = (uint8*) segmentInfo.shmaddr;
  220127. if (XShmAttach (display, &segmentInfo) != 0)
  220128. usingXShm = true;
  220129. else
  220130. jassertfalse;
  220131. }
  220132. else
  220133. {
  220134. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220135. }
  220136. }
  220137. }
  220138. }
  220139. }
  220140. if (! usingXShm)
  220141. #endif
  220142. {
  220143. imageDataAllocated.malloc (lineStride * h);
  220144. imageData = imageDataAllocated;
  220145. if (format_ == Image::ARGB && clearImage)
  220146. zeromem (imageData, h * lineStride);
  220147. xImage = (XImage*) juce_calloc (sizeof (XImage));
  220148. xImage->width = w;
  220149. xImage->height = h;
  220150. xImage->xoffset = 0;
  220151. xImage->format = ZPixmap;
  220152. xImage->data = (char*) imageData;
  220153. xImage->byte_order = ImageByteOrder (display);
  220154. xImage->bitmap_unit = BitmapUnit (display);
  220155. xImage->bitmap_bit_order = BitmapBitOrder (display);
  220156. xImage->bitmap_pad = 32;
  220157. xImage->depth = pixelStride * 8;
  220158. xImage->bytes_per_line = lineStride;
  220159. xImage->bits_per_pixel = pixelStride * 8;
  220160. xImage->red_mask = 0x00FF0000;
  220161. xImage->green_mask = 0x0000FF00;
  220162. xImage->blue_mask = 0x000000FF;
  220163. if (imageDepth == 16)
  220164. {
  220165. const int pixelStride = 2;
  220166. const int lineStride = ((w * pixelStride + 3) & ~3);
  220167. imageData16Bit.malloc (lineStride * h);
  220168. xImage->data = imageData16Bit;
  220169. xImage->bitmap_pad = 16;
  220170. xImage->depth = pixelStride * 8;
  220171. xImage->bytes_per_line = lineStride;
  220172. xImage->bits_per_pixel = pixelStride * 8;
  220173. xImage->red_mask = visual->red_mask;
  220174. xImage->green_mask = visual->green_mask;
  220175. xImage->blue_mask = visual->blue_mask;
  220176. }
  220177. if (! XInitImage (xImage))
  220178. jassertfalse;
  220179. }
  220180. }
  220181. ~XBitmapImage()
  220182. {
  220183. ScopedXLock xlock;
  220184. if (gc != None)
  220185. XFreeGC (display, gc);
  220186. #if JUCE_USE_XSHM
  220187. if (usingXShm)
  220188. {
  220189. XShmDetach (display, &segmentInfo);
  220190. XFlush (display);
  220191. XDestroyImage (xImage);
  220192. shmdt (segmentInfo.shmaddr);
  220193. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220194. }
  220195. else
  220196. #endif
  220197. {
  220198. xImage->data = 0;
  220199. XDestroyImage (xImage);
  220200. }
  220201. }
  220202. Image::ImageType getType() const { return Image::NativeImage; }
  220203. LowLevelGraphicsContext* createLowLevelContext()
  220204. {
  220205. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220206. }
  220207. SharedImage* clone()
  220208. {
  220209. jassertfalse;
  220210. return 0;
  220211. }
  220212. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220213. {
  220214. ScopedXLock xlock;
  220215. if (gc == None)
  220216. {
  220217. XGCValues gcvalues;
  220218. gcvalues.foreground = None;
  220219. gcvalues.background = None;
  220220. gcvalues.function = GXcopy;
  220221. gcvalues.plane_mask = AllPlanes;
  220222. gcvalues.clip_mask = None;
  220223. gcvalues.graphics_exposures = False;
  220224. gc = XCreateGC (display, window,
  220225. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220226. &gcvalues);
  220227. }
  220228. if (imageDepth == 16)
  220229. {
  220230. const uint32 rMask = xImage->red_mask;
  220231. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220232. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220233. const uint32 gMask = xImage->green_mask;
  220234. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220235. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220236. const uint32 bMask = xImage->blue_mask;
  220237. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220238. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220239. const Image::BitmapData srcData (Image (this), false);
  220240. for (int y = sy; y < sy + dh; ++y)
  220241. {
  220242. const uint8* p = srcData.getPixelPointer (sx, y);
  220243. for (int x = sx; x < sx + dw; ++x)
  220244. {
  220245. const PixelRGB* const pixel = (const PixelRGB*) p;
  220246. p += srcData.pixelStride;
  220247. XPutPixel (xImage, x, y,
  220248. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220249. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220250. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220251. }
  220252. }
  220253. }
  220254. // blit results to screen.
  220255. #if JUCE_USE_XSHM
  220256. if (usingXShm)
  220257. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220258. else
  220259. #endif
  220260. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220261. }
  220262. juce_UseDebuggingNewOperator
  220263. private:
  220264. XImage* xImage;
  220265. const int imageDepth;
  220266. HeapBlock <uint8> imageDataAllocated;
  220267. HeapBlock <char> imageData16Bit;
  220268. GC gc;
  220269. #if JUCE_USE_XSHM
  220270. XShmSegmentInfo segmentInfo;
  220271. bool usingXShm;
  220272. #endif
  220273. static int getShiftNeeded (const uint32 mask) throw()
  220274. {
  220275. for (int i = 32; --i >= 0;)
  220276. if (((mask >> i) & 1) != 0)
  220277. return i - 7;
  220278. jassertfalse;
  220279. return 0;
  220280. }
  220281. };
  220282. class LinuxComponentPeer : public ComponentPeer
  220283. {
  220284. public:
  220285. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220286. : ComponentPeer (component, windowStyleFlags),
  220287. windowH (0),
  220288. parentWindow (0),
  220289. wx (0),
  220290. wy (0),
  220291. ww (0),
  220292. wh (0),
  220293. fullScreen (false),
  220294. mapped (false),
  220295. visual (0),
  220296. depth (0)
  220297. {
  220298. // it's dangerous to create a window on a thread other than the message thread..
  220299. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220300. repainter = new LinuxRepaintManager (this);
  220301. createWindow();
  220302. setTitle (component->getName());
  220303. }
  220304. ~LinuxComponentPeer()
  220305. {
  220306. // it's dangerous to delete a window on a thread other than the message thread..
  220307. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220308. deleteIconPixmaps();
  220309. destroyWindow();
  220310. windowH = 0;
  220311. }
  220312. void* getNativeHandle() const
  220313. {
  220314. return (void*) windowH;
  220315. }
  220316. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220317. {
  220318. XPointer peer = 0;
  220319. ScopedXLock xlock;
  220320. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220321. {
  220322. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220323. peer = 0;
  220324. }
  220325. return (LinuxComponentPeer*) peer;
  220326. }
  220327. void setVisible (bool shouldBeVisible)
  220328. {
  220329. ScopedXLock xlock;
  220330. if (shouldBeVisible)
  220331. XMapWindow (display, windowH);
  220332. else
  220333. XUnmapWindow (display, windowH);
  220334. }
  220335. void setTitle (const String& title)
  220336. {
  220337. setWindowTitle (windowH, title);
  220338. }
  220339. void setPosition (int x, int y)
  220340. {
  220341. setBounds (x, y, ww, wh, false);
  220342. }
  220343. void setSize (int w, int h)
  220344. {
  220345. setBounds (wx, wy, w, h, false);
  220346. }
  220347. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220348. {
  220349. fullScreen = isNowFullScreen;
  220350. if (windowH != 0)
  220351. {
  220352. Component::SafePointer<Component> deletionChecker (component);
  220353. wx = x;
  220354. wy = y;
  220355. ww = jmax (1, w);
  220356. wh = jmax (1, h);
  220357. ScopedXLock xlock;
  220358. // Make sure the Window manager does what we want
  220359. XSizeHints* hints = XAllocSizeHints();
  220360. hints->flags = USSize | USPosition;
  220361. hints->width = ww;
  220362. hints->height = wh;
  220363. hints->x = wx;
  220364. hints->y = wy;
  220365. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220366. {
  220367. hints->min_width = hints->max_width = hints->width;
  220368. hints->min_height = hints->max_height = hints->height;
  220369. hints->flags |= PMinSize | PMaxSize;
  220370. }
  220371. XSetWMNormalHints (display, windowH, hints);
  220372. XFree (hints);
  220373. XMoveResizeWindow (display, windowH,
  220374. wx - windowBorder.getLeft(),
  220375. wy - windowBorder.getTop(), ww, wh);
  220376. if (deletionChecker != 0)
  220377. {
  220378. updateBorderSize();
  220379. handleMovedOrResized();
  220380. }
  220381. }
  220382. }
  220383. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220384. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220385. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220386. {
  220387. return relativePosition + getScreenPosition();
  220388. }
  220389. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220390. {
  220391. return screenPosition - getScreenPosition();
  220392. }
  220393. void setMinimised (bool shouldBeMinimised)
  220394. {
  220395. if (shouldBeMinimised)
  220396. {
  220397. Window root = RootWindow (display, DefaultScreen (display));
  220398. XClientMessageEvent clientMsg;
  220399. clientMsg.display = display;
  220400. clientMsg.window = windowH;
  220401. clientMsg.type = ClientMessage;
  220402. clientMsg.format = 32;
  220403. clientMsg.message_type = Atoms::ChangeState;
  220404. clientMsg.data.l[0] = IconicState;
  220405. ScopedXLock xlock;
  220406. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220407. }
  220408. else
  220409. {
  220410. setVisible (true);
  220411. }
  220412. }
  220413. bool isMinimised() const
  220414. {
  220415. bool minimised = false;
  220416. unsigned char* stateProp;
  220417. unsigned long nitems, bytesLeft;
  220418. Atom actualType;
  220419. int actualFormat;
  220420. ScopedXLock xlock;
  220421. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220422. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220423. &stateProp) == Success
  220424. && actualType == Atoms::State
  220425. && actualFormat == 32
  220426. && nitems > 0)
  220427. {
  220428. if (((unsigned long*) stateProp)[0] == IconicState)
  220429. minimised = true;
  220430. XFree (stateProp);
  220431. }
  220432. return minimised;
  220433. }
  220434. void setFullScreen (const bool shouldBeFullScreen)
  220435. {
  220436. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220437. setMinimised (false);
  220438. if (fullScreen != shouldBeFullScreen)
  220439. {
  220440. if (shouldBeFullScreen)
  220441. r = Desktop::getInstance().getMainMonitorArea();
  220442. if (! r.isEmpty())
  220443. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220444. getComponent()->repaint();
  220445. }
  220446. }
  220447. bool isFullScreen() const
  220448. {
  220449. return fullScreen;
  220450. }
  220451. bool isChildWindowOf (Window possibleParent) const
  220452. {
  220453. Window* windowList = 0;
  220454. uint32 windowListSize = 0;
  220455. Window parent, root;
  220456. ScopedXLock xlock;
  220457. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220458. {
  220459. if (windowList != 0)
  220460. XFree (windowList);
  220461. return parent == possibleParent;
  220462. }
  220463. return false;
  220464. }
  220465. bool isFrontWindow() const
  220466. {
  220467. Window* windowList = 0;
  220468. uint32 windowListSize = 0;
  220469. bool result = false;
  220470. ScopedXLock xlock;
  220471. Window parent, root = RootWindow (display, DefaultScreen (display));
  220472. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220473. {
  220474. for (int i = windowListSize; --i >= 0;)
  220475. {
  220476. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220477. if (peer != 0)
  220478. {
  220479. result = (peer == this);
  220480. break;
  220481. }
  220482. }
  220483. }
  220484. if (windowList != 0)
  220485. XFree (windowList);
  220486. return result;
  220487. }
  220488. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220489. {
  220490. int x = position.getX();
  220491. int y = position.getY();
  220492. if (((unsigned int) x) >= (unsigned int) ww
  220493. || ((unsigned int) y) >= (unsigned int) wh)
  220494. return false;
  220495. bool inFront = false;
  220496. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220497. {
  220498. Component* const c = Desktop::getInstance().getComponent (i);
  220499. if (inFront)
  220500. {
  220501. if (c->contains (x + wx - c->getScreenX(),
  220502. y + wy - c->getScreenY()))
  220503. {
  220504. return false;
  220505. }
  220506. }
  220507. else if (c == getComponent())
  220508. {
  220509. inFront = true;
  220510. }
  220511. }
  220512. if (trueIfInAChildWindow)
  220513. return true;
  220514. ::Window root, child;
  220515. unsigned int bw, depth;
  220516. int wx, wy, w, h;
  220517. ScopedXLock xlock;
  220518. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220519. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220520. &bw, &depth))
  220521. {
  220522. return false;
  220523. }
  220524. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220525. return false;
  220526. return child == None;
  220527. }
  220528. const BorderSize getFrameSize() const
  220529. {
  220530. return BorderSize();
  220531. }
  220532. bool setAlwaysOnTop (bool alwaysOnTop)
  220533. {
  220534. return false;
  220535. }
  220536. void toFront (bool makeActive)
  220537. {
  220538. if (makeActive)
  220539. {
  220540. setVisible (true);
  220541. grabFocus();
  220542. }
  220543. XEvent ev;
  220544. ev.xclient.type = ClientMessage;
  220545. ev.xclient.serial = 0;
  220546. ev.xclient.send_event = True;
  220547. ev.xclient.message_type = Atoms::ActiveWin;
  220548. ev.xclient.window = windowH;
  220549. ev.xclient.format = 32;
  220550. ev.xclient.data.l[0] = 2;
  220551. ev.xclient.data.l[1] = CurrentTime;
  220552. ev.xclient.data.l[2] = 0;
  220553. ev.xclient.data.l[3] = 0;
  220554. ev.xclient.data.l[4] = 0;
  220555. {
  220556. ScopedXLock xlock;
  220557. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220558. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220559. XWindowAttributes attr;
  220560. XGetWindowAttributes (display, windowH, &attr);
  220561. if (component->isAlwaysOnTop())
  220562. XRaiseWindow (display, windowH);
  220563. XSync (display, False);
  220564. }
  220565. handleBroughtToFront();
  220566. }
  220567. void toBehind (ComponentPeer* other)
  220568. {
  220569. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220570. jassert (otherPeer != 0); // wrong type of window?
  220571. if (otherPeer != 0)
  220572. {
  220573. setMinimised (false);
  220574. Window newStack[] = { otherPeer->windowH, windowH };
  220575. ScopedXLock xlock;
  220576. XRestackWindows (display, newStack, 2);
  220577. }
  220578. }
  220579. bool isFocused() const
  220580. {
  220581. int revert = 0;
  220582. Window focusedWindow = 0;
  220583. ScopedXLock xlock;
  220584. XGetInputFocus (display, &focusedWindow, &revert);
  220585. return focusedWindow == windowH;
  220586. }
  220587. void grabFocus()
  220588. {
  220589. XWindowAttributes atts;
  220590. ScopedXLock xlock;
  220591. if (windowH != 0
  220592. && XGetWindowAttributes (display, windowH, &atts)
  220593. && atts.map_state == IsViewable
  220594. && ! isFocused())
  220595. {
  220596. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220597. isActiveApplication = true;
  220598. }
  220599. }
  220600. void textInputRequired (const Point<int>&)
  220601. {
  220602. }
  220603. void repaint (const Rectangle<int>& area)
  220604. {
  220605. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220606. }
  220607. void performAnyPendingRepaintsNow()
  220608. {
  220609. repainter->performAnyPendingRepaintsNow();
  220610. }
  220611. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220612. {
  220613. ScopedXLock xlock;
  220614. const int width = image.getWidth();
  220615. const int height = image.getHeight();
  220616. HeapBlock <char> colour (width * height);
  220617. int index = 0;
  220618. for (int y = 0; y < height; ++y)
  220619. for (int x = 0; x < width; ++x)
  220620. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  220621. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220622. 0, colour.getData(),
  220623. width, height, 32, 0);
  220624. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220625. width, height, 24);
  220626. GC gc = XCreateGC (display, pixmap, 0, 0);
  220627. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220628. XFreeGC (display, gc);
  220629. return pixmap;
  220630. }
  220631. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220632. {
  220633. ScopedXLock xlock;
  220634. const int width = image.getWidth();
  220635. const int height = image.getHeight();
  220636. const int stride = (width + 7) >> 3;
  220637. HeapBlock <char> mask;
  220638. mask.calloc (stride * height);
  220639. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220640. for (int y = 0; y < height; ++y)
  220641. {
  220642. for (int x = 0; x < width; ++x)
  220643. {
  220644. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220645. const int offset = y * stride + (x >> 3);
  220646. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220647. mask[offset] |= bit;
  220648. }
  220649. }
  220650. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220651. mask.getData(), width, height, 1, 0, 1);
  220652. }
  220653. void setIcon (const Image& newIcon)
  220654. {
  220655. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220656. HeapBlock <unsigned long> data (dataSize);
  220657. int index = 0;
  220658. data[index++] = newIcon.getWidth();
  220659. data[index++] = newIcon.getHeight();
  220660. for (int y = 0; y < newIcon.getHeight(); ++y)
  220661. for (int x = 0; x < newIcon.getWidth(); ++x)
  220662. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220663. ScopedXLock xlock;
  220664. XChangeProperty (display, windowH,
  220665. XInternAtom (display, "_NET_WM_ICON", False),
  220666. XA_CARDINAL, 32, PropModeReplace,
  220667. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220668. deleteIconPixmaps();
  220669. XWMHints* wmHints = XGetWMHints (display, windowH);
  220670. if (wmHints == 0)
  220671. wmHints = XAllocWMHints();
  220672. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220673. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220674. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220675. XSetWMHints (display, windowH, wmHints);
  220676. XFree (wmHints);
  220677. XSync (display, False);
  220678. }
  220679. void deleteIconPixmaps()
  220680. {
  220681. ScopedXLock xlock;
  220682. XWMHints* wmHints = XGetWMHints (display, windowH);
  220683. if (wmHints != 0)
  220684. {
  220685. if ((wmHints->flags & IconPixmapHint) != 0)
  220686. {
  220687. wmHints->flags &= ~IconPixmapHint;
  220688. XFreePixmap (display, wmHints->icon_pixmap);
  220689. }
  220690. if ((wmHints->flags & IconMaskHint) != 0)
  220691. {
  220692. wmHints->flags &= ~IconMaskHint;
  220693. XFreePixmap (display, wmHints->icon_mask);
  220694. }
  220695. XSetWMHints (display, windowH, wmHints);
  220696. XFree (wmHints);
  220697. }
  220698. }
  220699. void handleWindowMessage (XEvent* event)
  220700. {
  220701. switch (event->xany.type)
  220702. {
  220703. case 2: // 'KeyPress'
  220704. {
  220705. ScopedXLock xlock;
  220706. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220707. updateKeyStates (keyEvent->keycode, true);
  220708. char utf8 [64];
  220709. zeromem (utf8, sizeof (utf8));
  220710. KeySym sym;
  220711. {
  220712. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220713. ::setlocale (LC_ALL, "");
  220714. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220715. ::setlocale (LC_ALL, oldLocale);
  220716. }
  220717. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220718. int keyCode = (int) unicodeChar;
  220719. if (keyCode < 0x20)
  220720. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220721. const ModifierKeys oldMods (currentModifiers);
  220722. bool keyPressed = false;
  220723. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220724. if ((sym & 0xff00) == 0xff00)
  220725. {
  220726. // Translate keypad
  220727. if (sym == XK_KP_Divide)
  220728. keyCode = XK_slash;
  220729. else if (sym == XK_KP_Multiply)
  220730. keyCode = XK_asterisk;
  220731. else if (sym == XK_KP_Subtract)
  220732. keyCode = XK_hyphen;
  220733. else if (sym == XK_KP_Add)
  220734. keyCode = XK_plus;
  220735. else if (sym == XK_KP_Enter)
  220736. keyCode = XK_Return;
  220737. else if (sym == XK_KP_Decimal)
  220738. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220739. else if (sym == XK_KP_0)
  220740. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220741. else if (sym == XK_KP_1)
  220742. keyCode = Keys::numLock ? XK_1 : XK_End;
  220743. else if (sym == XK_KP_2)
  220744. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220745. else if (sym == XK_KP_3)
  220746. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220747. else if (sym == XK_KP_4)
  220748. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220749. else if (sym == XK_KP_5)
  220750. keyCode = XK_5;
  220751. else if (sym == XK_KP_6)
  220752. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220753. else if (sym == XK_KP_7)
  220754. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220755. else if (sym == XK_KP_8)
  220756. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220757. else if (sym == XK_KP_9)
  220758. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220759. switch (sym)
  220760. {
  220761. case XK_Left:
  220762. case XK_Right:
  220763. case XK_Up:
  220764. case XK_Down:
  220765. case XK_Page_Up:
  220766. case XK_Page_Down:
  220767. case XK_End:
  220768. case XK_Home:
  220769. case XK_Delete:
  220770. case XK_Insert:
  220771. keyPressed = true;
  220772. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220773. break;
  220774. case XK_Tab:
  220775. case XK_Return:
  220776. case XK_Escape:
  220777. case XK_BackSpace:
  220778. keyPressed = true;
  220779. keyCode &= 0xff;
  220780. break;
  220781. default:
  220782. {
  220783. if (sym >= XK_F1 && sym <= XK_F16)
  220784. {
  220785. keyPressed = true;
  220786. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220787. }
  220788. break;
  220789. }
  220790. }
  220791. }
  220792. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220793. keyPressed = true;
  220794. if (oldMods != currentModifiers)
  220795. handleModifierKeysChange();
  220796. if (keyDownChange)
  220797. handleKeyUpOrDown (true);
  220798. if (keyPressed)
  220799. handleKeyPress (keyCode, unicodeChar);
  220800. break;
  220801. }
  220802. case KeyRelease:
  220803. {
  220804. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220805. updateKeyStates (keyEvent->keycode, false);
  220806. ScopedXLock xlock;
  220807. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220808. const ModifierKeys oldMods (currentModifiers);
  220809. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220810. if (oldMods != currentModifiers)
  220811. handleModifierKeysChange();
  220812. if (keyDownChange)
  220813. handleKeyUpOrDown (false);
  220814. break;
  220815. }
  220816. case ButtonPress:
  220817. {
  220818. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220819. updateKeyModifiers (buttonPressEvent->state);
  220820. bool buttonMsg = false;
  220821. const int map = pointerMap [buttonPressEvent->button - Button1];
  220822. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220823. {
  220824. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220825. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220826. }
  220827. if (map == Keys::LeftButton)
  220828. {
  220829. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220830. buttonMsg = true;
  220831. }
  220832. else if (map == Keys::RightButton)
  220833. {
  220834. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220835. buttonMsg = true;
  220836. }
  220837. else if (map == Keys::MiddleButton)
  220838. {
  220839. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220840. buttonMsg = true;
  220841. }
  220842. if (buttonMsg)
  220843. {
  220844. toFront (true);
  220845. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220846. getEventTime (buttonPressEvent->time));
  220847. }
  220848. clearLastMousePos();
  220849. break;
  220850. }
  220851. case ButtonRelease:
  220852. {
  220853. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220854. updateKeyModifiers (buttonRelEvent->state);
  220855. const int map = pointerMap [buttonRelEvent->button - Button1];
  220856. if (map == Keys::LeftButton)
  220857. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220858. else if (map == Keys::RightButton)
  220859. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220860. else if (map == Keys::MiddleButton)
  220861. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220862. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220863. getEventTime (buttonRelEvent->time));
  220864. clearLastMousePos();
  220865. break;
  220866. }
  220867. case MotionNotify:
  220868. {
  220869. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220870. updateKeyModifiers (movedEvent->state);
  220871. const Point<int> mousePos (Desktop::getMousePosition());
  220872. if (lastMousePos != mousePos)
  220873. {
  220874. lastMousePos = mousePos;
  220875. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220876. {
  220877. Window wRoot = 0, wParent = 0;
  220878. {
  220879. ScopedXLock xlock;
  220880. unsigned int numChildren;
  220881. Window* wChild = 0;
  220882. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220883. }
  220884. if (wParent != 0
  220885. && wParent != windowH
  220886. && wParent != wRoot)
  220887. {
  220888. parentWindow = wParent;
  220889. updateBounds();
  220890. }
  220891. else
  220892. {
  220893. parentWindow = 0;
  220894. }
  220895. }
  220896. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220897. }
  220898. break;
  220899. }
  220900. case EnterNotify:
  220901. {
  220902. clearLastMousePos();
  220903. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220904. if (! currentModifiers.isAnyMouseButtonDown())
  220905. {
  220906. updateKeyModifiers (enterEvent->state);
  220907. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220908. }
  220909. break;
  220910. }
  220911. case LeaveNotify:
  220912. {
  220913. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220914. // Suppress the normal leave if we've got a pointer grab, or if
  220915. // it's a bogus one caused by clicking a mouse button when running
  220916. // in a Window manager
  220917. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220918. || leaveEvent->mode == NotifyUngrab)
  220919. {
  220920. updateKeyModifiers (leaveEvent->state);
  220921. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220922. }
  220923. break;
  220924. }
  220925. case FocusIn:
  220926. {
  220927. isActiveApplication = true;
  220928. if (isFocused())
  220929. handleFocusGain();
  220930. break;
  220931. }
  220932. case FocusOut:
  220933. {
  220934. isActiveApplication = false;
  220935. if (! isFocused())
  220936. handleFocusLoss();
  220937. break;
  220938. }
  220939. case Expose:
  220940. {
  220941. // Batch together all pending expose events
  220942. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220943. XEvent nextEvent;
  220944. ScopedXLock xlock;
  220945. if (exposeEvent->window != windowH)
  220946. {
  220947. Window child;
  220948. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220949. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220950. &child);
  220951. }
  220952. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220953. exposeEvent->width, exposeEvent->height));
  220954. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220955. {
  220956. XPeekEvent (display, (XEvent*) &nextEvent);
  220957. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220958. break;
  220959. XNextEvent (display, (XEvent*) &nextEvent);
  220960. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220961. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220962. nextExposeEvent->width, nextExposeEvent->height));
  220963. }
  220964. break;
  220965. }
  220966. case CirculateNotify:
  220967. case CreateNotify:
  220968. case DestroyNotify:
  220969. // Think we can ignore these
  220970. break;
  220971. case ConfigureNotify:
  220972. {
  220973. updateBounds();
  220974. updateBorderSize();
  220975. handleMovedOrResized();
  220976. // if the native title bar is dragged, need to tell any active menus, etc.
  220977. if ((styleFlags & windowHasTitleBar) != 0
  220978. && component->isCurrentlyBlockedByAnotherModalComponent())
  220979. {
  220980. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220981. if (currentModalComp != 0)
  220982. currentModalComp->inputAttemptWhenModal();
  220983. }
  220984. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220985. if (confEvent->window == windowH
  220986. && confEvent->above != 0
  220987. && isFrontWindow())
  220988. {
  220989. handleBroughtToFront();
  220990. }
  220991. break;
  220992. }
  220993. case ReparentNotify:
  220994. {
  220995. parentWindow = 0;
  220996. Window wRoot = 0;
  220997. Window* wChild = 0;
  220998. unsigned int numChildren;
  220999. {
  221000. ScopedXLock xlock;
  221001. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  221002. }
  221003. if (parentWindow == windowH || parentWindow == wRoot)
  221004. parentWindow = 0;
  221005. updateBounds();
  221006. updateBorderSize();
  221007. handleMovedOrResized();
  221008. break;
  221009. }
  221010. case GravityNotify:
  221011. {
  221012. updateBounds();
  221013. updateBorderSize();
  221014. handleMovedOrResized();
  221015. break;
  221016. }
  221017. case MapNotify:
  221018. mapped = true;
  221019. handleBroughtToFront();
  221020. break;
  221021. case UnmapNotify:
  221022. mapped = false;
  221023. break;
  221024. case MappingNotify:
  221025. {
  221026. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  221027. if (mappingEvent->request != MappingPointer)
  221028. {
  221029. // Deal with modifier/keyboard mapping
  221030. ScopedXLock xlock;
  221031. XRefreshKeyboardMapping (mappingEvent);
  221032. updateModifierMappings();
  221033. }
  221034. break;
  221035. }
  221036. case ClientMessage:
  221037. {
  221038. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  221039. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  221040. {
  221041. const Atom atom = (Atom) clientMsg->data.l[0];
  221042. if (atom == Atoms::ProtocolList [Atoms::PING])
  221043. {
  221044. Window root = RootWindow (display, DefaultScreen (display));
  221045. event->xclient.window = root;
  221046. XSendEvent (display, root, False, NoEventMask, event);
  221047. XFlush (display);
  221048. }
  221049. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  221050. {
  221051. XWindowAttributes atts;
  221052. ScopedXLock xlock;
  221053. if (clientMsg->window != 0
  221054. && XGetWindowAttributes (display, clientMsg->window, &atts))
  221055. {
  221056. if (atts.map_state == IsViewable)
  221057. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  221058. }
  221059. }
  221060. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  221061. {
  221062. handleUserClosingWindow();
  221063. }
  221064. }
  221065. else if (clientMsg->message_type == Atoms::XdndEnter)
  221066. {
  221067. handleDragAndDropEnter (clientMsg);
  221068. }
  221069. else if (clientMsg->message_type == Atoms::XdndLeave)
  221070. {
  221071. resetDragAndDrop();
  221072. }
  221073. else if (clientMsg->message_type == Atoms::XdndPosition)
  221074. {
  221075. handleDragAndDropPosition (clientMsg);
  221076. }
  221077. else if (clientMsg->message_type == Atoms::XdndDrop)
  221078. {
  221079. handleDragAndDropDrop (clientMsg);
  221080. }
  221081. else if (clientMsg->message_type == Atoms::XdndStatus)
  221082. {
  221083. handleDragAndDropStatus (clientMsg);
  221084. }
  221085. else if (clientMsg->message_type == Atoms::XdndFinished)
  221086. {
  221087. resetDragAndDrop();
  221088. }
  221089. break;
  221090. }
  221091. case SelectionNotify:
  221092. handleDragAndDropSelection (event);
  221093. break;
  221094. case SelectionClear:
  221095. case SelectionRequest:
  221096. break;
  221097. default:
  221098. #if JUCE_USE_XSHM
  221099. {
  221100. ScopedXLock xlock;
  221101. if (event->xany.type == XShmGetEventBase (display))
  221102. repainter->notifyPaintCompleted();
  221103. }
  221104. #endif
  221105. break;
  221106. }
  221107. }
  221108. void showMouseCursor (Cursor cursor) throw()
  221109. {
  221110. ScopedXLock xlock;
  221111. XDefineCursor (display, windowH, cursor);
  221112. }
  221113. void setTaskBarIcon (const Image& image)
  221114. {
  221115. ScopedXLock xlock;
  221116. taskbarImage = image;
  221117. Screen* const screen = XDefaultScreenOfDisplay (display);
  221118. const int screenNumber = XScreenNumberOfScreen (screen);
  221119. String screenAtom ("_NET_SYSTEM_TRAY_S");
  221120. screenAtom << screenNumber;
  221121. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  221122. XGrabServer (display);
  221123. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  221124. if (managerWin != None)
  221125. XSelectInput (display, managerWin, StructureNotifyMask);
  221126. XUngrabServer (display);
  221127. XFlush (display);
  221128. if (managerWin != None)
  221129. {
  221130. XEvent ev;
  221131. zerostruct (ev);
  221132. ev.xclient.type = ClientMessage;
  221133. ev.xclient.window = managerWin;
  221134. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  221135. ev.xclient.format = 32;
  221136. ev.xclient.data.l[0] = CurrentTime;
  221137. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  221138. ev.xclient.data.l[2] = windowH;
  221139. ev.xclient.data.l[3] = 0;
  221140. ev.xclient.data.l[4] = 0;
  221141. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  221142. XSync (display, False);
  221143. }
  221144. // For older KDE's ...
  221145. long atomData = 1;
  221146. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  221147. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  221148. // For more recent KDE's...
  221149. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  221150. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  221151. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  221152. XSizeHints* hints = XAllocSizeHints();
  221153. hints->flags = PMinSize;
  221154. hints->min_width = 22;
  221155. hints->min_height = 22;
  221156. XSetWMNormalHints (display, windowH, hints);
  221157. XFree (hints);
  221158. }
  221159. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  221160. juce_UseDebuggingNewOperator
  221161. bool dontRepaint;
  221162. static ModifierKeys currentModifiers;
  221163. static bool isActiveApplication;
  221164. private:
  221165. class LinuxRepaintManager : public Timer
  221166. {
  221167. public:
  221168. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  221169. : peer (peer_),
  221170. lastTimeImageUsed (0)
  221171. {
  221172. #if JUCE_USE_XSHM
  221173. shmCompletedDrawing = true;
  221174. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  221175. if (useARGBImagesForRendering)
  221176. {
  221177. ScopedXLock xlock;
  221178. XShmSegmentInfo segmentinfo;
  221179. XImage* const testImage
  221180. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  221181. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  221182. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  221183. XDestroyImage (testImage);
  221184. }
  221185. #endif
  221186. }
  221187. ~LinuxRepaintManager()
  221188. {
  221189. }
  221190. void timerCallback()
  221191. {
  221192. #if JUCE_USE_XSHM
  221193. if (! shmCompletedDrawing)
  221194. return;
  221195. #endif
  221196. if (! regionsNeedingRepaint.isEmpty())
  221197. {
  221198. stopTimer();
  221199. performAnyPendingRepaintsNow();
  221200. }
  221201. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221202. {
  221203. stopTimer();
  221204. image = Image::null;
  221205. }
  221206. }
  221207. void repaint (const Rectangle<int>& area)
  221208. {
  221209. if (! isTimerRunning())
  221210. startTimer (repaintTimerPeriod);
  221211. regionsNeedingRepaint.add (area);
  221212. }
  221213. void performAnyPendingRepaintsNow()
  221214. {
  221215. #if JUCE_USE_XSHM
  221216. if (! shmCompletedDrawing)
  221217. {
  221218. startTimer (repaintTimerPeriod);
  221219. return;
  221220. }
  221221. #endif
  221222. peer->clearMaskedRegion();
  221223. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221224. regionsNeedingRepaint.clear();
  221225. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221226. if (! totalArea.isEmpty())
  221227. {
  221228. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221229. || image.getHeight() < totalArea.getHeight())
  221230. {
  221231. #if JUCE_USE_XSHM
  221232. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221233. : Image::RGB,
  221234. #else
  221235. image = Image (new XBitmapImage (Image::RGB,
  221236. #endif
  221237. (totalArea.getWidth() + 31) & ~31,
  221238. (totalArea.getHeight() + 31) & ~31,
  221239. false, peer->depth, peer->visual));
  221240. }
  221241. startTimer (repaintTimerPeriod);
  221242. RectangleList adjustedList (originalRepaintRegion);
  221243. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221244. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221245. if (peer->depth == 32)
  221246. {
  221247. RectangleList::Iterator i (originalRepaintRegion);
  221248. while (i.next())
  221249. image.clear (*i.getRectangle() - totalArea.getPosition());
  221250. }
  221251. peer->handlePaint (context);
  221252. if (! peer->maskedRegion.isEmpty())
  221253. originalRepaintRegion.subtract (peer->maskedRegion);
  221254. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221255. {
  221256. #if JUCE_USE_XSHM
  221257. shmCompletedDrawing = false;
  221258. #endif
  221259. const Rectangle<int>& r = *i.getRectangle();
  221260. static_cast<XBitmapImage*> (image.getSharedImage())
  221261. ->blitToWindow (peer->windowH,
  221262. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221263. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221264. }
  221265. }
  221266. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221267. startTimer (repaintTimerPeriod);
  221268. }
  221269. #if JUCE_USE_XSHM
  221270. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221271. #endif
  221272. private:
  221273. enum { repaintTimerPeriod = 1000 / 100 };
  221274. LinuxComponentPeer* const peer;
  221275. Image image;
  221276. uint32 lastTimeImageUsed;
  221277. RectangleList regionsNeedingRepaint;
  221278. #if JUCE_USE_XSHM
  221279. bool useARGBImagesForRendering, shmCompletedDrawing;
  221280. #endif
  221281. LinuxRepaintManager (const LinuxRepaintManager&);
  221282. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221283. };
  221284. ScopedPointer <LinuxRepaintManager> repainter;
  221285. friend class LinuxRepaintManager;
  221286. Window windowH, parentWindow;
  221287. int wx, wy, ww, wh;
  221288. Image taskbarImage;
  221289. bool fullScreen, mapped;
  221290. Visual* visual;
  221291. int depth;
  221292. BorderSize windowBorder;
  221293. struct MotifWmHints
  221294. {
  221295. unsigned long flags;
  221296. unsigned long functions;
  221297. unsigned long decorations;
  221298. long input_mode;
  221299. unsigned long status;
  221300. };
  221301. static void updateKeyStates (const int keycode, const bool press) throw()
  221302. {
  221303. const int keybyte = keycode >> 3;
  221304. const int keybit = (1 << (keycode & 7));
  221305. if (press)
  221306. Keys::keyStates [keybyte] |= keybit;
  221307. else
  221308. Keys::keyStates [keybyte] &= ~keybit;
  221309. }
  221310. static void updateKeyModifiers (const int status) throw()
  221311. {
  221312. int keyMods = 0;
  221313. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221314. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221315. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221316. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221317. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221318. Keys::capsLock = ((status & LockMask) != 0);
  221319. }
  221320. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221321. {
  221322. int modifier = 0;
  221323. bool isModifier = true;
  221324. switch (sym)
  221325. {
  221326. case XK_Shift_L:
  221327. case XK_Shift_R:
  221328. modifier = ModifierKeys::shiftModifier;
  221329. break;
  221330. case XK_Control_L:
  221331. case XK_Control_R:
  221332. modifier = ModifierKeys::ctrlModifier;
  221333. break;
  221334. case XK_Alt_L:
  221335. case XK_Alt_R:
  221336. modifier = ModifierKeys::altModifier;
  221337. break;
  221338. case XK_Num_Lock:
  221339. if (press)
  221340. Keys::numLock = ! Keys::numLock;
  221341. break;
  221342. case XK_Caps_Lock:
  221343. if (press)
  221344. Keys::capsLock = ! Keys::capsLock;
  221345. break;
  221346. case XK_Scroll_Lock:
  221347. break;
  221348. default:
  221349. isModifier = false;
  221350. break;
  221351. }
  221352. if (modifier != 0)
  221353. {
  221354. if (press)
  221355. currentModifiers = currentModifiers.withFlags (modifier);
  221356. else
  221357. currentModifiers = currentModifiers.withoutFlags (modifier);
  221358. }
  221359. return isModifier;
  221360. }
  221361. // Alt and Num lock are not defined by standard X
  221362. // modifier constants: check what they're mapped to
  221363. static void updateModifierMappings() throw()
  221364. {
  221365. ScopedXLock xlock;
  221366. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221367. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221368. Keys::AltMask = 0;
  221369. Keys::NumLockMask = 0;
  221370. XModifierKeymap* mapping = XGetModifierMapping (display);
  221371. if (mapping)
  221372. {
  221373. for (int i = 0; i < 8; i++)
  221374. {
  221375. if (mapping->modifiermap [i << 1] == altLeftCode)
  221376. Keys::AltMask = 1 << i;
  221377. else if (mapping->modifiermap [i << 1] == numLockCode)
  221378. Keys::NumLockMask = 1 << i;
  221379. }
  221380. XFreeModifiermap (mapping);
  221381. }
  221382. }
  221383. void removeWindowDecorations (Window wndH)
  221384. {
  221385. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221386. if (hints != None)
  221387. {
  221388. MotifWmHints motifHints;
  221389. zerostruct (motifHints);
  221390. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221391. motifHints.decorations = 0;
  221392. ScopedXLock xlock;
  221393. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221394. (unsigned char*) &motifHints, 4);
  221395. }
  221396. hints = XInternAtom (display, "_WIN_HINTS", True);
  221397. if (hints != None)
  221398. {
  221399. long gnomeHints = 0;
  221400. ScopedXLock xlock;
  221401. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221402. (unsigned char*) &gnomeHints, 1);
  221403. }
  221404. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221405. if (hints != None)
  221406. {
  221407. long kwmHints = 2; /*KDE_tinyDecoration*/
  221408. ScopedXLock xlock;
  221409. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221410. (unsigned char*) &kwmHints, 1);
  221411. }
  221412. }
  221413. void addWindowButtons (Window wndH)
  221414. {
  221415. ScopedXLock xlock;
  221416. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221417. if (hints != None)
  221418. {
  221419. MotifWmHints motifHints;
  221420. zerostruct (motifHints);
  221421. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221422. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221423. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221424. if ((styleFlags & windowHasCloseButton) != 0)
  221425. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221426. if ((styleFlags & windowHasMinimiseButton) != 0)
  221427. {
  221428. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221429. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221430. }
  221431. if ((styleFlags & windowHasMaximiseButton) != 0)
  221432. {
  221433. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221434. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221435. }
  221436. if ((styleFlags & windowIsResizable) != 0)
  221437. {
  221438. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221439. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221440. }
  221441. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221442. }
  221443. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221444. if (hints != None)
  221445. {
  221446. int netHints [6];
  221447. int num = 0;
  221448. if ((styleFlags & windowIsResizable) != 0)
  221449. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221450. if ((styleFlags & windowHasMaximiseButton) != 0)
  221451. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221452. if ((styleFlags & windowHasMinimiseButton) != 0)
  221453. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221454. if ((styleFlags & windowHasCloseButton) != 0)
  221455. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221456. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221457. }
  221458. }
  221459. void setWindowType()
  221460. {
  221461. int netHints [2];
  221462. int numHints = 0;
  221463. if ((styleFlags & windowIsTemporary) != 0
  221464. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221465. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221466. else
  221467. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221468. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221469. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221470. (unsigned char*) &netHints, numHints);
  221471. numHints = 0;
  221472. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221473. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221474. if (component->isAlwaysOnTop())
  221475. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221476. if (numHints > 0)
  221477. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221478. (unsigned char*) &netHints, numHints);
  221479. }
  221480. void createWindow()
  221481. {
  221482. ScopedXLock xlock;
  221483. Atoms::initialiseAtoms();
  221484. resetDragAndDrop();
  221485. // Get defaults for various properties
  221486. const int screen = DefaultScreen (display);
  221487. Window root = RootWindow (display, screen);
  221488. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221489. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221490. if (visual == 0)
  221491. {
  221492. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221493. Process::terminate();
  221494. }
  221495. // Create and install a colormap suitable fr our visual
  221496. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221497. XInstallColormap (display, colormap);
  221498. // Set up the window attributes
  221499. XSetWindowAttributes swa;
  221500. swa.border_pixel = 0;
  221501. swa.background_pixmap = None;
  221502. swa.colormap = colormap;
  221503. swa.event_mask = getAllEventsMask();
  221504. windowH = XCreateWindow (display, root,
  221505. 0, 0, 1, 1,
  221506. 0, depth, InputOutput, visual,
  221507. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221508. &swa);
  221509. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221510. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221511. GrabModeAsync, GrabModeAsync, None, None);
  221512. // Set the window context to identify the window handle object
  221513. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221514. {
  221515. // Failed
  221516. jassertfalse;
  221517. Logger::outputDebugString ("Failed to create context information for window.\n");
  221518. XDestroyWindow (display, windowH);
  221519. windowH = 0;
  221520. return;
  221521. }
  221522. // Set window manager hints
  221523. XWMHints* wmHints = XAllocWMHints();
  221524. wmHints->flags = InputHint | StateHint;
  221525. wmHints->input = True; // Locally active input model
  221526. wmHints->initial_state = NormalState;
  221527. XSetWMHints (display, windowH, wmHints);
  221528. XFree (wmHints);
  221529. // Set the window type
  221530. setWindowType();
  221531. // Define decoration
  221532. if ((styleFlags & windowHasTitleBar) == 0)
  221533. removeWindowDecorations (windowH);
  221534. else
  221535. addWindowButtons (windowH);
  221536. // Set window name
  221537. setWindowTitle (windowH, getComponent()->getName());
  221538. // Associate the PID, allowing to be shut down when something goes wrong
  221539. unsigned long pid = getpid();
  221540. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221541. (unsigned char*) &pid, 1);
  221542. // Set window manager protocols
  221543. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221544. (unsigned char*) Atoms::ProtocolList, 2);
  221545. // Set drag and drop flags
  221546. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221547. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221548. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221549. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221550. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221551. (const unsigned char*) "", 0);
  221552. unsigned long dndVersion = Atoms::DndVersion;
  221553. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221554. (const unsigned char*) &dndVersion, 1);
  221555. // Initialise the pointer and keyboard mapping
  221556. // This is not the same as the logical pointer mapping the X server uses:
  221557. // we don't mess with this.
  221558. static bool mappingInitialised = false;
  221559. if (! mappingInitialised)
  221560. {
  221561. mappingInitialised = true;
  221562. const int numButtons = XGetPointerMapping (display, 0, 0);
  221563. if (numButtons == 2)
  221564. {
  221565. pointerMap[0] = Keys::LeftButton;
  221566. pointerMap[1] = Keys::RightButton;
  221567. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221568. }
  221569. else if (numButtons >= 3)
  221570. {
  221571. pointerMap[0] = Keys::LeftButton;
  221572. pointerMap[1] = Keys::MiddleButton;
  221573. pointerMap[2] = Keys::RightButton;
  221574. if (numButtons >= 5)
  221575. {
  221576. pointerMap[3] = Keys::WheelUp;
  221577. pointerMap[4] = Keys::WheelDown;
  221578. }
  221579. }
  221580. updateModifierMappings();
  221581. }
  221582. }
  221583. void destroyWindow()
  221584. {
  221585. ScopedXLock xlock;
  221586. XPointer handlePointer;
  221587. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221588. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221589. XDestroyWindow (display, windowH);
  221590. // Wait for it to complete and then remove any events for this
  221591. // window from the event queue.
  221592. XSync (display, false);
  221593. XEvent event;
  221594. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221595. {}
  221596. }
  221597. static int getAllEventsMask() throw()
  221598. {
  221599. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221600. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221601. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221602. }
  221603. static int64 getEventTime (::Time t)
  221604. {
  221605. static int64 eventTimeOffset = 0x12345678;
  221606. const int64 thisMessageTime = t;
  221607. if (eventTimeOffset == 0x12345678)
  221608. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221609. return eventTimeOffset + thisMessageTime;
  221610. }
  221611. static void setWindowTitle (Window xwin, const String& title)
  221612. {
  221613. XTextProperty nameProperty;
  221614. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221615. ScopedXLock xlock;
  221616. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221617. {
  221618. XSetWMName (display, xwin, &nameProperty);
  221619. XSetWMIconName (display, xwin, &nameProperty);
  221620. XFree (nameProperty.value);
  221621. }
  221622. }
  221623. void updateBorderSize()
  221624. {
  221625. if ((styleFlags & windowHasTitleBar) == 0)
  221626. {
  221627. windowBorder = BorderSize (0);
  221628. }
  221629. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221630. {
  221631. ScopedXLock xlock;
  221632. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221633. if (hints != None)
  221634. {
  221635. unsigned char* data = 0;
  221636. unsigned long nitems, bytesLeft;
  221637. Atom actualType;
  221638. int actualFormat;
  221639. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221640. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221641. &data) == Success)
  221642. {
  221643. const unsigned long* const sizes = (const unsigned long*) data;
  221644. if (actualFormat == 32)
  221645. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221646. (int) sizes[3], (int) sizes[1]);
  221647. XFree (data);
  221648. }
  221649. }
  221650. }
  221651. }
  221652. void updateBounds()
  221653. {
  221654. jassert (windowH != 0);
  221655. if (windowH != 0)
  221656. {
  221657. Window root, child;
  221658. unsigned int bw, depth;
  221659. ScopedXLock xlock;
  221660. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221661. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221662. &bw, &depth))
  221663. {
  221664. wx = wy = ww = wh = 0;
  221665. }
  221666. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221667. {
  221668. wx = wy = 0;
  221669. }
  221670. }
  221671. }
  221672. void resetDragAndDrop()
  221673. {
  221674. dragAndDropFiles.clear();
  221675. lastDropPos = Point<int> (-1, -1);
  221676. dragAndDropCurrentMimeType = 0;
  221677. dragAndDropSourceWindow = 0;
  221678. srcMimeTypeAtomList.clear();
  221679. }
  221680. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221681. {
  221682. msg.type = ClientMessage;
  221683. msg.display = display;
  221684. msg.window = dragAndDropSourceWindow;
  221685. msg.format = 32;
  221686. msg.data.l[0] = windowH;
  221687. ScopedXLock xlock;
  221688. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221689. }
  221690. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221691. {
  221692. XClientMessageEvent msg;
  221693. zerostruct (msg);
  221694. msg.message_type = Atoms::XdndStatus;
  221695. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221696. msg.data.l[4] = dropAction;
  221697. sendDragAndDropMessage (msg);
  221698. }
  221699. void sendDragAndDropLeave()
  221700. {
  221701. XClientMessageEvent msg;
  221702. zerostruct (msg);
  221703. msg.message_type = Atoms::XdndLeave;
  221704. sendDragAndDropMessage (msg);
  221705. }
  221706. void sendDragAndDropFinish()
  221707. {
  221708. XClientMessageEvent msg;
  221709. zerostruct (msg);
  221710. msg.message_type = Atoms::XdndFinished;
  221711. sendDragAndDropMessage (msg);
  221712. }
  221713. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221714. {
  221715. if ((clientMsg->data.l[1] & 1) == 0)
  221716. {
  221717. sendDragAndDropLeave();
  221718. if (dragAndDropFiles.size() > 0)
  221719. handleFileDragExit (dragAndDropFiles);
  221720. dragAndDropFiles.clear();
  221721. }
  221722. }
  221723. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221724. {
  221725. if (dragAndDropSourceWindow == 0)
  221726. return;
  221727. dragAndDropSourceWindow = clientMsg->data.l[0];
  221728. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221729. (int) clientMsg->data.l[2] & 0xffff);
  221730. dropPos -= getScreenPosition();
  221731. if (lastDropPos != dropPos)
  221732. {
  221733. lastDropPos = dropPos;
  221734. dragAndDropTimestamp = clientMsg->data.l[3];
  221735. Atom targetAction = Atoms::XdndActionCopy;
  221736. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221737. {
  221738. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221739. {
  221740. targetAction = Atoms::allowedActions[i];
  221741. break;
  221742. }
  221743. }
  221744. sendDragAndDropStatus (true, targetAction);
  221745. if (dragAndDropFiles.size() == 0)
  221746. updateDraggedFileList (clientMsg);
  221747. if (dragAndDropFiles.size() > 0)
  221748. handleFileDragMove (dragAndDropFiles, dropPos);
  221749. }
  221750. }
  221751. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221752. {
  221753. if (dragAndDropFiles.size() == 0)
  221754. updateDraggedFileList (clientMsg);
  221755. const StringArray files (dragAndDropFiles);
  221756. const Point<int> lastPos (lastDropPos);
  221757. sendDragAndDropFinish();
  221758. resetDragAndDrop();
  221759. if (files.size() > 0)
  221760. handleFileDragDrop (files, lastPos);
  221761. }
  221762. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221763. {
  221764. dragAndDropFiles.clear();
  221765. srcMimeTypeAtomList.clear();
  221766. dragAndDropCurrentMimeType = 0;
  221767. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221768. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221769. {
  221770. dragAndDropSourceWindow = 0;
  221771. return;
  221772. }
  221773. dragAndDropSourceWindow = clientMsg->data.l[0];
  221774. if ((clientMsg->data.l[1] & 1) != 0)
  221775. {
  221776. Atom actual;
  221777. int format;
  221778. unsigned long count = 0, remaining = 0;
  221779. unsigned char* data = 0;
  221780. ScopedXLock xlock;
  221781. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221782. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221783. &count, &remaining, &data);
  221784. if (data != 0)
  221785. {
  221786. if (actual == XA_ATOM && format == 32 && count != 0)
  221787. {
  221788. const unsigned long* const types = (const unsigned long*) data;
  221789. for (unsigned int i = 0; i < count; ++i)
  221790. if (types[i] != None)
  221791. srcMimeTypeAtomList.add (types[i]);
  221792. }
  221793. XFree (data);
  221794. }
  221795. }
  221796. if (srcMimeTypeAtomList.size() == 0)
  221797. {
  221798. for (int i = 2; i < 5; ++i)
  221799. if (clientMsg->data.l[i] != None)
  221800. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221801. if (srcMimeTypeAtomList.size() == 0)
  221802. {
  221803. dragAndDropSourceWindow = 0;
  221804. return;
  221805. }
  221806. }
  221807. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221808. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221809. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221810. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221811. handleDragAndDropPosition (clientMsg);
  221812. }
  221813. void handleDragAndDropSelection (const XEvent* const evt)
  221814. {
  221815. dragAndDropFiles.clear();
  221816. if (evt->xselection.property != 0)
  221817. {
  221818. StringArray lines;
  221819. {
  221820. MemoryBlock dropData;
  221821. for (;;)
  221822. {
  221823. Atom actual;
  221824. uint8* data = 0;
  221825. unsigned long count = 0, remaining = 0;
  221826. int format = 0;
  221827. ScopedXLock xlock;
  221828. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221829. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221830. &format, &count, &remaining, &data) == Success)
  221831. {
  221832. dropData.append (data, count * format / 8);
  221833. XFree (data);
  221834. if (remaining == 0)
  221835. break;
  221836. }
  221837. else
  221838. {
  221839. XFree (data);
  221840. break;
  221841. }
  221842. }
  221843. lines.addLines (dropData.toString());
  221844. }
  221845. for (int i = 0; i < lines.size(); ++i)
  221846. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221847. dragAndDropFiles.trim();
  221848. dragAndDropFiles.removeEmptyStrings();
  221849. }
  221850. }
  221851. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221852. {
  221853. dragAndDropFiles.clear();
  221854. if (dragAndDropSourceWindow != None
  221855. && dragAndDropCurrentMimeType != 0)
  221856. {
  221857. dragAndDropTimestamp = clientMsg->data.l[2];
  221858. ScopedXLock xlock;
  221859. XConvertSelection (display,
  221860. Atoms::XdndSelection,
  221861. dragAndDropCurrentMimeType,
  221862. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221863. windowH,
  221864. dragAndDropTimestamp);
  221865. }
  221866. }
  221867. StringArray dragAndDropFiles;
  221868. int dragAndDropTimestamp;
  221869. Point<int> lastDropPos;
  221870. Atom dragAndDropCurrentMimeType;
  221871. Window dragAndDropSourceWindow;
  221872. Array <Atom> srcMimeTypeAtomList;
  221873. static int pointerMap[5];
  221874. static Point<int> lastMousePos;
  221875. static void clearLastMousePos() throw()
  221876. {
  221877. lastMousePos = Point<int> (0x100000, 0x100000);
  221878. }
  221879. };
  221880. ModifierKeys LinuxComponentPeer::currentModifiers;
  221881. bool LinuxComponentPeer::isActiveApplication = false;
  221882. int LinuxComponentPeer::pointerMap[5];
  221883. Point<int> LinuxComponentPeer::lastMousePos;
  221884. bool Process::isForegroundProcess()
  221885. {
  221886. return LinuxComponentPeer::isActiveApplication;
  221887. }
  221888. void ModifierKeys::updateCurrentModifiers() throw()
  221889. {
  221890. currentModifiers = LinuxComponentPeer::currentModifiers;
  221891. }
  221892. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221893. {
  221894. Window root, child;
  221895. int x, y, winx, winy;
  221896. unsigned int mask;
  221897. int mouseMods = 0;
  221898. ScopedXLock xlock;
  221899. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221900. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221901. {
  221902. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221903. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221904. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221905. }
  221906. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221907. return LinuxComponentPeer::currentModifiers;
  221908. }
  221909. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221910. {
  221911. if (enableOrDisable)
  221912. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221913. }
  221914. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221915. {
  221916. return new LinuxComponentPeer (this, styleFlags);
  221917. }
  221918. // (this callback is hooked up in the messaging code)
  221919. void juce_windowMessageReceive (XEvent* event)
  221920. {
  221921. if (event->xany.window != None)
  221922. {
  221923. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221924. if (ComponentPeer::isValidPeer (peer))
  221925. peer->handleWindowMessage (event);
  221926. }
  221927. else
  221928. {
  221929. switch (event->xany.type)
  221930. {
  221931. case KeymapNotify:
  221932. {
  221933. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221934. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221935. break;
  221936. }
  221937. default:
  221938. break;
  221939. }
  221940. }
  221941. }
  221942. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221943. {
  221944. if (display == 0)
  221945. return;
  221946. #if JUCE_USE_XINERAMA
  221947. int major_opcode, first_event, first_error;
  221948. ScopedXLock xlock;
  221949. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221950. {
  221951. typedef Bool (*tXineramaIsActive) (Display*);
  221952. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221953. static tXineramaIsActive xXineramaIsActive = 0;
  221954. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221955. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221956. {
  221957. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221958. if (h == 0)
  221959. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221960. if (h != 0)
  221961. {
  221962. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221963. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221964. }
  221965. }
  221966. if (xXineramaIsActive != 0
  221967. && xXineramaQueryScreens != 0
  221968. && xXineramaIsActive (display))
  221969. {
  221970. int numMonitors = 0;
  221971. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221972. if (screens != 0)
  221973. {
  221974. for (int i = numMonitors; --i >= 0;)
  221975. {
  221976. int index = screens[i].screen_number;
  221977. if (index >= 0)
  221978. {
  221979. while (monitorCoords.size() < index)
  221980. monitorCoords.add (Rectangle<int>());
  221981. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221982. screens[i].y_org,
  221983. screens[i].width,
  221984. screens[i].height));
  221985. }
  221986. }
  221987. XFree (screens);
  221988. }
  221989. }
  221990. }
  221991. if (monitorCoords.size() == 0)
  221992. #endif
  221993. {
  221994. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221995. if (hints != None)
  221996. {
  221997. const int numMonitors = ScreenCount (display);
  221998. for (int i = 0; i < numMonitors; ++i)
  221999. {
  222000. Window root = RootWindow (display, i);
  222001. unsigned long nitems, bytesLeft;
  222002. Atom actualType;
  222003. int actualFormat;
  222004. unsigned char* data = 0;
  222005. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  222006. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  222007. &data) == Success)
  222008. {
  222009. const long* const position = (const long*) data;
  222010. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  222011. monitorCoords.add (Rectangle<int> (position[0], position[1],
  222012. position[2], position[3]));
  222013. XFree (data);
  222014. }
  222015. }
  222016. }
  222017. if (monitorCoords.size() == 0)
  222018. {
  222019. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  222020. DisplayHeight (display, DefaultScreen (display))));
  222021. }
  222022. }
  222023. }
  222024. void Desktop::createMouseInputSources()
  222025. {
  222026. mouseSources.add (new MouseInputSource (0, true));
  222027. }
  222028. bool Desktop::canUseSemiTransparentWindows() throw()
  222029. {
  222030. int matchedDepth = 0;
  222031. const int desiredDepth = 32;
  222032. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  222033. && (matchedDepth == desiredDepth);
  222034. }
  222035. const Point<int> Desktop::getMousePosition()
  222036. {
  222037. Window root, child;
  222038. int x, y, winx, winy;
  222039. unsigned int mask;
  222040. ScopedXLock xlock;
  222041. if (XQueryPointer (display,
  222042. RootWindow (display, DefaultScreen (display)),
  222043. &root, &child,
  222044. &x, &y, &winx, &winy, &mask) == False)
  222045. {
  222046. // Pointer not on the default screen
  222047. x = y = -1;
  222048. }
  222049. return Point<int> (x, y);
  222050. }
  222051. void Desktop::setMousePosition (const Point<int>& newPosition)
  222052. {
  222053. ScopedXLock xlock;
  222054. Window root = RootWindow (display, DefaultScreen (display));
  222055. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  222056. }
  222057. static bool screenSaverAllowed = true;
  222058. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  222059. {
  222060. if (screenSaverAllowed != isEnabled)
  222061. {
  222062. screenSaverAllowed = isEnabled;
  222063. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  222064. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  222065. if (xScreenSaverSuspend == 0)
  222066. {
  222067. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  222068. if (h != 0)
  222069. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  222070. }
  222071. ScopedXLock xlock;
  222072. if (xScreenSaverSuspend != 0)
  222073. xScreenSaverSuspend (display, ! isEnabled);
  222074. }
  222075. }
  222076. bool Desktop::isScreenSaverEnabled()
  222077. {
  222078. return screenSaverAllowed;
  222079. }
  222080. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  222081. {
  222082. ScopedXLock xlock;
  222083. const unsigned int imageW = image.getWidth();
  222084. const unsigned int imageH = image.getHeight();
  222085. #if JUCE_USE_XCURSOR
  222086. {
  222087. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  222088. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  222089. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  222090. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  222091. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  222092. static tXcursorImageCreate xXcursorImageCreate = 0;
  222093. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  222094. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  222095. static bool hasBeenLoaded = false;
  222096. if (! hasBeenLoaded)
  222097. {
  222098. hasBeenLoaded = true;
  222099. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  222100. if (h != 0)
  222101. {
  222102. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  222103. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  222104. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  222105. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  222106. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  222107. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  222108. || ! xXcursorSupportsARGB (display))
  222109. xXcursorSupportsARGB = 0;
  222110. }
  222111. }
  222112. if (xXcursorSupportsARGB != 0)
  222113. {
  222114. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  222115. if (xcImage != 0)
  222116. {
  222117. xcImage->xhot = hotspotX;
  222118. xcImage->yhot = hotspotY;
  222119. XcursorPixel* dest = xcImage->pixels;
  222120. for (int y = 0; y < (int) imageH; ++y)
  222121. for (int x = 0; x < (int) imageW; ++x)
  222122. *dest++ = image.getPixelAt (x, y).getARGB();
  222123. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  222124. xXcursorImageDestroy (xcImage);
  222125. if (result != 0)
  222126. return result;
  222127. }
  222128. }
  222129. }
  222130. #endif
  222131. Window root = RootWindow (display, DefaultScreen (display));
  222132. unsigned int cursorW, cursorH;
  222133. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  222134. return 0;
  222135. Image im (Image::ARGB, cursorW, cursorH, true);
  222136. {
  222137. Graphics g (im);
  222138. if (imageW > cursorW || imageH > cursorH)
  222139. {
  222140. hotspotX = (hotspotX * cursorW) / imageW;
  222141. hotspotY = (hotspotY * cursorH) / imageH;
  222142. g.drawImageWithin (image, 0, 0, imageW, imageH,
  222143. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222144. false);
  222145. }
  222146. else
  222147. {
  222148. g.drawImageAt (image, 0, 0);
  222149. }
  222150. }
  222151. const int stride = (cursorW + 7) >> 3;
  222152. HeapBlock <char> maskPlane, sourcePlane;
  222153. maskPlane.calloc (stride * cursorH);
  222154. sourcePlane.calloc (stride * cursorH);
  222155. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  222156. for (int y = cursorH; --y >= 0;)
  222157. {
  222158. for (int x = cursorW; --x >= 0;)
  222159. {
  222160. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  222161. const int offset = y * stride + (x >> 3);
  222162. const Colour c (im.getPixelAt (x, y));
  222163. if (c.getAlpha() >= 128)
  222164. maskPlane[offset] |= mask;
  222165. if (c.getBrightness() >= 0.5f)
  222166. sourcePlane[offset] |= mask;
  222167. }
  222168. }
  222169. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222170. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222171. XColor white, black;
  222172. black.red = black.green = black.blue = 0;
  222173. white.red = white.green = white.blue = 0xffff;
  222174. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  222175. XFreePixmap (display, sourcePixmap);
  222176. XFreePixmap (display, maskPixmap);
  222177. return result;
  222178. }
  222179. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  222180. {
  222181. ScopedXLock xlock;
  222182. if (cursorHandle != 0)
  222183. XFreeCursor (display, (Cursor) cursorHandle);
  222184. }
  222185. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  222186. {
  222187. unsigned int shape;
  222188. switch (type)
  222189. {
  222190. case NormalCursor: return None; // Use parent cursor
  222191. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  222192. case WaitCursor: shape = XC_watch; break;
  222193. case IBeamCursor: shape = XC_xterm; break;
  222194. case PointingHandCursor: shape = XC_hand2; break;
  222195. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  222196. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  222197. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  222198. case TopEdgeResizeCursor: shape = XC_top_side; break;
  222199. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  222200. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  222201. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222202. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222203. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222204. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222205. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222206. case CrosshairCursor: shape = XC_crosshair; break;
  222207. case DraggingHandCursor:
  222208. {
  222209. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222210. 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,
  222211. 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 };
  222212. const int dragHandDataSize = 99;
  222213. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222214. }
  222215. case CopyingCursor:
  222216. {
  222217. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222218. 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,
  222219. 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,
  222220. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222221. const int copyCursorSize = 119;
  222222. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222223. }
  222224. default:
  222225. jassertfalse;
  222226. return None;
  222227. }
  222228. ScopedXLock xlock;
  222229. return (void*) XCreateFontCursor (display, shape);
  222230. }
  222231. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222232. {
  222233. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222234. if (lp != 0)
  222235. lp->showMouseCursor ((Cursor) getHandle());
  222236. }
  222237. void MouseCursor::showInAllWindows() const
  222238. {
  222239. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222240. showInWindow (ComponentPeer::getPeer (i));
  222241. }
  222242. const Image juce_createIconForFile (const File& file)
  222243. {
  222244. return Image::null;
  222245. }
  222246. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222247. {
  222248. return createSoftwareImage (format, width, height, clearImage);
  222249. }
  222250. #if JUCE_OPENGL
  222251. class WindowedGLContext : public OpenGLContext
  222252. {
  222253. public:
  222254. WindowedGLContext (Component* const component,
  222255. const OpenGLPixelFormat& pixelFormat_,
  222256. GLXContext sharedContext)
  222257. : renderContext (0),
  222258. embeddedWindow (0),
  222259. pixelFormat (pixelFormat_),
  222260. swapInterval (0)
  222261. {
  222262. jassert (component != 0);
  222263. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222264. if (peer == 0)
  222265. return;
  222266. ScopedXLock xlock;
  222267. XSync (display, False);
  222268. GLint attribs [64];
  222269. int n = 0;
  222270. attribs[n++] = GLX_RGBA;
  222271. attribs[n++] = GLX_DOUBLEBUFFER;
  222272. attribs[n++] = GLX_RED_SIZE;
  222273. attribs[n++] = pixelFormat.redBits;
  222274. attribs[n++] = GLX_GREEN_SIZE;
  222275. attribs[n++] = pixelFormat.greenBits;
  222276. attribs[n++] = GLX_BLUE_SIZE;
  222277. attribs[n++] = pixelFormat.blueBits;
  222278. attribs[n++] = GLX_ALPHA_SIZE;
  222279. attribs[n++] = pixelFormat.alphaBits;
  222280. attribs[n++] = GLX_DEPTH_SIZE;
  222281. attribs[n++] = pixelFormat.depthBufferBits;
  222282. attribs[n++] = GLX_STENCIL_SIZE;
  222283. attribs[n++] = pixelFormat.stencilBufferBits;
  222284. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222285. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222286. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222287. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222288. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222289. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222290. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222291. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222292. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222293. attribs[n++] = None;
  222294. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222295. if (bestVisual == 0)
  222296. return;
  222297. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222298. Window windowH = (Window) peer->getNativeHandle();
  222299. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222300. XSetWindowAttributes swa;
  222301. swa.colormap = colourMap;
  222302. swa.border_pixel = 0;
  222303. swa.event_mask = ExposureMask | StructureNotifyMask;
  222304. embeddedWindow = XCreateWindow (display, windowH,
  222305. 0, 0, 1, 1, 0,
  222306. bestVisual->depth,
  222307. InputOutput,
  222308. bestVisual->visual,
  222309. CWBorderPixel | CWColormap | CWEventMask,
  222310. &swa);
  222311. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222312. XMapWindow (display, embeddedWindow);
  222313. XFreeColormap (display, colourMap);
  222314. XFree (bestVisual);
  222315. XSync (display, False);
  222316. }
  222317. ~WindowedGLContext()
  222318. {
  222319. ScopedXLock xlock;
  222320. deleteContext();
  222321. XUnmapWindow (display, embeddedWindow);
  222322. XDestroyWindow (display, embeddedWindow);
  222323. }
  222324. void deleteContext()
  222325. {
  222326. makeInactive();
  222327. if (renderContext != 0)
  222328. {
  222329. ScopedXLock xlock;
  222330. glXDestroyContext (display, renderContext);
  222331. renderContext = 0;
  222332. }
  222333. }
  222334. bool makeActive() const throw()
  222335. {
  222336. jassert (renderContext != 0);
  222337. ScopedXLock xlock;
  222338. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222339. && XSync (display, False);
  222340. }
  222341. bool makeInactive() const throw()
  222342. {
  222343. ScopedXLock xlock;
  222344. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222345. }
  222346. bool isActive() const throw()
  222347. {
  222348. ScopedXLock xlock;
  222349. return glXGetCurrentContext() == renderContext;
  222350. }
  222351. const OpenGLPixelFormat getPixelFormat() const
  222352. {
  222353. return pixelFormat;
  222354. }
  222355. void* getRawContext() const throw()
  222356. {
  222357. return renderContext;
  222358. }
  222359. void updateWindowPosition (int x, int y, int w, int h, int)
  222360. {
  222361. ScopedXLock xlock;
  222362. XMoveResizeWindow (display, embeddedWindow,
  222363. x, y, jmax (1, w), jmax (1, h));
  222364. }
  222365. void swapBuffers()
  222366. {
  222367. ScopedXLock xlock;
  222368. glXSwapBuffers (display, embeddedWindow);
  222369. }
  222370. bool setSwapInterval (const int numFramesPerSwap)
  222371. {
  222372. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222373. if (GLXSwapIntervalSGI != 0)
  222374. {
  222375. swapInterval = numFramesPerSwap;
  222376. GLXSwapIntervalSGI (numFramesPerSwap);
  222377. return true;
  222378. }
  222379. return false;
  222380. }
  222381. int getSwapInterval() const
  222382. {
  222383. return swapInterval;
  222384. }
  222385. void repaint()
  222386. {
  222387. }
  222388. juce_UseDebuggingNewOperator
  222389. GLXContext renderContext;
  222390. private:
  222391. Window embeddedWindow;
  222392. OpenGLPixelFormat pixelFormat;
  222393. int swapInterval;
  222394. WindowedGLContext (const WindowedGLContext&);
  222395. WindowedGLContext& operator= (const WindowedGLContext&);
  222396. };
  222397. OpenGLContext* OpenGLComponent::createContext()
  222398. {
  222399. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222400. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222401. return (c->renderContext != 0) ? c.release() : 0;
  222402. }
  222403. void juce_glViewport (const int w, const int h)
  222404. {
  222405. glViewport (0, 0, w, h);
  222406. }
  222407. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222408. OwnedArray <OpenGLPixelFormat>& results)
  222409. {
  222410. results.add (new OpenGLPixelFormat()); // xxx
  222411. }
  222412. #endif
  222413. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222414. {
  222415. jassertfalse; // not implemented!
  222416. return false;
  222417. }
  222418. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222419. {
  222420. jassertfalse; // not implemented!
  222421. return false;
  222422. }
  222423. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222424. {
  222425. if (! isOnDesktop ())
  222426. addToDesktop (0);
  222427. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222428. if (wp != 0)
  222429. {
  222430. wp->setTaskBarIcon (newImage);
  222431. setVisible (true);
  222432. toFront (false);
  222433. repaint();
  222434. }
  222435. }
  222436. void SystemTrayIconComponent::paint (Graphics& g)
  222437. {
  222438. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222439. if (wp != 0)
  222440. {
  222441. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222442. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222443. false);
  222444. }
  222445. }
  222446. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222447. {
  222448. // xxx not yet implemented!
  222449. }
  222450. void PlatformUtilities::beep()
  222451. {
  222452. std::cout << "\a" << std::flush;
  222453. }
  222454. bool AlertWindow::showNativeDialogBox (const String& title,
  222455. const String& bodyText,
  222456. bool isOkCancel)
  222457. {
  222458. // use a non-native one for the time being..
  222459. if (isOkCancel)
  222460. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222461. else
  222462. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222463. return true;
  222464. }
  222465. const int KeyPress::spaceKey = XK_space & 0xff;
  222466. const int KeyPress::returnKey = XK_Return & 0xff;
  222467. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222468. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222469. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222470. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222471. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222472. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222473. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222474. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222475. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222476. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222477. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222478. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222479. const int KeyPress::tabKey = XK_Tab & 0xff;
  222480. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222481. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222482. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222483. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222484. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222485. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222486. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222487. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222488. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222489. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222490. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222491. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222492. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222493. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222494. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222495. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222496. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222497. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222498. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222499. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222500. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222501. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222502. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222503. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222504. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222505. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222506. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222507. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222508. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222509. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222510. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222511. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222512. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222513. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222514. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222515. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222516. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222517. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222518. #endif
  222519. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222520. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222521. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222522. // compiled on its own).
  222523. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222524. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222525. {
  222526. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222527. snd_pcm_hw_params_t* hwParams;
  222528. snd_pcm_hw_params_alloca (&hwParams);
  222529. for (int i = 0; ratesToTry[i] != 0; ++i)
  222530. {
  222531. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222532. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222533. {
  222534. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222535. }
  222536. }
  222537. }
  222538. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222539. {
  222540. snd_pcm_hw_params_t *params;
  222541. snd_pcm_hw_params_alloca (&params);
  222542. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222543. {
  222544. snd_pcm_hw_params_get_channels_min (params, minChans);
  222545. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222546. }
  222547. }
  222548. static void getDeviceProperties (const String& deviceID,
  222549. unsigned int& minChansOut,
  222550. unsigned int& maxChansOut,
  222551. unsigned int& minChansIn,
  222552. unsigned int& maxChansIn,
  222553. Array <int>& rates)
  222554. {
  222555. if (deviceID.isEmpty())
  222556. return;
  222557. snd_ctl_t* handle;
  222558. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222559. {
  222560. snd_pcm_info_t* info;
  222561. snd_pcm_info_alloca (&info);
  222562. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222563. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222564. snd_pcm_info_set_subdevice (info, 0);
  222565. if (snd_ctl_pcm_info (handle, info) >= 0)
  222566. {
  222567. snd_pcm_t* pcmHandle;
  222568. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  222569. {
  222570. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222571. getDeviceSampleRates (pcmHandle, rates);
  222572. snd_pcm_close (pcmHandle);
  222573. }
  222574. }
  222575. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222576. if (snd_ctl_pcm_info (handle, info) >= 0)
  222577. {
  222578. snd_pcm_t* pcmHandle;
  222579. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  222580. {
  222581. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222582. if (rates.size() == 0)
  222583. getDeviceSampleRates (pcmHandle, rates);
  222584. snd_pcm_close (pcmHandle);
  222585. }
  222586. }
  222587. snd_ctl_close (handle);
  222588. }
  222589. }
  222590. class ALSADevice
  222591. {
  222592. public:
  222593. ALSADevice (const String& deviceID,
  222594. const bool forInput)
  222595. : handle (0),
  222596. bitDepth (16),
  222597. numChannelsRunning (0),
  222598. latency (0),
  222599. isInput (forInput),
  222600. sampleFormat (AudioDataConverters::int16LE)
  222601. {
  222602. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222603. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222604. SND_PCM_ASYNC));
  222605. }
  222606. ~ALSADevice()
  222607. {
  222608. if (handle != 0)
  222609. snd_pcm_close (handle);
  222610. }
  222611. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222612. {
  222613. if (handle == 0)
  222614. return false;
  222615. snd_pcm_hw_params_t* hwParams;
  222616. snd_pcm_hw_params_alloca (&hwParams);
  222617. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222618. return false;
  222619. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222620. isInterleaved = false;
  222621. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222622. isInterleaved = true;
  222623. else
  222624. {
  222625. jassertfalse;
  222626. return false;
  222627. }
  222628. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  222629. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  222630. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  222631. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  222632. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  222633. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  222634. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  222635. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  222636. bitDepth = 0;
  222637. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  222638. {
  222639. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222640. {
  222641. bitDepth = formatsToTry [i + 1];
  222642. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  222643. break;
  222644. }
  222645. }
  222646. if (bitDepth == 0)
  222647. {
  222648. error = "device doesn't support a compatible PCM format";
  222649. DBG ("ALSA error: " + error + "\n");
  222650. return false;
  222651. }
  222652. int dir = 0;
  222653. unsigned int periods = 4;
  222654. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222655. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222656. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222657. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222658. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222659. || failed (snd_pcm_hw_params (handle, hwParams)))
  222660. {
  222661. return false;
  222662. }
  222663. snd_pcm_uframes_t frames = 0;
  222664. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222665. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222666. latency = 0;
  222667. else
  222668. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222669. snd_pcm_sw_params_t* swParams;
  222670. snd_pcm_sw_params_alloca (&swParams);
  222671. snd_pcm_uframes_t boundary;
  222672. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222673. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222674. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222675. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222676. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222677. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222678. || failed (snd_pcm_sw_params (handle, swParams)))
  222679. {
  222680. return false;
  222681. }
  222682. /*
  222683. #if JUCE_DEBUG
  222684. // enable this to dump the config of the devices that get opened
  222685. snd_output_t* out;
  222686. snd_output_stdio_attach (&out, stderr, 0);
  222687. snd_pcm_hw_params_dump (hwParams, out);
  222688. snd_pcm_sw_params_dump (swParams, out);
  222689. #endif
  222690. */
  222691. numChannelsRunning = numChannels;
  222692. return true;
  222693. }
  222694. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222695. {
  222696. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222697. float** const data = outputChannelBuffer.getArrayOfChannels();
  222698. if (isInterleaved)
  222699. {
  222700. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222701. float* interleaved = static_cast <float*> (scratch.getData());
  222702. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  222703. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  222704. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  222705. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222706. return false;
  222707. }
  222708. else
  222709. {
  222710. for (int i = 0; i < numChannelsRunning; ++i)
  222711. if (data[i] != 0)
  222712. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  222713. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  222714. if (failed (num))
  222715. {
  222716. if (num == -EPIPE)
  222717. {
  222718. if (failed (snd_pcm_prepare (handle)))
  222719. return false;
  222720. }
  222721. else if (num != -ESTRPIPE)
  222722. return false;
  222723. }
  222724. }
  222725. return true;
  222726. }
  222727. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222728. {
  222729. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222730. float** const data = inputChannelBuffer.getArrayOfChannels();
  222731. if (isInterleaved)
  222732. {
  222733. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222734. float* interleaved = static_cast <float*> (scratch.getData());
  222735. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  222736. if (failed (num))
  222737. {
  222738. if (num == -EPIPE)
  222739. {
  222740. if (failed (snd_pcm_prepare (handle)))
  222741. return false;
  222742. }
  222743. else if (num != -ESTRPIPE)
  222744. return false;
  222745. }
  222746. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  222747. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  222748. }
  222749. else
  222750. {
  222751. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222752. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222753. return false;
  222754. for (int i = 0; i < numChannelsRunning; ++i)
  222755. if (data[i] != 0)
  222756. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  222757. }
  222758. return true;
  222759. }
  222760. juce_UseDebuggingNewOperator
  222761. snd_pcm_t* handle;
  222762. String error;
  222763. int bitDepth, numChannelsRunning, latency;
  222764. private:
  222765. const bool isInput;
  222766. bool isInterleaved;
  222767. MemoryBlock scratch;
  222768. AudioDataConverters::DataFormat sampleFormat;
  222769. bool failed (const int errorNum)
  222770. {
  222771. if (errorNum >= 0)
  222772. return false;
  222773. error = snd_strerror (errorNum);
  222774. DBG ("ALSA error: " + error + "\n");
  222775. return true;
  222776. }
  222777. };
  222778. class ALSAThread : public Thread
  222779. {
  222780. public:
  222781. ALSAThread (const String& inputId_,
  222782. const String& outputId_)
  222783. : Thread ("Juce ALSA"),
  222784. sampleRate (0),
  222785. bufferSize (0),
  222786. outputLatency (0),
  222787. inputLatency (0),
  222788. callback (0),
  222789. inputId (inputId_),
  222790. outputId (outputId_),
  222791. numCallbacks (0),
  222792. inputChannelBuffer (1, 1),
  222793. outputChannelBuffer (1, 1)
  222794. {
  222795. initialiseRatesAndChannels();
  222796. }
  222797. ~ALSAThread()
  222798. {
  222799. close();
  222800. }
  222801. void open (BigInteger inputChannels,
  222802. BigInteger outputChannels,
  222803. const double sampleRate_,
  222804. const int bufferSize_)
  222805. {
  222806. close();
  222807. error = String::empty;
  222808. sampleRate = sampleRate_;
  222809. bufferSize = bufferSize_;
  222810. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222811. inputChannelBuffer.clear();
  222812. inputChannelDataForCallback.clear();
  222813. currentInputChans.clear();
  222814. if (inputChannels.getHighestBit() >= 0)
  222815. {
  222816. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222817. {
  222818. if (inputChannels[i])
  222819. {
  222820. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222821. currentInputChans.setBit (i);
  222822. }
  222823. }
  222824. }
  222825. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222826. outputChannelBuffer.clear();
  222827. outputChannelDataForCallback.clear();
  222828. currentOutputChans.clear();
  222829. if (outputChannels.getHighestBit() >= 0)
  222830. {
  222831. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222832. {
  222833. if (outputChannels[i])
  222834. {
  222835. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222836. currentOutputChans.setBit (i);
  222837. }
  222838. }
  222839. }
  222840. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222841. {
  222842. outputDevice = new ALSADevice (outputId, false);
  222843. if (outputDevice->error.isNotEmpty())
  222844. {
  222845. error = outputDevice->error;
  222846. outputDevice = 0;
  222847. return;
  222848. }
  222849. currentOutputChans.setRange (0, minChansOut, true);
  222850. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222851. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222852. bufferSize))
  222853. {
  222854. error = outputDevice->error;
  222855. outputDevice = 0;
  222856. return;
  222857. }
  222858. outputLatency = outputDevice->latency;
  222859. }
  222860. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222861. {
  222862. inputDevice = new ALSADevice (inputId, true);
  222863. if (inputDevice->error.isNotEmpty())
  222864. {
  222865. error = inputDevice->error;
  222866. inputDevice = 0;
  222867. return;
  222868. }
  222869. currentInputChans.setRange (0, minChansIn, true);
  222870. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222871. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222872. bufferSize))
  222873. {
  222874. error = inputDevice->error;
  222875. inputDevice = 0;
  222876. return;
  222877. }
  222878. inputLatency = inputDevice->latency;
  222879. }
  222880. if (outputDevice == 0 && inputDevice == 0)
  222881. {
  222882. error = "no channels";
  222883. return;
  222884. }
  222885. if (outputDevice != 0 && inputDevice != 0)
  222886. {
  222887. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222888. }
  222889. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222890. return;
  222891. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222892. return;
  222893. startThread (9);
  222894. int count = 1000;
  222895. while (numCallbacks == 0)
  222896. {
  222897. sleep (5);
  222898. if (--count < 0 || ! isThreadRunning())
  222899. {
  222900. error = "device didn't start";
  222901. break;
  222902. }
  222903. }
  222904. }
  222905. void close()
  222906. {
  222907. stopThread (6000);
  222908. inputDevice = 0;
  222909. outputDevice = 0;
  222910. inputChannelBuffer.setSize (1, 1);
  222911. outputChannelBuffer.setSize (1, 1);
  222912. numCallbacks = 0;
  222913. }
  222914. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222915. {
  222916. const ScopedLock sl (callbackLock);
  222917. callback = newCallback;
  222918. }
  222919. void run()
  222920. {
  222921. while (! threadShouldExit())
  222922. {
  222923. if (inputDevice != 0)
  222924. {
  222925. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  222926. {
  222927. DBG ("ALSA: read failure");
  222928. break;
  222929. }
  222930. }
  222931. if (threadShouldExit())
  222932. break;
  222933. {
  222934. const ScopedLock sl (callbackLock);
  222935. ++numCallbacks;
  222936. if (callback != 0)
  222937. {
  222938. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222939. inputChannelDataForCallback.size(),
  222940. outputChannelDataForCallback.getRawDataPointer(),
  222941. outputChannelDataForCallback.size(),
  222942. bufferSize);
  222943. }
  222944. else
  222945. {
  222946. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222947. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222948. }
  222949. }
  222950. if (outputDevice != 0)
  222951. {
  222952. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222953. if (threadShouldExit())
  222954. break;
  222955. failed (snd_pcm_avail_update (outputDevice->handle));
  222956. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  222957. {
  222958. DBG ("ALSA: write failure");
  222959. break;
  222960. }
  222961. }
  222962. }
  222963. }
  222964. int getBitDepth() const throw()
  222965. {
  222966. if (outputDevice != 0)
  222967. return outputDevice->bitDepth;
  222968. if (inputDevice != 0)
  222969. return inputDevice->bitDepth;
  222970. return 16;
  222971. }
  222972. juce_UseDebuggingNewOperator
  222973. String error;
  222974. double sampleRate;
  222975. int bufferSize, outputLatency, inputLatency;
  222976. BigInteger currentInputChans, currentOutputChans;
  222977. Array <int> sampleRates;
  222978. StringArray channelNamesOut, channelNamesIn;
  222979. AudioIODeviceCallback* callback;
  222980. private:
  222981. const String inputId, outputId;
  222982. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222983. int numCallbacks;
  222984. CriticalSection callbackLock;
  222985. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222986. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222987. unsigned int minChansOut, maxChansOut;
  222988. unsigned int minChansIn, maxChansIn;
  222989. bool failed (const int errorNum)
  222990. {
  222991. if (errorNum >= 0)
  222992. return false;
  222993. error = snd_strerror (errorNum);
  222994. DBG ("ALSA error: " + error + "\n");
  222995. return true;
  222996. }
  222997. void initialiseRatesAndChannels()
  222998. {
  222999. sampleRates.clear();
  223000. channelNamesOut.clear();
  223001. channelNamesIn.clear();
  223002. minChansOut = 0;
  223003. maxChansOut = 0;
  223004. minChansIn = 0;
  223005. maxChansIn = 0;
  223006. unsigned int dummy = 0;
  223007. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  223008. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  223009. unsigned int i;
  223010. for (i = 0; i < maxChansOut; ++i)
  223011. channelNamesOut.add ("channel " + String ((int) i + 1));
  223012. for (i = 0; i < maxChansIn; ++i)
  223013. channelNamesIn.add ("channel " + String ((int) i + 1));
  223014. }
  223015. };
  223016. class ALSAAudioIODevice : public AudioIODevice
  223017. {
  223018. public:
  223019. ALSAAudioIODevice (const String& deviceName,
  223020. const String& inputId_,
  223021. const String& outputId_)
  223022. : AudioIODevice (deviceName, "ALSA"),
  223023. inputId (inputId_),
  223024. outputId (outputId_),
  223025. isOpen_ (false),
  223026. isStarted (false),
  223027. internal (inputId_, outputId_)
  223028. {
  223029. }
  223030. ~ALSAAudioIODevice()
  223031. {
  223032. }
  223033. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  223034. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  223035. int getNumSampleRates() { return internal.sampleRates.size(); }
  223036. double getSampleRate (int index) { return internal.sampleRates [index]; }
  223037. int getDefaultBufferSize() { return 512; }
  223038. int getNumBufferSizesAvailable() { return 50; }
  223039. int getBufferSizeSamples (int index)
  223040. {
  223041. int n = 16;
  223042. for (int i = 0; i < index; ++i)
  223043. n += n < 64 ? 16
  223044. : (n < 512 ? 32
  223045. : (n < 1024 ? 64
  223046. : (n < 2048 ? 128 : 256)));
  223047. return n;
  223048. }
  223049. const String open (const BigInteger& inputChannels,
  223050. const BigInteger& outputChannels,
  223051. double sampleRate,
  223052. int bufferSizeSamples)
  223053. {
  223054. close();
  223055. if (bufferSizeSamples <= 0)
  223056. bufferSizeSamples = getDefaultBufferSize();
  223057. if (sampleRate <= 0)
  223058. {
  223059. for (int i = 0; i < getNumSampleRates(); ++i)
  223060. {
  223061. if (getSampleRate (i) >= 44100)
  223062. {
  223063. sampleRate = getSampleRate (i);
  223064. break;
  223065. }
  223066. }
  223067. }
  223068. internal.open (inputChannels, outputChannels,
  223069. sampleRate, bufferSizeSamples);
  223070. isOpen_ = internal.error.isEmpty();
  223071. return internal.error;
  223072. }
  223073. void close()
  223074. {
  223075. stop();
  223076. internal.close();
  223077. isOpen_ = false;
  223078. }
  223079. bool isOpen() { return isOpen_; }
  223080. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  223081. const String getLastError() { return internal.error; }
  223082. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  223083. double getCurrentSampleRate() { return internal.sampleRate; }
  223084. int getCurrentBitDepth() { return internal.getBitDepth(); }
  223085. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  223086. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  223087. int getOutputLatencyInSamples() { return internal.outputLatency; }
  223088. int getInputLatencyInSamples() { return internal.inputLatency; }
  223089. void start (AudioIODeviceCallback* callback)
  223090. {
  223091. if (! isOpen_)
  223092. callback = 0;
  223093. if (callback != 0)
  223094. callback->audioDeviceAboutToStart (this);
  223095. internal.setCallback (callback);
  223096. isStarted = (callback != 0);
  223097. }
  223098. void stop()
  223099. {
  223100. AudioIODeviceCallback* const oldCallback = internal.callback;
  223101. start (0);
  223102. if (oldCallback != 0)
  223103. oldCallback->audioDeviceStopped();
  223104. }
  223105. String inputId, outputId;
  223106. private:
  223107. bool isOpen_, isStarted;
  223108. ALSAThread internal;
  223109. };
  223110. class ALSAAudioIODeviceType : public AudioIODeviceType
  223111. {
  223112. public:
  223113. ALSAAudioIODeviceType()
  223114. : AudioIODeviceType ("ALSA"),
  223115. hasScanned (false)
  223116. {
  223117. }
  223118. ~ALSAAudioIODeviceType()
  223119. {
  223120. }
  223121. void scanForDevices()
  223122. {
  223123. if (hasScanned)
  223124. return;
  223125. hasScanned = true;
  223126. inputNames.clear();
  223127. inputIds.clear();
  223128. outputNames.clear();
  223129. outputIds.clear();
  223130. /* void** hints = 0;
  223131. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  223132. {
  223133. for (void** hint = hints; *hint != 0; ++hint)
  223134. {
  223135. const String name (getHint (*hint, "NAME"));
  223136. if (name.isNotEmpty())
  223137. {
  223138. const String ioid (getHint (*hint, "IOID"));
  223139. String desc (getHint (*hint, "DESC"));
  223140. if (desc.isEmpty())
  223141. desc = name;
  223142. desc = desc.replaceCharacters ("\n\r", " ");
  223143. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  223144. if (ioid.isEmpty() || ioid == "Input")
  223145. {
  223146. inputNames.add (desc);
  223147. inputIds.add (name);
  223148. }
  223149. if (ioid.isEmpty() || ioid == "Output")
  223150. {
  223151. outputNames.add (desc);
  223152. outputIds.add (name);
  223153. }
  223154. }
  223155. }
  223156. snd_device_name_free_hint (hints);
  223157. }
  223158. */
  223159. snd_ctl_t* handle = 0;
  223160. snd_ctl_card_info_t* info = 0;
  223161. snd_ctl_card_info_alloca (&info);
  223162. int cardNum = -1;
  223163. while (outputIds.size() + inputIds.size() <= 32)
  223164. {
  223165. snd_card_next (&cardNum);
  223166. if (cardNum < 0)
  223167. break;
  223168. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  223169. {
  223170. if (snd_ctl_card_info (handle, info) >= 0)
  223171. {
  223172. String cardId (snd_ctl_card_info_get_id (info));
  223173. if (cardId.removeCharacters ("0123456789").isEmpty())
  223174. cardId = String (cardNum);
  223175. int device = -1;
  223176. for (;;)
  223177. {
  223178. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223179. break;
  223180. String id, name;
  223181. id << "hw:" << cardId << ',' << device;
  223182. bool isInput, isOutput;
  223183. if (testDevice (id, isInput, isOutput))
  223184. {
  223185. name << snd_ctl_card_info_get_name (info);
  223186. if (name.isEmpty())
  223187. name = id;
  223188. if (isInput)
  223189. {
  223190. inputNames.add (name);
  223191. inputIds.add (id);
  223192. }
  223193. if (isOutput)
  223194. {
  223195. outputNames.add (name);
  223196. outputIds.add (id);
  223197. }
  223198. }
  223199. }
  223200. }
  223201. snd_ctl_close (handle);
  223202. }
  223203. }
  223204. inputNames.appendNumbersToDuplicates (false, true);
  223205. outputNames.appendNumbersToDuplicates (false, true);
  223206. }
  223207. const StringArray getDeviceNames (bool wantInputNames) const
  223208. {
  223209. jassert (hasScanned); // need to call scanForDevices() before doing this
  223210. return wantInputNames ? inputNames : outputNames;
  223211. }
  223212. int getDefaultDeviceIndex (bool forInput) const
  223213. {
  223214. jassert (hasScanned); // need to call scanForDevices() before doing this
  223215. return 0;
  223216. }
  223217. bool hasSeparateInputsAndOutputs() const { return true; }
  223218. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223219. {
  223220. jassert (hasScanned); // need to call scanForDevices() before doing this
  223221. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223222. if (d == 0)
  223223. return -1;
  223224. return asInput ? inputIds.indexOf (d->inputId)
  223225. : outputIds.indexOf (d->outputId);
  223226. }
  223227. AudioIODevice* createDevice (const String& outputDeviceName,
  223228. const String& inputDeviceName)
  223229. {
  223230. jassert (hasScanned); // need to call scanForDevices() before doing this
  223231. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223232. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223233. String deviceName (outputIndex >= 0 ? outputDeviceName
  223234. : inputDeviceName);
  223235. if (inputIndex >= 0 || outputIndex >= 0)
  223236. return new ALSAAudioIODevice (deviceName,
  223237. inputIds [inputIndex],
  223238. outputIds [outputIndex]);
  223239. return 0;
  223240. }
  223241. juce_UseDebuggingNewOperator
  223242. private:
  223243. StringArray inputNames, outputNames, inputIds, outputIds;
  223244. bool hasScanned;
  223245. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223246. {
  223247. unsigned int minChansOut = 0, maxChansOut = 0;
  223248. unsigned int minChansIn = 0, maxChansIn = 0;
  223249. Array <int> rates;
  223250. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223251. DBG ("ALSA device: " + id
  223252. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223253. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223254. + " rates=" + String (rates.size()));
  223255. isInput = maxChansIn > 0;
  223256. isOutput = maxChansOut > 0;
  223257. return (isInput || isOutput) && rates.size() > 0;
  223258. }
  223259. /*static const String getHint (void* hint, const char* type)
  223260. {
  223261. char* const n = snd_device_name_get_hint (hint, type);
  223262. const String s ((const char*) n);
  223263. free (n);
  223264. return s;
  223265. }*/
  223266. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223267. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223268. };
  223269. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223270. {
  223271. return new ALSAAudioIODeviceType();
  223272. }
  223273. #endif
  223274. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223275. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223276. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223277. // compiled on its own).
  223278. #ifdef JUCE_INCLUDED_FILE
  223279. #if JUCE_JACK
  223280. static void* juce_libjack_handle = 0;
  223281. void* juce_load_jack_function (const char* const name)
  223282. {
  223283. if (juce_libjack_handle == 0)
  223284. return 0;
  223285. return dlsym (juce_libjack_handle, name);
  223286. }
  223287. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223288. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223289. return_type fn_name argument_types { \
  223290. static fn_name##_ptr_t fn = 0; \
  223291. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223292. if (fn) return (*fn)arguments; \
  223293. else return 0; \
  223294. }
  223295. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223296. typedef void (*fn_name##_ptr_t)argument_types; \
  223297. void fn_name argument_types { \
  223298. static fn_name##_ptr_t fn = 0; \
  223299. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223300. if (fn) (*fn)arguments; \
  223301. }
  223302. 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));
  223303. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223304. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223305. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223306. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223307. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223308. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223309. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223310. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223311. 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));
  223312. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223313. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223314. 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));
  223315. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223316. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223317. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223318. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223319. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223320. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223321. #if JUCE_DEBUG
  223322. #define JACK_LOGGING_ENABLED 1
  223323. #endif
  223324. #if JACK_LOGGING_ENABLED
  223325. static void jack_Log (const String& s)
  223326. {
  223327. std::cerr << s << std::endl;
  223328. }
  223329. static void dumpJackErrorMessage (const jack_status_t status)
  223330. {
  223331. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223332. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223333. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223334. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223335. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223336. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223337. }
  223338. #else
  223339. #define dumpJackErrorMessage(a) {}
  223340. #define jack_Log(...) {}
  223341. #endif
  223342. #ifndef JUCE_JACK_CLIENT_NAME
  223343. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223344. #endif
  223345. class JackAudioIODevice : public AudioIODevice
  223346. {
  223347. public:
  223348. JackAudioIODevice (const String& deviceName,
  223349. const String& inputId_,
  223350. const String& outputId_)
  223351. : AudioIODevice (deviceName, "JACK"),
  223352. inputId (inputId_),
  223353. outputId (outputId_),
  223354. isOpen_ (false),
  223355. callback (0),
  223356. totalNumberOfInputChannels (0),
  223357. totalNumberOfOutputChannels (0)
  223358. {
  223359. jassert (deviceName.isNotEmpty());
  223360. jack_status_t status;
  223361. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223362. if (client == 0)
  223363. {
  223364. dumpJackErrorMessage (status);
  223365. }
  223366. else
  223367. {
  223368. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223369. // open input ports
  223370. const StringArray inputChannels (getInputChannelNames());
  223371. for (int i = 0; i < inputChannels.size(); i++)
  223372. {
  223373. String inputName;
  223374. inputName << "in_" << ++totalNumberOfInputChannels;
  223375. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223376. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223377. }
  223378. // open output ports
  223379. const StringArray outputChannels (getOutputChannelNames());
  223380. for (int i = 0; i < outputChannels.size (); i++)
  223381. {
  223382. String outputName;
  223383. outputName << "out_" << ++totalNumberOfOutputChannels;
  223384. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223385. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223386. }
  223387. inChans.calloc (totalNumberOfInputChannels + 2);
  223388. outChans.calloc (totalNumberOfOutputChannels + 2);
  223389. }
  223390. }
  223391. ~JackAudioIODevice()
  223392. {
  223393. close();
  223394. if (client != 0)
  223395. {
  223396. JUCE_NAMESPACE::jack_client_close (client);
  223397. client = 0;
  223398. }
  223399. }
  223400. const StringArray getChannelNames (bool forInput) const
  223401. {
  223402. StringArray names;
  223403. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223404. forInput ? JackPortIsInput : JackPortIsOutput);
  223405. if (ports != 0)
  223406. {
  223407. int j = 0;
  223408. while (ports[j] != 0)
  223409. {
  223410. const String portName (ports [j++]);
  223411. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223412. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223413. }
  223414. free (ports);
  223415. }
  223416. return names;
  223417. }
  223418. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223419. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223420. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223421. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223422. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223423. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223424. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223425. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223426. double sampleRate, int bufferSizeSamples)
  223427. {
  223428. if (client == 0)
  223429. {
  223430. lastError = "No JACK client running";
  223431. return lastError;
  223432. }
  223433. lastError = String::empty;
  223434. close();
  223435. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223436. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223437. JUCE_NAMESPACE::jack_activate (client);
  223438. isOpen_ = true;
  223439. if (! inputChannels.isZero())
  223440. {
  223441. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223442. if (ports != 0)
  223443. {
  223444. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223445. for (int i = 0; i < numInputChannels; ++i)
  223446. {
  223447. const String portName (ports[i]);
  223448. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223449. {
  223450. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223451. if (error != 0)
  223452. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223453. }
  223454. }
  223455. free (ports);
  223456. }
  223457. }
  223458. if (! outputChannels.isZero())
  223459. {
  223460. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223461. if (ports != 0)
  223462. {
  223463. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223464. for (int i = 0; i < numOutputChannels; ++i)
  223465. {
  223466. const String portName (ports[i]);
  223467. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223468. {
  223469. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223470. if (error != 0)
  223471. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223472. }
  223473. }
  223474. free (ports);
  223475. }
  223476. }
  223477. return lastError;
  223478. }
  223479. void close()
  223480. {
  223481. stop();
  223482. if (client != 0)
  223483. {
  223484. JUCE_NAMESPACE::jack_deactivate (client);
  223485. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223486. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223487. }
  223488. isOpen_ = false;
  223489. }
  223490. void start (AudioIODeviceCallback* newCallback)
  223491. {
  223492. if (isOpen_ && newCallback != callback)
  223493. {
  223494. if (newCallback != 0)
  223495. newCallback->audioDeviceAboutToStart (this);
  223496. AudioIODeviceCallback* const oldCallback = callback;
  223497. {
  223498. const ScopedLock sl (callbackLock);
  223499. callback = newCallback;
  223500. }
  223501. if (oldCallback != 0)
  223502. oldCallback->audioDeviceStopped();
  223503. }
  223504. }
  223505. void stop()
  223506. {
  223507. start (0);
  223508. }
  223509. bool isOpen() { return isOpen_; }
  223510. bool isPlaying() { return callback != 0; }
  223511. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223512. double getCurrentSampleRate() { return getSampleRate (0); }
  223513. int getCurrentBitDepth() { return 32; }
  223514. const String getLastError() { return lastError; }
  223515. const BigInteger getActiveOutputChannels() const
  223516. {
  223517. BigInteger outputBits;
  223518. for (int i = 0; i < outputPorts.size(); i++)
  223519. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223520. outputBits.setBit (i);
  223521. return outputBits;
  223522. }
  223523. const BigInteger getActiveInputChannels() const
  223524. {
  223525. BigInteger inputBits;
  223526. for (int i = 0; i < inputPorts.size(); i++)
  223527. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223528. inputBits.setBit (i);
  223529. return inputBits;
  223530. }
  223531. int getOutputLatencyInSamples()
  223532. {
  223533. int latency = 0;
  223534. for (int i = 0; i < outputPorts.size(); i++)
  223535. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223536. return latency;
  223537. }
  223538. int getInputLatencyInSamples()
  223539. {
  223540. int latency = 0;
  223541. for (int i = 0; i < inputPorts.size(); i++)
  223542. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223543. return latency;
  223544. }
  223545. String inputId, outputId;
  223546. private:
  223547. void process (const int numSamples)
  223548. {
  223549. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223550. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223551. {
  223552. jack_default_audio_sample_t* in
  223553. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223554. if (in != 0)
  223555. inChans [numActiveInChans++] = (float*) in;
  223556. }
  223557. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223558. {
  223559. jack_default_audio_sample_t* out
  223560. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223561. if (out != 0)
  223562. outChans [numActiveOutChans++] = (float*) out;
  223563. }
  223564. const ScopedLock sl (callbackLock);
  223565. if (callback != 0)
  223566. {
  223567. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223568. outChans, numActiveOutChans, numSamples);
  223569. }
  223570. else
  223571. {
  223572. for (i = 0; i < numActiveOutChans; ++i)
  223573. zeromem (outChans[i], sizeof (float) * numSamples);
  223574. }
  223575. }
  223576. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223577. {
  223578. if (callbackArgument != 0)
  223579. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223580. return 0;
  223581. }
  223582. static void threadInitCallback (void* callbackArgument)
  223583. {
  223584. jack_Log ("JackAudioIODevice::initialise");
  223585. }
  223586. static void shutdownCallback (void* callbackArgument)
  223587. {
  223588. jack_Log ("JackAudioIODevice::shutdown");
  223589. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223590. if (device != 0)
  223591. {
  223592. device->client = 0;
  223593. device->close();
  223594. }
  223595. }
  223596. static void errorCallback (const char* msg)
  223597. {
  223598. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223599. }
  223600. bool isOpen_;
  223601. jack_client_t* client;
  223602. String lastError;
  223603. AudioIODeviceCallback* callback;
  223604. CriticalSection callbackLock;
  223605. HeapBlock <float*> inChans, outChans;
  223606. int totalNumberOfInputChannels;
  223607. int totalNumberOfOutputChannels;
  223608. Array<void*> inputPorts, outputPorts;
  223609. };
  223610. class JackAudioIODeviceType : public AudioIODeviceType
  223611. {
  223612. public:
  223613. JackAudioIODeviceType()
  223614. : AudioIODeviceType ("JACK"),
  223615. hasScanned (false)
  223616. {
  223617. }
  223618. ~JackAudioIODeviceType()
  223619. {
  223620. }
  223621. void scanForDevices()
  223622. {
  223623. hasScanned = true;
  223624. inputNames.clear();
  223625. inputIds.clear();
  223626. outputNames.clear();
  223627. outputIds.clear();
  223628. if (juce_libjack_handle == 0)
  223629. {
  223630. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223631. if (juce_libjack_handle == 0)
  223632. return;
  223633. }
  223634. // open a dummy client
  223635. jack_status_t status;
  223636. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223637. if (client == 0)
  223638. {
  223639. dumpJackErrorMessage (status);
  223640. }
  223641. else
  223642. {
  223643. // scan for output devices
  223644. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223645. if (ports != 0)
  223646. {
  223647. int j = 0;
  223648. while (ports[j] != 0)
  223649. {
  223650. String clientName (ports[j]);
  223651. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223652. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223653. && ! inputNames.contains (clientName))
  223654. {
  223655. inputNames.add (clientName);
  223656. inputIds.add (ports [j]);
  223657. }
  223658. ++j;
  223659. }
  223660. free (ports);
  223661. }
  223662. // scan for input devices
  223663. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223664. if (ports != 0)
  223665. {
  223666. int j = 0;
  223667. while (ports[j] != 0)
  223668. {
  223669. String clientName (ports[j]);
  223670. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223671. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223672. && ! outputNames.contains (clientName))
  223673. {
  223674. outputNames.add (clientName);
  223675. outputIds.add (ports [j]);
  223676. }
  223677. ++j;
  223678. }
  223679. free (ports);
  223680. }
  223681. JUCE_NAMESPACE::jack_client_close (client);
  223682. }
  223683. }
  223684. const StringArray getDeviceNames (bool wantInputNames) const
  223685. {
  223686. jassert (hasScanned); // need to call scanForDevices() before doing this
  223687. return wantInputNames ? inputNames : outputNames;
  223688. }
  223689. int getDefaultDeviceIndex (bool forInput) const
  223690. {
  223691. jassert (hasScanned); // need to call scanForDevices() before doing this
  223692. return 0;
  223693. }
  223694. bool hasSeparateInputsAndOutputs() const { return true; }
  223695. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223696. {
  223697. jassert (hasScanned); // need to call scanForDevices() before doing this
  223698. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223699. if (d == 0)
  223700. return -1;
  223701. return asInput ? inputIds.indexOf (d->inputId)
  223702. : outputIds.indexOf (d->outputId);
  223703. }
  223704. AudioIODevice* createDevice (const String& outputDeviceName,
  223705. const String& inputDeviceName)
  223706. {
  223707. jassert (hasScanned); // need to call scanForDevices() before doing this
  223708. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223709. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223710. if (inputIndex >= 0 || outputIndex >= 0)
  223711. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223712. : inputDeviceName,
  223713. inputIds [inputIndex],
  223714. outputIds [outputIndex]);
  223715. return 0;
  223716. }
  223717. juce_UseDebuggingNewOperator
  223718. private:
  223719. StringArray inputNames, outputNames, inputIds, outputIds;
  223720. bool hasScanned;
  223721. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223722. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223723. };
  223724. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223725. {
  223726. return new JackAudioIODeviceType();
  223727. }
  223728. #else // if JACK is turned off..
  223729. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223730. #endif
  223731. #endif
  223732. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223733. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223734. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223735. // compiled on its own).
  223736. #if JUCE_INCLUDED_FILE
  223737. #if JUCE_ALSA
  223738. static snd_seq_t* iterateMidiDevices (const bool forInput,
  223739. StringArray& deviceNamesFound,
  223740. const int deviceIndexToOpen)
  223741. {
  223742. snd_seq_t* returnedHandle = 0;
  223743. snd_seq_t* seqHandle;
  223744. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223745. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223746. {
  223747. snd_seq_system_info_t* systemInfo;
  223748. snd_seq_client_info_t* clientInfo;
  223749. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223750. {
  223751. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223752. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223753. {
  223754. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223755. while (--numClients >= 0 && returnedHandle == 0)
  223756. {
  223757. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223758. {
  223759. snd_seq_port_info_t* portInfo;
  223760. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223761. {
  223762. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223763. const int client = snd_seq_client_info_get_client (clientInfo);
  223764. snd_seq_port_info_set_client (portInfo, client);
  223765. snd_seq_port_info_set_port (portInfo, -1);
  223766. while (--numPorts >= 0)
  223767. {
  223768. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223769. && (snd_seq_port_info_get_capability (portInfo)
  223770. & (forInput ? SND_SEQ_PORT_CAP_READ
  223771. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223772. {
  223773. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223774. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223775. {
  223776. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223777. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223778. if (sourcePort != -1)
  223779. {
  223780. snd_seq_set_client_name (seqHandle,
  223781. forInput ? "Juce Midi Input"
  223782. : "Juce Midi Output");
  223783. const int portId
  223784. = snd_seq_create_simple_port (seqHandle,
  223785. forInput ? "Juce Midi In Port"
  223786. : "Juce Midi Out Port",
  223787. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223788. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223789. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223790. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223791. returnedHandle = seqHandle;
  223792. }
  223793. }
  223794. }
  223795. }
  223796. snd_seq_port_info_free (portInfo);
  223797. }
  223798. }
  223799. }
  223800. snd_seq_client_info_free (clientInfo);
  223801. }
  223802. snd_seq_system_info_free (systemInfo);
  223803. }
  223804. if (returnedHandle == 0)
  223805. snd_seq_close (seqHandle);
  223806. }
  223807. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223808. return returnedHandle;
  223809. }
  223810. static snd_seq_t* createMidiDevice (const bool forInput,
  223811. const String& deviceNameToOpen)
  223812. {
  223813. snd_seq_t* seqHandle = 0;
  223814. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223815. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223816. {
  223817. snd_seq_set_client_name (seqHandle,
  223818. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223819. const int portId
  223820. = snd_seq_create_simple_port (seqHandle,
  223821. forInput ? "in"
  223822. : "out",
  223823. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223824. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223825. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223826. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223827. if (portId < 0)
  223828. {
  223829. snd_seq_close (seqHandle);
  223830. seqHandle = 0;
  223831. }
  223832. }
  223833. return seqHandle;
  223834. }
  223835. class MidiOutputDevice
  223836. {
  223837. public:
  223838. MidiOutputDevice (MidiOutput* const midiOutput_,
  223839. snd_seq_t* const seqHandle_)
  223840. :
  223841. midiOutput (midiOutput_),
  223842. seqHandle (seqHandle_),
  223843. maxEventSize (16 * 1024)
  223844. {
  223845. jassert (seqHandle != 0 && midiOutput != 0);
  223846. snd_midi_event_new (maxEventSize, &midiParser);
  223847. }
  223848. ~MidiOutputDevice()
  223849. {
  223850. snd_midi_event_free (midiParser);
  223851. snd_seq_close (seqHandle);
  223852. }
  223853. void sendMessageNow (const MidiMessage& message)
  223854. {
  223855. if (message.getRawDataSize() > maxEventSize)
  223856. {
  223857. maxEventSize = message.getRawDataSize();
  223858. snd_midi_event_free (midiParser);
  223859. snd_midi_event_new (maxEventSize, &midiParser);
  223860. }
  223861. snd_seq_event_t event;
  223862. snd_seq_ev_clear (&event);
  223863. snd_midi_event_encode (midiParser,
  223864. message.getRawData(),
  223865. message.getRawDataSize(),
  223866. &event);
  223867. snd_midi_event_reset_encode (midiParser);
  223868. snd_seq_ev_set_source (&event, 0);
  223869. snd_seq_ev_set_subs (&event);
  223870. snd_seq_ev_set_direct (&event);
  223871. snd_seq_event_output (seqHandle, &event);
  223872. snd_seq_drain_output (seqHandle);
  223873. }
  223874. juce_UseDebuggingNewOperator
  223875. private:
  223876. MidiOutput* const midiOutput;
  223877. snd_seq_t* const seqHandle;
  223878. snd_midi_event_t* midiParser;
  223879. int maxEventSize;
  223880. };
  223881. const StringArray MidiOutput::getDevices()
  223882. {
  223883. StringArray devices;
  223884. iterateMidiDevices (false, devices, -1);
  223885. return devices;
  223886. }
  223887. int MidiOutput::getDefaultDeviceIndex()
  223888. {
  223889. return 0;
  223890. }
  223891. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223892. {
  223893. MidiOutput* newDevice = 0;
  223894. StringArray devices;
  223895. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223896. if (handle != 0)
  223897. {
  223898. newDevice = new MidiOutput();
  223899. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223900. }
  223901. return newDevice;
  223902. }
  223903. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223904. {
  223905. MidiOutput* newDevice = 0;
  223906. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223907. if (handle != 0)
  223908. {
  223909. newDevice = new MidiOutput();
  223910. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223911. }
  223912. return newDevice;
  223913. }
  223914. MidiOutput::~MidiOutput()
  223915. {
  223916. delete static_cast <MidiOutputDevice*> (internal);
  223917. }
  223918. void MidiOutput::reset()
  223919. {
  223920. }
  223921. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223922. {
  223923. return false;
  223924. }
  223925. void MidiOutput::setVolume (float leftVol, float rightVol)
  223926. {
  223927. }
  223928. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223929. {
  223930. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223931. }
  223932. class MidiInputThread : public Thread
  223933. {
  223934. public:
  223935. MidiInputThread (MidiInput* const midiInput_,
  223936. snd_seq_t* const seqHandle_,
  223937. MidiInputCallback* const callback_)
  223938. : Thread ("Juce MIDI Input"),
  223939. midiInput (midiInput_),
  223940. seqHandle (seqHandle_),
  223941. callback (callback_)
  223942. {
  223943. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223944. }
  223945. ~MidiInputThread()
  223946. {
  223947. snd_seq_close (seqHandle);
  223948. }
  223949. void run()
  223950. {
  223951. const int maxEventSize = 16 * 1024;
  223952. snd_midi_event_t* midiParser;
  223953. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223954. {
  223955. HeapBlock <uint8> buffer (maxEventSize);
  223956. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223957. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223958. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223959. while (! threadShouldExit())
  223960. {
  223961. if (poll (pfd, numPfds, 500) > 0)
  223962. {
  223963. snd_seq_event_t* inputEvent = 0;
  223964. snd_seq_nonblock (seqHandle, 1);
  223965. do
  223966. {
  223967. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223968. {
  223969. // xxx what about SYSEXes that are too big for the buffer?
  223970. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223971. snd_midi_event_reset_decode (midiParser);
  223972. if (numBytes > 0)
  223973. {
  223974. const MidiMessage message ((const uint8*) buffer,
  223975. numBytes,
  223976. Time::getMillisecondCounter() * 0.001);
  223977. callback->handleIncomingMidiMessage (midiInput, message);
  223978. }
  223979. snd_seq_free_event (inputEvent);
  223980. }
  223981. }
  223982. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223983. snd_seq_free_event (inputEvent);
  223984. }
  223985. }
  223986. snd_midi_event_free (midiParser);
  223987. }
  223988. };
  223989. juce_UseDebuggingNewOperator
  223990. private:
  223991. MidiInput* const midiInput;
  223992. snd_seq_t* const seqHandle;
  223993. MidiInputCallback* const callback;
  223994. };
  223995. MidiInput::MidiInput (const String& name_)
  223996. : name (name_),
  223997. internal (0)
  223998. {
  223999. }
  224000. MidiInput::~MidiInput()
  224001. {
  224002. stop();
  224003. delete static_cast <MidiInputThread*> (internal);
  224004. }
  224005. void MidiInput::start()
  224006. {
  224007. static_cast <MidiInputThread*> (internal)->startThread();
  224008. }
  224009. void MidiInput::stop()
  224010. {
  224011. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  224012. }
  224013. int MidiInput::getDefaultDeviceIndex()
  224014. {
  224015. return 0;
  224016. }
  224017. const StringArray MidiInput::getDevices()
  224018. {
  224019. StringArray devices;
  224020. iterateMidiDevices (true, devices, -1);
  224021. return devices;
  224022. }
  224023. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  224024. {
  224025. MidiInput* newDevice = 0;
  224026. StringArray devices;
  224027. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  224028. if (handle != 0)
  224029. {
  224030. newDevice = new MidiInput (devices [deviceIndex]);
  224031. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224032. }
  224033. return newDevice;
  224034. }
  224035. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  224036. {
  224037. MidiInput* newDevice = 0;
  224038. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  224039. if (handle != 0)
  224040. {
  224041. newDevice = new MidiInput (deviceName);
  224042. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224043. }
  224044. return newDevice;
  224045. }
  224046. #else
  224047. // (These are just stub functions if ALSA is unavailable...)
  224048. const StringArray MidiOutput::getDevices() { return StringArray(); }
  224049. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  224050. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  224051. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  224052. MidiOutput::~MidiOutput() {}
  224053. void MidiOutput::reset() {}
  224054. bool MidiOutput::getVolume (float&, float&) { return false; }
  224055. void MidiOutput::setVolume (float, float) {}
  224056. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  224057. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  224058. MidiInput::~MidiInput() {}
  224059. void MidiInput::start() {}
  224060. void MidiInput::stop() {}
  224061. int MidiInput::getDefaultDeviceIndex() { return 0; }
  224062. const StringArray MidiInput::getDevices() { return StringArray(); }
  224063. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  224064. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  224065. #endif
  224066. #endif
  224067. /*** End of inlined file: juce_linux_Midi.cpp ***/
  224068. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  224069. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224070. // compiled on its own).
  224071. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  224072. AudioCDReader::AudioCDReader()
  224073. : AudioFormatReader (0, "CD Audio")
  224074. {
  224075. }
  224076. const StringArray AudioCDReader::getAvailableCDNames()
  224077. {
  224078. StringArray names;
  224079. return names;
  224080. }
  224081. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  224082. {
  224083. return 0;
  224084. }
  224085. AudioCDReader::~AudioCDReader()
  224086. {
  224087. }
  224088. void AudioCDReader::refreshTrackLengths()
  224089. {
  224090. }
  224091. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  224092. int64 startSampleInFile, int numSamples)
  224093. {
  224094. return false;
  224095. }
  224096. bool AudioCDReader::isCDStillPresent() const
  224097. {
  224098. return false;
  224099. }
  224100. bool AudioCDReader::isTrackAudio (int trackNum) const
  224101. {
  224102. return false;
  224103. }
  224104. void AudioCDReader::enableIndexScanning (bool b)
  224105. {
  224106. }
  224107. int AudioCDReader::getLastIndex() const
  224108. {
  224109. return 0;
  224110. }
  224111. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  224112. {
  224113. return Array<int>();
  224114. }
  224115. #endif
  224116. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  224117. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  224118. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224119. // compiled on its own).
  224120. #if JUCE_INCLUDED_FILE
  224121. void FileChooser::showPlatformDialog (Array<File>& results,
  224122. const String& title,
  224123. const File& file,
  224124. const String& filters,
  224125. bool isDirectory,
  224126. bool selectsFiles,
  224127. bool isSave,
  224128. bool warnAboutOverwritingExistingFiles,
  224129. bool selectMultipleFiles,
  224130. FilePreviewComponent* previewComponent)
  224131. {
  224132. const String separator (":");
  224133. String command ("zenity --file-selection");
  224134. if (title.isNotEmpty())
  224135. command << " --title=\"" << title << "\"";
  224136. if (file != File::nonexistent)
  224137. command << " --filename=\"" << file.getFullPathName () << "\"";
  224138. if (isDirectory)
  224139. command << " --directory";
  224140. if (isSave)
  224141. command << " --save";
  224142. if (selectMultipleFiles)
  224143. command << " --multiple --separator=\"" << separator << "\"";
  224144. command << " 2>&1";
  224145. MemoryOutputStream result;
  224146. int status = -1;
  224147. FILE* stream = popen (command.toUTF8(), "r");
  224148. if (stream != 0)
  224149. {
  224150. for (;;)
  224151. {
  224152. char buffer [1024];
  224153. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  224154. if (bytesRead <= 0)
  224155. break;
  224156. result.write (buffer, bytesRead);
  224157. }
  224158. status = pclose (stream);
  224159. }
  224160. if (status == 0)
  224161. {
  224162. StringArray tokens;
  224163. if (selectMultipleFiles)
  224164. tokens.addTokens (result.toUTF8(), separator, String::empty);
  224165. else
  224166. tokens.add (result.toUTF8());
  224167. for (int i = 0; i < tokens.size(); i++)
  224168. results.add (File (tokens[i]));
  224169. return;
  224170. }
  224171. //xxx ain't got one!
  224172. jassertfalse;
  224173. }
  224174. #endif
  224175. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224176. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224177. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224178. // compiled on its own).
  224179. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224180. /*
  224181. Sorry.. This class isn't implemented on Linux!
  224182. */
  224183. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224184. : browser (0),
  224185. blankPageShown (false),
  224186. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224187. {
  224188. setOpaque (true);
  224189. }
  224190. WebBrowserComponent::~WebBrowserComponent()
  224191. {
  224192. }
  224193. void WebBrowserComponent::goToURL (const String& url,
  224194. const StringArray* headers,
  224195. const MemoryBlock* postData)
  224196. {
  224197. lastURL = url;
  224198. lastHeaders.clear();
  224199. if (headers != 0)
  224200. lastHeaders = *headers;
  224201. lastPostData.setSize (0);
  224202. if (postData != 0)
  224203. lastPostData = *postData;
  224204. blankPageShown = false;
  224205. }
  224206. void WebBrowserComponent::stop()
  224207. {
  224208. }
  224209. void WebBrowserComponent::goBack()
  224210. {
  224211. lastURL = String::empty;
  224212. blankPageShown = false;
  224213. }
  224214. void WebBrowserComponent::goForward()
  224215. {
  224216. lastURL = String::empty;
  224217. }
  224218. void WebBrowserComponent::refresh()
  224219. {
  224220. }
  224221. void WebBrowserComponent::paint (Graphics& g)
  224222. {
  224223. g.fillAll (Colours::white);
  224224. }
  224225. void WebBrowserComponent::checkWindowAssociation()
  224226. {
  224227. }
  224228. void WebBrowserComponent::reloadLastURL()
  224229. {
  224230. if (lastURL.isNotEmpty())
  224231. {
  224232. goToURL (lastURL, &lastHeaders, &lastPostData);
  224233. lastURL = String::empty;
  224234. }
  224235. }
  224236. void WebBrowserComponent::parentHierarchyChanged()
  224237. {
  224238. checkWindowAssociation();
  224239. }
  224240. void WebBrowserComponent::resized()
  224241. {
  224242. }
  224243. void WebBrowserComponent::visibilityChanged()
  224244. {
  224245. checkWindowAssociation();
  224246. }
  224247. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224248. {
  224249. return true;
  224250. }
  224251. #endif
  224252. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224253. #endif
  224254. END_JUCE_NAMESPACE
  224255. #endif
  224256. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224257. #endif
  224258. #if JUCE_MAC || JUCE_IPHONE
  224259. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224260. /*
  224261. This file wraps together all the mac-specific code, so that
  224262. we can include all the native headers just once, and compile all our
  224263. platform-specific stuff in one big lump, keeping it out of the way of
  224264. the rest of the codebase.
  224265. */
  224266. #if JUCE_MAC || JUCE_IOS
  224267. BEGIN_JUCE_NAMESPACE
  224268. #undef Point
  224269. #define JUCE_INCLUDED_FILE 1
  224270. // Now include the actual code files..
  224271. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224272. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224273. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224274. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224275. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224276. actually calling into a similarly named class in the other module's address space.
  224277. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224278. have unique names, and should avoid this problem.
  224279. If you're using the amalgamated version, you can just set this macro to something unique before
  224280. you include juce_amalgamated.cpp.
  224281. */
  224282. #ifndef JUCE_ObjCExtraSuffix
  224283. #define JUCE_ObjCExtraSuffix 3
  224284. #endif
  224285. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224286. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224287. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224288. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224289. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224290. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224291. // compiled on its own).
  224292. #if JUCE_INCLUDED_FILE
  224293. static const String nsStringToJuce (NSString* s)
  224294. {
  224295. return String::fromUTF8 ([s UTF8String]);
  224296. }
  224297. static NSString* juceStringToNS (const String& s)
  224298. {
  224299. return [NSString stringWithUTF8String: s.toUTF8()];
  224300. }
  224301. static const String convertUTF16ToString (const UniChar* utf16)
  224302. {
  224303. String s;
  224304. while (*utf16 != 0)
  224305. s += (juce_wchar) *utf16++;
  224306. return s;
  224307. }
  224308. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224309. {
  224310. String result;
  224311. if (cfString != 0)
  224312. {
  224313. CFRange range = { 0, CFStringGetLength (cfString) };
  224314. HeapBlock <UniChar> u (range.length + 1);
  224315. CFStringGetCharacters (cfString, range, u);
  224316. u[range.length] = 0;
  224317. result = convertUTF16ToString (u);
  224318. }
  224319. return result;
  224320. }
  224321. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224322. {
  224323. const int len = s.length();
  224324. HeapBlock <UniChar> temp (len + 2);
  224325. for (int i = 0; i <= len; ++i)
  224326. temp[i] = s[i];
  224327. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224328. }
  224329. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224330. {
  224331. #if JUCE_IOS
  224332. const ScopedAutoReleasePool pool;
  224333. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224334. #else
  224335. UnicodeMapping map;
  224336. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224337. kUnicodeNoSubset,
  224338. kTextEncodingDefaultFormat);
  224339. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224340. kUnicodeCanonicalCompVariant,
  224341. kTextEncodingDefaultFormat);
  224342. map.mappingVersion = kUnicodeUseLatestMapping;
  224343. UnicodeToTextInfo conversionInfo = 0;
  224344. String result;
  224345. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224346. {
  224347. const int len = s.length();
  224348. HeapBlock <UniChar> tempIn, tempOut;
  224349. tempIn.calloc (len + 2);
  224350. tempOut.calloc (len + 2);
  224351. for (int i = 0; i <= len; ++i)
  224352. tempIn[i] = s[i];
  224353. ByteCount bytesRead = 0;
  224354. ByteCount outputBufferSize = 0;
  224355. if (ConvertFromUnicodeToText (conversionInfo,
  224356. len * sizeof (UniChar), tempIn,
  224357. kUnicodeDefaultDirectionMask,
  224358. 0, 0, 0, 0,
  224359. len * sizeof (UniChar), &bytesRead,
  224360. &outputBufferSize, tempOut) == noErr)
  224361. {
  224362. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224363. juce_wchar* t = result;
  224364. unsigned int i;
  224365. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224366. t[i] = (juce_wchar) tempOut[i];
  224367. t[i] = 0;
  224368. }
  224369. DisposeUnicodeToTextInfo (&conversionInfo);
  224370. }
  224371. return result;
  224372. #endif
  224373. }
  224374. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224375. void SystemClipboard::copyTextToClipboard (const String& text)
  224376. {
  224377. #if JUCE_IOS
  224378. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224379. forPasteboardType: @"public.text"];
  224380. #else
  224381. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224382. owner: nil];
  224383. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224384. forType: NSStringPboardType];
  224385. #endif
  224386. }
  224387. const String SystemClipboard::getTextFromClipboard()
  224388. {
  224389. #if JUCE_IOS
  224390. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224391. #else
  224392. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224393. #endif
  224394. return text == 0 ? String::empty
  224395. : nsStringToJuce (text);
  224396. }
  224397. #endif
  224398. #endif
  224399. /*** End of inlined file: juce_mac_Strings.mm ***/
  224400. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224401. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224402. // compiled on its own).
  224403. #if JUCE_INCLUDED_FILE
  224404. namespace SystemStatsHelpers
  224405. {
  224406. static int64 highResTimerFrequency = 0;
  224407. static double highResTimerToMillisecRatio = 0;
  224408. #if JUCE_INTEL
  224409. static void juce_getCpuVendor (char* const v) throw()
  224410. {
  224411. int vendor[4];
  224412. zerostruct (vendor);
  224413. int dummy = 0;
  224414. asm ("mov %%ebx, %%esi \n\t"
  224415. "cpuid \n\t"
  224416. "xchg %%esi, %%ebx"
  224417. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224418. memcpy (v, vendor, 16);
  224419. }
  224420. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224421. {
  224422. unsigned int cpu = 0;
  224423. unsigned int ext = 0;
  224424. unsigned int family = 0;
  224425. unsigned int dummy = 0;
  224426. asm ("mov %%ebx, %%esi \n\t"
  224427. "cpuid \n\t"
  224428. "xchg %%esi, %%ebx"
  224429. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224430. familyModel = family;
  224431. extFeatures = ext;
  224432. return cpu;
  224433. }
  224434. #endif
  224435. }
  224436. void SystemStats::initialiseStats()
  224437. {
  224438. using namespace SystemStatsHelpers;
  224439. static bool initialised = false;
  224440. if (! initialised)
  224441. {
  224442. initialised = true;
  224443. #if JUCE_MAC
  224444. [NSApplication sharedApplication];
  224445. #endif
  224446. #if JUCE_INTEL
  224447. unsigned int familyModel, extFeatures;
  224448. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224449. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224450. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224451. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224452. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224453. #else
  224454. cpuFlags.hasMMX = false;
  224455. cpuFlags.hasSSE = false;
  224456. cpuFlags.hasSSE2 = false;
  224457. cpuFlags.has3DNow = false;
  224458. #endif
  224459. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224460. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224461. #else
  224462. cpuFlags.numCpus = (int) MPProcessors();
  224463. #endif
  224464. mach_timebase_info_data_t timebase;
  224465. (void) mach_timebase_info (&timebase);
  224466. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224467. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224468. String s (SystemStats::getJUCEVersion());
  224469. rlimit lim;
  224470. getrlimit (RLIMIT_NOFILE, &lim);
  224471. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224472. setrlimit (RLIMIT_NOFILE, &lim);
  224473. }
  224474. }
  224475. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224476. {
  224477. return MacOSX;
  224478. }
  224479. const String SystemStats::getOperatingSystemName()
  224480. {
  224481. return "Mac OS X";
  224482. }
  224483. #if ! JUCE_IOS
  224484. int PlatformUtilities::getOSXMinorVersionNumber()
  224485. {
  224486. SInt32 versionMinor = 0;
  224487. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224488. (void) err;
  224489. jassert (err == noErr);
  224490. return (int) versionMinor;
  224491. }
  224492. #endif
  224493. bool SystemStats::isOperatingSystem64Bit()
  224494. {
  224495. #if JUCE_IOS
  224496. return false;
  224497. #elif JUCE_64BIT
  224498. return true;
  224499. #else
  224500. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224501. #endif
  224502. }
  224503. int SystemStats::getMemorySizeInMegabytes()
  224504. {
  224505. uint64 mem = 0;
  224506. size_t memSize = sizeof (mem);
  224507. int mib[] = { CTL_HW, HW_MEMSIZE };
  224508. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224509. return (int) (mem / (1024 * 1024));
  224510. }
  224511. const String SystemStats::getCpuVendor()
  224512. {
  224513. #if JUCE_INTEL
  224514. char v [16];
  224515. SystemStatsHelpers::juce_getCpuVendor (v);
  224516. return String (v, 16);
  224517. #else
  224518. return String::empty;
  224519. #endif
  224520. }
  224521. int SystemStats::getCpuSpeedInMegaherz()
  224522. {
  224523. uint64 speedHz = 0;
  224524. size_t speedSize = sizeof (speedHz);
  224525. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224526. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224527. #if JUCE_BIG_ENDIAN
  224528. if (speedSize == 4)
  224529. speedHz >>= 32;
  224530. #endif
  224531. return (int) (speedHz / 1000000);
  224532. }
  224533. const String SystemStats::getLogonName()
  224534. {
  224535. return nsStringToJuce (NSUserName());
  224536. }
  224537. const String SystemStats::getFullUserName()
  224538. {
  224539. return nsStringToJuce (NSFullUserName());
  224540. }
  224541. uint32 juce_millisecondsSinceStartup() throw()
  224542. {
  224543. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224544. }
  224545. double Time::getMillisecondCounterHiRes() throw()
  224546. {
  224547. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224548. }
  224549. int64 Time::getHighResolutionTicks() throw()
  224550. {
  224551. return (int64) mach_absolute_time();
  224552. }
  224553. int64 Time::getHighResolutionTicksPerSecond() throw()
  224554. {
  224555. return SystemStatsHelpers::highResTimerFrequency;
  224556. }
  224557. bool Time::setSystemTimeToThisTime() const
  224558. {
  224559. jassertfalse;
  224560. return false;
  224561. }
  224562. int SystemStats::getPageSize()
  224563. {
  224564. return (int) NSPageSize();
  224565. }
  224566. void PlatformUtilities::fpuReset()
  224567. {
  224568. }
  224569. #endif
  224570. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224571. /*** Start of inlined file: juce_mac_Network.mm ***/
  224572. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224573. // compiled on its own).
  224574. #if JUCE_INCLUDED_FILE
  224575. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224576. {
  224577. #ifndef IFT_ETHER
  224578. #define IFT_ETHER 6
  224579. #endif
  224580. ifaddrs* addrs = 0;
  224581. int numResults = 0;
  224582. if (getifaddrs (&addrs) == 0)
  224583. {
  224584. const ifaddrs* cursor = addrs;
  224585. while (cursor != 0 && numResults < maxNum)
  224586. {
  224587. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224588. if (sto->ss_family == AF_LINK)
  224589. {
  224590. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224591. if (sadd->sdl_type == IFT_ETHER)
  224592. {
  224593. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224594. uint64 a = 0;
  224595. for (int i = 6; --i >= 0;)
  224596. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224597. *addresses++ = (int64) a;
  224598. ++numResults;
  224599. }
  224600. }
  224601. cursor = cursor->ifa_next;
  224602. }
  224603. freeifaddrs (addrs);
  224604. }
  224605. return numResults;
  224606. }
  224607. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224608. const String& emailSubject,
  224609. const String& bodyText,
  224610. const StringArray& filesToAttach)
  224611. {
  224612. #if JUCE_IOS
  224613. //xxx probably need to use MFMailComposeViewController
  224614. jassertfalse;
  224615. return false;
  224616. #else
  224617. const ScopedAutoReleasePool pool;
  224618. String script;
  224619. script << "tell application \"Mail\"\r\n"
  224620. "set newMessage to make new outgoing message with properties {subject:\""
  224621. << emailSubject.replace ("\"", "\\\"")
  224622. << "\", content:\""
  224623. << bodyText.replace ("\"", "\\\"")
  224624. << "\" & return & return}\r\n"
  224625. "tell newMessage\r\n"
  224626. "set visible to true\r\n"
  224627. "set sender to \"sdfsdfsdfewf\"\r\n"
  224628. "make new to recipient at end of to recipients with properties {address:\""
  224629. << targetEmailAddress
  224630. << "\"}\r\n";
  224631. for (int i = 0; i < filesToAttach.size(); ++i)
  224632. {
  224633. script << "tell content\r\n"
  224634. "make new attachment with properties {file name:\""
  224635. << filesToAttach[i].replace ("\"", "\\\"")
  224636. << "\"} at after the last paragraph\r\n"
  224637. "end tell\r\n";
  224638. }
  224639. script << "end tell\r\n"
  224640. "end tell\r\n";
  224641. NSAppleScript* s = [[NSAppleScript alloc]
  224642. initWithSource: juceStringToNS (script)];
  224643. NSDictionary* error = 0;
  224644. const bool ok = [s executeAndReturnError: &error] != nil;
  224645. [s release];
  224646. return ok;
  224647. #endif
  224648. }
  224649. END_JUCE_NAMESPACE
  224650. using namespace JUCE_NAMESPACE;
  224651. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224652. @interface JuceURLConnection : NSObject
  224653. {
  224654. @public
  224655. NSURLRequest* request;
  224656. NSURLConnection* connection;
  224657. NSMutableData* data;
  224658. Thread* runLoopThread;
  224659. bool initialised, hasFailed, hasFinished;
  224660. int position;
  224661. int64 contentLength;
  224662. NSDictionary* headers;
  224663. NSLock* dataLock;
  224664. }
  224665. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224666. - (void) dealloc;
  224667. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224668. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224669. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224670. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224671. - (BOOL) isOpen;
  224672. - (int) read: (char*) dest numBytes: (int) num;
  224673. - (int) readPosition;
  224674. - (void) stop;
  224675. - (void) createConnection;
  224676. @end
  224677. class JuceURLConnectionMessageThread : public Thread
  224678. {
  224679. JuceURLConnection* owner;
  224680. public:
  224681. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224682. : Thread ("http connection"),
  224683. owner (owner_)
  224684. {
  224685. }
  224686. ~JuceURLConnectionMessageThread()
  224687. {
  224688. stopThread (10000);
  224689. }
  224690. void run()
  224691. {
  224692. [owner createConnection];
  224693. while (! threadShouldExit())
  224694. {
  224695. const ScopedAutoReleasePool pool;
  224696. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224697. }
  224698. }
  224699. };
  224700. @implementation JuceURLConnection
  224701. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224702. withCallback: (URL::OpenStreamProgressCallback*) callback
  224703. withContext: (void*) context;
  224704. {
  224705. [super init];
  224706. request = req;
  224707. [request retain];
  224708. data = [[NSMutableData data] retain];
  224709. dataLock = [[NSLock alloc] init];
  224710. connection = 0;
  224711. initialised = false;
  224712. hasFailed = false;
  224713. hasFinished = false;
  224714. contentLength = -1;
  224715. headers = 0;
  224716. runLoopThread = new JuceURLConnectionMessageThread (self);
  224717. runLoopThread->startThread();
  224718. while (runLoopThread->isThreadRunning() && ! initialised)
  224719. {
  224720. if (callback != 0)
  224721. callback (context, -1, (int) [[request HTTPBody] length]);
  224722. Thread::sleep (1);
  224723. }
  224724. return self;
  224725. }
  224726. - (void) dealloc
  224727. {
  224728. [self stop];
  224729. deleteAndZero (runLoopThread);
  224730. [connection release];
  224731. [data release];
  224732. [dataLock release];
  224733. [request release];
  224734. [headers release];
  224735. [super dealloc];
  224736. }
  224737. - (void) createConnection
  224738. {
  224739. NSUInteger oldRetainCount = [self retainCount];
  224740. connection = [[NSURLConnection alloc] initWithRequest: request
  224741. delegate: self];
  224742. if (oldRetainCount == [self retainCount])
  224743. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224744. if (connection == nil)
  224745. runLoopThread->signalThreadShouldExit();
  224746. }
  224747. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224748. {
  224749. (void) conn;
  224750. [dataLock lock];
  224751. [data setLength: 0];
  224752. [dataLock unlock];
  224753. initialised = true;
  224754. contentLength = [response expectedContentLength];
  224755. [headers release];
  224756. headers = 0;
  224757. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224758. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224759. }
  224760. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224761. {
  224762. (void) conn;
  224763. DBG (nsStringToJuce ([error description]));
  224764. hasFailed = true;
  224765. initialised = true;
  224766. if (runLoopThread != 0)
  224767. runLoopThread->signalThreadShouldExit();
  224768. }
  224769. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224770. {
  224771. (void) conn;
  224772. [dataLock lock];
  224773. [data appendData: newData];
  224774. [dataLock unlock];
  224775. initialised = true;
  224776. }
  224777. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224778. {
  224779. (void) conn;
  224780. hasFinished = true;
  224781. initialised = true;
  224782. if (runLoopThread != 0)
  224783. runLoopThread->signalThreadShouldExit();
  224784. }
  224785. - (BOOL) isOpen
  224786. {
  224787. return connection != 0 && ! hasFailed;
  224788. }
  224789. - (int) readPosition
  224790. {
  224791. return position;
  224792. }
  224793. - (int) read: (char*) dest numBytes: (int) numNeeded
  224794. {
  224795. int numDone = 0;
  224796. while (numNeeded > 0)
  224797. {
  224798. int available = jmin (numNeeded, (int) [data length]);
  224799. if (available > 0)
  224800. {
  224801. [dataLock lock];
  224802. [data getBytes: dest length: available];
  224803. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224804. [dataLock unlock];
  224805. numDone += available;
  224806. numNeeded -= available;
  224807. dest += available;
  224808. }
  224809. else
  224810. {
  224811. if (hasFailed || hasFinished)
  224812. break;
  224813. Thread::sleep (1);
  224814. }
  224815. }
  224816. position += numDone;
  224817. return numDone;
  224818. }
  224819. - (void) stop
  224820. {
  224821. [connection cancel];
  224822. if (runLoopThread != 0)
  224823. runLoopThread->stopThread (10000);
  224824. }
  224825. @end
  224826. BEGIN_JUCE_NAMESPACE
  224827. void* juce_openInternetFile (const String& url,
  224828. const String& headers,
  224829. const MemoryBlock& postData,
  224830. const bool isPost,
  224831. URL::OpenStreamProgressCallback* callback,
  224832. void* callbackContext,
  224833. int timeOutMs)
  224834. {
  224835. const ScopedAutoReleasePool pool;
  224836. NSMutableURLRequest* req = [NSMutableURLRequest
  224837. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224838. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224839. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224840. if (req == nil)
  224841. return 0;
  224842. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224843. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224844. StringArray headerLines;
  224845. headerLines.addLines (headers);
  224846. headerLines.removeEmptyStrings (true);
  224847. for (int i = 0; i < headerLines.size(); ++i)
  224848. {
  224849. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224850. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224851. if (key.isNotEmpty() && value.isNotEmpty())
  224852. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224853. }
  224854. if (isPost && postData.getSize() > 0)
  224855. {
  224856. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224857. length: postData.getSize()]];
  224858. }
  224859. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224860. withCallback: callback
  224861. withContext: callbackContext];
  224862. if ([s isOpen])
  224863. return s;
  224864. [s release];
  224865. return 0;
  224866. }
  224867. void juce_closeInternetFile (void* handle)
  224868. {
  224869. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224870. if (s != 0)
  224871. {
  224872. const ScopedAutoReleasePool pool;
  224873. [s stop];
  224874. [s release];
  224875. }
  224876. }
  224877. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224878. {
  224879. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224880. if (s != 0)
  224881. {
  224882. const ScopedAutoReleasePool pool;
  224883. return [s read: (char*) buffer numBytes: bytesToRead];
  224884. }
  224885. return 0;
  224886. }
  224887. int64 juce_getInternetFileContentLength (void* handle)
  224888. {
  224889. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224890. if (s != 0)
  224891. return s->contentLength;
  224892. return -1;
  224893. }
  224894. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224895. {
  224896. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224897. if (s != 0 && s->headers != 0)
  224898. {
  224899. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224900. NSString* key;
  224901. while ((key = [enumerator nextObject]) != nil)
  224902. headers.set (nsStringToJuce (key),
  224903. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224904. }
  224905. }
  224906. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224907. {
  224908. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224909. if (s != 0)
  224910. return [s readPosition];
  224911. return 0;
  224912. }
  224913. #endif
  224914. /*** End of inlined file: juce_mac_Network.mm ***/
  224915. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224916. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224917. // compiled on its own).
  224918. #if JUCE_INCLUDED_FILE
  224919. struct NamedPipeInternal
  224920. {
  224921. String pipeInName, pipeOutName;
  224922. int pipeIn, pipeOut;
  224923. bool volatile createdPipe, blocked, stopReadOperation;
  224924. static void signalHandler (int) {}
  224925. };
  224926. void NamedPipe::cancelPendingReads()
  224927. {
  224928. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224929. {
  224930. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224931. intern->stopReadOperation = true;
  224932. char buffer [1] = { 0 };
  224933. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224934. (void) bytesWritten;
  224935. int timeout = 2000;
  224936. while (intern->blocked && --timeout >= 0)
  224937. Thread::sleep (2);
  224938. intern->stopReadOperation = false;
  224939. }
  224940. }
  224941. void NamedPipe::close()
  224942. {
  224943. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224944. if (intern != 0)
  224945. {
  224946. internal = 0;
  224947. if (intern->pipeIn != -1)
  224948. ::close (intern->pipeIn);
  224949. if (intern->pipeOut != -1)
  224950. ::close (intern->pipeOut);
  224951. if (intern->createdPipe)
  224952. {
  224953. unlink (intern->pipeInName.toUTF8());
  224954. unlink (intern->pipeOutName.toUTF8());
  224955. }
  224956. delete intern;
  224957. }
  224958. }
  224959. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224960. {
  224961. close();
  224962. NamedPipeInternal* const intern = new NamedPipeInternal();
  224963. internal = intern;
  224964. intern->createdPipe = createPipe;
  224965. intern->blocked = false;
  224966. intern->stopReadOperation = false;
  224967. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224968. siginterrupt (SIGPIPE, 1);
  224969. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224970. intern->pipeInName = pipePath + "_in";
  224971. intern->pipeOutName = pipePath + "_out";
  224972. intern->pipeIn = -1;
  224973. intern->pipeOut = -1;
  224974. if (createPipe)
  224975. {
  224976. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224977. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224978. {
  224979. delete intern;
  224980. internal = 0;
  224981. return false;
  224982. }
  224983. }
  224984. return true;
  224985. }
  224986. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224987. {
  224988. int bytesRead = -1;
  224989. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224990. if (intern != 0)
  224991. {
  224992. intern->blocked = true;
  224993. if (intern->pipeIn == -1)
  224994. {
  224995. if (intern->createdPipe)
  224996. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224997. else
  224998. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224999. if (intern->pipeIn == -1)
  225000. {
  225001. intern->blocked = false;
  225002. return -1;
  225003. }
  225004. }
  225005. bytesRead = 0;
  225006. char* p = static_cast<char*> (destBuffer);
  225007. while (bytesRead < maxBytesToRead)
  225008. {
  225009. const int bytesThisTime = maxBytesToRead - bytesRead;
  225010. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  225011. if (numRead <= 0 || intern->stopReadOperation)
  225012. {
  225013. bytesRead = -1;
  225014. break;
  225015. }
  225016. bytesRead += numRead;
  225017. p += bytesRead;
  225018. }
  225019. intern->blocked = false;
  225020. }
  225021. return bytesRead;
  225022. }
  225023. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  225024. {
  225025. int bytesWritten = -1;
  225026. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225027. if (intern != 0)
  225028. {
  225029. if (intern->pipeOut == -1)
  225030. {
  225031. if (intern->createdPipe)
  225032. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  225033. else
  225034. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  225035. if (intern->pipeOut == -1)
  225036. {
  225037. return -1;
  225038. }
  225039. }
  225040. const char* p = static_cast<const char*> (sourceBuffer);
  225041. bytesWritten = 0;
  225042. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  225043. while (bytesWritten < numBytesToWrite
  225044. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  225045. {
  225046. const int bytesThisTime = numBytesToWrite - bytesWritten;
  225047. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  225048. if (numWritten <= 0)
  225049. {
  225050. bytesWritten = -1;
  225051. break;
  225052. }
  225053. bytesWritten += numWritten;
  225054. p += bytesWritten;
  225055. }
  225056. }
  225057. return bytesWritten;
  225058. }
  225059. #endif
  225060. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  225061. /*** Start of inlined file: juce_mac_Threads.mm ***/
  225062. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225063. // compiled on its own).
  225064. #if JUCE_INCLUDED_FILE
  225065. /*
  225066. Note that a lot of methods that you'd expect to find in this file actually
  225067. live in juce_posix_SharedCode.h!
  225068. */
  225069. bool Process::isForegroundProcess()
  225070. {
  225071. #if JUCE_MAC
  225072. return [NSApp isActive];
  225073. #else
  225074. return true; // xxx change this if more than one app is ever possible on the iPhone!
  225075. #endif
  225076. }
  225077. void Process::raisePrivilege()
  225078. {
  225079. jassertfalse;
  225080. }
  225081. void Process::lowerPrivilege()
  225082. {
  225083. jassertfalse;
  225084. }
  225085. void Process::terminate()
  225086. {
  225087. exit (0);
  225088. }
  225089. void Process::setPriority (ProcessPriority)
  225090. {
  225091. // xxx
  225092. }
  225093. #endif
  225094. /*** End of inlined file: juce_mac_Threads.mm ***/
  225095. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  225096. /*
  225097. This file contains posix routines that are common to both the Linux and Mac builds.
  225098. It gets included directly in the cpp files for these platforms.
  225099. */
  225100. CriticalSection::CriticalSection() throw()
  225101. {
  225102. pthread_mutexattr_t atts;
  225103. pthread_mutexattr_init (&atts);
  225104. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  225105. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225106. pthread_mutex_init (&internal, &atts);
  225107. }
  225108. CriticalSection::~CriticalSection() throw()
  225109. {
  225110. pthread_mutex_destroy (&internal);
  225111. }
  225112. void CriticalSection::enter() const throw()
  225113. {
  225114. pthread_mutex_lock (&internal);
  225115. }
  225116. bool CriticalSection::tryEnter() const throw()
  225117. {
  225118. return pthread_mutex_trylock (&internal) == 0;
  225119. }
  225120. void CriticalSection::exit() const throw()
  225121. {
  225122. pthread_mutex_unlock (&internal);
  225123. }
  225124. class WaitableEventImpl
  225125. {
  225126. public:
  225127. WaitableEventImpl (const bool manualReset_)
  225128. : triggered (false),
  225129. manualReset (manualReset_)
  225130. {
  225131. pthread_cond_init (&condition, 0);
  225132. pthread_mutexattr_t atts;
  225133. pthread_mutexattr_init (&atts);
  225134. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225135. pthread_mutex_init (&mutex, &atts);
  225136. }
  225137. ~WaitableEventImpl()
  225138. {
  225139. pthread_cond_destroy (&condition);
  225140. pthread_mutex_destroy (&mutex);
  225141. }
  225142. bool wait (const int timeOutMillisecs) throw()
  225143. {
  225144. pthread_mutex_lock (&mutex);
  225145. if (! triggered)
  225146. {
  225147. if (timeOutMillisecs < 0)
  225148. {
  225149. do
  225150. {
  225151. pthread_cond_wait (&condition, &mutex);
  225152. }
  225153. while (! triggered);
  225154. }
  225155. else
  225156. {
  225157. struct timeval now;
  225158. gettimeofday (&now, 0);
  225159. struct timespec time;
  225160. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  225161. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  225162. if (time.tv_nsec >= 1000000000)
  225163. {
  225164. time.tv_nsec -= 1000000000;
  225165. time.tv_sec++;
  225166. }
  225167. do
  225168. {
  225169. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  225170. {
  225171. pthread_mutex_unlock (&mutex);
  225172. return false;
  225173. }
  225174. }
  225175. while (! triggered);
  225176. }
  225177. }
  225178. if (! manualReset)
  225179. triggered = false;
  225180. pthread_mutex_unlock (&mutex);
  225181. return true;
  225182. }
  225183. void signal() throw()
  225184. {
  225185. pthread_mutex_lock (&mutex);
  225186. triggered = true;
  225187. pthread_cond_broadcast (&condition);
  225188. pthread_mutex_unlock (&mutex);
  225189. }
  225190. void reset() throw()
  225191. {
  225192. pthread_mutex_lock (&mutex);
  225193. triggered = false;
  225194. pthread_mutex_unlock (&mutex);
  225195. }
  225196. private:
  225197. pthread_cond_t condition;
  225198. pthread_mutex_t mutex;
  225199. bool triggered;
  225200. const bool manualReset;
  225201. WaitableEventImpl (const WaitableEventImpl&);
  225202. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225203. };
  225204. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225205. : internal (new WaitableEventImpl (manualReset))
  225206. {
  225207. }
  225208. WaitableEvent::~WaitableEvent() throw()
  225209. {
  225210. delete static_cast <WaitableEventImpl*> (internal);
  225211. }
  225212. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225213. {
  225214. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225215. }
  225216. void WaitableEvent::signal() const throw()
  225217. {
  225218. static_cast <WaitableEventImpl*> (internal)->signal();
  225219. }
  225220. void WaitableEvent::reset() const throw()
  225221. {
  225222. static_cast <WaitableEventImpl*> (internal)->reset();
  225223. }
  225224. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225225. {
  225226. struct timespec time;
  225227. time.tv_sec = millisecs / 1000;
  225228. time.tv_nsec = (millisecs % 1000) * 1000000;
  225229. nanosleep (&time, 0);
  225230. }
  225231. const juce_wchar File::separator = '/';
  225232. const String File::separatorString ("/");
  225233. const File File::getCurrentWorkingDirectory()
  225234. {
  225235. HeapBlock<char> heapBuffer;
  225236. char localBuffer [1024];
  225237. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225238. int bufferSize = 4096;
  225239. while (cwd == 0 && errno == ERANGE)
  225240. {
  225241. heapBuffer.malloc (bufferSize);
  225242. cwd = getcwd (heapBuffer, bufferSize - 1);
  225243. bufferSize += 1024;
  225244. }
  225245. return File (String::fromUTF8 (cwd));
  225246. }
  225247. bool File::setAsCurrentWorkingDirectory() const
  225248. {
  225249. return chdir (getFullPathName().toUTF8()) == 0;
  225250. }
  225251. static bool juce_stat (const String& fileName, struct stat& info)
  225252. {
  225253. return fileName.isNotEmpty()
  225254. && (stat (fileName.toUTF8(), &info) == 0);
  225255. }
  225256. bool File::isDirectory() const
  225257. {
  225258. struct stat info;
  225259. return fullPath.isEmpty()
  225260. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225261. }
  225262. bool File::exists() const
  225263. {
  225264. return fullPath.isNotEmpty()
  225265. && access (fullPath.toUTF8(), F_OK) == 0;
  225266. }
  225267. bool File::existsAsFile() const
  225268. {
  225269. return exists() && ! isDirectory();
  225270. }
  225271. int64 File::getSize() const
  225272. {
  225273. struct stat info;
  225274. return juce_stat (fullPath, info) ? info.st_size : 0;
  225275. }
  225276. bool File::hasWriteAccess() const
  225277. {
  225278. if (exists())
  225279. return access (fullPath.toUTF8(), W_OK) == 0;
  225280. if ((! isDirectory()) && fullPath.containsChar (separator))
  225281. return getParentDirectory().hasWriteAccess();
  225282. return false;
  225283. }
  225284. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225285. {
  225286. struct stat info;
  225287. const int res = stat (fullPath.toUTF8(), &info);
  225288. if (res != 0)
  225289. return false;
  225290. info.st_mode &= 0777; // Just permissions
  225291. if (shouldBeReadOnly)
  225292. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225293. else
  225294. // Give everybody write permission?
  225295. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225296. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225297. }
  225298. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225299. {
  225300. modificationTime = 0;
  225301. accessTime = 0;
  225302. creationTime = 0;
  225303. struct stat info;
  225304. const int res = stat (fullPath.toUTF8(), &info);
  225305. if (res == 0)
  225306. {
  225307. modificationTime = (int64) info.st_mtime * 1000;
  225308. accessTime = (int64) info.st_atime * 1000;
  225309. creationTime = (int64) info.st_ctime * 1000;
  225310. }
  225311. }
  225312. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225313. {
  225314. struct utimbuf times;
  225315. times.actime = (time_t) (accessTime / 1000);
  225316. times.modtime = (time_t) (modificationTime / 1000);
  225317. return utime (fullPath.toUTF8(), &times) == 0;
  225318. }
  225319. bool File::deleteFile() const
  225320. {
  225321. if (! exists())
  225322. return true;
  225323. else if (isDirectory())
  225324. return rmdir (fullPath.toUTF8()) == 0;
  225325. else
  225326. return remove (fullPath.toUTF8()) == 0;
  225327. }
  225328. bool File::moveInternal (const File& dest) const
  225329. {
  225330. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225331. return true;
  225332. if (hasWriteAccess() && copyInternal (dest))
  225333. {
  225334. if (deleteFile())
  225335. return true;
  225336. dest.deleteFile();
  225337. }
  225338. return false;
  225339. }
  225340. void File::createDirectoryInternal (const String& fileName) const
  225341. {
  225342. mkdir (fileName.toUTF8(), 0777);
  225343. }
  225344. int64 juce_fileSetPosition (void* handle, int64 pos)
  225345. {
  225346. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225347. return pos;
  225348. return -1;
  225349. }
  225350. void FileInputStream::openHandle()
  225351. {
  225352. totalSize = file.getSize();
  225353. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225354. if (f != -1)
  225355. fileHandle = (void*) f;
  225356. }
  225357. void FileInputStream::closeHandle()
  225358. {
  225359. if (fileHandle != 0)
  225360. {
  225361. close ((int) (pointer_sized_int) fileHandle);
  225362. fileHandle = 0;
  225363. }
  225364. }
  225365. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225366. {
  225367. if (fileHandle != 0)
  225368. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225369. return 0;
  225370. }
  225371. void FileOutputStream::openHandle()
  225372. {
  225373. if (file.exists())
  225374. {
  225375. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225376. if (f != -1)
  225377. {
  225378. currentPosition = lseek (f, 0, SEEK_END);
  225379. if (currentPosition >= 0)
  225380. fileHandle = (void*) f;
  225381. else
  225382. close (f);
  225383. }
  225384. }
  225385. else
  225386. {
  225387. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225388. if (f != -1)
  225389. fileHandle = (void*) f;
  225390. }
  225391. }
  225392. void FileOutputStream::closeHandle()
  225393. {
  225394. if (fileHandle != 0)
  225395. {
  225396. close ((int) (pointer_sized_int) fileHandle);
  225397. fileHandle = 0;
  225398. }
  225399. }
  225400. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225401. {
  225402. if (fileHandle != 0)
  225403. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225404. return 0;
  225405. }
  225406. void FileOutputStream::flushInternal()
  225407. {
  225408. if (fileHandle != 0)
  225409. fsync ((int) (pointer_sized_int) fileHandle);
  225410. }
  225411. const File juce_getExecutableFile()
  225412. {
  225413. Dl_info exeInfo;
  225414. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225415. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225416. }
  225417. // if this file doesn't exist, find a parent of it that does..
  225418. static bool juce_doStatFS (File f, struct statfs& result)
  225419. {
  225420. for (int i = 5; --i >= 0;)
  225421. {
  225422. if (f.exists())
  225423. break;
  225424. f = f.getParentDirectory();
  225425. }
  225426. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225427. }
  225428. int64 File::getBytesFreeOnVolume() const
  225429. {
  225430. struct statfs buf;
  225431. if (juce_doStatFS (*this, buf))
  225432. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225433. return 0;
  225434. }
  225435. int64 File::getVolumeTotalSize() const
  225436. {
  225437. struct statfs buf;
  225438. if (juce_doStatFS (*this, buf))
  225439. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225440. return 0;
  225441. }
  225442. const String File::getVolumeLabel() const
  225443. {
  225444. #if JUCE_MAC
  225445. struct VolAttrBuf
  225446. {
  225447. u_int32_t length;
  225448. attrreference_t mountPointRef;
  225449. char mountPointSpace [MAXPATHLEN];
  225450. } attrBuf;
  225451. struct attrlist attrList;
  225452. zerostruct (attrList);
  225453. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225454. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225455. File f (*this);
  225456. for (;;)
  225457. {
  225458. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225459. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225460. (int) attrBuf.mountPointRef.attr_length);
  225461. const File parent (f.getParentDirectory());
  225462. if (f == parent)
  225463. break;
  225464. f = parent;
  225465. }
  225466. #endif
  225467. return String::empty;
  225468. }
  225469. int File::getVolumeSerialNumber() const
  225470. {
  225471. return 0; // xxx
  225472. }
  225473. void juce_runSystemCommand (const String& command)
  225474. {
  225475. int result = system (command.toUTF8());
  225476. (void) result;
  225477. }
  225478. const String juce_getOutputFromCommand (const String& command)
  225479. {
  225480. // slight bodge here, as we just pipe the output into a temp file and read it...
  225481. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225482. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225483. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225484. String result (tempFile.loadFileAsString());
  225485. tempFile.deleteFile();
  225486. return result;
  225487. }
  225488. class InterProcessLock::Pimpl
  225489. {
  225490. public:
  225491. Pimpl (const String& name, const int timeOutMillisecs)
  225492. : handle (0), refCount (1)
  225493. {
  225494. #if JUCE_MAC
  225495. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225496. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225497. #else
  225498. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225499. #endif
  225500. temp.create();
  225501. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225502. if (handle != 0)
  225503. {
  225504. struct flock fl;
  225505. zerostruct (fl);
  225506. fl.l_whence = SEEK_SET;
  225507. fl.l_type = F_WRLCK;
  225508. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225509. for (;;)
  225510. {
  225511. const int result = fcntl (handle, F_SETLK, &fl);
  225512. if (result >= 0)
  225513. return;
  225514. if (errno != EINTR)
  225515. {
  225516. if (timeOutMillisecs == 0
  225517. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225518. break;
  225519. Thread::sleep (10);
  225520. }
  225521. }
  225522. }
  225523. closeFile();
  225524. }
  225525. ~Pimpl()
  225526. {
  225527. closeFile();
  225528. }
  225529. void closeFile()
  225530. {
  225531. if (handle != 0)
  225532. {
  225533. struct flock fl;
  225534. zerostruct (fl);
  225535. fl.l_whence = SEEK_SET;
  225536. fl.l_type = F_UNLCK;
  225537. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225538. {}
  225539. close (handle);
  225540. handle = 0;
  225541. }
  225542. }
  225543. int handle, refCount;
  225544. };
  225545. InterProcessLock::InterProcessLock (const String& name_)
  225546. : name (name_)
  225547. {
  225548. }
  225549. InterProcessLock::~InterProcessLock()
  225550. {
  225551. }
  225552. bool InterProcessLock::enter (const int timeOutMillisecs)
  225553. {
  225554. const ScopedLock sl (lock);
  225555. if (pimpl == 0)
  225556. {
  225557. pimpl = new Pimpl (name, timeOutMillisecs);
  225558. if (pimpl->handle == 0)
  225559. pimpl = 0;
  225560. }
  225561. else
  225562. {
  225563. pimpl->refCount++;
  225564. }
  225565. return pimpl != 0;
  225566. }
  225567. void InterProcessLock::exit()
  225568. {
  225569. const ScopedLock sl (lock);
  225570. // Trying to release the lock too many times!
  225571. jassert (pimpl != 0);
  225572. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225573. pimpl = 0;
  225574. }
  225575. void JUCE_API juce_threadEntryPoint (void*);
  225576. void* threadEntryProc (void* userData)
  225577. {
  225578. JUCE_AUTORELEASEPOOL
  225579. juce_threadEntryPoint (userData);
  225580. return 0;
  225581. }
  225582. void* juce_createThread (void* userData)
  225583. {
  225584. pthread_t handle = 0;
  225585. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225586. {
  225587. pthread_detach (handle);
  225588. return (void*) handle;
  225589. }
  225590. return 0;
  225591. }
  225592. void juce_killThread (void* handle)
  225593. {
  225594. if (handle != 0)
  225595. pthread_cancel ((pthread_t) handle);
  225596. }
  225597. void juce_setCurrentThreadName (const String& /*name*/)
  225598. {
  225599. }
  225600. bool juce_setThreadPriority (void* handle, int priority)
  225601. {
  225602. struct sched_param param;
  225603. int policy;
  225604. priority = jlimit (0, 10, priority);
  225605. if (handle == 0)
  225606. handle = (void*) pthread_self();
  225607. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225608. return false;
  225609. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225610. const int minPriority = sched_get_priority_min (policy);
  225611. const int maxPriority = sched_get_priority_max (policy);
  225612. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225613. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225614. }
  225615. Thread::ThreadID Thread::getCurrentThreadId()
  225616. {
  225617. return (ThreadID) pthread_self();
  225618. }
  225619. void Thread::yield()
  225620. {
  225621. sched_yield();
  225622. }
  225623. /* Remove this macro if you're having problems compiling the cpu affinity
  225624. calls (the API for these has changed about quite a bit in various Linux
  225625. versions, and a lot of distros seem to ship with obsolete versions)
  225626. */
  225627. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225628. #define SUPPORT_AFFINITIES 1
  225629. #endif
  225630. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225631. {
  225632. #if SUPPORT_AFFINITIES
  225633. cpu_set_t affinity;
  225634. CPU_ZERO (&affinity);
  225635. for (int i = 0; i < 32; ++i)
  225636. if ((affinityMask & (1 << i)) != 0)
  225637. CPU_SET (i, &affinity);
  225638. /*
  225639. N.B. If this line causes a compile error, then you've probably not got the latest
  225640. version of glibc installed.
  225641. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225642. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225643. */
  225644. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225645. sched_yield();
  225646. #else
  225647. /* affinities aren't supported because either the appropriate header files weren't found,
  225648. or the SUPPORT_AFFINITIES macro was turned off
  225649. */
  225650. jassertfalse;
  225651. #endif
  225652. }
  225653. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225654. /*** Start of inlined file: juce_mac_Files.mm ***/
  225655. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225656. // compiled on its own).
  225657. #if JUCE_INCLUDED_FILE
  225658. /*
  225659. Note that a lot of methods that you'd expect to find in this file actually
  225660. live in juce_posix_SharedCode.h!
  225661. */
  225662. bool File::copyInternal (const File& dest) const
  225663. {
  225664. const ScopedAutoReleasePool pool;
  225665. NSFileManager* fm = [NSFileManager defaultManager];
  225666. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225667. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225668. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225669. toPath: juceStringToNS (dest.getFullPathName())
  225670. error: nil];
  225671. #else
  225672. && [fm copyPath: juceStringToNS (fullPath)
  225673. toPath: juceStringToNS (dest.getFullPathName())
  225674. handler: nil];
  225675. #endif
  225676. }
  225677. void File::findFileSystemRoots (Array<File>& destArray)
  225678. {
  225679. destArray.add (File ("/"));
  225680. }
  225681. static bool isFileOnDriveType (const File& f, const char* const* types)
  225682. {
  225683. struct statfs buf;
  225684. if (juce_doStatFS (f, buf))
  225685. {
  225686. const String type (buf.f_fstypename);
  225687. while (*types != 0)
  225688. if (type.equalsIgnoreCase (*types++))
  225689. return true;
  225690. }
  225691. return false;
  225692. }
  225693. bool File::isOnCDRomDrive() const
  225694. {
  225695. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225696. return isFileOnDriveType (*this, cdTypes);
  225697. }
  225698. bool File::isOnHardDisk() const
  225699. {
  225700. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225701. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225702. }
  225703. bool File::isOnRemovableDrive() const
  225704. {
  225705. #if JUCE_IOS
  225706. return false; // xxx is this possible?
  225707. #else
  225708. const ScopedAutoReleasePool pool;
  225709. BOOL removable = false;
  225710. [[NSWorkspace sharedWorkspace]
  225711. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225712. isRemovable: &removable
  225713. isWritable: nil
  225714. isUnmountable: nil
  225715. description: nil
  225716. type: nil];
  225717. return removable;
  225718. #endif
  225719. }
  225720. static bool juce_isHiddenFile (const String& path)
  225721. {
  225722. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225723. const ScopedAutoReleasePool pool;
  225724. NSNumber* hidden = nil;
  225725. NSError* err = nil;
  225726. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225727. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225728. && [hidden boolValue];
  225729. #else
  225730. #if JUCE_IOS
  225731. return File (path).getFileName().startsWithChar ('.');
  225732. #else
  225733. FSRef ref;
  225734. LSItemInfoRecord info;
  225735. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225736. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225737. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225738. #endif
  225739. #endif
  225740. }
  225741. bool File::isHidden() const
  225742. {
  225743. return juce_isHiddenFile (getFullPathName());
  225744. }
  225745. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225746. const File File::getSpecialLocation (const SpecialLocationType type)
  225747. {
  225748. const ScopedAutoReleasePool pool;
  225749. String resultPath;
  225750. switch (type)
  225751. {
  225752. case userHomeDirectory:
  225753. resultPath = nsStringToJuce (NSHomeDirectory());
  225754. break;
  225755. case userDocumentsDirectory:
  225756. resultPath = "~/Documents";
  225757. break;
  225758. case userDesktopDirectory:
  225759. resultPath = "~/Desktop";
  225760. break;
  225761. case userApplicationDataDirectory:
  225762. resultPath = "~/Library";
  225763. break;
  225764. case commonApplicationDataDirectory:
  225765. resultPath = "/Library";
  225766. break;
  225767. case globalApplicationsDirectory:
  225768. resultPath = "/Applications";
  225769. break;
  225770. case userMusicDirectory:
  225771. resultPath = "~/Music";
  225772. break;
  225773. case userMoviesDirectory:
  225774. resultPath = "~/Movies";
  225775. break;
  225776. case tempDirectory:
  225777. {
  225778. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225779. tmp.createDirectory();
  225780. return tmp.getFullPathName();
  225781. }
  225782. case invokedExecutableFile:
  225783. if (juce_Argv0 != 0)
  225784. return File (String::fromUTF8 (juce_Argv0));
  225785. // deliberate fall-through...
  225786. case currentExecutableFile:
  225787. return juce_getExecutableFile();
  225788. case currentApplicationFile:
  225789. {
  225790. const File exe (juce_getExecutableFile());
  225791. const File parent (exe.getParentDirectory());
  225792. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225793. ? parent.getParentDirectory().getParentDirectory()
  225794. : exe;
  225795. }
  225796. case hostApplicationPath:
  225797. {
  225798. unsigned int size = 8192;
  225799. HeapBlock<char> buffer;
  225800. buffer.calloc (size + 8);
  225801. _NSGetExecutablePath (buffer.getData(), &size);
  225802. return String::fromUTF8 (buffer, size);
  225803. }
  225804. default:
  225805. jassertfalse; // unknown type?
  225806. break;
  225807. }
  225808. if (resultPath.isNotEmpty())
  225809. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225810. return File::nonexistent;
  225811. }
  225812. const String File::getVersion() const
  225813. {
  225814. const ScopedAutoReleasePool pool;
  225815. String result;
  225816. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225817. if (bundle != 0)
  225818. {
  225819. NSDictionary* info = [bundle infoDictionary];
  225820. if (info != 0)
  225821. {
  225822. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225823. if (name != nil)
  225824. result = nsStringToJuce (name);
  225825. }
  225826. }
  225827. return result;
  225828. }
  225829. const File File::getLinkedTarget() const
  225830. {
  225831. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225832. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225833. #else
  225834. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225835. #endif
  225836. if (dest != nil)
  225837. return File (nsStringToJuce (dest));
  225838. return *this;
  225839. }
  225840. bool File::moveToTrash() const
  225841. {
  225842. if (! exists())
  225843. return true;
  225844. #if JUCE_IOS
  225845. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225846. #else
  225847. const ScopedAutoReleasePool pool;
  225848. NSString* p = juceStringToNS (getFullPathName());
  225849. return [[NSWorkspace sharedWorkspace]
  225850. performFileOperation: NSWorkspaceRecycleOperation
  225851. source: [p stringByDeletingLastPathComponent]
  225852. destination: @""
  225853. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225854. tag: nil ];
  225855. #endif
  225856. }
  225857. class DirectoryIterator::NativeIterator::Pimpl
  225858. {
  225859. public:
  225860. Pimpl (const File& directory, const String& wildCard_)
  225861. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225862. wildCard (wildCard_),
  225863. enumerator (0)
  225864. {
  225865. const ScopedAutoReleasePool pool;
  225866. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225867. wildcardUTF8 = wildCard.toUTF8();
  225868. }
  225869. ~Pimpl()
  225870. {
  225871. [enumerator release];
  225872. }
  225873. bool next (String& filenameFound,
  225874. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225875. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225876. {
  225877. const ScopedAutoReleasePool pool;
  225878. for (;;)
  225879. {
  225880. NSString* file;
  225881. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225882. return false;
  225883. [enumerator skipDescendents];
  225884. filenameFound = nsStringToJuce (file);
  225885. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225886. continue;
  225887. const String path (parentDir + filenameFound);
  225888. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225889. {
  225890. struct stat info;
  225891. const bool statOk = juce_stat (path, info);
  225892. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225893. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225894. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225895. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225896. }
  225897. if (isHidden != 0)
  225898. *isHidden = juce_isHiddenFile (path);
  225899. if (isReadOnly != 0)
  225900. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225901. return true;
  225902. }
  225903. }
  225904. private:
  225905. String parentDir, wildCard;
  225906. const char* wildcardUTF8;
  225907. NSDirectoryEnumerator* enumerator;
  225908. Pimpl (const Pimpl&);
  225909. Pimpl& operator= (const Pimpl&);
  225910. };
  225911. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225912. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225913. {
  225914. }
  225915. DirectoryIterator::NativeIterator::~NativeIterator()
  225916. {
  225917. }
  225918. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225919. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225920. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225921. {
  225922. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225923. }
  225924. bool juce_launchExecutable (const String& pathAndArguments)
  225925. {
  225926. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225927. const int cpid = fork();
  225928. if (cpid == 0)
  225929. {
  225930. // Child process
  225931. if (execve (argv[0], (char**) argv, 0) < 0)
  225932. exit (0);
  225933. }
  225934. else
  225935. {
  225936. if (cpid < 0)
  225937. return false;
  225938. }
  225939. return true;
  225940. }
  225941. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225942. {
  225943. #if JUCE_IOS
  225944. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225945. #else
  225946. const ScopedAutoReleasePool pool;
  225947. if (parameters.isEmpty())
  225948. {
  225949. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225950. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225951. }
  225952. bool ok = false;
  225953. if (PlatformUtilities::isBundle (fileName))
  225954. {
  225955. NSMutableArray* urls = [NSMutableArray array];
  225956. StringArray docs;
  225957. docs.addTokens (parameters, true);
  225958. for (int i = 0; i < docs.size(); ++i)
  225959. [urls addObject: juceStringToNS (docs[i])];
  225960. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225961. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225962. options: 0
  225963. additionalEventParamDescriptor: nil
  225964. launchIdentifiers: nil];
  225965. }
  225966. else if (File (fileName).exists())
  225967. {
  225968. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  225969. }
  225970. return ok;
  225971. #endif
  225972. }
  225973. void File::revealToUser() const
  225974. {
  225975. #if ! JUCE_IOS
  225976. if (exists())
  225977. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225978. else if (getParentDirectory().exists())
  225979. getParentDirectory().revealToUser();
  225980. #endif
  225981. }
  225982. #if ! JUCE_IOS
  225983. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225984. {
  225985. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225986. }
  225987. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225988. {
  225989. char path [2048];
  225990. zerostruct (path);
  225991. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225992. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225993. return String::empty;
  225994. }
  225995. #endif
  225996. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225997. {
  225998. const ScopedAutoReleasePool pool;
  225999. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  226000. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  226001. #else
  226002. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  226003. #endif
  226004. return [fileDict fileHFSTypeCode];
  226005. }
  226006. bool PlatformUtilities::isBundle (const String& filename)
  226007. {
  226008. #if JUCE_IOS
  226009. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  226010. #else
  226011. const ScopedAutoReleasePool pool;
  226012. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  226013. #endif
  226014. }
  226015. #endif
  226016. /*** End of inlined file: juce_mac_Files.mm ***/
  226017. #if JUCE_IOS
  226018. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  226019. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226020. // compiled on its own).
  226021. #if JUCE_INCLUDED_FILE
  226022. END_JUCE_NAMESPACE
  226023. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  226024. {
  226025. }
  226026. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  226027. - (void) applicationWillTerminate: (UIApplication*) application;
  226028. @end
  226029. @implementation JuceAppStartupDelegate
  226030. - (void) applicationDidFinishLaunching: (UIApplication*) application
  226031. {
  226032. initialiseJuce_GUI();
  226033. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  226034. exit (0);
  226035. }
  226036. - (void) applicationWillTerminate: (UIApplication*) application
  226037. {
  226038. jassert (JUCEApplication::getInstance() != 0);
  226039. JUCEApplication::getInstance()->shutdownApp();
  226040. delete JUCEApplication::getInstance();
  226041. shutdownJuce_GUI();
  226042. }
  226043. @end
  226044. BEGIN_JUCE_NAMESPACE
  226045. int juce_iOSMain (int argc, const char* argv[])
  226046. {
  226047. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  226048. }
  226049. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226050. {
  226051. pool = [[NSAutoreleasePool alloc] init];
  226052. }
  226053. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226054. {
  226055. [((NSAutoreleasePool*) pool) release];
  226056. }
  226057. void PlatformUtilities::beep()
  226058. {
  226059. //xxx
  226060. //AudioServicesPlaySystemSound ();
  226061. }
  226062. void PlatformUtilities::addItemToDock (const File& file)
  226063. {
  226064. }
  226065. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226066. END_JUCE_NAMESPACE
  226067. @interface JuceAlertBoxDelegate : NSObject
  226068. {
  226069. @public
  226070. bool clickedOk;
  226071. }
  226072. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  226073. @end
  226074. @implementation JuceAlertBoxDelegate
  226075. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  226076. {
  226077. clickedOk = (buttonIndex == 0);
  226078. alertView.hidden = true;
  226079. }
  226080. @end
  226081. BEGIN_JUCE_NAMESPACE
  226082. // (This function is used directly by other bits of code)
  226083. bool juce_iPhoneShowModalAlert (const String& title,
  226084. const String& bodyText,
  226085. NSString* okButtonText,
  226086. NSString* cancelButtonText)
  226087. {
  226088. const ScopedAutoReleasePool pool;
  226089. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  226090. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  226091. message: juceStringToNS (bodyText)
  226092. delegate: callback
  226093. cancelButtonTitle: okButtonText
  226094. otherButtonTitles: cancelButtonText, nil];
  226095. [alert retain];
  226096. [alert show];
  226097. while (! alert.hidden && alert.superview != nil)
  226098. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  226099. const bool result = callback->clickedOk;
  226100. [alert release];
  226101. [callback release];
  226102. return result;
  226103. }
  226104. bool AlertWindow::showNativeDialogBox (const String& title,
  226105. const String& bodyText,
  226106. bool isOkCancel)
  226107. {
  226108. return juce_iPhoneShowModalAlert (title, bodyText,
  226109. @"OK",
  226110. isOkCancel ? @"Cancel" : nil);
  226111. }
  226112. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  226113. {
  226114. jassertfalse; // no such thing on the iphone!
  226115. return false;
  226116. }
  226117. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  226118. {
  226119. jassertfalse; // no such thing on the iphone!
  226120. return false;
  226121. }
  226122. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226123. {
  226124. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  226125. }
  226126. bool Desktop::isScreenSaverEnabled()
  226127. {
  226128. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  226129. }
  226130. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  226131. {
  226132. const ScopedAutoReleasePool pool;
  226133. monitorCoords.clear();
  226134. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  226135. : [[UIScreen mainScreen] bounds];
  226136. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  226137. (int) r.origin.y,
  226138. (int) r.size.width,
  226139. (int) r.size.height));
  226140. }
  226141. #endif
  226142. #endif
  226143. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  226144. #else
  226145. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  226146. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226147. // compiled on its own).
  226148. #if JUCE_INCLUDED_FILE
  226149. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226150. {
  226151. pool = [[NSAutoreleasePool alloc] init];
  226152. }
  226153. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226154. {
  226155. [((NSAutoreleasePool*) pool) release];
  226156. }
  226157. void PlatformUtilities::beep()
  226158. {
  226159. NSBeep();
  226160. }
  226161. void PlatformUtilities::addItemToDock (const File& file)
  226162. {
  226163. // check that it's not already there...
  226164. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  226165. .containsIgnoreCase (file.getFullPathName()))
  226166. {
  226167. 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>"
  226168. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  226169. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  226170. }
  226171. }
  226172. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226173. bool AlertWindow::showNativeDialogBox (const String& title,
  226174. const String& bodyText,
  226175. bool isOkCancel)
  226176. {
  226177. const ScopedAutoReleasePool pool;
  226178. return NSRunAlertPanel (juceStringToNS (title),
  226179. juceStringToNS (bodyText),
  226180. @"Ok",
  226181. isOkCancel ? @"Cancel" : nil,
  226182. nil) == NSAlertDefaultReturn;
  226183. }
  226184. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226185. {
  226186. if (files.size() == 0)
  226187. return false;
  226188. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226189. if (draggingSource == 0)
  226190. {
  226191. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226192. return false;
  226193. }
  226194. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226195. if (sourceComp == 0)
  226196. {
  226197. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226198. return false;
  226199. }
  226200. const ScopedAutoReleasePool pool;
  226201. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226202. if (view == 0)
  226203. return false;
  226204. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226205. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226206. owner: nil];
  226207. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226208. for (int i = 0; i < files.size(); ++i)
  226209. [filesArray addObject: juceStringToNS (files[i])];
  226210. [pboard setPropertyList: filesArray
  226211. forType: NSFilenamesPboardType];
  226212. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226213. fromView: nil];
  226214. dragPosition.x -= 16;
  226215. dragPosition.y -= 16;
  226216. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226217. at: dragPosition
  226218. offset: NSMakeSize (0, 0)
  226219. event: [[view window] currentEvent]
  226220. pasteboard: pboard
  226221. source: view
  226222. slideBack: YES];
  226223. return true;
  226224. }
  226225. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226226. {
  226227. jassertfalse; // not implemented!
  226228. return false;
  226229. }
  226230. bool Desktop::canUseSemiTransparentWindows() throw()
  226231. {
  226232. return true;
  226233. }
  226234. const Point<int> Desktop::getMousePosition()
  226235. {
  226236. const ScopedAutoReleasePool pool;
  226237. const NSPoint p ([NSEvent mouseLocation]);
  226238. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226239. }
  226240. void Desktop::setMousePosition (const Point<int>& newPosition)
  226241. {
  226242. // this rubbish needs to be done around the warp call, to avoid causing a
  226243. // bizarre glitch..
  226244. CGAssociateMouseAndMouseCursorPosition (false);
  226245. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226246. CGAssociateMouseAndMouseCursorPosition (true);
  226247. }
  226248. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226249. class ScreenSaverDefeater : public Timer,
  226250. public DeletedAtShutdown
  226251. {
  226252. public:
  226253. ScreenSaverDefeater()
  226254. {
  226255. startTimer (10000);
  226256. timerCallback();
  226257. }
  226258. ~ScreenSaverDefeater() {}
  226259. void timerCallback()
  226260. {
  226261. if (Process::isForegroundProcess())
  226262. UpdateSystemActivity (UsrActivity);
  226263. }
  226264. };
  226265. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226266. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226267. {
  226268. if (isEnabled)
  226269. deleteAndZero (screenSaverDefeater);
  226270. else if (screenSaverDefeater == 0)
  226271. screenSaverDefeater = new ScreenSaverDefeater();
  226272. }
  226273. bool Desktop::isScreenSaverEnabled()
  226274. {
  226275. return screenSaverDefeater == 0;
  226276. }
  226277. #else
  226278. static IOPMAssertionID screenSaverDisablerID = 0;
  226279. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226280. {
  226281. if (isEnabled)
  226282. {
  226283. if (screenSaverDisablerID != 0)
  226284. {
  226285. IOPMAssertionRelease (screenSaverDisablerID);
  226286. screenSaverDisablerID = 0;
  226287. }
  226288. }
  226289. else
  226290. {
  226291. if (screenSaverDisablerID == 0)
  226292. {
  226293. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226294. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226295. CFSTR ("Juce"), &screenSaverDisablerID);
  226296. #else
  226297. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226298. &screenSaverDisablerID);
  226299. #endif
  226300. }
  226301. }
  226302. }
  226303. bool Desktop::isScreenSaverEnabled()
  226304. {
  226305. return screenSaverDisablerID == 0;
  226306. }
  226307. #endif
  226308. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226309. {
  226310. const ScopedAutoReleasePool pool;
  226311. monitorCoords.clear();
  226312. NSArray* screens = [NSScreen screens];
  226313. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226314. for (unsigned int i = 0; i < [screens count]; ++i)
  226315. {
  226316. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226317. NSRect r = clipToWorkArea ? [s visibleFrame]
  226318. : [s frame];
  226319. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  226320. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  226321. (int) r.size.width,
  226322. (int) r.size.height));
  226323. }
  226324. jassert (monitorCoords.size() > 0);
  226325. }
  226326. #endif
  226327. #endif
  226328. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226329. #endif
  226330. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226331. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226332. // compiled on its own).
  226333. #if JUCE_INCLUDED_FILE
  226334. void Logger::outputDebugString (const String& text)
  226335. {
  226336. std::cerr << text << std::endl;
  226337. }
  226338. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  226339. {
  226340. static char testResult = 0;
  226341. if (testResult == 0)
  226342. {
  226343. struct kinfo_proc info;
  226344. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226345. size_t sz = sizeof (info);
  226346. sysctl (m, 4, &info, &sz, 0, 0);
  226347. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226348. }
  226349. return testResult > 0;
  226350. }
  226351. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226352. {
  226353. return juce_isRunningUnderDebugger();
  226354. }
  226355. #endif
  226356. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226357. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226358. #if JUCE_IOS
  226359. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226360. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226361. // compiled on its own).
  226362. #if JUCE_INCLUDED_FILE
  226363. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226364. #define SUPPORT_10_4_FONTS 1
  226365. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226366. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226367. #define SUPPORT_ONLY_10_4_FONTS 1
  226368. #endif
  226369. END_JUCE_NAMESPACE
  226370. @interface NSFont (PrivateHack)
  226371. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226372. @end
  226373. BEGIN_JUCE_NAMESPACE
  226374. #endif
  226375. class MacTypeface : public Typeface
  226376. {
  226377. public:
  226378. MacTypeface (const Font& font)
  226379. : Typeface (font.getTypefaceName())
  226380. {
  226381. const ScopedAutoReleasePool pool;
  226382. renderingTransform = CGAffineTransformIdentity;
  226383. bool needsItalicTransform = false;
  226384. #if JUCE_IOS
  226385. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226386. if (font.isItalic() || font.isBold())
  226387. {
  226388. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226389. for (NSString* i in familyFonts)
  226390. {
  226391. const String fn (nsStringToJuce (i));
  226392. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226393. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226394. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226395. || afterDash.containsIgnoreCase ("italic")
  226396. || fn.endsWithIgnoreCase ("oblique")
  226397. || fn.endsWithIgnoreCase ("italic");
  226398. if (probablyBold == font.isBold()
  226399. && probablyItalic == font.isItalic())
  226400. {
  226401. fontName = i;
  226402. needsItalicTransform = false;
  226403. break;
  226404. }
  226405. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226406. {
  226407. fontName = i;
  226408. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226409. }
  226410. }
  226411. if (needsItalicTransform)
  226412. renderingTransform.c = 0.15f;
  226413. }
  226414. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226415. const int ascender = abs (CGFontGetAscent (fontRef));
  226416. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226417. ascent = ascender / totalHeight;
  226418. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226419. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226420. #else
  226421. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226422. if (font.isItalic())
  226423. {
  226424. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226425. toHaveTrait: NSItalicFontMask];
  226426. if (newFont == nsFont)
  226427. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226428. nsFont = newFont;
  226429. }
  226430. if (font.isBold())
  226431. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226432. [nsFont retain];
  226433. ascent = std::abs ((float) [nsFont ascender]);
  226434. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226435. ascent /= totalSize;
  226436. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226437. if (needsItalicTransform)
  226438. {
  226439. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226440. renderingTransform.c = 0.15f;
  226441. }
  226442. #if SUPPORT_ONLY_10_4_FONTS
  226443. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226444. if (atsFont == 0)
  226445. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226446. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226447. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226448. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226449. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226450. #else
  226451. #if SUPPORT_10_4_FONTS
  226452. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226453. {
  226454. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226455. if (atsFont == 0)
  226456. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226457. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226458. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226459. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226460. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226461. }
  226462. else
  226463. #endif
  226464. {
  226465. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226466. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226467. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226468. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226469. }
  226470. #endif
  226471. #endif
  226472. }
  226473. ~MacTypeface()
  226474. {
  226475. #if ! JUCE_IOS
  226476. [nsFont release];
  226477. #endif
  226478. if (fontRef != 0)
  226479. CGFontRelease (fontRef);
  226480. }
  226481. float getAscent() const
  226482. {
  226483. return ascent;
  226484. }
  226485. float getDescent() const
  226486. {
  226487. return 1.0f - ascent;
  226488. }
  226489. float getStringWidth (const String& text)
  226490. {
  226491. if (fontRef == 0 || text.isEmpty())
  226492. return 0;
  226493. const int length = text.length();
  226494. HeapBlock <CGGlyph> glyphs;
  226495. createGlyphsForString (text, length, glyphs);
  226496. float x = 0;
  226497. #if SUPPORT_ONLY_10_4_FONTS
  226498. HeapBlock <NSSize> advances (length);
  226499. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226500. for (int i = 0; i < length; ++i)
  226501. x += advances[i].width;
  226502. #else
  226503. #if SUPPORT_10_4_FONTS
  226504. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226505. {
  226506. HeapBlock <NSSize> advances (length);
  226507. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226508. for (int i = 0; i < length; ++i)
  226509. x += advances[i].width;
  226510. }
  226511. else
  226512. #endif
  226513. {
  226514. HeapBlock <int> advances (length);
  226515. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226516. for (int i = 0; i < length; ++i)
  226517. x += advances[i];
  226518. }
  226519. #endif
  226520. return x * unitsToHeightScaleFactor;
  226521. }
  226522. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226523. {
  226524. xOffsets.add (0);
  226525. if (fontRef == 0 || text.isEmpty())
  226526. return;
  226527. const int length = text.length();
  226528. HeapBlock <CGGlyph> glyphs;
  226529. createGlyphsForString (text, length, glyphs);
  226530. #if SUPPORT_ONLY_10_4_FONTS
  226531. HeapBlock <NSSize> advances (length);
  226532. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226533. int x = 0;
  226534. for (int i = 0; i < length; ++i)
  226535. {
  226536. x += advances[i].width;
  226537. xOffsets.add (x * unitsToHeightScaleFactor);
  226538. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226539. }
  226540. #else
  226541. #if SUPPORT_10_4_FONTS
  226542. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226543. {
  226544. HeapBlock <NSSize> advances (length);
  226545. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226546. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226547. float x = 0;
  226548. for (int i = 0; i < length; ++i)
  226549. {
  226550. x += advances[i].width;
  226551. xOffsets.add (x * unitsToHeightScaleFactor);
  226552. resultGlyphs.add (nsGlyphs[i]);
  226553. }
  226554. }
  226555. else
  226556. #endif
  226557. {
  226558. HeapBlock <int> advances (length);
  226559. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226560. {
  226561. int x = 0;
  226562. for (int i = 0; i < length; ++i)
  226563. {
  226564. x += advances [i];
  226565. xOffsets.add (x * unitsToHeightScaleFactor);
  226566. resultGlyphs.add (glyphs[i]);
  226567. }
  226568. }
  226569. }
  226570. #endif
  226571. }
  226572. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226573. {
  226574. #if JUCE_IOS
  226575. return false;
  226576. #else
  226577. if (nsFont == 0)
  226578. return false;
  226579. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226580. jassert (path.isEmpty());
  226581. const ScopedAutoReleasePool pool;
  226582. NSBezierPath* bez = [NSBezierPath bezierPath];
  226583. [bez moveToPoint: NSMakePoint (0, 0)];
  226584. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226585. inFont: nsFont];
  226586. for (int i = 0; i < [bez elementCount]; ++i)
  226587. {
  226588. NSPoint p[3];
  226589. switch ([bez elementAtIndex: i associatedPoints: p])
  226590. {
  226591. case NSMoveToBezierPathElement:
  226592. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226593. break;
  226594. case NSLineToBezierPathElement:
  226595. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226596. break;
  226597. case NSCurveToBezierPathElement:
  226598. 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);
  226599. break;
  226600. case NSClosePathBezierPathElement:
  226601. path.closeSubPath();
  226602. break;
  226603. default:
  226604. jassertfalse;
  226605. break;
  226606. }
  226607. }
  226608. path.applyTransform (pathTransform);
  226609. return true;
  226610. #endif
  226611. }
  226612. juce_UseDebuggingNewOperator
  226613. CGFontRef fontRef;
  226614. float fontHeightToCGSizeFactor;
  226615. CGAffineTransform renderingTransform;
  226616. private:
  226617. float ascent, unitsToHeightScaleFactor;
  226618. #if JUCE_IOS
  226619. #else
  226620. NSFont* nsFont;
  226621. AffineTransform pathTransform;
  226622. #endif
  226623. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226624. {
  226625. #if SUPPORT_10_4_FONTS
  226626. #if ! SUPPORT_ONLY_10_4_FONTS
  226627. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226628. #endif
  226629. {
  226630. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226631. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226632. for (int i = 0; i < length; ++i)
  226633. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226634. return;
  226635. }
  226636. #endif
  226637. #if ! SUPPORT_ONLY_10_4_FONTS
  226638. if (charToGlyphMapper == 0)
  226639. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226640. glyphs.malloc (length);
  226641. for (int i = 0; i < length; ++i)
  226642. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226643. #endif
  226644. }
  226645. #if ! SUPPORT_ONLY_10_4_FONTS
  226646. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226647. class CharToGlyphMapper
  226648. {
  226649. public:
  226650. CharToGlyphMapper (CGFontRef fontRef)
  226651. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226652. idRangeOffset (0), glyphIndexes (0)
  226653. {
  226654. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226655. if (cmapTable != 0)
  226656. {
  226657. const int numSubtables = getValue16 (cmapTable, 2);
  226658. for (int i = 0; i < numSubtables; ++i)
  226659. {
  226660. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226661. {
  226662. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226663. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226664. {
  226665. const int length = getValue16 (cmapTable, offset + 2);
  226666. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226667. segCount = segCountX2 / 2;
  226668. const int endCodeOffset = offset + 14;
  226669. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226670. const int idDeltaOffset = startCodeOffset + segCountX2;
  226671. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226672. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226673. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226674. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226675. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226676. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226677. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226678. }
  226679. break;
  226680. }
  226681. }
  226682. CFRelease (cmapTable);
  226683. }
  226684. }
  226685. ~CharToGlyphMapper()
  226686. {
  226687. if (endCode != 0)
  226688. {
  226689. CFRelease (endCode);
  226690. CFRelease (startCode);
  226691. CFRelease (idDelta);
  226692. CFRelease (idRangeOffset);
  226693. CFRelease (glyphIndexes);
  226694. }
  226695. }
  226696. int getGlyphForCharacter (const juce_wchar c) const
  226697. {
  226698. for (int i = 0; i < segCount; ++i)
  226699. {
  226700. if (getValue16 (endCode, i * 2) >= c)
  226701. {
  226702. const int start = getValue16 (startCode, i * 2);
  226703. if (start > c)
  226704. break;
  226705. const int delta = getValue16 (idDelta, i * 2);
  226706. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226707. if (rangeOffset == 0)
  226708. return delta + c;
  226709. else
  226710. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226711. }
  226712. }
  226713. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226714. return jmax (-1, c - 29);
  226715. }
  226716. private:
  226717. int segCount;
  226718. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226719. static uint16 getValue16 (CFDataRef data, const int index)
  226720. {
  226721. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226722. }
  226723. static uint32 getValue32 (CFDataRef data, const int index)
  226724. {
  226725. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226726. }
  226727. };
  226728. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226729. #endif
  226730. MacTypeface (const MacTypeface&);
  226731. MacTypeface& operator= (const MacTypeface&);
  226732. };
  226733. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226734. {
  226735. return new MacTypeface (font);
  226736. }
  226737. const StringArray Font::findAllTypefaceNames()
  226738. {
  226739. StringArray names;
  226740. const ScopedAutoReleasePool pool;
  226741. #if JUCE_IOS
  226742. NSArray* fonts = [UIFont familyNames];
  226743. #else
  226744. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226745. #endif
  226746. for (unsigned int i = 0; i < [fonts count]; ++i)
  226747. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226748. names.sort (true);
  226749. return names;
  226750. }
  226751. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226752. {
  226753. #if JUCE_IOS
  226754. defaultSans = "Helvetica";
  226755. defaultSerif = "Times New Roman";
  226756. defaultFixed = "Courier New";
  226757. #else
  226758. defaultSans = "Lucida Grande";
  226759. defaultSerif = "Times New Roman";
  226760. defaultFixed = "Monaco";
  226761. #endif
  226762. }
  226763. #endif
  226764. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226765. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226766. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226767. // compiled on its own).
  226768. #if JUCE_INCLUDED_FILE
  226769. class CoreGraphicsImage : public Image::SharedImage
  226770. {
  226771. public:
  226772. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226773. : Image::SharedImage (format_, width_, height_)
  226774. {
  226775. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226776. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226777. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226778. imageData = imageDataAllocated;
  226779. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226780. : CGColorSpaceCreateDeviceRGB();
  226781. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226782. colourSpace, getCGImageFlags (format_));
  226783. CGColorSpaceRelease (colourSpace);
  226784. }
  226785. ~CoreGraphicsImage()
  226786. {
  226787. CGContextRelease (context);
  226788. }
  226789. Image::ImageType getType() const { return Image::NativeImage; }
  226790. LowLevelGraphicsContext* createLowLevelContext();
  226791. SharedImage* clone()
  226792. {
  226793. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226794. memcpy (im->imageData, imageData, lineStride * height);
  226795. return im;
  226796. }
  226797. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226798. {
  226799. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226800. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226801. {
  226802. return CGBitmapContextCreateImage (nativeImage->context);
  226803. }
  226804. else
  226805. {
  226806. const Image::BitmapData srcData (juceImage, false);
  226807. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226808. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226809. 8, srcData.pixelStride * 8, srcData.lineStride,
  226810. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226811. 0, true, kCGRenderingIntentDefault);
  226812. CGDataProviderRelease (provider);
  226813. return imageRef;
  226814. }
  226815. }
  226816. #if JUCE_MAC
  226817. static NSImage* createNSImage (const Image& image)
  226818. {
  226819. const ScopedAutoReleasePool pool;
  226820. NSImage* im = [[NSImage alloc] init];
  226821. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226822. [im lockFocus];
  226823. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226824. CGImageRef imageRef = createImage (image, false, colourSpace);
  226825. CGColorSpaceRelease (colourSpace);
  226826. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226827. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226828. CGImageRelease (imageRef);
  226829. [im unlockFocus];
  226830. return im;
  226831. }
  226832. #endif
  226833. CGContextRef context;
  226834. HeapBlock<uint8> imageDataAllocated;
  226835. private:
  226836. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226837. {
  226838. #if JUCE_BIG_ENDIAN
  226839. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226840. #else
  226841. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226842. #endif
  226843. }
  226844. };
  226845. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226846. {
  226847. #if USE_COREGRAPHICS_RENDERING
  226848. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226849. #else
  226850. return createSoftwareImage (format, width, height, clearImage);
  226851. #endif
  226852. }
  226853. class CoreGraphicsContext : public LowLevelGraphicsContext
  226854. {
  226855. public:
  226856. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226857. : context (context_),
  226858. flipHeight (flipHeight_),
  226859. state (new SavedState()),
  226860. numGradientLookupEntries (0),
  226861. lastClipRectIsValid (false)
  226862. {
  226863. CGContextRetain (context);
  226864. CGContextSaveGState(context);
  226865. CGContextSetShouldSmoothFonts (context, true);
  226866. CGContextSetShouldAntialias (context, true);
  226867. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226868. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226869. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226870. gradientCallbacks.version = 0;
  226871. gradientCallbacks.evaluate = gradientCallback;
  226872. gradientCallbacks.releaseInfo = 0;
  226873. setFont (Font());
  226874. }
  226875. ~CoreGraphicsContext()
  226876. {
  226877. CGContextRestoreGState (context);
  226878. CGContextRelease (context);
  226879. CGColorSpaceRelease (rgbColourSpace);
  226880. CGColorSpaceRelease (greyColourSpace);
  226881. }
  226882. bool isVectorDevice() const { return false; }
  226883. void setOrigin (int x, int y)
  226884. {
  226885. CGContextTranslateCTM (context, x, -y);
  226886. if (lastClipRectIsValid)
  226887. lastClipRect.translate (-x, -y);
  226888. }
  226889. bool clipToRectangle (const Rectangle<int>& r)
  226890. {
  226891. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226892. if (lastClipRectIsValid)
  226893. {
  226894. // This is actually incorrect, because the actual clip region may be complex, and
  226895. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226896. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226897. // when calculating the resultant clip bounds, and makes the same mistake!
  226898. lastClipRect = lastClipRect.getIntersection (r);
  226899. return ! lastClipRect.isEmpty();
  226900. }
  226901. return ! isClipEmpty();
  226902. }
  226903. bool clipToRectangleList (const RectangleList& clipRegion)
  226904. {
  226905. if (clipRegion.isEmpty())
  226906. {
  226907. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226908. lastClipRectIsValid = true;
  226909. lastClipRect = Rectangle<int>();
  226910. return false;
  226911. }
  226912. else
  226913. {
  226914. const int numRects = clipRegion.getNumRectangles();
  226915. HeapBlock <CGRect> rects (numRects);
  226916. for (int i = 0; i < numRects; ++i)
  226917. {
  226918. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226919. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226920. }
  226921. CGContextClipToRects (context, rects, numRects);
  226922. lastClipRectIsValid = false;
  226923. return ! isClipEmpty();
  226924. }
  226925. }
  226926. void excludeClipRectangle (const Rectangle<int>& r)
  226927. {
  226928. RectangleList remaining (getClipBounds());
  226929. remaining.subtract (r);
  226930. clipToRectangleList (remaining);
  226931. lastClipRectIsValid = false;
  226932. }
  226933. void clipToPath (const Path& path, const AffineTransform& transform)
  226934. {
  226935. createPath (path, transform);
  226936. CGContextClip (context);
  226937. lastClipRectIsValid = false;
  226938. }
  226939. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226940. {
  226941. if (! transform.isSingularity())
  226942. {
  226943. Image singleChannelImage (sourceImage);
  226944. if (sourceImage.getFormat() != Image::SingleChannel)
  226945. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226946. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226947. flip();
  226948. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226949. applyTransform (t);
  226950. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226951. CGContextClipToMask (context, r, image);
  226952. applyTransform (t.inverted());
  226953. flip();
  226954. CGImageRelease (image);
  226955. lastClipRectIsValid = false;
  226956. }
  226957. }
  226958. bool clipRegionIntersects (const Rectangle<int>& r)
  226959. {
  226960. return getClipBounds().intersects (r);
  226961. }
  226962. const Rectangle<int> getClipBounds() const
  226963. {
  226964. if (! lastClipRectIsValid)
  226965. {
  226966. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226967. lastClipRectIsValid = true;
  226968. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226969. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226970. roundToInt (bounds.size.width),
  226971. roundToInt (bounds.size.height));
  226972. }
  226973. return lastClipRect;
  226974. }
  226975. bool isClipEmpty() const
  226976. {
  226977. return getClipBounds().isEmpty();
  226978. }
  226979. void saveState()
  226980. {
  226981. CGContextSaveGState (context);
  226982. stateStack.add (new SavedState (*state));
  226983. }
  226984. void restoreState()
  226985. {
  226986. CGContextRestoreGState (context);
  226987. SavedState* const top = stateStack.getLast();
  226988. if (top != 0)
  226989. {
  226990. state = top;
  226991. stateStack.removeLast (1, false);
  226992. lastClipRectIsValid = false;
  226993. }
  226994. else
  226995. {
  226996. jassertfalse; // trying to pop with an empty stack!
  226997. }
  226998. }
  226999. void setFill (const FillType& fillType)
  227000. {
  227001. state->fillType = fillType;
  227002. if (fillType.isColour())
  227003. {
  227004. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  227005. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  227006. CGContextSetAlpha (context, 1.0f);
  227007. }
  227008. }
  227009. void setOpacity (float newOpacity)
  227010. {
  227011. state->fillType.setOpacity (newOpacity);
  227012. setFill (state->fillType);
  227013. }
  227014. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  227015. {
  227016. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  227017. ? kCGInterpolationLow
  227018. : kCGInterpolationHigh);
  227019. }
  227020. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  227021. {
  227022. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  227023. }
  227024. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  227025. {
  227026. if (replaceExistingContents)
  227027. {
  227028. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  227029. CGContextClearRect (context, cgRect);
  227030. #else
  227031. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227032. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  227033. CGContextClearRect (context, cgRect);
  227034. else
  227035. #endif
  227036. CGContextSetBlendMode (context, kCGBlendModeCopy);
  227037. #endif
  227038. fillCGRect (cgRect, false);
  227039. CGContextSetBlendMode (context, kCGBlendModeNormal);
  227040. }
  227041. else
  227042. {
  227043. if (state->fillType.isColour())
  227044. {
  227045. CGContextFillRect (context, cgRect);
  227046. }
  227047. else if (state->fillType.isGradient())
  227048. {
  227049. CGContextSaveGState (context);
  227050. CGContextClipToRect (context, cgRect);
  227051. drawGradient();
  227052. CGContextRestoreGState (context);
  227053. }
  227054. else
  227055. {
  227056. CGContextSaveGState (context);
  227057. CGContextClipToRect (context, cgRect);
  227058. drawImage (state->fillType.image, state->fillType.transform, true);
  227059. CGContextRestoreGState (context);
  227060. }
  227061. }
  227062. }
  227063. void fillPath (const Path& path, const AffineTransform& transform)
  227064. {
  227065. CGContextSaveGState (context);
  227066. if (state->fillType.isColour())
  227067. {
  227068. flip();
  227069. applyTransform (transform);
  227070. createPath (path);
  227071. if (path.isUsingNonZeroWinding())
  227072. CGContextFillPath (context);
  227073. else
  227074. CGContextEOFillPath (context);
  227075. }
  227076. else
  227077. {
  227078. createPath (path, transform);
  227079. if (path.isUsingNonZeroWinding())
  227080. CGContextClip (context);
  227081. else
  227082. CGContextEOClip (context);
  227083. if (state->fillType.isGradient())
  227084. drawGradient();
  227085. else
  227086. drawImage (state->fillType.image, state->fillType.transform, true);
  227087. }
  227088. CGContextRestoreGState (context);
  227089. }
  227090. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  227091. {
  227092. const int iw = sourceImage.getWidth();
  227093. const int ih = sourceImage.getHeight();
  227094. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  227095. CGContextSaveGState (context);
  227096. CGContextSetAlpha (context, state->fillType.getOpacity());
  227097. flip();
  227098. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  227099. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  227100. if (fillEntireClipAsTiles)
  227101. {
  227102. #if JUCE_IOS
  227103. CGContextDrawTiledImage (context, imageRect, image);
  227104. #else
  227105. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  227106. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  227107. // if it's doing a transformation - it's quicker to just draw lots of images manually
  227108. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  227109. CGContextDrawTiledImage (context, imageRect, image);
  227110. else
  227111. #endif
  227112. {
  227113. // Fallback to manually doing a tiled fill on 10.4
  227114. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227115. int x = 0, y = 0;
  227116. while (x > clip.origin.x) x -= iw;
  227117. while (y > clip.origin.y) y -= ih;
  227118. const int right = (int) (clip.origin.x + clip.size.width);
  227119. const int bottom = (int) (clip.origin.y + clip.size.height);
  227120. while (y < bottom)
  227121. {
  227122. for (int x2 = x; x2 < right; x2 += iw)
  227123. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  227124. y += ih;
  227125. }
  227126. }
  227127. #endif
  227128. }
  227129. else
  227130. {
  227131. CGContextDrawImage (context, imageRect, image);
  227132. }
  227133. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  227134. CGContextRestoreGState (context);
  227135. }
  227136. void drawLine (const Line<float>& line)
  227137. {
  227138. if (state->fillType.isColour())
  227139. {
  227140. CGContextSetLineCap (context, kCGLineCapSquare);
  227141. CGContextSetLineWidth (context, 1.0f);
  227142. CGContextSetRGBStrokeColor (context,
  227143. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  227144. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  227145. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  227146. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  227147. CGContextStrokeLineSegments (context, cgLine, 1);
  227148. }
  227149. else
  227150. {
  227151. Path p;
  227152. p.addLineSegment (line, 1.0f);
  227153. fillPath (p, AffineTransform::identity);
  227154. }
  227155. }
  227156. void drawVerticalLine (const int x, float top, float bottom)
  227157. {
  227158. if (state->fillType.isColour())
  227159. {
  227160. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227161. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227162. #else
  227163. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227164. // the x co-ord slightly to trick it..
  227165. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227166. #endif
  227167. }
  227168. else
  227169. {
  227170. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  227171. }
  227172. }
  227173. void drawHorizontalLine (const int y, float left, float right)
  227174. {
  227175. if (state->fillType.isColour())
  227176. {
  227177. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227178. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227179. #else
  227180. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227181. // the x co-ord slightly to trick it..
  227182. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227183. #endif
  227184. }
  227185. else
  227186. {
  227187. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227188. }
  227189. }
  227190. void setFont (const Font& newFont)
  227191. {
  227192. if (state->font != newFont)
  227193. {
  227194. state->fontRef = 0;
  227195. state->font = newFont;
  227196. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227197. if (mf != 0)
  227198. {
  227199. state->fontRef = mf->fontRef;
  227200. CGContextSetFont (context, state->fontRef);
  227201. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227202. state->fontTransform = mf->renderingTransform;
  227203. state->fontTransform.a *= state->font.getHorizontalScale();
  227204. CGContextSetTextMatrix (context, state->fontTransform);
  227205. }
  227206. }
  227207. }
  227208. const Font getFont()
  227209. {
  227210. return state->font;
  227211. }
  227212. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227213. {
  227214. if (state->fontRef != 0 && state->fillType.isColour())
  227215. {
  227216. if (transform.isOnlyTranslation())
  227217. {
  227218. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227219. CGGlyph g = glyphNumber;
  227220. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227221. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227222. }
  227223. else
  227224. {
  227225. CGContextSaveGState (context);
  227226. flip();
  227227. applyTransform (transform);
  227228. CGAffineTransform t = state->fontTransform;
  227229. t.d = -t.d;
  227230. CGContextSetTextMatrix (context, t);
  227231. CGGlyph g = glyphNumber;
  227232. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227233. CGContextRestoreGState (context);
  227234. }
  227235. }
  227236. else
  227237. {
  227238. Path p;
  227239. Font& f = state->font;
  227240. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227241. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227242. .followedBy (transform));
  227243. }
  227244. }
  227245. private:
  227246. CGContextRef context;
  227247. const CGFloat flipHeight;
  227248. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227249. CGFunctionCallbacks gradientCallbacks;
  227250. mutable Rectangle<int> lastClipRect;
  227251. mutable bool lastClipRectIsValid;
  227252. struct SavedState
  227253. {
  227254. SavedState()
  227255. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227256. {
  227257. }
  227258. SavedState (const SavedState& other)
  227259. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227260. fontTransform (other.fontTransform)
  227261. {
  227262. }
  227263. ~SavedState()
  227264. {
  227265. }
  227266. FillType fillType;
  227267. Font font;
  227268. CGFontRef fontRef;
  227269. CGAffineTransform fontTransform;
  227270. };
  227271. ScopedPointer <SavedState> state;
  227272. OwnedArray <SavedState> stateStack;
  227273. HeapBlock <PixelARGB> gradientLookupTable;
  227274. int numGradientLookupEntries;
  227275. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227276. {
  227277. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227278. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227279. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227280. colour.unpremultiply();
  227281. outData[0] = colour.getRed() / 255.0f;
  227282. outData[1] = colour.getGreen() / 255.0f;
  227283. outData[2] = colour.getBlue() / 255.0f;
  227284. outData[3] = colour.getAlpha() / 255.0f;
  227285. }
  227286. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227287. {
  227288. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227289. --numGradientLookupEntries;
  227290. CGShadingRef result = 0;
  227291. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227292. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227293. if (gradient.isRadial)
  227294. {
  227295. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227296. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227297. function, true, true);
  227298. }
  227299. else
  227300. {
  227301. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227302. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227303. function, true, true);
  227304. }
  227305. CGFunctionRelease (function);
  227306. return result;
  227307. }
  227308. void drawGradient()
  227309. {
  227310. flip();
  227311. applyTransform (state->fillType.transform);
  227312. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227313. // you draw a gradient with high quality interp enabled).
  227314. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227315. CGContextSetAlpha (context, state->fillType.getOpacity());
  227316. CGContextDrawShading (context, shading);
  227317. CGShadingRelease (shading);
  227318. }
  227319. void createPath (const Path& path) const
  227320. {
  227321. CGContextBeginPath (context);
  227322. Path::Iterator i (path);
  227323. while (i.next())
  227324. {
  227325. switch (i.elementType)
  227326. {
  227327. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227328. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227329. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227330. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227331. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227332. default: jassertfalse; break;
  227333. }
  227334. }
  227335. }
  227336. void createPath (const Path& path, const AffineTransform& transform) const
  227337. {
  227338. CGContextBeginPath (context);
  227339. Path::Iterator i (path);
  227340. while (i.next())
  227341. {
  227342. switch (i.elementType)
  227343. {
  227344. case Path::Iterator::startNewSubPath:
  227345. transform.transformPoint (i.x1, i.y1);
  227346. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227347. break;
  227348. case Path::Iterator::lineTo:
  227349. transform.transformPoint (i.x1, i.y1);
  227350. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227351. break;
  227352. case Path::Iterator::quadraticTo:
  227353. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227354. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227355. break;
  227356. case Path::Iterator::cubicTo:
  227357. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227358. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227359. break;
  227360. case Path::Iterator::closePath:
  227361. CGContextClosePath (context); break;
  227362. default:
  227363. jassertfalse;
  227364. break;
  227365. }
  227366. }
  227367. }
  227368. void flip() const
  227369. {
  227370. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227371. }
  227372. void applyTransform (const AffineTransform& transform) const
  227373. {
  227374. CGAffineTransform t;
  227375. t.a = transform.mat00;
  227376. t.b = transform.mat10;
  227377. t.c = transform.mat01;
  227378. t.d = transform.mat11;
  227379. t.tx = transform.mat02;
  227380. t.ty = transform.mat12;
  227381. CGContextConcatCTM (context, t);
  227382. }
  227383. CoreGraphicsContext (const CoreGraphicsContext&);
  227384. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227385. };
  227386. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227387. {
  227388. return new CoreGraphicsContext (context, height);
  227389. }
  227390. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227391. const Image juce_loadWithCoreImage (InputStream& input)
  227392. {
  227393. MemoryBlock data;
  227394. input.readIntoMemoryBlock (data, -1);
  227395. #if JUCE_IOS
  227396. JUCE_AUTORELEASEPOOL
  227397. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData() length: data.getSize()]];
  227398. if (image != nil)
  227399. {
  227400. CGImageRef loadedImage = image.CGImage;
  227401. #else
  227402. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227403. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227404. CGDataProviderRelease (provider);
  227405. if (imageSource != 0)
  227406. {
  227407. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227408. CFRelease (imageSource);
  227409. #endif
  227410. if (loadedImage != 0)
  227411. {
  227412. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  227413. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  227414. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227415. hasAlphaChan, Image::NativeImage);
  227416. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227417. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227418. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227419. CGContextFlush (cgImage->context);
  227420. #if ! JUCE_IOS
  227421. CFRelease (loadedImage);
  227422. #endif
  227423. return image;
  227424. }
  227425. }
  227426. return Image::null;
  227427. }
  227428. #endif
  227429. #endif
  227430. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227431. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227432. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227433. // compiled on its own).
  227434. #if JUCE_INCLUDED_FILE
  227435. class UIViewComponentPeer;
  227436. END_JUCE_NAMESPACE
  227437. #define JuceUIView MakeObjCClassName(JuceUIView)
  227438. @interface JuceUIView : UIView <UITextViewDelegate>
  227439. {
  227440. @public
  227441. UIViewComponentPeer* owner;
  227442. UITextView* hiddenTextView;
  227443. }
  227444. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227445. - (void) dealloc;
  227446. - (void) drawRect: (CGRect) r;
  227447. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227448. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227449. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227450. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227451. - (BOOL) becomeFirstResponder;
  227452. - (BOOL) resignFirstResponder;
  227453. - (BOOL) canBecomeFirstResponder;
  227454. - (void) asyncRepaint: (id) rect;
  227455. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227456. @end
  227457. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227458. @interface JuceUIWindow : UIWindow
  227459. {
  227460. @private
  227461. UIViewComponentPeer* owner;
  227462. bool isZooming;
  227463. }
  227464. - (void) setOwner: (UIViewComponentPeer*) owner;
  227465. - (void) becomeKeyWindow;
  227466. @end
  227467. BEGIN_JUCE_NAMESPACE
  227468. class UIViewComponentPeer : public ComponentPeer,
  227469. public FocusChangeListener
  227470. {
  227471. public:
  227472. UIViewComponentPeer (Component* const component,
  227473. const int windowStyleFlags,
  227474. UIView* viewToAttachTo);
  227475. ~UIViewComponentPeer();
  227476. void* getNativeHandle() const;
  227477. void setVisible (bool shouldBeVisible);
  227478. void setTitle (const String& title);
  227479. void setPosition (int x, int y);
  227480. void setSize (int w, int h);
  227481. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227482. const Rectangle<int> getBounds() const;
  227483. const Rectangle<int> getBounds (const bool global) const;
  227484. const Point<int> getScreenPosition() const;
  227485. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227486. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227487. void setMinimised (bool shouldBeMinimised);
  227488. bool isMinimised() const;
  227489. void setFullScreen (bool shouldBeFullScreen);
  227490. bool isFullScreen() const;
  227491. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227492. const BorderSize getFrameSize() const;
  227493. bool setAlwaysOnTop (bool alwaysOnTop);
  227494. void toFront (bool makeActiveWindow);
  227495. void toBehind (ComponentPeer* other);
  227496. void setIcon (const Image& newIcon);
  227497. virtual void drawRect (CGRect r);
  227498. virtual bool canBecomeKeyWindow();
  227499. virtual bool windowShouldClose();
  227500. virtual void redirectMovedOrResized();
  227501. virtual CGRect constrainRect (CGRect r);
  227502. virtual void viewFocusGain();
  227503. virtual void viewFocusLoss();
  227504. bool isFocused() const;
  227505. void grabFocus();
  227506. void textInputRequired (const Point<int>& position);
  227507. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227508. void updateHiddenTextContent (TextInputTarget* target);
  227509. void globalFocusChanged (Component*);
  227510. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227511. void repaint (const Rectangle<int>& area);
  227512. void performAnyPendingRepaintsNow();
  227513. juce_UseDebuggingNewOperator
  227514. UIWindow* window;
  227515. JuceUIView* view;
  227516. bool isSharedWindow, fullScreen, insideDrawRect;
  227517. static ModifierKeys currentModifiers;
  227518. static int64 getMouseTime (UIEvent* e)
  227519. {
  227520. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227521. + (int64) ([e timestamp] * 1000.0);
  227522. }
  227523. Array <UITouch*> currentTouches;
  227524. };
  227525. END_JUCE_NAMESPACE
  227526. @implementation JuceUIView
  227527. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227528. withFrame: (CGRect) frame
  227529. {
  227530. [super initWithFrame: frame];
  227531. owner = owner_;
  227532. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227533. [self addSubview: hiddenTextView];
  227534. hiddenTextView.delegate = self;
  227535. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227536. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227537. return self;
  227538. }
  227539. - (void) dealloc
  227540. {
  227541. [hiddenTextView removeFromSuperview];
  227542. [hiddenTextView release];
  227543. [super dealloc];
  227544. }
  227545. - (void) drawRect: (CGRect) r
  227546. {
  227547. if (owner != 0)
  227548. owner->drawRect (r);
  227549. }
  227550. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227551. {
  227552. return false;
  227553. }
  227554. ModifierKeys UIViewComponentPeer::currentModifiers;
  227555. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227556. {
  227557. return UIViewComponentPeer::currentModifiers;
  227558. }
  227559. void ModifierKeys::updateCurrentModifiers() throw()
  227560. {
  227561. currentModifiers = UIViewComponentPeer::currentModifiers;
  227562. }
  227563. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227564. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227565. {
  227566. if (owner != 0)
  227567. owner->handleTouches (event, true, false, false);
  227568. }
  227569. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227570. {
  227571. if (owner != 0)
  227572. owner->handleTouches (event, false, false, false);
  227573. }
  227574. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227575. {
  227576. if (owner != 0)
  227577. owner->handleTouches (event, false, true, false);
  227578. }
  227579. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227580. {
  227581. if (owner != 0)
  227582. owner->handleTouches (event, false, true, true);
  227583. [self touchesEnded: touches withEvent: event];
  227584. }
  227585. - (BOOL) becomeFirstResponder
  227586. {
  227587. if (owner != 0)
  227588. owner->viewFocusGain();
  227589. return true;
  227590. }
  227591. - (BOOL) resignFirstResponder
  227592. {
  227593. if (owner != 0)
  227594. owner->viewFocusLoss();
  227595. return true;
  227596. }
  227597. - (BOOL) canBecomeFirstResponder
  227598. {
  227599. return owner != 0 && owner->canBecomeKeyWindow();
  227600. }
  227601. - (void) asyncRepaint: (id) rect
  227602. {
  227603. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227604. [self setNeedsDisplayInRect: *r];
  227605. }
  227606. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227607. {
  227608. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227609. nsStringToJuce (text));
  227610. }
  227611. @end
  227612. @implementation JuceUIWindow
  227613. - (void) setOwner: (UIViewComponentPeer*) owner_
  227614. {
  227615. owner = owner_;
  227616. isZooming = false;
  227617. }
  227618. - (void) becomeKeyWindow
  227619. {
  227620. [super becomeKeyWindow];
  227621. if (owner != 0)
  227622. owner->grabFocus();
  227623. }
  227624. @end
  227625. BEGIN_JUCE_NAMESPACE
  227626. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227627. const int windowStyleFlags,
  227628. UIView* viewToAttachTo)
  227629. : ComponentPeer (component, windowStyleFlags),
  227630. window (0),
  227631. view (0),
  227632. isSharedWindow (viewToAttachTo != 0),
  227633. fullScreen (false),
  227634. insideDrawRect (false)
  227635. {
  227636. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  227637. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227638. if (isSharedWindow)
  227639. {
  227640. window = [viewToAttachTo window];
  227641. [viewToAttachTo addSubview: view];
  227642. setVisible (component->isVisible());
  227643. }
  227644. else
  227645. {
  227646. r.origin.x = (float) component->getX();
  227647. r.origin.y = (float) component->getY();
  227648. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227649. window = [[JuceUIWindow alloc] init];
  227650. window.frame = r;
  227651. window.opaque = component->isOpaque();
  227652. view.opaque = component->isOpaque();
  227653. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227654. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227655. [((JuceUIWindow*) window) setOwner: this];
  227656. if (component->isAlwaysOnTop())
  227657. window.windowLevel = UIWindowLevelAlert;
  227658. [window addSubview: view];
  227659. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227660. view.hidden = ! component->isVisible();
  227661. window.hidden = ! component->isVisible();
  227662. view.multipleTouchEnabled = YES;
  227663. }
  227664. setTitle (component->getName());
  227665. Desktop::getInstance().addFocusChangeListener (this);
  227666. }
  227667. UIViewComponentPeer::~UIViewComponentPeer()
  227668. {
  227669. Desktop::getInstance().removeFocusChangeListener (this);
  227670. view->owner = 0;
  227671. [view removeFromSuperview];
  227672. [view release];
  227673. if (! isSharedWindow)
  227674. {
  227675. [((JuceUIWindow*) window) setOwner: 0];
  227676. [window release];
  227677. }
  227678. }
  227679. void* UIViewComponentPeer::getNativeHandle() const
  227680. {
  227681. return view;
  227682. }
  227683. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227684. {
  227685. view.hidden = ! shouldBeVisible;
  227686. if (! isSharedWindow)
  227687. window.hidden = ! shouldBeVisible;
  227688. }
  227689. void UIViewComponentPeer::setTitle (const String& title)
  227690. {
  227691. // xxx is this possible?
  227692. }
  227693. void UIViewComponentPeer::setPosition (int x, int y)
  227694. {
  227695. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227696. }
  227697. void UIViewComponentPeer::setSize (int w, int h)
  227698. {
  227699. setBounds (component->getX(), component->getY(), w, h, false);
  227700. }
  227701. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227702. {
  227703. fullScreen = isNowFullScreen;
  227704. w = jmax (0, w);
  227705. h = jmax (0, h);
  227706. CGRect r;
  227707. r.origin.x = (float) x;
  227708. r.origin.y = (float) y;
  227709. r.size.width = (float) w;
  227710. r.size.height = (float) h;
  227711. if (isSharedWindow)
  227712. {
  227713. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  227714. if ([view frame].size.width != r.size.width
  227715. || [view frame].size.height != r.size.height)
  227716. [view setNeedsDisplay];
  227717. view.frame = r;
  227718. }
  227719. else
  227720. {
  227721. window.frame = r;
  227722. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227723. }
  227724. }
  227725. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227726. {
  227727. CGRect r = [view frame];
  227728. if (global && [view window] != 0)
  227729. {
  227730. r = [view convertRect: r toView: nil];
  227731. CGRect wr = [[view window] frame];
  227732. r.origin.x += wr.origin.x;
  227733. r.origin.y += wr.origin.y;
  227734. }
  227735. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  227736. (int) r.size.width, (int) r.size.height);
  227737. }
  227738. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227739. {
  227740. return getBounds (! isSharedWindow);
  227741. }
  227742. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227743. {
  227744. return getBounds (true).getPosition();
  227745. }
  227746. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227747. {
  227748. return relativePosition + getScreenPosition();
  227749. }
  227750. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227751. {
  227752. return screenPosition - getScreenPosition();
  227753. }
  227754. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227755. {
  227756. if (constrainer != 0)
  227757. {
  227758. CGRect current = [window frame];
  227759. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227760. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227761. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  227762. (int) r.size.width, (int) r.size.height);
  227763. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  227764. (int) current.size.width, (int) current.size.height);
  227765. constrainer->checkBounds (pos, original,
  227766. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227767. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227768. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227769. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227770. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227771. r.origin.x = pos.getX();
  227772. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227773. r.size.width = pos.getWidth();
  227774. r.size.height = pos.getHeight();
  227775. }
  227776. return r;
  227777. }
  227778. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227779. {
  227780. // xxx
  227781. }
  227782. bool UIViewComponentPeer::isMinimised() const
  227783. {
  227784. return false;
  227785. }
  227786. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227787. {
  227788. if (! isSharedWindow)
  227789. {
  227790. Rectangle<int> r (lastNonFullscreenBounds);
  227791. setMinimised (false);
  227792. if (fullScreen != shouldBeFullScreen)
  227793. {
  227794. if (shouldBeFullScreen)
  227795. r = Desktop::getInstance().getMainMonitorArea();
  227796. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227797. if (r != getComponent()->getBounds() && ! r.isEmpty())
  227798. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227799. }
  227800. }
  227801. }
  227802. bool UIViewComponentPeer::isFullScreen() const
  227803. {
  227804. return fullScreen;
  227805. }
  227806. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227807. {
  227808. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227809. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227810. return false;
  227811. CGPoint p;
  227812. p.x = (float) position.getX();
  227813. p.y = (float) position.getY();
  227814. UIView* v = [view hitTest: p withEvent: nil];
  227815. if (trueIfInAChildWindow)
  227816. return v != nil;
  227817. return v == view;
  227818. }
  227819. const BorderSize UIViewComponentPeer::getFrameSize() const
  227820. {
  227821. BorderSize b;
  227822. if (! isSharedWindow)
  227823. {
  227824. CGRect v = [view convertRect: [view frame] toView: nil];
  227825. CGRect w = [window frame];
  227826. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  227827. b.setBottom ((int) v.origin.y);
  227828. b.setLeft ((int) v.origin.x);
  227829. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  227830. }
  227831. return b;
  227832. }
  227833. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227834. {
  227835. if (! isSharedWindow)
  227836. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227837. return true;
  227838. }
  227839. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227840. {
  227841. if (isSharedWindow)
  227842. [[view superview] bringSubviewToFront: view];
  227843. if (window != 0 && component->isVisible())
  227844. [window makeKeyAndVisible];
  227845. }
  227846. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227847. {
  227848. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227849. jassert (otherPeer != 0); // wrong type of window?
  227850. if (otherPeer != 0)
  227851. {
  227852. if (isSharedWindow)
  227853. {
  227854. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227855. }
  227856. else
  227857. {
  227858. jassertfalse; // don't know how to do this
  227859. }
  227860. }
  227861. }
  227862. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227863. {
  227864. // to do..
  227865. }
  227866. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227867. {
  227868. NSArray* touches = [[event touchesForView: view] allObjects];
  227869. for (unsigned int i = 0; i < [touches count]; ++i)
  227870. {
  227871. UITouch* touch = [touches objectAtIndex: i];
  227872. CGPoint p = [touch locationInView: view];
  227873. const Point<int> pos ((int) p.x, (int) p.y);
  227874. juce_lastMousePos = pos + getScreenPosition();
  227875. const int64 time = getMouseTime (event);
  227876. int touchIndex = currentTouches.indexOf (touch);
  227877. if (touchIndex < 0)
  227878. {
  227879. touchIndex = currentTouches.size();
  227880. currentTouches.add (touch);
  227881. }
  227882. if (isDown)
  227883. {
  227884. currentModifiers = currentModifiers.withoutMouseButtons();
  227885. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227886. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227887. }
  227888. else if (isUp)
  227889. {
  227890. currentModifiers = currentModifiers.withoutMouseButtons();
  227891. currentTouches.remove (touchIndex);
  227892. }
  227893. if (isCancel)
  227894. currentTouches.clear();
  227895. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227896. }
  227897. }
  227898. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227899. void UIViewComponentPeer::viewFocusGain()
  227900. {
  227901. if (currentlyFocusedPeer != this)
  227902. {
  227903. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227904. currentlyFocusedPeer->handleFocusLoss();
  227905. currentlyFocusedPeer = this;
  227906. handleFocusGain();
  227907. }
  227908. }
  227909. void UIViewComponentPeer::viewFocusLoss()
  227910. {
  227911. if (currentlyFocusedPeer == this)
  227912. {
  227913. currentlyFocusedPeer = 0;
  227914. handleFocusLoss();
  227915. }
  227916. }
  227917. void juce_HandleProcessFocusChange()
  227918. {
  227919. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227920. {
  227921. if (Process::isForegroundProcess())
  227922. {
  227923. currentlyFocusedPeer->handleFocusGain();
  227924. ComponentPeer::bringModalComponentToFront();
  227925. }
  227926. else
  227927. {
  227928. currentlyFocusedPeer->handleFocusLoss();
  227929. // turn kiosk mode off if we lose focus..
  227930. Desktop::getInstance().setKioskModeComponent (0);
  227931. }
  227932. }
  227933. }
  227934. bool UIViewComponentPeer::isFocused() const
  227935. {
  227936. return isSharedWindow ? this == currentlyFocusedPeer
  227937. : (window != 0 && [window isKeyWindow]);
  227938. }
  227939. void UIViewComponentPeer::grabFocus()
  227940. {
  227941. if (window != 0)
  227942. {
  227943. [window makeKeyWindow];
  227944. viewFocusGain();
  227945. }
  227946. }
  227947. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227948. {
  227949. }
  227950. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227951. {
  227952. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227953. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227954. }
  227955. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227956. {
  227957. TextInputTarget* const target = findCurrentTextInputTarget();
  227958. if (target != 0)
  227959. {
  227960. const Range<int> currentSelection (target->getHighlightedRegion());
  227961. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227962. if (currentSelection.isEmpty())
  227963. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227964. target->insertTextAtCaret (text);
  227965. updateHiddenTextContent (target);
  227966. }
  227967. return NO;
  227968. }
  227969. void UIViewComponentPeer::globalFocusChanged (Component*)
  227970. {
  227971. TextInputTarget* const target = findCurrentTextInputTarget();
  227972. if (target != 0)
  227973. {
  227974. Component* comp = dynamic_cast<Component*> (target);
  227975. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  227976. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227977. updateHiddenTextContent (target);
  227978. [view->hiddenTextView becomeFirstResponder];
  227979. }
  227980. else
  227981. {
  227982. [view->hiddenTextView resignFirstResponder];
  227983. }
  227984. }
  227985. void UIViewComponentPeer::drawRect (CGRect r)
  227986. {
  227987. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227988. return;
  227989. CGContextRef cg = UIGraphicsGetCurrentContext();
  227990. if (! component->isOpaque())
  227991. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227992. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227993. CoreGraphicsContext g (cg, view.bounds.size.height);
  227994. insideDrawRect = true;
  227995. handlePaint (g);
  227996. insideDrawRect = false;
  227997. }
  227998. bool UIViewComponentPeer::canBecomeKeyWindow()
  227999. {
  228000. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228001. }
  228002. bool UIViewComponentPeer::windowShouldClose()
  228003. {
  228004. if (! isValidPeer (this))
  228005. return YES;
  228006. handleUserClosingWindow();
  228007. return NO;
  228008. }
  228009. void UIViewComponentPeer::redirectMovedOrResized()
  228010. {
  228011. handleMovedOrResized();
  228012. }
  228013. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228014. {
  228015. }
  228016. class AsyncRepaintMessage : public CallbackMessage
  228017. {
  228018. public:
  228019. UIViewComponentPeer* const peer;
  228020. const Rectangle<int> rect;
  228021. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228022. : peer (peer_), rect (rect_)
  228023. {
  228024. }
  228025. void messageCallback()
  228026. {
  228027. if (ComponentPeer::isValidPeer (peer))
  228028. peer->repaint (rect);
  228029. }
  228030. };
  228031. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  228032. {
  228033. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  228034. {
  228035. (new AsyncRepaintMessage (this, area))->post();
  228036. }
  228037. else
  228038. {
  228039. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  228040. (float) area.getWidth(), (float) area.getHeight())];
  228041. }
  228042. }
  228043. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  228044. {
  228045. }
  228046. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228047. {
  228048. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  228049. }
  228050. const Image juce_createIconForFile (const File& file)
  228051. {
  228052. return Image::null;
  228053. }
  228054. void Desktop::createMouseInputSources()
  228055. {
  228056. for (int i = 0; i < 10; ++i)
  228057. mouseSources.add (new MouseInputSource (i, false));
  228058. }
  228059. bool Desktop::canUseSemiTransparentWindows() throw()
  228060. {
  228061. return true;
  228062. }
  228063. const Point<int> Desktop::getMousePosition()
  228064. {
  228065. return juce_lastMousePos;
  228066. }
  228067. void Desktop::setMousePosition (const Point<int>&)
  228068. {
  228069. }
  228070. const int KeyPress::spaceKey = ' ';
  228071. const int KeyPress::returnKey = 0x0d;
  228072. const int KeyPress::escapeKey = 0x1b;
  228073. const int KeyPress::backspaceKey = 0x7f;
  228074. const int KeyPress::leftKey = 0x1000;
  228075. const int KeyPress::rightKey = 0x1001;
  228076. const int KeyPress::upKey = 0x1002;
  228077. const int KeyPress::downKey = 0x1003;
  228078. const int KeyPress::pageUpKey = 0x1004;
  228079. const int KeyPress::pageDownKey = 0x1005;
  228080. const int KeyPress::endKey = 0x1006;
  228081. const int KeyPress::homeKey = 0x1007;
  228082. const int KeyPress::deleteKey = 0x1008;
  228083. const int KeyPress::insertKey = -1;
  228084. const int KeyPress::tabKey = 9;
  228085. const int KeyPress::F1Key = 0x2001;
  228086. const int KeyPress::F2Key = 0x2002;
  228087. const int KeyPress::F3Key = 0x2003;
  228088. const int KeyPress::F4Key = 0x2004;
  228089. const int KeyPress::F5Key = 0x2005;
  228090. const int KeyPress::F6Key = 0x2006;
  228091. const int KeyPress::F7Key = 0x2007;
  228092. const int KeyPress::F8Key = 0x2008;
  228093. const int KeyPress::F9Key = 0x2009;
  228094. const int KeyPress::F10Key = 0x200a;
  228095. const int KeyPress::F11Key = 0x200b;
  228096. const int KeyPress::F12Key = 0x200c;
  228097. const int KeyPress::F13Key = 0x200d;
  228098. const int KeyPress::F14Key = 0x200e;
  228099. const int KeyPress::F15Key = 0x200f;
  228100. const int KeyPress::F16Key = 0x2010;
  228101. const int KeyPress::numberPad0 = 0x30020;
  228102. const int KeyPress::numberPad1 = 0x30021;
  228103. const int KeyPress::numberPad2 = 0x30022;
  228104. const int KeyPress::numberPad3 = 0x30023;
  228105. const int KeyPress::numberPad4 = 0x30024;
  228106. const int KeyPress::numberPad5 = 0x30025;
  228107. const int KeyPress::numberPad6 = 0x30026;
  228108. const int KeyPress::numberPad7 = 0x30027;
  228109. const int KeyPress::numberPad8 = 0x30028;
  228110. const int KeyPress::numberPad9 = 0x30029;
  228111. const int KeyPress::numberPadAdd = 0x3002a;
  228112. const int KeyPress::numberPadSubtract = 0x3002b;
  228113. const int KeyPress::numberPadMultiply = 0x3002c;
  228114. const int KeyPress::numberPadDivide = 0x3002d;
  228115. const int KeyPress::numberPadSeparator = 0x3002e;
  228116. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228117. const int KeyPress::numberPadEquals = 0x30030;
  228118. const int KeyPress::numberPadDelete = 0x30031;
  228119. const int KeyPress::playKey = 0x30000;
  228120. const int KeyPress::stopKey = 0x30001;
  228121. const int KeyPress::fastForwardKey = 0x30002;
  228122. const int KeyPress::rewindKey = 0x30003;
  228123. #endif
  228124. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  228125. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  228126. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228127. // compiled on its own).
  228128. #if JUCE_INCLUDED_FILE
  228129. struct CallbackMessagePayload
  228130. {
  228131. MessageCallbackFunction* function;
  228132. void* parameter;
  228133. void* volatile result;
  228134. bool volatile hasBeenExecuted;
  228135. };
  228136. END_JUCE_NAMESPACE
  228137. @interface JuceCustomMessageHandler : NSObject
  228138. {
  228139. }
  228140. - (void) performCallback: (id) info;
  228141. @end
  228142. @implementation JuceCustomMessageHandler
  228143. - (void) performCallback: (id) info
  228144. {
  228145. if ([info isKindOfClass: [NSData class]])
  228146. {
  228147. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  228148. if (pl != 0)
  228149. {
  228150. pl->result = (*pl->function) (pl->parameter);
  228151. pl->hasBeenExecuted = true;
  228152. }
  228153. }
  228154. else
  228155. {
  228156. jassertfalse; // should never get here!
  228157. }
  228158. }
  228159. @end
  228160. BEGIN_JUCE_NAMESPACE
  228161. void MessageManager::runDispatchLoop()
  228162. {
  228163. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228164. runDispatchLoopUntil (-1);
  228165. }
  228166. void MessageManager::stopDispatchLoop()
  228167. {
  228168. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228169. exit (0); // iPhone apps get no mercy..
  228170. }
  228171. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228172. {
  228173. const ScopedAutoReleasePool pool;
  228174. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228175. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228176. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228177. while (! quitMessagePosted)
  228178. {
  228179. const ScopedAutoReleasePool pool;
  228180. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228181. beforeDate: endDate];
  228182. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228183. break;
  228184. }
  228185. return ! quitMessagePosted;
  228186. }
  228187. static CFRunLoopRef runLoop = 0;
  228188. static CFRunLoopSourceRef runLoopSource = 0;
  228189. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228190. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228191. static void runLoopSourceCallback (void*)
  228192. {
  228193. if (pendingMessages != 0)
  228194. {
  228195. int numDispatched = 0;
  228196. do
  228197. {
  228198. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228199. if (nextMessage == 0)
  228200. return;
  228201. const ScopedAutoReleasePool pool;
  228202. MessageManager::getInstance()->deliverMessage (nextMessage);
  228203. } while (++numDispatched <= 4);
  228204. CFRunLoopSourceSignal (runLoopSource);
  228205. CFRunLoopWakeUp (runLoop);
  228206. }
  228207. }
  228208. void MessageManager::doPlatformSpecificInitialisation()
  228209. {
  228210. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228211. runLoop = CFRunLoopGetCurrent();
  228212. CFRunLoopSourceContext sourceContext;
  228213. zerostruct (sourceContext);
  228214. sourceContext.perform = runLoopSourceCallback;
  228215. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228216. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228217. if (juceCustomMessageHandler == 0)
  228218. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228219. }
  228220. void MessageManager::doPlatformSpecificShutdown()
  228221. {
  228222. CFRunLoopSourceInvalidate (runLoopSource);
  228223. CFRelease (runLoopSource);
  228224. runLoopSource = 0;
  228225. deleteAndZero (pendingMessages);
  228226. if (juceCustomMessageHandler != 0)
  228227. {
  228228. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228229. [juceCustomMessageHandler release];
  228230. juceCustomMessageHandler = 0;
  228231. }
  228232. }
  228233. bool juce_postMessageToSystemQueue (Message* message)
  228234. {
  228235. if (pendingMessages != 0)
  228236. {
  228237. pendingMessages->add (message);
  228238. CFRunLoopSourceSignal (runLoopSource);
  228239. CFRunLoopWakeUp (runLoop);
  228240. }
  228241. return true;
  228242. }
  228243. void MessageManager::broadcastMessage (const String& value)
  228244. {
  228245. }
  228246. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228247. {
  228248. if (isThisTheMessageThread())
  228249. {
  228250. return (*callback) (data);
  228251. }
  228252. else
  228253. {
  228254. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228255. // deadlock because the message manager is blocked from running, so can never
  228256. // call your function..
  228257. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228258. const ScopedAutoReleasePool pool;
  228259. CallbackMessagePayload cmp;
  228260. cmp.function = callback;
  228261. cmp.parameter = data;
  228262. cmp.result = 0;
  228263. cmp.hasBeenExecuted = false;
  228264. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228265. withObject: [NSData dataWithBytesNoCopy: &cmp
  228266. length: sizeof (cmp)
  228267. freeWhenDone: NO]
  228268. waitUntilDone: YES];
  228269. return cmp.result;
  228270. }
  228271. }
  228272. #endif
  228273. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228274. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228275. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228276. // compiled on its own).
  228277. #if JUCE_INCLUDED_FILE
  228278. #if JUCE_MAC
  228279. END_JUCE_NAMESPACE
  228280. using namespace JUCE_NAMESPACE;
  228281. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228282. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228283. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228284. #else
  228285. @interface JuceFileChooserDelegate : NSObject
  228286. #endif
  228287. {
  228288. StringArray* filters;
  228289. }
  228290. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228291. - (void) dealloc;
  228292. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228293. @end
  228294. @implementation JuceFileChooserDelegate
  228295. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228296. {
  228297. [super init];
  228298. filters = filters_;
  228299. return self;
  228300. }
  228301. - (void) dealloc
  228302. {
  228303. delete filters;
  228304. [super dealloc];
  228305. }
  228306. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228307. {
  228308. (void) sender;
  228309. const File f (nsStringToJuce (filename));
  228310. for (int i = filters->size(); --i >= 0;)
  228311. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228312. return true;
  228313. return f.isDirectory();
  228314. }
  228315. @end
  228316. BEGIN_JUCE_NAMESPACE
  228317. void FileChooser::showPlatformDialog (Array<File>& results,
  228318. const String& title,
  228319. const File& currentFileOrDirectory,
  228320. const String& filter,
  228321. bool selectsDirectory,
  228322. bool selectsFiles,
  228323. bool isSaveDialogue,
  228324. bool warnAboutOverwritingExistingFiles,
  228325. bool selectMultipleFiles,
  228326. FilePreviewComponent* extraInfoComponent)
  228327. {
  228328. const ScopedAutoReleasePool pool;
  228329. StringArray* filters = new StringArray();
  228330. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228331. filters->trim();
  228332. filters->removeEmptyStrings();
  228333. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228334. [delegate autorelease];
  228335. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228336. : [NSOpenPanel openPanel];
  228337. [panel setTitle: juceStringToNS (title)];
  228338. if (! isSaveDialogue)
  228339. {
  228340. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228341. [openPanel setCanChooseDirectories: selectsDirectory];
  228342. [openPanel setCanChooseFiles: selectsFiles];
  228343. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228344. }
  228345. [panel setDelegate: delegate];
  228346. if (isSaveDialogue || selectsDirectory)
  228347. [panel setCanCreateDirectories: YES];
  228348. String directory, filename;
  228349. if (currentFileOrDirectory.isDirectory())
  228350. {
  228351. directory = currentFileOrDirectory.getFullPathName();
  228352. }
  228353. else
  228354. {
  228355. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228356. filename = currentFileOrDirectory.getFileName();
  228357. }
  228358. if ([panel runModalForDirectory: juceStringToNS (directory)
  228359. file: juceStringToNS (filename)]
  228360. == NSOKButton)
  228361. {
  228362. if (isSaveDialogue)
  228363. {
  228364. results.add (File (nsStringToJuce ([panel filename])));
  228365. }
  228366. else
  228367. {
  228368. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228369. NSArray* urls = [openPanel filenames];
  228370. for (unsigned int i = 0; i < [urls count]; ++i)
  228371. {
  228372. NSString* f = [urls objectAtIndex: i];
  228373. results.add (File (nsStringToJuce (f)));
  228374. }
  228375. }
  228376. }
  228377. [panel setDelegate: nil];
  228378. }
  228379. #else
  228380. void FileChooser::showPlatformDialog (Array<File>& results,
  228381. const String& title,
  228382. const File& currentFileOrDirectory,
  228383. const String& filter,
  228384. bool selectsDirectory,
  228385. bool selectsFiles,
  228386. bool isSaveDialogue,
  228387. bool warnAboutOverwritingExistingFiles,
  228388. bool selectMultipleFiles,
  228389. FilePreviewComponent* extraInfoComponent)
  228390. {
  228391. const ScopedAutoReleasePool pool;
  228392. jassertfalse; //xxx to do
  228393. }
  228394. #endif
  228395. #endif
  228396. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228397. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228398. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228399. // compiled on its own).
  228400. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228401. #if JUCE_MAC
  228402. END_JUCE_NAMESPACE
  228403. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228404. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228405. {
  228406. CriticalSection* contextLock;
  228407. bool needsUpdate;
  228408. }
  228409. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228410. - (bool) makeActive;
  228411. - (void) makeInactive;
  228412. - (void) reshape;
  228413. @end
  228414. @implementation ThreadSafeNSOpenGLView
  228415. - (id) initWithFrame: (NSRect) frameRect
  228416. pixelFormat: (NSOpenGLPixelFormat*) format
  228417. {
  228418. contextLock = new CriticalSection();
  228419. self = [super initWithFrame: frameRect pixelFormat: format];
  228420. if (self != nil)
  228421. [[NSNotificationCenter defaultCenter] addObserver: self
  228422. selector: @selector (_surfaceNeedsUpdate:)
  228423. name: NSViewGlobalFrameDidChangeNotification
  228424. object: self];
  228425. return self;
  228426. }
  228427. - (void) dealloc
  228428. {
  228429. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228430. delete contextLock;
  228431. [super dealloc];
  228432. }
  228433. - (bool) makeActive
  228434. {
  228435. const ScopedLock sl (*contextLock);
  228436. if ([self openGLContext] == 0)
  228437. return false;
  228438. [[self openGLContext] makeCurrentContext];
  228439. if (needsUpdate)
  228440. {
  228441. [super update];
  228442. needsUpdate = false;
  228443. }
  228444. return true;
  228445. }
  228446. - (void) makeInactive
  228447. {
  228448. const ScopedLock sl (*contextLock);
  228449. [NSOpenGLContext clearCurrentContext];
  228450. }
  228451. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228452. {
  228453. const ScopedLock sl (*contextLock);
  228454. needsUpdate = true;
  228455. }
  228456. - (void) update
  228457. {
  228458. const ScopedLock sl (*contextLock);
  228459. needsUpdate = true;
  228460. }
  228461. - (void) reshape
  228462. {
  228463. const ScopedLock sl (*contextLock);
  228464. needsUpdate = true;
  228465. }
  228466. @end
  228467. BEGIN_JUCE_NAMESPACE
  228468. class WindowedGLContext : public OpenGLContext
  228469. {
  228470. public:
  228471. WindowedGLContext (Component* const component,
  228472. const OpenGLPixelFormat& pixelFormat_,
  228473. NSOpenGLContext* sharedContext)
  228474. : renderContext (0),
  228475. pixelFormat (pixelFormat_)
  228476. {
  228477. jassert (component != 0);
  228478. NSOpenGLPixelFormatAttribute attribs [64];
  228479. int n = 0;
  228480. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228481. attribs[n++] = NSOpenGLPFAAccelerated;
  228482. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228483. attribs[n++] = NSOpenGLPFAColorSize;
  228484. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228485. pixelFormat.greenBits,
  228486. pixelFormat.blueBits);
  228487. attribs[n++] = NSOpenGLPFAAlphaSize;
  228488. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228489. attribs[n++] = NSOpenGLPFADepthSize;
  228490. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228491. attribs[n++] = NSOpenGLPFAStencilSize;
  228492. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228493. attribs[n++] = NSOpenGLPFAAccumSize;
  228494. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228495. pixelFormat.accumulationBufferGreenBits,
  228496. pixelFormat.accumulationBufferBlueBits,
  228497. pixelFormat.accumulationBufferAlphaBits);
  228498. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228499. attribs[n++] = NSOpenGLPFASampleBuffers;
  228500. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228501. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228502. attribs[n++] = NSOpenGLPFANoRecovery;
  228503. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228504. NSOpenGLPixelFormat* format
  228505. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228506. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228507. pixelFormat: format];
  228508. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228509. shareContext: sharedContext] autorelease];
  228510. const GLint swapInterval = 1;
  228511. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228512. [view setOpenGLContext: renderContext];
  228513. [format release];
  228514. viewHolder = new NSViewComponentInternal (view, component);
  228515. }
  228516. ~WindowedGLContext()
  228517. {
  228518. deleteContext();
  228519. viewHolder = 0;
  228520. }
  228521. void deleteContext()
  228522. {
  228523. makeInactive();
  228524. [renderContext clearDrawable];
  228525. [renderContext setView: nil];
  228526. [view setOpenGLContext: nil];
  228527. renderContext = nil;
  228528. }
  228529. bool makeActive() const throw()
  228530. {
  228531. jassert (renderContext != 0);
  228532. if ([renderContext view] != view)
  228533. [renderContext setView: view];
  228534. [view makeActive];
  228535. return isActive();
  228536. }
  228537. bool makeInactive() const throw()
  228538. {
  228539. [view makeInactive];
  228540. return true;
  228541. }
  228542. bool isActive() const throw()
  228543. {
  228544. return [NSOpenGLContext currentContext] == renderContext;
  228545. }
  228546. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228547. void* getRawContext() const throw() { return renderContext; }
  228548. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228549. {
  228550. }
  228551. void swapBuffers()
  228552. {
  228553. [renderContext flushBuffer];
  228554. }
  228555. bool setSwapInterval (const int numFramesPerSwap)
  228556. {
  228557. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228558. forParameter: NSOpenGLCPSwapInterval];
  228559. return true;
  228560. }
  228561. int getSwapInterval() const
  228562. {
  228563. GLint numFrames = 0;
  228564. [renderContext getValues: &numFrames
  228565. forParameter: NSOpenGLCPSwapInterval];
  228566. return numFrames;
  228567. }
  228568. void repaint()
  228569. {
  228570. // we need to invalidate the juce view that holds this gl view, to make it
  228571. // cause a repaint callback
  228572. NSView* v = (NSView*) viewHolder->view;
  228573. NSRect r = [v frame];
  228574. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228575. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228576. // repaint message, thus never causing our paint() callback, and never repainting
  228577. // the comp. So invalidating just a little bit around the edge helps..
  228578. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228579. }
  228580. void* getNativeWindowHandle() const { return viewHolder->view; }
  228581. juce_UseDebuggingNewOperator
  228582. NSOpenGLContext* renderContext;
  228583. ThreadSafeNSOpenGLView* view;
  228584. private:
  228585. OpenGLPixelFormat pixelFormat;
  228586. ScopedPointer <NSViewComponentInternal> viewHolder;
  228587. WindowedGLContext (const WindowedGLContext&);
  228588. WindowedGLContext& operator= (const WindowedGLContext&);
  228589. };
  228590. OpenGLContext* OpenGLComponent::createContext()
  228591. {
  228592. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228593. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228594. return (c->renderContext != 0) ? c.release() : 0;
  228595. }
  228596. void* OpenGLComponent::getNativeWindowHandle() const
  228597. {
  228598. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228599. : 0;
  228600. }
  228601. void juce_glViewport (const int w, const int h)
  228602. {
  228603. glViewport (0, 0, w, h);
  228604. }
  228605. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228606. OwnedArray <OpenGLPixelFormat>& results)
  228607. {
  228608. /* GLint attribs [64];
  228609. int n = 0;
  228610. attribs[n++] = AGL_RGBA;
  228611. attribs[n++] = AGL_DOUBLEBUFFER;
  228612. attribs[n++] = AGL_ACCELERATED;
  228613. attribs[n++] = AGL_NO_RECOVERY;
  228614. attribs[n++] = AGL_NONE;
  228615. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228616. while (p != 0)
  228617. {
  228618. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228619. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228620. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228621. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228622. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228623. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228624. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228625. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228626. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228627. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228628. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228629. results.add (pf);
  228630. p = aglNextPixelFormat (p);
  228631. }*/
  228632. //jassertfalse // can't see how you do this in cocoa!
  228633. }
  228634. #else
  228635. END_JUCE_NAMESPACE
  228636. @interface JuceGLView : UIView
  228637. {
  228638. }
  228639. + (Class) layerClass;
  228640. @end
  228641. @implementation JuceGLView
  228642. + (Class) layerClass
  228643. {
  228644. return [CAEAGLLayer class];
  228645. }
  228646. @end
  228647. BEGIN_JUCE_NAMESPACE
  228648. class GLESContext : public OpenGLContext
  228649. {
  228650. public:
  228651. GLESContext (UIViewComponentPeer* peer,
  228652. Component* const component_,
  228653. const OpenGLPixelFormat& pixelFormat_,
  228654. const GLESContext* const sharedContext,
  228655. NSUInteger apiType)
  228656. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228657. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228658. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228659. {
  228660. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228661. view.opaque = YES;
  228662. view.hidden = NO;
  228663. view.backgroundColor = [UIColor blackColor];
  228664. view.userInteractionEnabled = NO;
  228665. glLayer = (CAEAGLLayer*) [view layer];
  228666. [peer->view addSubview: view];
  228667. if (sharedContext != 0)
  228668. context = [[EAGLContext alloc] initWithAPI: apiType
  228669. sharegroup: [sharedContext->context sharegroup]];
  228670. else
  228671. context = [[EAGLContext alloc] initWithAPI: apiType];
  228672. createGLBuffers();
  228673. }
  228674. ~GLESContext()
  228675. {
  228676. deleteContext();
  228677. [view removeFromSuperview];
  228678. [view release];
  228679. freeGLBuffers();
  228680. }
  228681. void deleteContext()
  228682. {
  228683. makeInactive();
  228684. [context release];
  228685. context = nil;
  228686. }
  228687. bool makeActive() const throw()
  228688. {
  228689. jassert (context != 0);
  228690. [EAGLContext setCurrentContext: context];
  228691. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228692. return true;
  228693. }
  228694. void swapBuffers()
  228695. {
  228696. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228697. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228698. }
  228699. bool makeInactive() const throw()
  228700. {
  228701. return [EAGLContext setCurrentContext: nil];
  228702. }
  228703. bool isActive() const throw()
  228704. {
  228705. return [EAGLContext currentContext] == context;
  228706. }
  228707. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228708. void* getRawContext() const throw() { return glLayer; }
  228709. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228710. {
  228711. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228712. if (lastWidth != w || lastHeight != h)
  228713. {
  228714. lastWidth = w;
  228715. lastHeight = h;
  228716. freeGLBuffers();
  228717. createGLBuffers();
  228718. }
  228719. }
  228720. bool setSwapInterval (const int numFramesPerSwap)
  228721. {
  228722. numFrames = numFramesPerSwap;
  228723. return true;
  228724. }
  228725. int getSwapInterval() const
  228726. {
  228727. return numFrames;
  228728. }
  228729. void repaint()
  228730. {
  228731. }
  228732. void createGLBuffers()
  228733. {
  228734. makeActive();
  228735. glGenFramebuffersOES (1, &frameBufferHandle);
  228736. glGenRenderbuffersOES (1, &colorBufferHandle);
  228737. glGenRenderbuffersOES (1, &depthBufferHandle);
  228738. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228739. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228740. GLint width, height;
  228741. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228742. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228743. if (useDepthBuffer)
  228744. {
  228745. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228746. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228747. }
  228748. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228749. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228750. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228751. if (useDepthBuffer)
  228752. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228753. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228754. }
  228755. void freeGLBuffers()
  228756. {
  228757. if (frameBufferHandle != 0)
  228758. {
  228759. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228760. frameBufferHandle = 0;
  228761. }
  228762. if (colorBufferHandle != 0)
  228763. {
  228764. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228765. colorBufferHandle = 0;
  228766. }
  228767. if (depthBufferHandle != 0)
  228768. {
  228769. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228770. depthBufferHandle = 0;
  228771. }
  228772. }
  228773. juce_UseDebuggingNewOperator
  228774. private:
  228775. Component::SafePointer<Component> component;
  228776. OpenGLPixelFormat pixelFormat;
  228777. JuceGLView* view;
  228778. CAEAGLLayer* glLayer;
  228779. EAGLContext* context;
  228780. bool useDepthBuffer;
  228781. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228782. int numFrames;
  228783. int lastWidth, lastHeight;
  228784. GLESContext (const GLESContext&);
  228785. GLESContext& operator= (const GLESContext&);
  228786. };
  228787. OpenGLContext* OpenGLComponent::createContext()
  228788. {
  228789. ScopedAutoReleasePool pool;
  228790. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228791. if (peer != 0)
  228792. return new GLESContext (peer, this, preferredPixelFormat,
  228793. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228794. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228795. return 0;
  228796. }
  228797. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228798. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228799. {
  228800. }
  228801. void juce_glViewport (const int w, const int h)
  228802. {
  228803. glViewport (0, 0, w, h);
  228804. }
  228805. #endif
  228806. #endif
  228807. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228808. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228809. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228810. // compiled on its own).
  228811. #if JUCE_INCLUDED_FILE
  228812. #if JUCE_MAC
  228813. namespace MouseCursorHelpers
  228814. {
  228815. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228816. {
  228817. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228818. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228819. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228820. [im release];
  228821. return c;
  228822. }
  228823. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228824. {
  228825. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228826. BufferedInputStream buf (&fileStream, 4096, false);
  228827. PNGImageFormat pngFormat;
  228828. Image im (pngFormat.decodeImage (buf));
  228829. if (im.isValid())
  228830. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228831. jassertfalse;
  228832. return 0;
  228833. }
  228834. }
  228835. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228836. {
  228837. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228838. }
  228839. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228840. {
  228841. const ScopedAutoReleasePool pool;
  228842. NSCursor* c = 0;
  228843. switch (type)
  228844. {
  228845. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228846. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228847. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228848. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228849. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228850. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228851. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228852. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228853. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228854. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228855. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228856. case UpDownResizeCursor:
  228857. case TopEdgeResizeCursor:
  228858. case BottomEdgeResizeCursor:
  228859. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228860. case TopLeftCornerResizeCursor:
  228861. case BottomRightCornerResizeCursor:
  228862. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228863. case TopRightCornerResizeCursor:
  228864. case BottomLeftCornerResizeCursor:
  228865. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228866. case UpDownLeftRightResizeCursor:
  228867. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228868. default:
  228869. jassertfalse;
  228870. break;
  228871. }
  228872. [c retain];
  228873. return c;
  228874. }
  228875. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228876. {
  228877. [((NSCursor*) cursorHandle) release];
  228878. }
  228879. void MouseCursor::showInAllWindows() const
  228880. {
  228881. showInWindow (0);
  228882. }
  228883. void MouseCursor::showInWindow (ComponentPeer*) const
  228884. {
  228885. [((NSCursor*) getHandle()) set];
  228886. }
  228887. #else
  228888. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228889. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228890. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228891. void MouseCursor::showInAllWindows() const {}
  228892. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228893. #endif
  228894. #endif
  228895. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228896. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228897. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228898. // compiled on its own).
  228899. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228900. #if JUCE_MAC
  228901. END_JUCE_NAMESPACE
  228902. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228903. @interface DownloadClickDetector : NSObject
  228904. {
  228905. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228906. }
  228907. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228908. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228909. request: (NSURLRequest*) request
  228910. frame: (WebFrame*) frame
  228911. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228912. @end
  228913. @implementation DownloadClickDetector
  228914. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228915. {
  228916. [super init];
  228917. ownerComponent = ownerComponent_;
  228918. return self;
  228919. }
  228920. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228921. request: (NSURLRequest*) request
  228922. frame: (WebFrame*) frame
  228923. decisionListener: (id <WebPolicyDecisionListener>) listener
  228924. {
  228925. (void) sender;
  228926. (void) request;
  228927. (void) frame;
  228928. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228929. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228930. [listener use];
  228931. else
  228932. [listener ignore];
  228933. }
  228934. @end
  228935. BEGIN_JUCE_NAMESPACE
  228936. class WebBrowserComponentInternal : public NSViewComponent
  228937. {
  228938. public:
  228939. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228940. {
  228941. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228942. frameName: @""
  228943. groupName: @""];
  228944. setView (webView);
  228945. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228946. [webView setPolicyDelegate: clickListener];
  228947. }
  228948. ~WebBrowserComponentInternal()
  228949. {
  228950. [webView setPolicyDelegate: nil];
  228951. [clickListener release];
  228952. setView (0);
  228953. }
  228954. void goToURL (const String& url,
  228955. const StringArray* headers,
  228956. const MemoryBlock* postData)
  228957. {
  228958. NSMutableURLRequest* r
  228959. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228960. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228961. timeoutInterval: 30.0];
  228962. if (postData != 0 && postData->getSize() > 0)
  228963. {
  228964. [r setHTTPMethod: @"POST"];
  228965. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228966. length: postData->getSize()]];
  228967. }
  228968. if (headers != 0)
  228969. {
  228970. for (int i = 0; i < headers->size(); ++i)
  228971. {
  228972. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228973. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228974. [r setValue: juceStringToNS (headerValue)
  228975. forHTTPHeaderField: juceStringToNS (headerName)];
  228976. }
  228977. }
  228978. stop();
  228979. [[webView mainFrame] loadRequest: r];
  228980. }
  228981. void goBack()
  228982. {
  228983. [webView goBack];
  228984. }
  228985. void goForward()
  228986. {
  228987. [webView goForward];
  228988. }
  228989. void stop()
  228990. {
  228991. [webView stopLoading: nil];
  228992. }
  228993. void refresh()
  228994. {
  228995. [webView reload: nil];
  228996. }
  228997. private:
  228998. WebView* webView;
  228999. DownloadClickDetector* clickListener;
  229000. };
  229001. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229002. : browser (0),
  229003. blankPageShown (false),
  229004. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  229005. {
  229006. setOpaque (true);
  229007. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  229008. }
  229009. WebBrowserComponent::~WebBrowserComponent()
  229010. {
  229011. deleteAndZero (browser);
  229012. }
  229013. void WebBrowserComponent::goToURL (const String& url,
  229014. const StringArray* headers,
  229015. const MemoryBlock* postData)
  229016. {
  229017. lastURL = url;
  229018. lastHeaders.clear();
  229019. if (headers != 0)
  229020. lastHeaders = *headers;
  229021. lastPostData.setSize (0);
  229022. if (postData != 0)
  229023. lastPostData = *postData;
  229024. blankPageShown = false;
  229025. browser->goToURL (url, headers, postData);
  229026. }
  229027. void WebBrowserComponent::stop()
  229028. {
  229029. browser->stop();
  229030. }
  229031. void WebBrowserComponent::goBack()
  229032. {
  229033. lastURL = String::empty;
  229034. blankPageShown = false;
  229035. browser->goBack();
  229036. }
  229037. void WebBrowserComponent::goForward()
  229038. {
  229039. lastURL = String::empty;
  229040. browser->goForward();
  229041. }
  229042. void WebBrowserComponent::refresh()
  229043. {
  229044. browser->refresh();
  229045. }
  229046. void WebBrowserComponent::paint (Graphics&)
  229047. {
  229048. }
  229049. void WebBrowserComponent::checkWindowAssociation()
  229050. {
  229051. if (isShowing())
  229052. {
  229053. if (blankPageShown)
  229054. goBack();
  229055. }
  229056. else
  229057. {
  229058. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  229059. {
  229060. // when the component becomes invisible, some stuff like flash
  229061. // carries on playing audio, so we need to force it onto a blank
  229062. // page to avoid this, (and send it back when it's made visible again).
  229063. blankPageShown = true;
  229064. browser->goToURL ("about:blank", 0, 0);
  229065. }
  229066. }
  229067. }
  229068. void WebBrowserComponent::reloadLastURL()
  229069. {
  229070. if (lastURL.isNotEmpty())
  229071. {
  229072. goToURL (lastURL, &lastHeaders, &lastPostData);
  229073. lastURL = String::empty;
  229074. }
  229075. }
  229076. void WebBrowserComponent::parentHierarchyChanged()
  229077. {
  229078. checkWindowAssociation();
  229079. }
  229080. void WebBrowserComponent::resized()
  229081. {
  229082. browser->setSize (getWidth(), getHeight());
  229083. }
  229084. void WebBrowserComponent::visibilityChanged()
  229085. {
  229086. checkWindowAssociation();
  229087. }
  229088. bool WebBrowserComponent::pageAboutToLoad (const String&)
  229089. {
  229090. return true;
  229091. }
  229092. #else
  229093. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229094. {
  229095. }
  229096. WebBrowserComponent::~WebBrowserComponent()
  229097. {
  229098. }
  229099. void WebBrowserComponent::goToURL (const String& url,
  229100. const StringArray* headers,
  229101. const MemoryBlock* postData)
  229102. {
  229103. }
  229104. void WebBrowserComponent::stop()
  229105. {
  229106. }
  229107. void WebBrowserComponent::goBack()
  229108. {
  229109. }
  229110. void WebBrowserComponent::goForward()
  229111. {
  229112. }
  229113. void WebBrowserComponent::refresh()
  229114. {
  229115. }
  229116. void WebBrowserComponent::paint (Graphics& g)
  229117. {
  229118. }
  229119. void WebBrowserComponent::checkWindowAssociation()
  229120. {
  229121. }
  229122. void WebBrowserComponent::reloadLastURL()
  229123. {
  229124. }
  229125. void WebBrowserComponent::parentHierarchyChanged()
  229126. {
  229127. }
  229128. void WebBrowserComponent::resized()
  229129. {
  229130. }
  229131. void WebBrowserComponent::visibilityChanged()
  229132. {
  229133. }
  229134. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  229135. {
  229136. return true;
  229137. }
  229138. #endif
  229139. #endif
  229140. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229141. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  229142. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229143. // compiled on its own).
  229144. #if JUCE_INCLUDED_FILE
  229145. class IPhoneAudioIODevice : public AudioIODevice
  229146. {
  229147. public:
  229148. IPhoneAudioIODevice (const String& deviceName)
  229149. : AudioIODevice (deviceName, "Audio"),
  229150. audioUnit (0),
  229151. isRunning (false),
  229152. callback (0),
  229153. actualBufferSize (0),
  229154. floatData (1, 2)
  229155. {
  229156. numInputChannels = 2;
  229157. numOutputChannels = 2;
  229158. preferredBufferSize = 0;
  229159. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229160. updateDeviceInfo();
  229161. }
  229162. ~IPhoneAudioIODevice()
  229163. {
  229164. close();
  229165. }
  229166. const StringArray getOutputChannelNames()
  229167. {
  229168. StringArray s;
  229169. s.add ("Left");
  229170. s.add ("Right");
  229171. return s;
  229172. }
  229173. const StringArray getInputChannelNames()
  229174. {
  229175. StringArray s;
  229176. if (audioInputIsAvailable)
  229177. {
  229178. s.add ("Left");
  229179. s.add ("Right");
  229180. }
  229181. return s;
  229182. }
  229183. int getNumSampleRates()
  229184. {
  229185. return 1;
  229186. }
  229187. double getSampleRate (int index)
  229188. {
  229189. return sampleRate;
  229190. }
  229191. int getNumBufferSizesAvailable()
  229192. {
  229193. return 1;
  229194. }
  229195. int getBufferSizeSamples (int index)
  229196. {
  229197. return getDefaultBufferSize();
  229198. }
  229199. int getDefaultBufferSize()
  229200. {
  229201. return 1024;
  229202. }
  229203. const String open (const BigInteger& inputChannels,
  229204. const BigInteger& outputChannels,
  229205. double sampleRate,
  229206. int bufferSize)
  229207. {
  229208. close();
  229209. lastError = String::empty;
  229210. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229211. // xxx set up channel mapping
  229212. activeOutputChans = outputChannels;
  229213. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229214. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229215. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229216. activeInputChans = inputChannels;
  229217. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229218. numInputChannels = activeInputChans.countNumberOfSetBits();
  229219. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229220. AudioSessionSetActive (true);
  229221. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229222. : kAudioSessionCategory_MediaPlayback;
  229223. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229224. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229225. fixAudioRouteIfSetToReceiver();
  229226. updateDeviceInfo();
  229227. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229228. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229229. actualBufferSize = preferredBufferSize;
  229230. prepareFloatBuffers();
  229231. isRunning = true;
  229232. propertyChanged (0, 0, 0); // creates and starts the AU
  229233. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229234. return lastError;
  229235. }
  229236. void close()
  229237. {
  229238. if (isRunning)
  229239. {
  229240. isRunning = false;
  229241. AudioSessionSetActive (false);
  229242. if (audioUnit != 0)
  229243. {
  229244. AudioComponentInstanceDispose (audioUnit);
  229245. audioUnit = 0;
  229246. }
  229247. }
  229248. }
  229249. bool isOpen()
  229250. {
  229251. return isRunning;
  229252. }
  229253. int getCurrentBufferSizeSamples()
  229254. {
  229255. return actualBufferSize;
  229256. }
  229257. double getCurrentSampleRate()
  229258. {
  229259. return sampleRate;
  229260. }
  229261. int getCurrentBitDepth()
  229262. {
  229263. return 16;
  229264. }
  229265. const BigInteger getActiveOutputChannels() const
  229266. {
  229267. return activeOutputChans;
  229268. }
  229269. const BigInteger getActiveInputChannels() const
  229270. {
  229271. return activeInputChans;
  229272. }
  229273. int getOutputLatencyInSamples()
  229274. {
  229275. return 0; //xxx
  229276. }
  229277. int getInputLatencyInSamples()
  229278. {
  229279. return 0; //xxx
  229280. }
  229281. void start (AudioIODeviceCallback* callback_)
  229282. {
  229283. if (isRunning && callback != callback_)
  229284. {
  229285. if (callback_ != 0)
  229286. callback_->audioDeviceAboutToStart (this);
  229287. const ScopedLock sl (callbackLock);
  229288. callback = callback_;
  229289. }
  229290. }
  229291. void stop()
  229292. {
  229293. if (isRunning)
  229294. {
  229295. AudioIODeviceCallback* lastCallback;
  229296. {
  229297. const ScopedLock sl (callbackLock);
  229298. lastCallback = callback;
  229299. callback = 0;
  229300. }
  229301. if (lastCallback != 0)
  229302. lastCallback->audioDeviceStopped();
  229303. }
  229304. }
  229305. bool isPlaying()
  229306. {
  229307. return isRunning && callback != 0;
  229308. }
  229309. const String getLastError()
  229310. {
  229311. return lastError;
  229312. }
  229313. private:
  229314. CriticalSection callbackLock;
  229315. Float64 sampleRate;
  229316. int numInputChannels, numOutputChannels;
  229317. int preferredBufferSize;
  229318. int actualBufferSize;
  229319. bool isRunning;
  229320. String lastError;
  229321. AudioStreamBasicDescription format;
  229322. AudioUnit audioUnit;
  229323. UInt32 audioInputIsAvailable;
  229324. AudioIODeviceCallback* callback;
  229325. BigInteger activeOutputChans, activeInputChans;
  229326. AudioSampleBuffer floatData;
  229327. float* inputChannels[3];
  229328. float* outputChannels[3];
  229329. bool monoInputChannelNumber, monoOutputChannelNumber;
  229330. void prepareFloatBuffers()
  229331. {
  229332. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229333. zerostruct (inputChannels);
  229334. zerostruct (outputChannels);
  229335. for (int i = 0; i < numInputChannels; ++i)
  229336. inputChannels[i] = floatData.getSampleData (i);
  229337. for (int i = 0; i < numOutputChannels; ++i)
  229338. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229339. }
  229340. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229341. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229342. {
  229343. OSStatus err = noErr;
  229344. if (audioInputIsAvailable)
  229345. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229346. const ScopedLock sl (callbackLock);
  229347. if (callback != 0)
  229348. {
  229349. if (audioInputIsAvailable && numInputChannels > 0)
  229350. {
  229351. short* shortData = (short*) ioData->mBuffers[0].mData;
  229352. if (numInputChannels >= 2)
  229353. {
  229354. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229355. {
  229356. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229357. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229358. }
  229359. }
  229360. else
  229361. {
  229362. if (monoInputChannelNumber > 0)
  229363. ++shortData;
  229364. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229365. {
  229366. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229367. ++shortData;
  229368. }
  229369. }
  229370. }
  229371. else
  229372. {
  229373. for (int i = numInputChannels; --i >= 0;)
  229374. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229375. }
  229376. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229377. outputChannels, numOutputChannels,
  229378. (int) inNumberFrames);
  229379. short* shortData = (short*) ioData->mBuffers[0].mData;
  229380. int n = 0;
  229381. if (numOutputChannels >= 2)
  229382. {
  229383. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229384. {
  229385. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229386. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229387. }
  229388. }
  229389. else if (numOutputChannels == 1)
  229390. {
  229391. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229392. {
  229393. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229394. shortData [n++] = s;
  229395. shortData [n++] = s;
  229396. }
  229397. }
  229398. else
  229399. {
  229400. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229401. }
  229402. }
  229403. else
  229404. {
  229405. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229406. }
  229407. return err;
  229408. }
  229409. void updateDeviceInfo()
  229410. {
  229411. UInt32 size = sizeof (sampleRate);
  229412. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229413. size = sizeof (audioInputIsAvailable);
  229414. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229415. }
  229416. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229417. {
  229418. if (! isRunning)
  229419. return;
  229420. if (inPropertyValue != 0)
  229421. {
  229422. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229423. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229424. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229425. SInt32 routeChangeReason;
  229426. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229427. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229428. fixAudioRouteIfSetToReceiver();
  229429. }
  229430. updateDeviceInfo();
  229431. createAudioUnit();
  229432. AudioSessionSetActive (true);
  229433. if (audioUnit != 0)
  229434. {
  229435. UInt32 formatSize = sizeof (format);
  229436. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229437. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229438. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229439. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229440. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229441. AudioOutputUnitStart (audioUnit);
  229442. }
  229443. }
  229444. void interruptionListener (UInt32 inInterruption)
  229445. {
  229446. /*if (inInterruption == kAudioSessionBeginInterruption)
  229447. {
  229448. isRunning = false;
  229449. AudioOutputUnitStop (audioUnit);
  229450. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229451. "This could have been interrupted by another application or by unplugging a headset",
  229452. @"Resume",
  229453. @"Cancel"))
  229454. {
  229455. isRunning = true;
  229456. propertyChanged (0, 0, 0);
  229457. }
  229458. }*/
  229459. if (inInterruption == kAudioSessionEndInterruption)
  229460. {
  229461. isRunning = true;
  229462. AudioSessionSetActive (true);
  229463. AudioOutputUnitStart (audioUnit);
  229464. }
  229465. }
  229466. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229467. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229468. {
  229469. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229470. }
  229471. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229472. {
  229473. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229474. }
  229475. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229476. {
  229477. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229478. }
  229479. void resetFormat (const int numChannels)
  229480. {
  229481. memset (&format, 0, sizeof (format));
  229482. format.mFormatID = kAudioFormatLinearPCM;
  229483. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229484. format.mBitsPerChannel = 8 * sizeof (short);
  229485. format.mChannelsPerFrame = 2;
  229486. format.mFramesPerPacket = 1;
  229487. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229488. }
  229489. bool createAudioUnit()
  229490. {
  229491. if (audioUnit != 0)
  229492. {
  229493. AudioComponentInstanceDispose (audioUnit);
  229494. audioUnit = 0;
  229495. }
  229496. resetFormat (2);
  229497. AudioComponentDescription desc;
  229498. desc.componentType = kAudioUnitType_Output;
  229499. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229500. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229501. desc.componentFlags = 0;
  229502. desc.componentFlagsMask = 0;
  229503. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229504. AudioComponentInstanceNew (comp, &audioUnit);
  229505. if (audioUnit == 0)
  229506. return false;
  229507. const UInt32 one = 1;
  229508. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229509. AudioChannelLayout layout;
  229510. layout.mChannelBitmap = 0;
  229511. layout.mNumberChannelDescriptions = 0;
  229512. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229513. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229514. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229515. AURenderCallbackStruct inputProc;
  229516. inputProc.inputProc = processStatic;
  229517. inputProc.inputProcRefCon = this;
  229518. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229519. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229520. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229521. AudioUnitInitialize (audioUnit);
  229522. return true;
  229523. }
  229524. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229525. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229526. static void fixAudioRouteIfSetToReceiver()
  229527. {
  229528. CFStringRef audioRoute = 0;
  229529. UInt32 propertySize = sizeof (audioRoute);
  229530. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229531. {
  229532. NSString* route = (NSString*) audioRoute;
  229533. //DBG ("audio route: " + nsStringToJuce (route));
  229534. if ([route hasPrefix: @"Receiver"])
  229535. {
  229536. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229537. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229538. }
  229539. CFRelease (audioRoute);
  229540. }
  229541. }
  229542. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229543. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229544. };
  229545. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229546. {
  229547. public:
  229548. IPhoneAudioIODeviceType()
  229549. : AudioIODeviceType ("iPhone Audio")
  229550. {
  229551. }
  229552. ~IPhoneAudioIODeviceType()
  229553. {
  229554. }
  229555. void scanForDevices()
  229556. {
  229557. }
  229558. const StringArray getDeviceNames (bool wantInputNames) const
  229559. {
  229560. StringArray s;
  229561. s.add ("iPhone Audio");
  229562. return s;
  229563. }
  229564. int getDefaultDeviceIndex (bool forInput) const
  229565. {
  229566. return 0;
  229567. }
  229568. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229569. {
  229570. return device != 0 ? 0 : -1;
  229571. }
  229572. bool hasSeparateInputsAndOutputs() const { return false; }
  229573. AudioIODevice* createDevice (const String& outputDeviceName,
  229574. const String& inputDeviceName)
  229575. {
  229576. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229577. {
  229578. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229579. : inputDeviceName);
  229580. }
  229581. return 0;
  229582. }
  229583. juce_UseDebuggingNewOperator
  229584. private:
  229585. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229586. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229587. };
  229588. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229589. {
  229590. return new IPhoneAudioIODeviceType();
  229591. }
  229592. #endif
  229593. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229594. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229595. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229596. // compiled on its own).
  229597. #if JUCE_INCLUDED_FILE
  229598. #if JUCE_MAC
  229599. #undef log
  229600. #define log(a) Logger::writeToLog(a)
  229601. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  229602. {
  229603. if (err == noErr)
  229604. return true;
  229605. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229606. jassertfalse;
  229607. return false;
  229608. }
  229609. #undef OK
  229610. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  229611. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229612. {
  229613. String result;
  229614. CFStringRef str = 0;
  229615. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229616. if (str != 0)
  229617. {
  229618. result = PlatformUtilities::cfStringToJuceString (str);
  229619. CFRelease (str);
  229620. str = 0;
  229621. }
  229622. MIDIEntityRef entity = 0;
  229623. MIDIEndpointGetEntity (endpoint, &entity);
  229624. if (entity == 0)
  229625. return result; // probably virtual
  229626. if (result.isEmpty())
  229627. {
  229628. // endpoint name has zero length - try the entity
  229629. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229630. if (str != 0)
  229631. {
  229632. result += PlatformUtilities::cfStringToJuceString (str);
  229633. CFRelease (str);
  229634. str = 0;
  229635. }
  229636. }
  229637. // now consider the device's name
  229638. MIDIDeviceRef device = 0;
  229639. MIDIEntityGetDevice (entity, &device);
  229640. if (device == 0)
  229641. return result;
  229642. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229643. if (str != 0)
  229644. {
  229645. const String s (PlatformUtilities::cfStringToJuceString (str));
  229646. CFRelease (str);
  229647. // if an external device has only one entity, throw away
  229648. // the endpoint name and just use the device name
  229649. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229650. {
  229651. result = s;
  229652. }
  229653. else if (! result.startsWithIgnoreCase (s))
  229654. {
  229655. // prepend the device name to the entity name
  229656. result = (s + " " + result).trimEnd();
  229657. }
  229658. }
  229659. return result;
  229660. }
  229661. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229662. {
  229663. String result;
  229664. // Does the endpoint have connections?
  229665. CFDataRef connections = 0;
  229666. int numConnections = 0;
  229667. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229668. if (connections != 0)
  229669. {
  229670. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229671. if (numConnections > 0)
  229672. {
  229673. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229674. for (int i = 0; i < numConnections; ++i, ++pid)
  229675. {
  229676. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229677. MIDIObjectRef connObject;
  229678. MIDIObjectType connObjectType;
  229679. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229680. if (err == noErr)
  229681. {
  229682. String s;
  229683. if (connObjectType == kMIDIObjectType_ExternalSource
  229684. || connObjectType == kMIDIObjectType_ExternalDestination)
  229685. {
  229686. // Connected to an external device's endpoint (10.3 and later).
  229687. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229688. }
  229689. else
  229690. {
  229691. // Connected to an external device (10.2) (or something else, catch-all)
  229692. CFStringRef str = 0;
  229693. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229694. if (str != 0)
  229695. {
  229696. s = PlatformUtilities::cfStringToJuceString (str);
  229697. CFRelease (str);
  229698. }
  229699. }
  229700. if (s.isNotEmpty())
  229701. {
  229702. if (result.isNotEmpty())
  229703. result += ", ";
  229704. result += s;
  229705. }
  229706. }
  229707. }
  229708. }
  229709. CFRelease (connections);
  229710. }
  229711. if (result.isNotEmpty())
  229712. return result;
  229713. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229714. return getEndpointName (endpoint, false);
  229715. }
  229716. const StringArray MidiOutput::getDevices()
  229717. {
  229718. StringArray s;
  229719. const ItemCount num = MIDIGetNumberOfDestinations();
  229720. for (ItemCount i = 0; i < num; ++i)
  229721. {
  229722. MIDIEndpointRef dest = MIDIGetDestination (i);
  229723. if (dest != 0)
  229724. {
  229725. String name (getConnectedEndpointName (dest));
  229726. if (name.isEmpty())
  229727. name = "<error>";
  229728. s.add (name);
  229729. }
  229730. else
  229731. {
  229732. s.add ("<error>");
  229733. }
  229734. }
  229735. return s;
  229736. }
  229737. int MidiOutput::getDefaultDeviceIndex()
  229738. {
  229739. return 0;
  229740. }
  229741. static MIDIClientRef globalMidiClient;
  229742. static bool hasGlobalClientBeenCreated = false;
  229743. static bool makeSureClientExists()
  229744. {
  229745. if (! hasGlobalClientBeenCreated)
  229746. {
  229747. String name ("JUCE");
  229748. if (JUCEApplication::getInstance() != 0)
  229749. name = JUCEApplication::getInstance()->getApplicationName();
  229750. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229751. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229752. CFRelease (appName);
  229753. }
  229754. return hasGlobalClientBeenCreated;
  229755. }
  229756. class MidiPortAndEndpoint
  229757. {
  229758. public:
  229759. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229760. : port (port_), endPoint (endPoint_)
  229761. {
  229762. }
  229763. ~MidiPortAndEndpoint()
  229764. {
  229765. if (port != 0)
  229766. MIDIPortDispose (port);
  229767. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229768. MIDIEndpointDispose (endPoint);
  229769. }
  229770. MIDIPortRef port;
  229771. MIDIEndpointRef endPoint;
  229772. };
  229773. MidiOutput* MidiOutput::openDevice (int index)
  229774. {
  229775. MidiOutput* mo = 0;
  229776. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229777. {
  229778. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229779. CFStringRef pname;
  229780. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229781. {
  229782. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  229783. if (makeSureClientExists())
  229784. {
  229785. MIDIPortRef port;
  229786. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  229787. {
  229788. mo = new MidiOutput();
  229789. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  229790. }
  229791. }
  229792. CFRelease (pname);
  229793. }
  229794. }
  229795. return mo;
  229796. }
  229797. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229798. {
  229799. MidiOutput* mo = 0;
  229800. if (makeSureClientExists())
  229801. {
  229802. MIDIEndpointRef endPoint;
  229803. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229804. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  229805. {
  229806. mo = new MidiOutput();
  229807. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  229808. }
  229809. CFRelease (name);
  229810. }
  229811. return mo;
  229812. }
  229813. MidiOutput::~MidiOutput()
  229814. {
  229815. delete static_cast<MidiPortAndEndpoint*> (internal);
  229816. }
  229817. void MidiOutput::reset()
  229818. {
  229819. }
  229820. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229821. {
  229822. return false;
  229823. }
  229824. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229825. {
  229826. }
  229827. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229828. {
  229829. MidiPortAndEndpoint* const mpe = static_cast<MidiPortAndEndpoint*> (internal);
  229830. if (message.isSysEx())
  229831. {
  229832. const int maxPacketSize = 256;
  229833. int pos = 0, bytesLeft = message.getRawDataSize();
  229834. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229835. HeapBlock <MIDIPacketList> packets;
  229836. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229837. packets->numPackets = numPackets;
  229838. MIDIPacket* p = packets->packet;
  229839. for (int i = 0; i < numPackets; ++i)
  229840. {
  229841. p->timeStamp = 0;
  229842. p->length = jmin (maxPacketSize, bytesLeft);
  229843. memcpy (p->data, message.getRawData() + pos, p->length);
  229844. pos += p->length;
  229845. bytesLeft -= p->length;
  229846. p = MIDIPacketNext (p);
  229847. }
  229848. if (mpe->port != 0)
  229849. MIDISend (mpe->port, mpe->endPoint, packets);
  229850. else
  229851. MIDIReceived (mpe->endPoint, packets);
  229852. }
  229853. else
  229854. {
  229855. MIDIPacketList packets;
  229856. packets.numPackets = 1;
  229857. packets.packet[0].timeStamp = 0;
  229858. packets.packet[0].length = message.getRawDataSize();
  229859. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229860. if (mpe->port != 0)
  229861. MIDISend (mpe->port, mpe->endPoint, &packets);
  229862. else
  229863. MIDIReceived (mpe->endPoint, &packets);
  229864. }
  229865. }
  229866. const StringArray MidiInput::getDevices()
  229867. {
  229868. StringArray s;
  229869. const ItemCount num = MIDIGetNumberOfSources();
  229870. for (ItemCount i = 0; i < num; ++i)
  229871. {
  229872. MIDIEndpointRef source = MIDIGetSource (i);
  229873. if (source != 0)
  229874. {
  229875. String name (getConnectedEndpointName (source));
  229876. if (name.isEmpty())
  229877. name = "<error>";
  229878. s.add (name);
  229879. }
  229880. else
  229881. {
  229882. s.add ("<error>");
  229883. }
  229884. }
  229885. return s;
  229886. }
  229887. int MidiInput::getDefaultDeviceIndex()
  229888. {
  229889. return 0;
  229890. }
  229891. struct MidiPortAndCallback
  229892. {
  229893. MidiInput* input;
  229894. MidiPortAndEndpoint* portAndEndpoint;
  229895. MidiInputCallback* callback;
  229896. MemoryBlock pendingData;
  229897. int pendingBytes;
  229898. double pendingDataTime;
  229899. bool active;
  229900. void processSysex (const uint8*& d, int& size, const double time)
  229901. {
  229902. if (*d == 0xf0)
  229903. {
  229904. pendingBytes = 0;
  229905. pendingDataTime = time;
  229906. }
  229907. pendingData.ensureSize (pendingBytes + size, false);
  229908. uint8* totalMessage = (uint8*) pendingData.getData();
  229909. uint8* dest = totalMessage + pendingBytes;
  229910. while (size > 0)
  229911. {
  229912. if (pendingBytes > 0 && *d >= 0x80)
  229913. {
  229914. if (*d >= 0xfa || *d == 0xf8)
  229915. {
  229916. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  229917. ++d;
  229918. --size;
  229919. }
  229920. else
  229921. {
  229922. if (*d == 0xf7)
  229923. {
  229924. *dest++ = *d++;
  229925. pendingBytes++;
  229926. --size;
  229927. }
  229928. break;
  229929. }
  229930. }
  229931. else
  229932. {
  229933. *dest++ = *d++;
  229934. pendingBytes++;
  229935. --size;
  229936. }
  229937. }
  229938. if (totalMessage [pendingBytes - 1] == 0xf7)
  229939. {
  229940. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  229941. pendingBytes = 0;
  229942. }
  229943. else
  229944. {
  229945. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  229946. }
  229947. }
  229948. };
  229949. namespace CoreMidiCallbacks
  229950. {
  229951. static CriticalSection callbackLock;
  229952. static Array<void*> activeCallbacks;
  229953. }
  229954. static void midiInputProc (const MIDIPacketList* pktlist,
  229955. void* readProcRefCon,
  229956. void* /*srcConnRefCon*/)
  229957. {
  229958. double time = Time::getMillisecondCounterHiRes() * 0.001;
  229959. const double originalTime = time;
  229960. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  229961. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229962. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  229963. {
  229964. const MIDIPacket* packet = &pktlist->packet[0];
  229965. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229966. {
  229967. const uint8* d = (const uint8*) (packet->data);
  229968. int size = packet->length;
  229969. while (size > 0)
  229970. {
  229971. time = originalTime;
  229972. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  229973. {
  229974. mpc->processSysex (d, size, time);
  229975. }
  229976. else
  229977. {
  229978. int used = 0;
  229979. const MidiMessage m (d, size, used, 0, time);
  229980. if (used <= 0)
  229981. {
  229982. jassertfalse; // malformed midi message
  229983. break;
  229984. }
  229985. else
  229986. {
  229987. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  229988. }
  229989. size -= used;
  229990. d += used;
  229991. }
  229992. }
  229993. packet = MIDIPacketNext (packet);
  229994. }
  229995. }
  229996. }
  229997. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229998. {
  229999. MidiInput* mi = 0;
  230000. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  230001. {
  230002. MIDIEndpointRef endPoint = MIDIGetSource (index);
  230003. if (endPoint != 0)
  230004. {
  230005. CFStringRef pname;
  230006. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  230007. {
  230008. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  230009. if (makeSureClientExists())
  230010. {
  230011. MIDIPortRef port;
  230012. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  230013. mpc->active = false;
  230014. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  230015. {
  230016. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  230017. {
  230018. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  230019. mpc->callback = callback;
  230020. mpc->pendingBytes = 0;
  230021. mpc->pendingData.ensureSize (128);
  230022. mi = new MidiInput (getDevices() [index]);
  230023. mpc->input = mi;
  230024. mi->internal = mpc;
  230025. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230026. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  230027. }
  230028. else
  230029. {
  230030. OK (MIDIPortDispose (port));
  230031. }
  230032. }
  230033. }
  230034. }
  230035. CFRelease (pname);
  230036. }
  230037. }
  230038. return mi;
  230039. }
  230040. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  230041. {
  230042. MidiInput* mi = 0;
  230043. if (makeSureClientExists())
  230044. {
  230045. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  230046. mpc->active = false;
  230047. MIDIEndpointRef endPoint;
  230048. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  230049. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  230050. {
  230051. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  230052. mpc->callback = callback;
  230053. mpc->pendingBytes = 0;
  230054. mpc->pendingData.ensureSize (128);
  230055. mi = new MidiInput (deviceName);
  230056. mpc->input = mi;
  230057. mi->internal = mpc;
  230058. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230059. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  230060. }
  230061. CFRelease (name);
  230062. }
  230063. return mi;
  230064. }
  230065. MidiInput::MidiInput (const String& name_)
  230066. : name (name_)
  230067. {
  230068. }
  230069. MidiInput::~MidiInput()
  230070. {
  230071. MidiPortAndCallback* const mpc = static_cast<MidiPortAndCallback*> (internal);
  230072. mpc->active = false;
  230073. {
  230074. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230075. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  230076. }
  230077. if (mpc->portAndEndpoint->port != 0)
  230078. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  230079. delete mpc->portAndEndpoint;
  230080. delete mpc;
  230081. }
  230082. void MidiInput::start()
  230083. {
  230084. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230085. static_cast<MidiPortAndCallback*> (internal)->active = true;
  230086. }
  230087. void MidiInput::stop()
  230088. {
  230089. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230090. static_cast<MidiPortAndCallback*> (internal)->active = false;
  230091. }
  230092. #undef log
  230093. #else
  230094. MidiOutput::~MidiOutput()
  230095. {
  230096. }
  230097. void MidiOutput::reset()
  230098. {
  230099. }
  230100. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  230101. {
  230102. return false;
  230103. }
  230104. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  230105. {
  230106. }
  230107. void MidiOutput::sendMessageNow (const MidiMessage& message)
  230108. {
  230109. }
  230110. const StringArray MidiOutput::getDevices()
  230111. {
  230112. return StringArray();
  230113. }
  230114. MidiOutput* MidiOutput::openDevice (int index)
  230115. {
  230116. return 0;
  230117. }
  230118. const StringArray MidiInput::getDevices()
  230119. {
  230120. return StringArray();
  230121. }
  230122. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  230123. {
  230124. return 0;
  230125. }
  230126. #endif
  230127. #endif
  230128. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  230129. #else
  230130. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  230131. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230132. // compiled on its own).
  230133. #if JUCE_INCLUDED_FILE
  230134. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230135. #define SUPPORT_10_4_FONTS 1
  230136. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  230137. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230138. #define SUPPORT_ONLY_10_4_FONTS 1
  230139. #endif
  230140. END_JUCE_NAMESPACE
  230141. @interface NSFont (PrivateHack)
  230142. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  230143. @end
  230144. BEGIN_JUCE_NAMESPACE
  230145. #endif
  230146. class MacTypeface : public Typeface
  230147. {
  230148. public:
  230149. MacTypeface (const Font& font)
  230150. : Typeface (font.getTypefaceName())
  230151. {
  230152. const ScopedAutoReleasePool pool;
  230153. renderingTransform = CGAffineTransformIdentity;
  230154. bool needsItalicTransform = false;
  230155. #if JUCE_IOS
  230156. NSString* fontName = juceStringToNS (font.getTypefaceName());
  230157. if (font.isItalic() || font.isBold())
  230158. {
  230159. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  230160. for (NSString* i in familyFonts)
  230161. {
  230162. const String fn (nsStringToJuce (i));
  230163. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  230164. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  230165. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  230166. || afterDash.containsIgnoreCase ("italic")
  230167. || fn.endsWithIgnoreCase ("oblique")
  230168. || fn.endsWithIgnoreCase ("italic");
  230169. if (probablyBold == font.isBold()
  230170. && probablyItalic == font.isItalic())
  230171. {
  230172. fontName = i;
  230173. needsItalicTransform = false;
  230174. break;
  230175. }
  230176. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  230177. {
  230178. fontName = i;
  230179. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  230180. }
  230181. }
  230182. if (needsItalicTransform)
  230183. renderingTransform.c = 0.15f;
  230184. }
  230185. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  230186. const int ascender = abs (CGFontGetAscent (fontRef));
  230187. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  230188. ascent = ascender / totalHeight;
  230189. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230190. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  230191. #else
  230192. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  230193. if (font.isItalic())
  230194. {
  230195. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  230196. toHaveTrait: NSItalicFontMask];
  230197. if (newFont == nsFont)
  230198. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  230199. nsFont = newFont;
  230200. }
  230201. if (font.isBold())
  230202. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  230203. [nsFont retain];
  230204. ascent = std::abs ((float) [nsFont ascender]);
  230205. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  230206. ascent /= totalSize;
  230207. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  230208. if (needsItalicTransform)
  230209. {
  230210. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  230211. renderingTransform.c = 0.15f;
  230212. }
  230213. #if SUPPORT_ONLY_10_4_FONTS
  230214. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230215. if (atsFont == 0)
  230216. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230217. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230218. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230219. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230220. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230221. #else
  230222. #if SUPPORT_10_4_FONTS
  230223. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230224. {
  230225. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230226. if (atsFont == 0)
  230227. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230228. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230229. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230230. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230231. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230232. }
  230233. else
  230234. #endif
  230235. {
  230236. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  230237. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  230238. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230239. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  230240. }
  230241. #endif
  230242. #endif
  230243. }
  230244. ~MacTypeface()
  230245. {
  230246. #if ! JUCE_IOS
  230247. [nsFont release];
  230248. #endif
  230249. if (fontRef != 0)
  230250. CGFontRelease (fontRef);
  230251. }
  230252. float getAscent() const
  230253. {
  230254. return ascent;
  230255. }
  230256. float getDescent() const
  230257. {
  230258. return 1.0f - ascent;
  230259. }
  230260. float getStringWidth (const String& text)
  230261. {
  230262. if (fontRef == 0 || text.isEmpty())
  230263. return 0;
  230264. const int length = text.length();
  230265. HeapBlock <CGGlyph> glyphs;
  230266. createGlyphsForString (text, length, glyphs);
  230267. float x = 0;
  230268. #if SUPPORT_ONLY_10_4_FONTS
  230269. HeapBlock <NSSize> advances (length);
  230270. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230271. for (int i = 0; i < length; ++i)
  230272. x += advances[i].width;
  230273. #else
  230274. #if SUPPORT_10_4_FONTS
  230275. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230276. {
  230277. HeapBlock <NSSize> advances (length);
  230278. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230279. for (int i = 0; i < length; ++i)
  230280. x += advances[i].width;
  230281. }
  230282. else
  230283. #endif
  230284. {
  230285. HeapBlock <int> advances (length);
  230286. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230287. for (int i = 0; i < length; ++i)
  230288. x += advances[i];
  230289. }
  230290. #endif
  230291. return x * unitsToHeightScaleFactor;
  230292. }
  230293. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230294. {
  230295. xOffsets.add (0);
  230296. if (fontRef == 0 || text.isEmpty())
  230297. return;
  230298. const int length = text.length();
  230299. HeapBlock <CGGlyph> glyphs;
  230300. createGlyphsForString (text, length, glyphs);
  230301. #if SUPPORT_ONLY_10_4_FONTS
  230302. HeapBlock <NSSize> advances (length);
  230303. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230304. int x = 0;
  230305. for (int i = 0; i < length; ++i)
  230306. {
  230307. x += advances[i].width;
  230308. xOffsets.add (x * unitsToHeightScaleFactor);
  230309. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230310. }
  230311. #else
  230312. #if SUPPORT_10_4_FONTS
  230313. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230314. {
  230315. HeapBlock <NSSize> advances (length);
  230316. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230317. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230318. float x = 0;
  230319. for (int i = 0; i < length; ++i)
  230320. {
  230321. x += advances[i].width;
  230322. xOffsets.add (x * unitsToHeightScaleFactor);
  230323. resultGlyphs.add (nsGlyphs[i]);
  230324. }
  230325. }
  230326. else
  230327. #endif
  230328. {
  230329. HeapBlock <int> advances (length);
  230330. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230331. {
  230332. int x = 0;
  230333. for (int i = 0; i < length; ++i)
  230334. {
  230335. x += advances [i];
  230336. xOffsets.add (x * unitsToHeightScaleFactor);
  230337. resultGlyphs.add (glyphs[i]);
  230338. }
  230339. }
  230340. }
  230341. #endif
  230342. }
  230343. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230344. {
  230345. #if JUCE_IOS
  230346. return false;
  230347. #else
  230348. if (nsFont == 0)
  230349. return false;
  230350. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230351. jassert (path.isEmpty());
  230352. const ScopedAutoReleasePool pool;
  230353. NSBezierPath* bez = [NSBezierPath bezierPath];
  230354. [bez moveToPoint: NSMakePoint (0, 0)];
  230355. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230356. inFont: nsFont];
  230357. for (int i = 0; i < [bez elementCount]; ++i)
  230358. {
  230359. NSPoint p[3];
  230360. switch ([bez elementAtIndex: i associatedPoints: p])
  230361. {
  230362. case NSMoveToBezierPathElement:
  230363. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230364. break;
  230365. case NSLineToBezierPathElement:
  230366. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230367. break;
  230368. case NSCurveToBezierPathElement:
  230369. 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);
  230370. break;
  230371. case NSClosePathBezierPathElement:
  230372. path.closeSubPath();
  230373. break;
  230374. default:
  230375. jassertfalse;
  230376. break;
  230377. }
  230378. }
  230379. path.applyTransform (pathTransform);
  230380. return true;
  230381. #endif
  230382. }
  230383. juce_UseDebuggingNewOperator
  230384. CGFontRef fontRef;
  230385. float fontHeightToCGSizeFactor;
  230386. CGAffineTransform renderingTransform;
  230387. private:
  230388. float ascent, unitsToHeightScaleFactor;
  230389. #if JUCE_IOS
  230390. #else
  230391. NSFont* nsFont;
  230392. AffineTransform pathTransform;
  230393. #endif
  230394. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230395. {
  230396. #if SUPPORT_10_4_FONTS
  230397. #if ! SUPPORT_ONLY_10_4_FONTS
  230398. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230399. #endif
  230400. {
  230401. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230402. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230403. for (int i = 0; i < length; ++i)
  230404. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230405. return;
  230406. }
  230407. #endif
  230408. #if ! SUPPORT_ONLY_10_4_FONTS
  230409. if (charToGlyphMapper == 0)
  230410. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230411. glyphs.malloc (length);
  230412. for (int i = 0; i < length; ++i)
  230413. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230414. #endif
  230415. }
  230416. #if ! SUPPORT_ONLY_10_4_FONTS
  230417. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230418. class CharToGlyphMapper
  230419. {
  230420. public:
  230421. CharToGlyphMapper (CGFontRef fontRef)
  230422. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230423. idRangeOffset (0), glyphIndexes (0)
  230424. {
  230425. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230426. if (cmapTable != 0)
  230427. {
  230428. const int numSubtables = getValue16 (cmapTable, 2);
  230429. for (int i = 0; i < numSubtables; ++i)
  230430. {
  230431. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230432. {
  230433. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230434. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230435. {
  230436. const int length = getValue16 (cmapTable, offset + 2);
  230437. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230438. segCount = segCountX2 / 2;
  230439. const int endCodeOffset = offset + 14;
  230440. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230441. const int idDeltaOffset = startCodeOffset + segCountX2;
  230442. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230443. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230444. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230445. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230446. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230447. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230448. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230449. }
  230450. break;
  230451. }
  230452. }
  230453. CFRelease (cmapTable);
  230454. }
  230455. }
  230456. ~CharToGlyphMapper()
  230457. {
  230458. if (endCode != 0)
  230459. {
  230460. CFRelease (endCode);
  230461. CFRelease (startCode);
  230462. CFRelease (idDelta);
  230463. CFRelease (idRangeOffset);
  230464. CFRelease (glyphIndexes);
  230465. }
  230466. }
  230467. int getGlyphForCharacter (const juce_wchar c) const
  230468. {
  230469. for (int i = 0; i < segCount; ++i)
  230470. {
  230471. if (getValue16 (endCode, i * 2) >= c)
  230472. {
  230473. const int start = getValue16 (startCode, i * 2);
  230474. if (start > c)
  230475. break;
  230476. const int delta = getValue16 (idDelta, i * 2);
  230477. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230478. if (rangeOffset == 0)
  230479. return delta + c;
  230480. else
  230481. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230482. }
  230483. }
  230484. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230485. return jmax (-1, c - 29);
  230486. }
  230487. private:
  230488. int segCount;
  230489. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230490. static uint16 getValue16 (CFDataRef data, const int index)
  230491. {
  230492. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230493. }
  230494. static uint32 getValue32 (CFDataRef data, const int index)
  230495. {
  230496. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230497. }
  230498. };
  230499. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230500. #endif
  230501. MacTypeface (const MacTypeface&);
  230502. MacTypeface& operator= (const MacTypeface&);
  230503. };
  230504. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230505. {
  230506. return new MacTypeface (font);
  230507. }
  230508. const StringArray Font::findAllTypefaceNames()
  230509. {
  230510. StringArray names;
  230511. const ScopedAutoReleasePool pool;
  230512. #if JUCE_IOS
  230513. NSArray* fonts = [UIFont familyNames];
  230514. #else
  230515. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230516. #endif
  230517. for (unsigned int i = 0; i < [fonts count]; ++i)
  230518. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230519. names.sort (true);
  230520. return names;
  230521. }
  230522. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230523. {
  230524. #if JUCE_IOS
  230525. defaultSans = "Helvetica";
  230526. defaultSerif = "Times New Roman";
  230527. defaultFixed = "Courier New";
  230528. #else
  230529. defaultSans = "Lucida Grande";
  230530. defaultSerif = "Times New Roman";
  230531. defaultFixed = "Monaco";
  230532. #endif
  230533. }
  230534. #endif
  230535. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230536. // (must go before juce_mac_CoreGraphicsContext.mm)
  230537. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230538. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230539. // compiled on its own).
  230540. #if JUCE_INCLUDED_FILE
  230541. class CoreGraphicsImage : public Image::SharedImage
  230542. {
  230543. public:
  230544. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230545. : Image::SharedImage (format_, width_, height_)
  230546. {
  230547. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230548. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230549. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230550. imageData = imageDataAllocated;
  230551. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230552. : CGColorSpaceCreateDeviceRGB();
  230553. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230554. colourSpace, getCGImageFlags (format_));
  230555. CGColorSpaceRelease (colourSpace);
  230556. }
  230557. ~CoreGraphicsImage()
  230558. {
  230559. CGContextRelease (context);
  230560. }
  230561. Image::ImageType getType() const { return Image::NativeImage; }
  230562. LowLevelGraphicsContext* createLowLevelContext();
  230563. SharedImage* clone()
  230564. {
  230565. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230566. memcpy (im->imageData, imageData, lineStride * height);
  230567. return im;
  230568. }
  230569. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230570. {
  230571. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230572. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230573. {
  230574. return CGBitmapContextCreateImage (nativeImage->context);
  230575. }
  230576. else
  230577. {
  230578. const Image::BitmapData srcData (juceImage, false);
  230579. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230580. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230581. 8, srcData.pixelStride * 8, srcData.lineStride,
  230582. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230583. 0, true, kCGRenderingIntentDefault);
  230584. CGDataProviderRelease (provider);
  230585. return imageRef;
  230586. }
  230587. }
  230588. #if JUCE_MAC
  230589. static NSImage* createNSImage (const Image& image)
  230590. {
  230591. const ScopedAutoReleasePool pool;
  230592. NSImage* im = [[NSImage alloc] init];
  230593. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230594. [im lockFocus];
  230595. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230596. CGImageRef imageRef = createImage (image, false, colourSpace);
  230597. CGColorSpaceRelease (colourSpace);
  230598. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230599. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230600. CGImageRelease (imageRef);
  230601. [im unlockFocus];
  230602. return im;
  230603. }
  230604. #endif
  230605. CGContextRef context;
  230606. HeapBlock<uint8> imageDataAllocated;
  230607. private:
  230608. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230609. {
  230610. #if JUCE_BIG_ENDIAN
  230611. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230612. #else
  230613. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230614. #endif
  230615. }
  230616. };
  230617. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230618. {
  230619. #if USE_COREGRAPHICS_RENDERING
  230620. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230621. #else
  230622. return createSoftwareImage (format, width, height, clearImage);
  230623. #endif
  230624. }
  230625. class CoreGraphicsContext : public LowLevelGraphicsContext
  230626. {
  230627. public:
  230628. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230629. : context (context_),
  230630. flipHeight (flipHeight_),
  230631. state (new SavedState()),
  230632. numGradientLookupEntries (0),
  230633. lastClipRectIsValid (false)
  230634. {
  230635. CGContextRetain (context);
  230636. CGContextSaveGState(context);
  230637. CGContextSetShouldSmoothFonts (context, true);
  230638. CGContextSetShouldAntialias (context, true);
  230639. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230640. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230641. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230642. gradientCallbacks.version = 0;
  230643. gradientCallbacks.evaluate = gradientCallback;
  230644. gradientCallbacks.releaseInfo = 0;
  230645. setFont (Font());
  230646. }
  230647. ~CoreGraphicsContext()
  230648. {
  230649. CGContextRestoreGState (context);
  230650. CGContextRelease (context);
  230651. CGColorSpaceRelease (rgbColourSpace);
  230652. CGColorSpaceRelease (greyColourSpace);
  230653. }
  230654. bool isVectorDevice() const { return false; }
  230655. void setOrigin (int x, int y)
  230656. {
  230657. CGContextTranslateCTM (context, x, -y);
  230658. if (lastClipRectIsValid)
  230659. lastClipRect.translate (-x, -y);
  230660. }
  230661. bool clipToRectangle (const Rectangle<int>& r)
  230662. {
  230663. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230664. if (lastClipRectIsValid)
  230665. {
  230666. // This is actually incorrect, because the actual clip region may be complex, and
  230667. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230668. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230669. // when calculating the resultant clip bounds, and makes the same mistake!
  230670. lastClipRect = lastClipRect.getIntersection (r);
  230671. return ! lastClipRect.isEmpty();
  230672. }
  230673. return ! isClipEmpty();
  230674. }
  230675. bool clipToRectangleList (const RectangleList& clipRegion)
  230676. {
  230677. if (clipRegion.isEmpty())
  230678. {
  230679. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230680. lastClipRectIsValid = true;
  230681. lastClipRect = Rectangle<int>();
  230682. return false;
  230683. }
  230684. else
  230685. {
  230686. const int numRects = clipRegion.getNumRectangles();
  230687. HeapBlock <CGRect> rects (numRects);
  230688. for (int i = 0; i < numRects; ++i)
  230689. {
  230690. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230691. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230692. }
  230693. CGContextClipToRects (context, rects, numRects);
  230694. lastClipRectIsValid = false;
  230695. return ! isClipEmpty();
  230696. }
  230697. }
  230698. void excludeClipRectangle (const Rectangle<int>& r)
  230699. {
  230700. RectangleList remaining (getClipBounds());
  230701. remaining.subtract (r);
  230702. clipToRectangleList (remaining);
  230703. lastClipRectIsValid = false;
  230704. }
  230705. void clipToPath (const Path& path, const AffineTransform& transform)
  230706. {
  230707. createPath (path, transform);
  230708. CGContextClip (context);
  230709. lastClipRectIsValid = false;
  230710. }
  230711. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230712. {
  230713. if (! transform.isSingularity())
  230714. {
  230715. Image singleChannelImage (sourceImage);
  230716. if (sourceImage.getFormat() != Image::SingleChannel)
  230717. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230718. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230719. flip();
  230720. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230721. applyTransform (t);
  230722. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230723. CGContextClipToMask (context, r, image);
  230724. applyTransform (t.inverted());
  230725. flip();
  230726. CGImageRelease (image);
  230727. lastClipRectIsValid = false;
  230728. }
  230729. }
  230730. bool clipRegionIntersects (const Rectangle<int>& r)
  230731. {
  230732. return getClipBounds().intersects (r);
  230733. }
  230734. const Rectangle<int> getClipBounds() const
  230735. {
  230736. if (! lastClipRectIsValid)
  230737. {
  230738. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230739. lastClipRectIsValid = true;
  230740. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230741. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230742. roundToInt (bounds.size.width),
  230743. roundToInt (bounds.size.height));
  230744. }
  230745. return lastClipRect;
  230746. }
  230747. bool isClipEmpty() const
  230748. {
  230749. return getClipBounds().isEmpty();
  230750. }
  230751. void saveState()
  230752. {
  230753. CGContextSaveGState (context);
  230754. stateStack.add (new SavedState (*state));
  230755. }
  230756. void restoreState()
  230757. {
  230758. CGContextRestoreGState (context);
  230759. SavedState* const top = stateStack.getLast();
  230760. if (top != 0)
  230761. {
  230762. state = top;
  230763. stateStack.removeLast (1, false);
  230764. lastClipRectIsValid = false;
  230765. }
  230766. else
  230767. {
  230768. jassertfalse; // trying to pop with an empty stack!
  230769. }
  230770. }
  230771. void setFill (const FillType& fillType)
  230772. {
  230773. state->fillType = fillType;
  230774. if (fillType.isColour())
  230775. {
  230776. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230777. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230778. CGContextSetAlpha (context, 1.0f);
  230779. }
  230780. }
  230781. void setOpacity (float newOpacity)
  230782. {
  230783. state->fillType.setOpacity (newOpacity);
  230784. setFill (state->fillType);
  230785. }
  230786. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230787. {
  230788. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230789. ? kCGInterpolationLow
  230790. : kCGInterpolationHigh);
  230791. }
  230792. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230793. {
  230794. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230795. }
  230796. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230797. {
  230798. if (replaceExistingContents)
  230799. {
  230800. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230801. CGContextClearRect (context, cgRect);
  230802. #else
  230803. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230804. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230805. CGContextClearRect (context, cgRect);
  230806. else
  230807. #endif
  230808. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230809. #endif
  230810. fillCGRect (cgRect, false);
  230811. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230812. }
  230813. else
  230814. {
  230815. if (state->fillType.isColour())
  230816. {
  230817. CGContextFillRect (context, cgRect);
  230818. }
  230819. else if (state->fillType.isGradient())
  230820. {
  230821. CGContextSaveGState (context);
  230822. CGContextClipToRect (context, cgRect);
  230823. drawGradient();
  230824. CGContextRestoreGState (context);
  230825. }
  230826. else
  230827. {
  230828. CGContextSaveGState (context);
  230829. CGContextClipToRect (context, cgRect);
  230830. drawImage (state->fillType.image, state->fillType.transform, true);
  230831. CGContextRestoreGState (context);
  230832. }
  230833. }
  230834. }
  230835. void fillPath (const Path& path, const AffineTransform& transform)
  230836. {
  230837. CGContextSaveGState (context);
  230838. if (state->fillType.isColour())
  230839. {
  230840. flip();
  230841. applyTransform (transform);
  230842. createPath (path);
  230843. if (path.isUsingNonZeroWinding())
  230844. CGContextFillPath (context);
  230845. else
  230846. CGContextEOFillPath (context);
  230847. }
  230848. else
  230849. {
  230850. createPath (path, transform);
  230851. if (path.isUsingNonZeroWinding())
  230852. CGContextClip (context);
  230853. else
  230854. CGContextEOClip (context);
  230855. if (state->fillType.isGradient())
  230856. drawGradient();
  230857. else
  230858. drawImage (state->fillType.image, state->fillType.transform, true);
  230859. }
  230860. CGContextRestoreGState (context);
  230861. }
  230862. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230863. {
  230864. const int iw = sourceImage.getWidth();
  230865. const int ih = sourceImage.getHeight();
  230866. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230867. CGContextSaveGState (context);
  230868. CGContextSetAlpha (context, state->fillType.getOpacity());
  230869. flip();
  230870. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230871. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230872. if (fillEntireClipAsTiles)
  230873. {
  230874. #if JUCE_IOS
  230875. CGContextDrawTiledImage (context, imageRect, image);
  230876. #else
  230877. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230878. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230879. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230880. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230881. CGContextDrawTiledImage (context, imageRect, image);
  230882. else
  230883. #endif
  230884. {
  230885. // Fallback to manually doing a tiled fill on 10.4
  230886. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230887. int x = 0, y = 0;
  230888. while (x > clip.origin.x) x -= iw;
  230889. while (y > clip.origin.y) y -= ih;
  230890. const int right = (int) (clip.origin.x + clip.size.width);
  230891. const int bottom = (int) (clip.origin.y + clip.size.height);
  230892. while (y < bottom)
  230893. {
  230894. for (int x2 = x; x2 < right; x2 += iw)
  230895. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230896. y += ih;
  230897. }
  230898. }
  230899. #endif
  230900. }
  230901. else
  230902. {
  230903. CGContextDrawImage (context, imageRect, image);
  230904. }
  230905. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230906. CGContextRestoreGState (context);
  230907. }
  230908. void drawLine (const Line<float>& line)
  230909. {
  230910. if (state->fillType.isColour())
  230911. {
  230912. CGContextSetLineCap (context, kCGLineCapSquare);
  230913. CGContextSetLineWidth (context, 1.0f);
  230914. CGContextSetRGBStrokeColor (context,
  230915. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230916. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230917. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230918. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230919. CGContextStrokeLineSegments (context, cgLine, 1);
  230920. }
  230921. else
  230922. {
  230923. Path p;
  230924. p.addLineSegment (line, 1.0f);
  230925. fillPath (p, AffineTransform::identity);
  230926. }
  230927. }
  230928. void drawVerticalLine (const int x, float top, float bottom)
  230929. {
  230930. if (state->fillType.isColour())
  230931. {
  230932. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230933. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230934. #else
  230935. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230936. // the x co-ord slightly to trick it..
  230937. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230938. #endif
  230939. }
  230940. else
  230941. {
  230942. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230943. }
  230944. }
  230945. void drawHorizontalLine (const int y, float left, float right)
  230946. {
  230947. if (state->fillType.isColour())
  230948. {
  230949. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230950. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230951. #else
  230952. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230953. // the x co-ord slightly to trick it..
  230954. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230955. #endif
  230956. }
  230957. else
  230958. {
  230959. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230960. }
  230961. }
  230962. void setFont (const Font& newFont)
  230963. {
  230964. if (state->font != newFont)
  230965. {
  230966. state->fontRef = 0;
  230967. state->font = newFont;
  230968. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230969. if (mf != 0)
  230970. {
  230971. state->fontRef = mf->fontRef;
  230972. CGContextSetFont (context, state->fontRef);
  230973. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230974. state->fontTransform = mf->renderingTransform;
  230975. state->fontTransform.a *= state->font.getHorizontalScale();
  230976. CGContextSetTextMatrix (context, state->fontTransform);
  230977. }
  230978. }
  230979. }
  230980. const Font getFont()
  230981. {
  230982. return state->font;
  230983. }
  230984. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230985. {
  230986. if (state->fontRef != 0 && state->fillType.isColour())
  230987. {
  230988. if (transform.isOnlyTranslation())
  230989. {
  230990. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230991. CGGlyph g = glyphNumber;
  230992. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230993. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230994. }
  230995. else
  230996. {
  230997. CGContextSaveGState (context);
  230998. flip();
  230999. applyTransform (transform);
  231000. CGAffineTransform t = state->fontTransform;
  231001. t.d = -t.d;
  231002. CGContextSetTextMatrix (context, t);
  231003. CGGlyph g = glyphNumber;
  231004. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  231005. CGContextRestoreGState (context);
  231006. }
  231007. }
  231008. else
  231009. {
  231010. Path p;
  231011. Font& f = state->font;
  231012. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  231013. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  231014. .followedBy (transform));
  231015. }
  231016. }
  231017. private:
  231018. CGContextRef context;
  231019. const CGFloat flipHeight;
  231020. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  231021. CGFunctionCallbacks gradientCallbacks;
  231022. mutable Rectangle<int> lastClipRect;
  231023. mutable bool lastClipRectIsValid;
  231024. struct SavedState
  231025. {
  231026. SavedState()
  231027. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  231028. {
  231029. }
  231030. SavedState (const SavedState& other)
  231031. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  231032. fontTransform (other.fontTransform)
  231033. {
  231034. }
  231035. ~SavedState()
  231036. {
  231037. }
  231038. FillType fillType;
  231039. Font font;
  231040. CGFontRef fontRef;
  231041. CGAffineTransform fontTransform;
  231042. };
  231043. ScopedPointer <SavedState> state;
  231044. OwnedArray <SavedState> stateStack;
  231045. HeapBlock <PixelARGB> gradientLookupTable;
  231046. int numGradientLookupEntries;
  231047. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  231048. {
  231049. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  231050. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  231051. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  231052. colour.unpremultiply();
  231053. outData[0] = colour.getRed() / 255.0f;
  231054. outData[1] = colour.getGreen() / 255.0f;
  231055. outData[2] = colour.getBlue() / 255.0f;
  231056. outData[3] = colour.getAlpha() / 255.0f;
  231057. }
  231058. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  231059. {
  231060. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  231061. --numGradientLookupEntries;
  231062. CGShadingRef result = 0;
  231063. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  231064. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  231065. if (gradient.isRadial)
  231066. {
  231067. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  231068. p1, gradient.point1.getDistanceFrom (gradient.point2),
  231069. function, true, true);
  231070. }
  231071. else
  231072. {
  231073. result = CGShadingCreateAxial (rgbColourSpace, p1,
  231074. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  231075. function, true, true);
  231076. }
  231077. CGFunctionRelease (function);
  231078. return result;
  231079. }
  231080. void drawGradient()
  231081. {
  231082. flip();
  231083. applyTransform (state->fillType.transform);
  231084. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  231085. // you draw a gradient with high quality interp enabled).
  231086. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  231087. CGContextSetAlpha (context, state->fillType.getOpacity());
  231088. CGContextDrawShading (context, shading);
  231089. CGShadingRelease (shading);
  231090. }
  231091. void createPath (const Path& path) const
  231092. {
  231093. CGContextBeginPath (context);
  231094. Path::Iterator i (path);
  231095. while (i.next())
  231096. {
  231097. switch (i.elementType)
  231098. {
  231099. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  231100. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  231101. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  231102. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  231103. case Path::Iterator::closePath: CGContextClosePath (context); break;
  231104. default: jassertfalse; break;
  231105. }
  231106. }
  231107. }
  231108. void createPath (const Path& path, const AffineTransform& transform) const
  231109. {
  231110. CGContextBeginPath (context);
  231111. Path::Iterator i (path);
  231112. while (i.next())
  231113. {
  231114. switch (i.elementType)
  231115. {
  231116. case Path::Iterator::startNewSubPath:
  231117. transform.transformPoint (i.x1, i.y1);
  231118. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  231119. break;
  231120. case Path::Iterator::lineTo:
  231121. transform.transformPoint (i.x1, i.y1);
  231122. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  231123. break;
  231124. case Path::Iterator::quadraticTo:
  231125. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  231126. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  231127. break;
  231128. case Path::Iterator::cubicTo:
  231129. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  231130. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  231131. break;
  231132. case Path::Iterator::closePath:
  231133. CGContextClosePath (context); break;
  231134. default:
  231135. jassertfalse;
  231136. break;
  231137. }
  231138. }
  231139. }
  231140. void flip() const
  231141. {
  231142. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  231143. }
  231144. void applyTransform (const AffineTransform& transform) const
  231145. {
  231146. CGAffineTransform t;
  231147. t.a = transform.mat00;
  231148. t.b = transform.mat10;
  231149. t.c = transform.mat01;
  231150. t.d = transform.mat11;
  231151. t.tx = transform.mat02;
  231152. t.ty = transform.mat12;
  231153. CGContextConcatCTM (context, t);
  231154. }
  231155. CoreGraphicsContext (const CoreGraphicsContext&);
  231156. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  231157. };
  231158. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  231159. {
  231160. return new CoreGraphicsContext (context, height);
  231161. }
  231162. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  231163. const Image juce_loadWithCoreImage (InputStream& input)
  231164. {
  231165. MemoryBlock data;
  231166. input.readIntoMemoryBlock (data, -1);
  231167. #if JUCE_IOS
  231168. JUCE_AUTORELEASEPOOL
  231169. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData() length: data.getSize()]];
  231170. if (image != nil)
  231171. {
  231172. CGImageRef loadedImage = image.CGImage;
  231173. #else
  231174. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  231175. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  231176. CGDataProviderRelease (provider);
  231177. if (imageSource != 0)
  231178. {
  231179. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  231180. CFRelease (imageSource);
  231181. #endif
  231182. if (loadedImage != 0)
  231183. {
  231184. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  231185. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  231186. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  231187. hasAlphaChan, Image::NativeImage);
  231188. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  231189. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  231190. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  231191. CGContextFlush (cgImage->context);
  231192. #if ! JUCE_IOS
  231193. CFRelease (loadedImage);
  231194. #endif
  231195. return image;
  231196. }
  231197. }
  231198. return Image::null;
  231199. }
  231200. #endif
  231201. #endif
  231202. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  231203. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231204. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231205. // compiled on its own).
  231206. #if JUCE_INCLUDED_FILE
  231207. class NSViewComponentPeer;
  231208. END_JUCE_NAMESPACE
  231209. @interface NSEvent (JuceDeviceDelta)
  231210. - (float) deviceDeltaX;
  231211. - (float) deviceDeltaY;
  231212. @end
  231213. #define JuceNSView MakeObjCClassName(JuceNSView)
  231214. @interface JuceNSView : NSView<NSTextInput>
  231215. {
  231216. @public
  231217. NSViewComponentPeer* owner;
  231218. NSNotificationCenter* notificationCenter;
  231219. String* stringBeingComposed;
  231220. bool textWasInserted;
  231221. }
  231222. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  231223. - (void) dealloc;
  231224. - (BOOL) isOpaque;
  231225. - (void) drawRect: (NSRect) r;
  231226. - (void) mouseDown: (NSEvent*) ev;
  231227. - (void) asyncMouseDown: (NSEvent*) ev;
  231228. - (void) mouseUp: (NSEvent*) ev;
  231229. - (void) asyncMouseUp: (NSEvent*) ev;
  231230. - (void) mouseDragged: (NSEvent*) ev;
  231231. - (void) mouseMoved: (NSEvent*) ev;
  231232. - (void) mouseEntered: (NSEvent*) ev;
  231233. - (void) mouseExited: (NSEvent*) ev;
  231234. - (void) rightMouseDown: (NSEvent*) ev;
  231235. - (void) rightMouseDragged: (NSEvent*) ev;
  231236. - (void) rightMouseUp: (NSEvent*) ev;
  231237. - (void) otherMouseDown: (NSEvent*) ev;
  231238. - (void) otherMouseDragged: (NSEvent*) ev;
  231239. - (void) otherMouseUp: (NSEvent*) ev;
  231240. - (void) scrollWheel: (NSEvent*) ev;
  231241. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  231242. - (void) frameChanged: (NSNotification*) n;
  231243. - (void) viewDidMoveToWindow;
  231244. - (void) keyDown: (NSEvent*) ev;
  231245. - (void) keyUp: (NSEvent*) ev;
  231246. // NSTextInput Methods
  231247. - (void) insertText: (id) aString;
  231248. - (void) doCommandBySelector: (SEL) aSelector;
  231249. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  231250. - (void) unmarkText;
  231251. - (BOOL) hasMarkedText;
  231252. - (long) conversationIdentifier;
  231253. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231254. - (NSRange) markedRange;
  231255. - (NSRange) selectedRange;
  231256. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231257. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231258. - (NSArray*) validAttributesForMarkedText;
  231259. - (void) flagsChanged: (NSEvent*) ev;
  231260. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231261. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231262. #endif
  231263. - (BOOL) becomeFirstResponder;
  231264. - (BOOL) resignFirstResponder;
  231265. - (BOOL) acceptsFirstResponder;
  231266. - (void) asyncRepaint: (id) rect;
  231267. - (NSArray*) getSupportedDragTypes;
  231268. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231269. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231270. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231271. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231272. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231273. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231274. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231275. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231276. @end
  231277. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231278. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231279. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231280. #else
  231281. @interface JuceNSWindow : NSWindow
  231282. #endif
  231283. {
  231284. @private
  231285. NSViewComponentPeer* owner;
  231286. bool isZooming;
  231287. }
  231288. - (void) setOwner: (NSViewComponentPeer*) owner;
  231289. - (BOOL) canBecomeKeyWindow;
  231290. - (void) becomeKeyWindow;
  231291. - (BOOL) windowShouldClose: (id) window;
  231292. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231293. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231294. - (void) zoom: (id) sender;
  231295. @end
  231296. BEGIN_JUCE_NAMESPACE
  231297. class NSViewComponentPeer : public ComponentPeer
  231298. {
  231299. public:
  231300. NSViewComponentPeer (Component* const component,
  231301. const int windowStyleFlags,
  231302. NSView* viewToAttachTo);
  231303. ~NSViewComponentPeer();
  231304. void* getNativeHandle() const;
  231305. void setVisible (bool shouldBeVisible);
  231306. void setTitle (const String& title);
  231307. void setPosition (int x, int y);
  231308. void setSize (int w, int h);
  231309. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231310. const Rectangle<int> getBounds (const bool global) const;
  231311. const Rectangle<int> getBounds() const;
  231312. const Point<int> getScreenPosition() const;
  231313. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  231314. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  231315. void setMinimised (bool shouldBeMinimised);
  231316. bool isMinimised() const;
  231317. void setFullScreen (bool shouldBeFullScreen);
  231318. bool isFullScreen() const;
  231319. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231320. const BorderSize getFrameSize() const;
  231321. bool setAlwaysOnTop (bool alwaysOnTop);
  231322. void toFront (bool makeActiveWindow);
  231323. void toBehind (ComponentPeer* other);
  231324. void setIcon (const Image& newIcon);
  231325. const StringArray getAvailableRenderingEngines();
  231326. int getCurrentRenderingEngine() throw();
  231327. void setCurrentRenderingEngine (int index);
  231328. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231329. for example having more than one juce plugin loaded into a host, then when a
  231330. method is called, the actual code that runs might actually be in a different module
  231331. than the one you expect... So any calls to library functions or statics that are
  231332. made inside obj-c methods will probably end up getting executed in a different DLL's
  231333. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231334. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231335. virtual methods of an object that's known to live inside the right module's space.
  231336. */
  231337. virtual void redirectMouseDown (NSEvent* ev);
  231338. virtual void redirectMouseUp (NSEvent* ev);
  231339. virtual void redirectMouseDrag (NSEvent* ev);
  231340. virtual void redirectMouseMove (NSEvent* ev);
  231341. virtual void redirectMouseEnter (NSEvent* ev);
  231342. virtual void redirectMouseExit (NSEvent* ev);
  231343. virtual void redirectMouseWheel (NSEvent* ev);
  231344. void sendMouseEvent (NSEvent* ev);
  231345. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231346. virtual bool redirectKeyDown (NSEvent* ev);
  231347. virtual bool redirectKeyUp (NSEvent* ev);
  231348. virtual void redirectModKeyChange (NSEvent* ev);
  231349. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231350. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231351. #endif
  231352. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231353. virtual bool isOpaque();
  231354. virtual void drawRect (NSRect r);
  231355. virtual bool canBecomeKeyWindow();
  231356. virtual bool windowShouldClose();
  231357. virtual void redirectMovedOrResized();
  231358. virtual void viewMovedToWindow();
  231359. virtual NSRect constrainRect (NSRect r);
  231360. static void showArrowCursorIfNeeded();
  231361. static void updateModifiers (NSEvent* e);
  231362. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231363. static int getKeyCodeFromEvent (NSEvent* ev)
  231364. {
  231365. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231366. int keyCode = unmodified[0];
  231367. if (keyCode == 0x19) // (backwards-tab)
  231368. keyCode = '\t';
  231369. else if (keyCode == 0x03) // (enter)
  231370. keyCode = '\r';
  231371. else
  231372. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231373. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231374. {
  231375. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231376. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231377. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231378. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231379. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231380. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231381. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231382. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231383. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231384. if (keyCode == numPadConversions [i])
  231385. keyCode = numPadConversions [i + 1];
  231386. }
  231387. return keyCode;
  231388. }
  231389. static int64 getMouseTime (NSEvent* e)
  231390. {
  231391. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231392. + (int64) ([e timestamp] * 1000.0);
  231393. }
  231394. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231395. {
  231396. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231397. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231398. }
  231399. static int getModifierForButtonNumber (const NSInteger num)
  231400. {
  231401. return num == 0 ? ModifierKeys::leftButtonModifier
  231402. : (num == 1 ? ModifierKeys::rightButtonModifier
  231403. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231404. }
  231405. virtual void viewFocusGain();
  231406. virtual void viewFocusLoss();
  231407. bool isFocused() const;
  231408. void grabFocus();
  231409. void textInputRequired (const Point<int>& position);
  231410. void repaint (const Rectangle<int>& area);
  231411. void performAnyPendingRepaintsNow();
  231412. juce_UseDebuggingNewOperator
  231413. NSWindow* window;
  231414. JuceNSView* view;
  231415. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231416. static ModifierKeys currentModifiers;
  231417. static ComponentPeer* currentlyFocusedPeer;
  231418. static Array<int> keysCurrentlyDown;
  231419. };
  231420. END_JUCE_NAMESPACE
  231421. @implementation JuceNSView
  231422. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231423. withFrame: (NSRect) frame
  231424. {
  231425. [super initWithFrame: frame];
  231426. owner = owner_;
  231427. stringBeingComposed = 0;
  231428. textWasInserted = false;
  231429. notificationCenter = [NSNotificationCenter defaultCenter];
  231430. [notificationCenter addObserver: self
  231431. selector: @selector (frameChanged:)
  231432. name: NSViewFrameDidChangeNotification
  231433. object: self];
  231434. if (! owner_->isSharedWindow)
  231435. {
  231436. [notificationCenter addObserver: self
  231437. selector: @selector (frameChanged:)
  231438. name: NSWindowDidMoveNotification
  231439. object: owner_->window];
  231440. }
  231441. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231442. return self;
  231443. }
  231444. - (void) dealloc
  231445. {
  231446. [notificationCenter removeObserver: self];
  231447. delete stringBeingComposed;
  231448. [super dealloc];
  231449. }
  231450. - (void) drawRect: (NSRect) r
  231451. {
  231452. if (owner != 0)
  231453. owner->drawRect (r);
  231454. }
  231455. - (BOOL) isOpaque
  231456. {
  231457. return owner == 0 || owner->isOpaque();
  231458. }
  231459. - (void) mouseDown: (NSEvent*) ev
  231460. {
  231461. if (JUCEApplication::isStandaloneApp())
  231462. [self asyncMouseDown: ev];
  231463. else
  231464. // In some host situations, the host will stop modal loops from working
  231465. // correctly if they're called from a mouse event, so we'll trigger
  231466. // the event asynchronously..
  231467. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231468. withObject: ev
  231469. waitUntilDone: NO];
  231470. }
  231471. - (void) asyncMouseDown: (NSEvent*) ev
  231472. {
  231473. if (owner != 0)
  231474. owner->redirectMouseDown (ev);
  231475. }
  231476. - (void) mouseUp: (NSEvent*) ev
  231477. {
  231478. if (! JUCEApplication::isStandaloneApp())
  231479. [self asyncMouseUp: ev];
  231480. else
  231481. // In some host situations, the host will stop modal loops from working
  231482. // correctly if they're called from a mouse event, so we'll trigger
  231483. // the event asynchronously..
  231484. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231485. withObject: ev
  231486. waitUntilDone: NO];
  231487. }
  231488. - (void) asyncMouseUp: (NSEvent*) ev
  231489. {
  231490. if (owner != 0)
  231491. owner->redirectMouseUp (ev);
  231492. }
  231493. - (void) mouseDragged: (NSEvent*) ev
  231494. {
  231495. if (owner != 0)
  231496. owner->redirectMouseDrag (ev);
  231497. }
  231498. - (void) mouseMoved: (NSEvent*) ev
  231499. {
  231500. if (owner != 0)
  231501. owner->redirectMouseMove (ev);
  231502. }
  231503. - (void) mouseEntered: (NSEvent*) ev
  231504. {
  231505. if (owner != 0)
  231506. owner->redirectMouseEnter (ev);
  231507. }
  231508. - (void) mouseExited: (NSEvent*) ev
  231509. {
  231510. if (owner != 0)
  231511. owner->redirectMouseExit (ev);
  231512. }
  231513. - (void) rightMouseDown: (NSEvent*) ev
  231514. {
  231515. [self mouseDown: ev];
  231516. }
  231517. - (void) rightMouseDragged: (NSEvent*) ev
  231518. {
  231519. [self mouseDragged: ev];
  231520. }
  231521. - (void) rightMouseUp: (NSEvent*) ev
  231522. {
  231523. [self mouseUp: ev];
  231524. }
  231525. - (void) otherMouseDown: (NSEvent*) ev
  231526. {
  231527. [self mouseDown: ev];
  231528. }
  231529. - (void) otherMouseDragged: (NSEvent*) ev
  231530. {
  231531. [self mouseDragged: ev];
  231532. }
  231533. - (void) otherMouseUp: (NSEvent*) ev
  231534. {
  231535. [self mouseUp: ev];
  231536. }
  231537. - (void) scrollWheel: (NSEvent*) ev
  231538. {
  231539. if (owner != 0)
  231540. owner->redirectMouseWheel (ev);
  231541. }
  231542. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231543. {
  231544. (void) ev;
  231545. return YES;
  231546. }
  231547. - (void) frameChanged: (NSNotification*) n
  231548. {
  231549. (void) n;
  231550. if (owner != 0)
  231551. owner->redirectMovedOrResized();
  231552. }
  231553. - (void) viewDidMoveToWindow
  231554. {
  231555. if (owner != 0)
  231556. owner->viewMovedToWindow();
  231557. }
  231558. - (void) asyncRepaint: (id) rect
  231559. {
  231560. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231561. [self setNeedsDisplayInRect: *r];
  231562. }
  231563. - (void) keyDown: (NSEvent*) ev
  231564. {
  231565. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231566. textWasInserted = false;
  231567. if (target != 0)
  231568. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231569. else
  231570. deleteAndZero (stringBeingComposed);
  231571. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231572. [super keyDown: ev];
  231573. }
  231574. - (void) keyUp: (NSEvent*) ev
  231575. {
  231576. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231577. [super keyUp: ev];
  231578. }
  231579. - (void) insertText: (id) aString
  231580. {
  231581. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231582. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231583. if ([newText length] > 0)
  231584. {
  231585. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231586. if (target != 0)
  231587. {
  231588. target->insertTextAtCaret (nsStringToJuce (newText));
  231589. textWasInserted = true;
  231590. }
  231591. }
  231592. deleteAndZero (stringBeingComposed);
  231593. }
  231594. - (void) doCommandBySelector: (SEL) aSelector
  231595. {
  231596. (void) aSelector;
  231597. }
  231598. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231599. {
  231600. (void) selectionRange;
  231601. if (stringBeingComposed == 0)
  231602. stringBeingComposed = new String();
  231603. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231604. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231605. if (target != 0)
  231606. {
  231607. const Range<int> currentHighlight (target->getHighlightedRegion());
  231608. target->insertTextAtCaret (*stringBeingComposed);
  231609. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231610. textWasInserted = true;
  231611. }
  231612. }
  231613. - (void) unmarkText
  231614. {
  231615. if (stringBeingComposed != 0)
  231616. {
  231617. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231618. if (target != 0)
  231619. {
  231620. target->insertTextAtCaret (*stringBeingComposed);
  231621. textWasInserted = true;
  231622. }
  231623. }
  231624. deleteAndZero (stringBeingComposed);
  231625. }
  231626. - (BOOL) hasMarkedText
  231627. {
  231628. return stringBeingComposed != 0;
  231629. }
  231630. - (long) conversationIdentifier
  231631. {
  231632. return (long) (pointer_sized_int) self;
  231633. }
  231634. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231635. {
  231636. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231637. if (target != 0)
  231638. {
  231639. const Range<int> r ((int) theRange.location,
  231640. (int) (theRange.location + theRange.length));
  231641. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231642. }
  231643. return nil;
  231644. }
  231645. - (NSRange) markedRange
  231646. {
  231647. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231648. : NSMakeRange (NSNotFound, 0);
  231649. }
  231650. - (NSRange) selectedRange
  231651. {
  231652. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231653. if (target != 0)
  231654. {
  231655. const Range<int> highlight (target->getHighlightedRegion());
  231656. if (! highlight.isEmpty())
  231657. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231658. }
  231659. return NSMakeRange (NSNotFound, 0);
  231660. }
  231661. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231662. {
  231663. (void) theRange;
  231664. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231665. if (comp == 0)
  231666. return NSMakeRect (0, 0, 0, 0);
  231667. const Rectangle<int> bounds (comp->getScreenBounds());
  231668. return NSMakeRect (bounds.getX(),
  231669. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231670. bounds.getWidth(),
  231671. bounds.getHeight());
  231672. }
  231673. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231674. {
  231675. (void) thePoint;
  231676. return NSNotFound;
  231677. }
  231678. - (NSArray*) validAttributesForMarkedText
  231679. {
  231680. return [NSArray array];
  231681. }
  231682. - (void) flagsChanged: (NSEvent*) ev
  231683. {
  231684. if (owner != 0)
  231685. owner->redirectModKeyChange (ev);
  231686. }
  231687. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231688. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231689. {
  231690. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231691. return true;
  231692. return [super performKeyEquivalent: ev];
  231693. }
  231694. #endif
  231695. - (BOOL) becomeFirstResponder
  231696. {
  231697. if (owner != 0)
  231698. owner->viewFocusGain();
  231699. return true;
  231700. }
  231701. - (BOOL) resignFirstResponder
  231702. {
  231703. if (owner != 0)
  231704. owner->viewFocusLoss();
  231705. return true;
  231706. }
  231707. - (BOOL) acceptsFirstResponder
  231708. {
  231709. return owner != 0 && owner->canBecomeKeyWindow();
  231710. }
  231711. - (NSArray*) getSupportedDragTypes
  231712. {
  231713. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231714. }
  231715. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231716. {
  231717. return owner != 0 && owner->sendDragCallback (type, sender);
  231718. }
  231719. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231720. {
  231721. if ([self sendDragCallback: 0 sender: sender])
  231722. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231723. else
  231724. return NSDragOperationNone;
  231725. }
  231726. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231727. {
  231728. if ([self sendDragCallback: 0 sender: sender])
  231729. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231730. else
  231731. return NSDragOperationNone;
  231732. }
  231733. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231734. {
  231735. [self sendDragCallback: 1 sender: sender];
  231736. }
  231737. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231738. {
  231739. [self sendDragCallback: 1 sender: sender];
  231740. }
  231741. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231742. {
  231743. (void) sender;
  231744. return YES;
  231745. }
  231746. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231747. {
  231748. return [self sendDragCallback: 2 sender: sender];
  231749. }
  231750. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231751. {
  231752. (void) sender;
  231753. }
  231754. @end
  231755. @implementation JuceNSWindow
  231756. - (void) setOwner: (NSViewComponentPeer*) owner_
  231757. {
  231758. owner = owner_;
  231759. isZooming = false;
  231760. }
  231761. - (BOOL) canBecomeKeyWindow
  231762. {
  231763. return owner != 0 && owner->canBecomeKeyWindow();
  231764. }
  231765. - (void) becomeKeyWindow
  231766. {
  231767. [super becomeKeyWindow];
  231768. if (owner != 0)
  231769. owner->grabFocus();
  231770. }
  231771. - (BOOL) windowShouldClose: (id) window
  231772. {
  231773. (void) window;
  231774. return owner == 0 || owner->windowShouldClose();
  231775. }
  231776. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231777. {
  231778. (void) screen;
  231779. if (owner != 0)
  231780. frameRect = owner->constrainRect (frameRect);
  231781. return frameRect;
  231782. }
  231783. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231784. {
  231785. (void) window;
  231786. if (isZooming)
  231787. return proposedFrameSize;
  231788. NSRect frameRect = [self frame];
  231789. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231790. frameRect.size = proposedFrameSize;
  231791. if (owner != 0)
  231792. frameRect = owner->constrainRect (frameRect);
  231793. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231794. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231795. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231796. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231797. return frameRect.size;
  231798. }
  231799. - (void) zoom: (id) sender
  231800. {
  231801. isZooming = true;
  231802. [super zoom: sender];
  231803. isZooming = false;
  231804. }
  231805. - (void) windowWillMove: (NSNotification*) notification
  231806. {
  231807. (void) notification;
  231808. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231809. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231810. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231811. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231812. }
  231813. @end
  231814. BEGIN_JUCE_NAMESPACE
  231815. ModifierKeys NSViewComponentPeer::currentModifiers;
  231816. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231817. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231818. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231819. {
  231820. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231821. return true;
  231822. if (keyCode >= 'A' && keyCode <= 'Z'
  231823. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231824. return true;
  231825. if (keyCode >= 'a' && keyCode <= 'z'
  231826. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231827. return true;
  231828. return false;
  231829. }
  231830. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231831. {
  231832. int m = 0;
  231833. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231834. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231835. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231836. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231837. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231838. }
  231839. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231840. {
  231841. updateModifiers (ev);
  231842. int keyCode = getKeyCodeFromEvent (ev);
  231843. if (keyCode != 0)
  231844. {
  231845. if (isKeyDown)
  231846. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231847. else
  231848. keysCurrentlyDown.removeValue (keyCode);
  231849. }
  231850. }
  231851. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231852. {
  231853. return NSViewComponentPeer::currentModifiers;
  231854. }
  231855. void ModifierKeys::updateCurrentModifiers() throw()
  231856. {
  231857. currentModifiers = NSViewComponentPeer::currentModifiers;
  231858. }
  231859. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231860. const int windowStyleFlags,
  231861. NSView* viewToAttachTo)
  231862. : ComponentPeer (component_, windowStyleFlags),
  231863. window (0),
  231864. view (0),
  231865. isSharedWindow (viewToAttachTo != 0),
  231866. fullScreen (false),
  231867. insideDrawRect (false),
  231868. #if USE_COREGRAPHICS_RENDERING
  231869. usingCoreGraphics (true),
  231870. #else
  231871. usingCoreGraphics (false),
  231872. #endif
  231873. recursiveToFrontCall (false)
  231874. {
  231875. NSRect r;
  231876. r.origin.x = 0;
  231877. r.origin.y = 0;
  231878. r.size.width = (float) component->getWidth();
  231879. r.size.height = (float) component->getHeight();
  231880. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231881. [view setPostsFrameChangedNotifications: YES];
  231882. if (isSharedWindow)
  231883. {
  231884. window = [viewToAttachTo window];
  231885. [viewToAttachTo addSubview: view];
  231886. setVisible (component->isVisible());
  231887. }
  231888. else
  231889. {
  231890. r.origin.x = (float) component->getX();
  231891. r.origin.y = (float) component->getY();
  231892. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231893. unsigned int style = 0;
  231894. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231895. style = NSBorderlessWindowMask;
  231896. else
  231897. style = NSTitledWindowMask;
  231898. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231899. style |= NSMiniaturizableWindowMask;
  231900. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231901. style |= NSClosableWindowMask;
  231902. if ((windowStyleFlags & windowIsResizable) != 0)
  231903. style |= NSResizableWindowMask;
  231904. window = [[JuceNSWindow alloc] initWithContentRect: r
  231905. styleMask: style
  231906. backing: NSBackingStoreBuffered
  231907. defer: YES];
  231908. [((JuceNSWindow*) window) setOwner: this];
  231909. [window orderOut: nil];
  231910. [window setDelegate: (JuceNSWindow*) window];
  231911. [window setOpaque: component->isOpaque()];
  231912. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231913. if (component->isAlwaysOnTop())
  231914. [window setLevel: NSFloatingWindowLevel];
  231915. [window setContentView: view];
  231916. [window setAutodisplay: YES];
  231917. [window setAcceptsMouseMovedEvents: YES];
  231918. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231919. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231920. [window setReleasedWhenClosed: YES];
  231921. [window retain];
  231922. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231923. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231924. }
  231925. setTitle (component->getName());
  231926. }
  231927. NSViewComponentPeer::~NSViewComponentPeer()
  231928. {
  231929. view->owner = 0;
  231930. [view removeFromSuperview];
  231931. [view release];
  231932. if (! isSharedWindow)
  231933. {
  231934. [((JuceNSWindow*) window) setOwner: 0];
  231935. [window close];
  231936. [window release];
  231937. }
  231938. }
  231939. void* NSViewComponentPeer::getNativeHandle() const
  231940. {
  231941. return view;
  231942. }
  231943. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231944. {
  231945. if (isSharedWindow)
  231946. {
  231947. [view setHidden: ! shouldBeVisible];
  231948. }
  231949. else
  231950. {
  231951. if (shouldBeVisible)
  231952. {
  231953. [window orderFront: nil];
  231954. handleBroughtToFront();
  231955. }
  231956. else
  231957. {
  231958. [window orderOut: nil];
  231959. }
  231960. }
  231961. }
  231962. void NSViewComponentPeer::setTitle (const String& title)
  231963. {
  231964. const ScopedAutoReleasePool pool;
  231965. if (! isSharedWindow)
  231966. [window setTitle: juceStringToNS (title)];
  231967. }
  231968. void NSViewComponentPeer::setPosition (int x, int y)
  231969. {
  231970. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231971. }
  231972. void NSViewComponentPeer::setSize (int w, int h)
  231973. {
  231974. setBounds (component->getX(), component->getY(), w, h, false);
  231975. }
  231976. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231977. {
  231978. fullScreen = isNowFullScreen;
  231979. w = jmax (0, w);
  231980. h = jmax (0, h);
  231981. NSRect r;
  231982. r.origin.x = (float) x;
  231983. r.origin.y = (float) y;
  231984. r.size.width = (float) w;
  231985. r.size.height = (float) h;
  231986. if (isSharedWindow)
  231987. {
  231988. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231989. if ([view frame].size.width != r.size.width
  231990. || [view frame].size.height != r.size.height)
  231991. [view setNeedsDisplay: true];
  231992. [view setFrame: r];
  231993. }
  231994. else
  231995. {
  231996. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231997. [window setFrame: [window frameRectForContentRect: r]
  231998. display: true];
  231999. }
  232000. }
  232001. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  232002. {
  232003. NSRect r = [view frame];
  232004. if (global && [view window] != 0)
  232005. {
  232006. r = [view convertRect: r toView: nil];
  232007. NSRect wr = [[view window] frame];
  232008. r.origin.x += wr.origin.x;
  232009. r.origin.y += wr.origin.y;
  232010. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232011. }
  232012. else
  232013. {
  232014. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  232015. }
  232016. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  232017. }
  232018. const Rectangle<int> NSViewComponentPeer::getBounds() const
  232019. {
  232020. return getBounds (! isSharedWindow);
  232021. }
  232022. const Point<int> NSViewComponentPeer::getScreenPosition() const
  232023. {
  232024. return getBounds (true).getPosition();
  232025. }
  232026. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  232027. {
  232028. return relativePosition + getScreenPosition();
  232029. }
  232030. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  232031. {
  232032. return screenPosition - getScreenPosition();
  232033. }
  232034. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  232035. {
  232036. if (constrainer != 0)
  232037. {
  232038. NSRect current = [window frame];
  232039. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  232040. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232041. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  232042. (int) r.size.width, (int) r.size.height);
  232043. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  232044. (int) current.size.width, (int) current.size.height);
  232045. constrainer->checkBounds (pos, original,
  232046. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232047. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  232048. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  232049. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  232050. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  232051. r.origin.x = pos.getX();
  232052. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  232053. r.size.width = pos.getWidth();
  232054. r.size.height = pos.getHeight();
  232055. }
  232056. return r;
  232057. }
  232058. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  232059. {
  232060. if (! isSharedWindow)
  232061. {
  232062. if (shouldBeMinimised)
  232063. [window miniaturize: nil];
  232064. else
  232065. [window deminiaturize: nil];
  232066. }
  232067. }
  232068. bool NSViewComponentPeer::isMinimised() const
  232069. {
  232070. return window != 0 && [window isMiniaturized];
  232071. }
  232072. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  232073. {
  232074. if (! isSharedWindow)
  232075. {
  232076. Rectangle<int> r (lastNonFullscreenBounds);
  232077. setMinimised (false);
  232078. if (fullScreen != shouldBeFullScreen)
  232079. {
  232080. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  232081. {
  232082. fullScreen = true;
  232083. [window performZoom: nil];
  232084. }
  232085. else
  232086. {
  232087. if (shouldBeFullScreen)
  232088. r = Desktop::getInstance().getMainMonitorArea();
  232089. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  232090. if (r != getComponent()->getBounds() && ! r.isEmpty())
  232091. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  232092. }
  232093. }
  232094. }
  232095. }
  232096. bool NSViewComponentPeer::isFullScreen() const
  232097. {
  232098. return fullScreen;
  232099. }
  232100. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  232101. {
  232102. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  232103. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  232104. return false;
  232105. NSPoint p;
  232106. p.x = (float) position.getX();
  232107. p.y = (float) position.getY();
  232108. NSView* v = [view hitTest: p];
  232109. if (trueIfInAChildWindow)
  232110. return v != nil;
  232111. return v == view;
  232112. }
  232113. const BorderSize NSViewComponentPeer::getFrameSize() const
  232114. {
  232115. BorderSize b;
  232116. if (! isSharedWindow)
  232117. {
  232118. NSRect v = [view convertRect: [view frame] toView: nil];
  232119. NSRect w = [window frame];
  232120. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  232121. b.setBottom ((int) v.origin.y);
  232122. b.setLeft ((int) v.origin.x);
  232123. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  232124. }
  232125. return b;
  232126. }
  232127. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  232128. {
  232129. if (! isSharedWindow)
  232130. {
  232131. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  232132. : NSNormalWindowLevel];
  232133. }
  232134. return true;
  232135. }
  232136. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  232137. {
  232138. if (isSharedWindow)
  232139. {
  232140. [[view superview] addSubview: view
  232141. positioned: NSWindowAbove
  232142. relativeTo: nil];
  232143. }
  232144. if (window != 0 && component->isVisible())
  232145. {
  232146. if (makeActiveWindow)
  232147. [window makeKeyAndOrderFront: nil];
  232148. else
  232149. [window orderFront: nil];
  232150. if (! recursiveToFrontCall)
  232151. {
  232152. recursiveToFrontCall = true;
  232153. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232154. handleBroughtToFront();
  232155. recursiveToFrontCall = false;
  232156. }
  232157. }
  232158. }
  232159. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  232160. {
  232161. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  232162. jassert (otherPeer != 0); // wrong type of window?
  232163. if (otherPeer != 0)
  232164. {
  232165. if (isSharedWindow)
  232166. {
  232167. [[view superview] addSubview: view
  232168. positioned: NSWindowBelow
  232169. relativeTo: otherPeer->view];
  232170. }
  232171. else
  232172. {
  232173. [window orderWindow: NSWindowBelow
  232174. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  232175. : nil ];
  232176. }
  232177. }
  232178. }
  232179. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  232180. {
  232181. // to do..
  232182. }
  232183. void NSViewComponentPeer::viewFocusGain()
  232184. {
  232185. if (currentlyFocusedPeer != this)
  232186. {
  232187. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  232188. currentlyFocusedPeer->handleFocusLoss();
  232189. currentlyFocusedPeer = this;
  232190. handleFocusGain();
  232191. }
  232192. }
  232193. void NSViewComponentPeer::viewFocusLoss()
  232194. {
  232195. if (currentlyFocusedPeer == this)
  232196. {
  232197. currentlyFocusedPeer = 0;
  232198. handleFocusLoss();
  232199. }
  232200. }
  232201. void juce_HandleProcessFocusChange()
  232202. {
  232203. NSViewComponentPeer::keysCurrentlyDown.clear();
  232204. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  232205. {
  232206. if (Process::isForegroundProcess())
  232207. {
  232208. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  232209. ComponentPeer::bringModalComponentToFront();
  232210. }
  232211. else
  232212. {
  232213. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  232214. // turn kiosk mode off if we lose focus..
  232215. Desktop::getInstance().setKioskModeComponent (0);
  232216. }
  232217. }
  232218. }
  232219. bool NSViewComponentPeer::isFocused() const
  232220. {
  232221. return isSharedWindow ? this == currentlyFocusedPeer
  232222. : (window != 0 && [window isKeyWindow]);
  232223. }
  232224. void NSViewComponentPeer::grabFocus()
  232225. {
  232226. if (window != 0)
  232227. {
  232228. [window makeKeyWindow];
  232229. [window makeFirstResponder: view];
  232230. viewFocusGain();
  232231. }
  232232. }
  232233. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  232234. {
  232235. }
  232236. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  232237. {
  232238. String unicode (nsStringToJuce ([ev characters]));
  232239. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  232240. int keyCode = getKeyCodeFromEvent (ev);
  232241. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  232242. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  232243. if (unicode.isNotEmpty() || keyCode != 0)
  232244. {
  232245. if (isKeyDown)
  232246. {
  232247. bool used = false;
  232248. while (unicode.length() > 0)
  232249. {
  232250. juce_wchar textCharacter = unicode[0];
  232251. unicode = unicode.substring (1);
  232252. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232253. textCharacter = 0;
  232254. used = handleKeyUpOrDown (true) || used;
  232255. used = handleKeyPress (keyCode, textCharacter) || used;
  232256. }
  232257. return used;
  232258. }
  232259. else
  232260. {
  232261. if (handleKeyUpOrDown (false))
  232262. return true;
  232263. }
  232264. }
  232265. return false;
  232266. }
  232267. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232268. {
  232269. updateKeysDown (ev, true);
  232270. bool used = handleKeyEvent (ev, true);
  232271. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232272. {
  232273. // for command keys, the key-up event is thrown away, so simulate one..
  232274. updateKeysDown (ev, false);
  232275. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232276. }
  232277. // (If we're running modally, don't allow unused keystrokes to be passed
  232278. // along to other blocked views..)
  232279. if (Component::getCurrentlyModalComponent() != 0)
  232280. used = true;
  232281. return used;
  232282. }
  232283. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232284. {
  232285. updateKeysDown (ev, false);
  232286. return handleKeyEvent (ev, false)
  232287. || Component::getCurrentlyModalComponent() != 0;
  232288. }
  232289. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232290. {
  232291. keysCurrentlyDown.clear();
  232292. handleKeyUpOrDown (true);
  232293. updateModifiers (ev);
  232294. handleModifierKeysChange();
  232295. }
  232296. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232297. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232298. {
  232299. if ([ev type] == NSKeyDown)
  232300. return redirectKeyDown (ev);
  232301. else if ([ev type] == NSKeyUp)
  232302. return redirectKeyUp (ev);
  232303. return false;
  232304. }
  232305. #endif
  232306. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232307. {
  232308. updateModifiers (ev);
  232309. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232310. }
  232311. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232312. {
  232313. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232314. sendMouseEvent (ev);
  232315. }
  232316. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232317. {
  232318. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232319. sendMouseEvent (ev);
  232320. showArrowCursorIfNeeded();
  232321. }
  232322. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232323. {
  232324. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232325. sendMouseEvent (ev);
  232326. }
  232327. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232328. {
  232329. currentModifiers = currentModifiers.withoutMouseButtons();
  232330. sendMouseEvent (ev);
  232331. showArrowCursorIfNeeded();
  232332. }
  232333. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232334. {
  232335. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232336. currentModifiers = currentModifiers.withoutMouseButtons();
  232337. sendMouseEvent (ev);
  232338. }
  232339. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232340. {
  232341. currentModifiers = currentModifiers.withoutMouseButtons();
  232342. sendMouseEvent (ev);
  232343. }
  232344. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232345. {
  232346. updateModifiers (ev);
  232347. float x = 0, y = 0;
  232348. @try
  232349. {
  232350. x = [ev deviceDeltaX] * 0.5f;
  232351. y = [ev deviceDeltaY] * 0.5f;
  232352. }
  232353. @catch (...)
  232354. {}
  232355. if (x == 0 && y == 0)
  232356. {
  232357. x = [ev deltaX] * 10.0f;
  232358. y = [ev deltaY] * 10.0f;
  232359. }
  232360. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232361. }
  232362. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232363. {
  232364. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232365. if (mouse.getComponentUnderMouse() == 0
  232366. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232367. {
  232368. [[NSCursor arrowCursor] set];
  232369. }
  232370. }
  232371. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232372. {
  232373. NSString* bestType
  232374. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232375. if (bestType == nil)
  232376. return false;
  232377. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232378. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232379. StringArray files;
  232380. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232381. if (list == nil)
  232382. return false;
  232383. if ([list isKindOfClass: [NSArray class]])
  232384. {
  232385. NSArray* items = (NSArray*) list;
  232386. for (unsigned int i = 0; i < [items count]; ++i)
  232387. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232388. }
  232389. if (files.size() == 0)
  232390. return false;
  232391. if (type == 0)
  232392. handleFileDragMove (files, pos);
  232393. else if (type == 1)
  232394. handleFileDragExit (files);
  232395. else if (type == 2)
  232396. handleFileDragDrop (files, pos);
  232397. return true;
  232398. }
  232399. bool NSViewComponentPeer::isOpaque()
  232400. {
  232401. return component == 0 || component->isOpaque();
  232402. }
  232403. void NSViewComponentPeer::drawRect (NSRect r)
  232404. {
  232405. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232406. return;
  232407. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232408. if (! component->isOpaque())
  232409. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232410. #if USE_COREGRAPHICS_RENDERING
  232411. if (usingCoreGraphics)
  232412. {
  232413. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232414. insideDrawRect = true;
  232415. handlePaint (context);
  232416. insideDrawRect = false;
  232417. }
  232418. else
  232419. #endif
  232420. {
  232421. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232422. (int) (r.size.width + 0.5f),
  232423. (int) (r.size.height + 0.5f),
  232424. ! getComponent()->isOpaque());
  232425. const int xOffset = -roundToInt (r.origin.x);
  232426. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232427. const NSRect* rects = 0;
  232428. NSInteger numRects = 0;
  232429. [view getRectsBeingDrawn: &rects count: &numRects];
  232430. const Rectangle<int> clipBounds (temp.getBounds());
  232431. RectangleList clip;
  232432. for (int i = 0; i < numRects; ++i)
  232433. {
  232434. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232435. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232436. roundToInt (rects[i].size.width),
  232437. roundToInt (rects[i].size.height))));
  232438. }
  232439. if (! clip.isEmpty())
  232440. {
  232441. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232442. insideDrawRect = true;
  232443. handlePaint (context);
  232444. insideDrawRect = false;
  232445. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232446. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232447. CGColorSpaceRelease (colourSpace);
  232448. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232449. CGImageRelease (image);
  232450. }
  232451. }
  232452. }
  232453. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232454. {
  232455. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232456. #if USE_COREGRAPHICS_RENDERING
  232457. s.add ("CoreGraphics Renderer");
  232458. #endif
  232459. return s;
  232460. }
  232461. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232462. {
  232463. return usingCoreGraphics ? 1 : 0;
  232464. }
  232465. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232466. {
  232467. #if USE_COREGRAPHICS_RENDERING
  232468. if (usingCoreGraphics != (index > 0))
  232469. {
  232470. usingCoreGraphics = index > 0;
  232471. [view setNeedsDisplay: true];
  232472. }
  232473. #endif
  232474. }
  232475. bool NSViewComponentPeer::canBecomeKeyWindow()
  232476. {
  232477. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232478. }
  232479. bool NSViewComponentPeer::windowShouldClose()
  232480. {
  232481. if (! isValidPeer (this))
  232482. return YES;
  232483. handleUserClosingWindow();
  232484. return NO;
  232485. }
  232486. void NSViewComponentPeer::redirectMovedOrResized()
  232487. {
  232488. handleMovedOrResized();
  232489. }
  232490. void NSViewComponentPeer::viewMovedToWindow()
  232491. {
  232492. if (isSharedWindow)
  232493. window = [view window];
  232494. }
  232495. void Desktop::createMouseInputSources()
  232496. {
  232497. mouseSources.add (new MouseInputSource (0, true));
  232498. }
  232499. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232500. {
  232501. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232502. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232503. // is apparently still available in 64-bit apps..
  232504. if (enableOrDisable)
  232505. {
  232506. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232507. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232508. }
  232509. else
  232510. {
  232511. SetSystemUIMode (kUIModeNormal, 0);
  232512. }
  232513. }
  232514. class AsyncRepaintMessage : public CallbackMessage
  232515. {
  232516. public:
  232517. NSViewComponentPeer* const peer;
  232518. const Rectangle<int> rect;
  232519. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232520. : peer (peer_), rect (rect_)
  232521. {
  232522. }
  232523. void messageCallback()
  232524. {
  232525. if (ComponentPeer::isValidPeer (peer))
  232526. peer->repaint (rect);
  232527. }
  232528. };
  232529. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232530. {
  232531. if (insideDrawRect)
  232532. {
  232533. (new AsyncRepaintMessage (this, area))->post();
  232534. }
  232535. else
  232536. {
  232537. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232538. (float) area.getWidth(), (float) area.getHeight())];
  232539. }
  232540. }
  232541. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232542. {
  232543. [view displayIfNeeded];
  232544. }
  232545. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232546. {
  232547. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232548. }
  232549. const Image juce_createIconForFile (const File& file)
  232550. {
  232551. const ScopedAutoReleasePool pool;
  232552. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232553. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232554. [NSGraphicsContext saveGraphicsState];
  232555. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232556. [image drawAtPoint: NSMakePoint (0, 0)
  232557. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232558. operation: NSCompositeSourceOver fraction: 1.0f];
  232559. [[NSGraphicsContext currentContext] flushGraphics];
  232560. [NSGraphicsContext restoreGraphicsState];
  232561. return Image (result);
  232562. }
  232563. const int KeyPress::spaceKey = ' ';
  232564. const int KeyPress::returnKey = 0x0d;
  232565. const int KeyPress::escapeKey = 0x1b;
  232566. const int KeyPress::backspaceKey = 0x7f;
  232567. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232568. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232569. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232570. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232571. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232572. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232573. const int KeyPress::endKey = NSEndFunctionKey;
  232574. const int KeyPress::homeKey = NSHomeFunctionKey;
  232575. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232576. const int KeyPress::insertKey = -1;
  232577. const int KeyPress::tabKey = 9;
  232578. const int KeyPress::F1Key = NSF1FunctionKey;
  232579. const int KeyPress::F2Key = NSF2FunctionKey;
  232580. const int KeyPress::F3Key = NSF3FunctionKey;
  232581. const int KeyPress::F4Key = NSF4FunctionKey;
  232582. const int KeyPress::F5Key = NSF5FunctionKey;
  232583. const int KeyPress::F6Key = NSF6FunctionKey;
  232584. const int KeyPress::F7Key = NSF7FunctionKey;
  232585. const int KeyPress::F8Key = NSF8FunctionKey;
  232586. const int KeyPress::F9Key = NSF9FunctionKey;
  232587. const int KeyPress::F10Key = NSF10FunctionKey;
  232588. const int KeyPress::F11Key = NSF1FunctionKey;
  232589. const int KeyPress::F12Key = NSF12FunctionKey;
  232590. const int KeyPress::F13Key = NSF13FunctionKey;
  232591. const int KeyPress::F14Key = NSF14FunctionKey;
  232592. const int KeyPress::F15Key = NSF15FunctionKey;
  232593. const int KeyPress::F16Key = NSF16FunctionKey;
  232594. const int KeyPress::numberPad0 = 0x30020;
  232595. const int KeyPress::numberPad1 = 0x30021;
  232596. const int KeyPress::numberPad2 = 0x30022;
  232597. const int KeyPress::numberPad3 = 0x30023;
  232598. const int KeyPress::numberPad4 = 0x30024;
  232599. const int KeyPress::numberPad5 = 0x30025;
  232600. const int KeyPress::numberPad6 = 0x30026;
  232601. const int KeyPress::numberPad7 = 0x30027;
  232602. const int KeyPress::numberPad8 = 0x30028;
  232603. const int KeyPress::numberPad9 = 0x30029;
  232604. const int KeyPress::numberPadAdd = 0x3002a;
  232605. const int KeyPress::numberPadSubtract = 0x3002b;
  232606. const int KeyPress::numberPadMultiply = 0x3002c;
  232607. const int KeyPress::numberPadDivide = 0x3002d;
  232608. const int KeyPress::numberPadSeparator = 0x3002e;
  232609. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232610. const int KeyPress::numberPadEquals = 0x30030;
  232611. const int KeyPress::numberPadDelete = 0x30031;
  232612. const int KeyPress::playKey = 0x30000;
  232613. const int KeyPress::stopKey = 0x30001;
  232614. const int KeyPress::fastForwardKey = 0x30002;
  232615. const int KeyPress::rewindKey = 0x30003;
  232616. #endif
  232617. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232618. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232619. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232620. // compiled on its own).
  232621. #if JUCE_INCLUDED_FILE
  232622. #if JUCE_MAC
  232623. namespace MouseCursorHelpers
  232624. {
  232625. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232626. {
  232627. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232628. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232629. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232630. [im release];
  232631. return c;
  232632. }
  232633. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232634. {
  232635. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232636. BufferedInputStream buf (&fileStream, 4096, false);
  232637. PNGImageFormat pngFormat;
  232638. Image im (pngFormat.decodeImage (buf));
  232639. if (im.isValid())
  232640. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232641. jassertfalse;
  232642. return 0;
  232643. }
  232644. }
  232645. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232646. {
  232647. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232648. }
  232649. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232650. {
  232651. const ScopedAutoReleasePool pool;
  232652. NSCursor* c = 0;
  232653. switch (type)
  232654. {
  232655. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232656. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232657. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232658. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232659. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232660. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232661. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232662. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232663. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232664. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232665. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232666. case UpDownResizeCursor:
  232667. case TopEdgeResizeCursor:
  232668. case BottomEdgeResizeCursor:
  232669. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232670. case TopLeftCornerResizeCursor:
  232671. case BottomRightCornerResizeCursor:
  232672. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232673. case TopRightCornerResizeCursor:
  232674. case BottomLeftCornerResizeCursor:
  232675. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232676. case UpDownLeftRightResizeCursor:
  232677. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232678. default:
  232679. jassertfalse;
  232680. break;
  232681. }
  232682. [c retain];
  232683. return c;
  232684. }
  232685. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232686. {
  232687. [((NSCursor*) cursorHandle) release];
  232688. }
  232689. void MouseCursor::showInAllWindows() const
  232690. {
  232691. showInWindow (0);
  232692. }
  232693. void MouseCursor::showInWindow (ComponentPeer*) const
  232694. {
  232695. [((NSCursor*) getHandle()) set];
  232696. }
  232697. #else
  232698. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232699. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232700. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232701. void MouseCursor::showInAllWindows() const {}
  232702. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232703. #endif
  232704. #endif
  232705. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232706. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232707. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232708. // compiled on its own).
  232709. #if JUCE_INCLUDED_FILE
  232710. class NSViewComponentInternal : public ComponentMovementWatcher
  232711. {
  232712. Component* const owner;
  232713. NSViewComponentPeer* currentPeer;
  232714. bool wasShowing;
  232715. public:
  232716. NSView* const view;
  232717. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232718. : ComponentMovementWatcher (owner_),
  232719. owner (owner_),
  232720. currentPeer (0),
  232721. wasShowing (false),
  232722. view (view_)
  232723. {
  232724. [view_ retain];
  232725. if (owner_->isShowing())
  232726. componentPeerChanged();
  232727. }
  232728. ~NSViewComponentInternal()
  232729. {
  232730. [view removeFromSuperview];
  232731. [view release];
  232732. }
  232733. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232734. {
  232735. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232736. // The ComponentMovementWatcher version of this method avoids calling
  232737. // us when the top-level comp is resized, but for an NSView we need to know this
  232738. // because with inverted co-ords, we need to update the position even if the
  232739. // top-left pos hasn't changed
  232740. if (comp.isOnDesktop() && wasResized)
  232741. componentMovedOrResized (wasMoved, wasResized);
  232742. }
  232743. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232744. {
  232745. Component* const topComp = owner->getTopLevelComponent();
  232746. if (topComp->getPeer() != 0)
  232747. {
  232748. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232749. NSRect r;
  232750. r.origin.x = (float) pos.getX();
  232751. r.origin.y = (float) pos.getY();
  232752. r.size.width = (float) owner->getWidth();
  232753. r.size.height = (float) owner->getHeight();
  232754. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232755. [view setFrame: r];
  232756. }
  232757. }
  232758. void componentPeerChanged()
  232759. {
  232760. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232761. if (currentPeer != peer)
  232762. {
  232763. [view removeFromSuperview];
  232764. currentPeer = peer;
  232765. if (peer != 0)
  232766. {
  232767. [peer->view addSubview: view];
  232768. componentMovedOrResized (false, false);
  232769. }
  232770. }
  232771. [view setHidden: ! owner->isShowing()];
  232772. }
  232773. void componentVisibilityChanged (Component&)
  232774. {
  232775. componentPeerChanged();
  232776. }
  232777. juce_UseDebuggingNewOperator
  232778. private:
  232779. NSViewComponentInternal (const NSViewComponentInternal&);
  232780. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232781. };
  232782. NSViewComponent::NSViewComponent()
  232783. {
  232784. }
  232785. NSViewComponent::~NSViewComponent()
  232786. {
  232787. }
  232788. void NSViewComponent::setView (void* view)
  232789. {
  232790. if (view != getView())
  232791. {
  232792. if (view != 0)
  232793. info = new NSViewComponentInternal ((NSView*) view, this);
  232794. else
  232795. info = 0;
  232796. }
  232797. }
  232798. void* NSViewComponent::getView() const
  232799. {
  232800. return info == 0 ? 0 : info->view;
  232801. }
  232802. void NSViewComponent::paint (Graphics&)
  232803. {
  232804. }
  232805. #endif
  232806. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232807. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232808. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232809. // compiled on its own).
  232810. #if JUCE_INCLUDED_FILE
  232811. AppleRemoteDevice::AppleRemoteDevice()
  232812. : device (0),
  232813. queue (0),
  232814. remoteId (0)
  232815. {
  232816. }
  232817. AppleRemoteDevice::~AppleRemoteDevice()
  232818. {
  232819. stop();
  232820. }
  232821. static io_object_t getAppleRemoteDevice()
  232822. {
  232823. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232824. io_iterator_t iter = 0;
  232825. io_object_t iod = 0;
  232826. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232827. && iter != 0)
  232828. {
  232829. iod = IOIteratorNext (iter);
  232830. }
  232831. IOObjectRelease (iter);
  232832. return iod;
  232833. }
  232834. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  232835. {
  232836. jassert (*device == 0);
  232837. io_name_t classname;
  232838. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232839. {
  232840. IOCFPlugInInterface** cfPlugInInterface = 0;
  232841. SInt32 score = 0;
  232842. if (IOCreatePlugInInterfaceForService (iod,
  232843. kIOHIDDeviceUserClientTypeID,
  232844. kIOCFPlugInInterfaceID,
  232845. &cfPlugInInterface,
  232846. &score) == kIOReturnSuccess)
  232847. {
  232848. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232849. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232850. device);
  232851. (void) hr;
  232852. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232853. }
  232854. }
  232855. return *device != 0;
  232856. }
  232857. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232858. {
  232859. if (queue != 0)
  232860. return true;
  232861. stop();
  232862. bool result = false;
  232863. io_object_t iod = getAppleRemoteDevice();
  232864. if (iod != 0)
  232865. {
  232866. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232867. result = true;
  232868. else
  232869. stop();
  232870. IOObjectRelease (iod);
  232871. }
  232872. return result;
  232873. }
  232874. void AppleRemoteDevice::stop()
  232875. {
  232876. if (queue != 0)
  232877. {
  232878. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232879. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232880. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232881. queue = 0;
  232882. }
  232883. if (device != 0)
  232884. {
  232885. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232886. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232887. device = 0;
  232888. }
  232889. }
  232890. bool AppleRemoteDevice::isActive() const
  232891. {
  232892. return queue != 0;
  232893. }
  232894. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232895. {
  232896. if (result == kIOReturnSuccess)
  232897. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232898. }
  232899. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232900. {
  232901. Array <int> cookies;
  232902. CFArrayRef elements;
  232903. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232904. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232905. return false;
  232906. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232907. {
  232908. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232909. // get the cookie
  232910. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232911. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232912. continue;
  232913. long number;
  232914. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232915. continue;
  232916. cookies.add ((int) number);
  232917. }
  232918. CFRelease (elements);
  232919. if ((*(IOHIDDeviceInterface**) device)
  232920. ->open ((IOHIDDeviceInterface**) device,
  232921. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232922. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232923. {
  232924. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232925. if (queue != 0)
  232926. {
  232927. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232928. for (int i = 0; i < cookies.size(); ++i)
  232929. {
  232930. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232931. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232932. }
  232933. CFRunLoopSourceRef eventSource;
  232934. if ((*(IOHIDQueueInterface**) queue)
  232935. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232936. {
  232937. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232938. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232939. {
  232940. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232941. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232942. return true;
  232943. }
  232944. }
  232945. }
  232946. }
  232947. return false;
  232948. }
  232949. void AppleRemoteDevice::handleCallbackInternal()
  232950. {
  232951. int totalValues = 0;
  232952. AbsoluteTime nullTime = { 0, 0 };
  232953. char cookies [12];
  232954. int numCookies = 0;
  232955. while (numCookies < numElementsInArray (cookies))
  232956. {
  232957. IOHIDEventStruct e;
  232958. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232959. break;
  232960. if ((int) e.elementCookie == 19)
  232961. {
  232962. remoteId = e.value;
  232963. buttonPressed (switched, false);
  232964. }
  232965. else
  232966. {
  232967. totalValues += e.value;
  232968. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232969. }
  232970. }
  232971. cookies [numCookies++] = 0;
  232972. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232973. static const char buttonPatterns[] =
  232974. {
  232975. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232976. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232977. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232978. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232979. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232980. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232981. 0x1f, 0x12, 0x04, 0x02, 0,
  232982. 0x1f, 0x12, 0x03, 0x02, 0,
  232983. 0x1f, 0x12, 0x1f, 0x12, 0,
  232984. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232985. 19, 0
  232986. };
  232987. int buttonNum = (int) menuButton;
  232988. int i = 0;
  232989. while (i < numElementsInArray (buttonPatterns))
  232990. {
  232991. if (strcmp (cookies, buttonPatterns + i) == 0)
  232992. {
  232993. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232994. break;
  232995. }
  232996. i += (int) strlen (buttonPatterns + i) + 1;
  232997. ++buttonNum;
  232998. }
  232999. }
  233000. #endif
  233001. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  233002. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  233003. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233004. // compiled on its own).
  233005. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  233006. #if JUCE_MAC
  233007. END_JUCE_NAMESPACE
  233008. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  233009. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  233010. {
  233011. CriticalSection* contextLock;
  233012. bool needsUpdate;
  233013. }
  233014. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  233015. - (bool) makeActive;
  233016. - (void) makeInactive;
  233017. - (void) reshape;
  233018. @end
  233019. @implementation ThreadSafeNSOpenGLView
  233020. - (id) initWithFrame: (NSRect) frameRect
  233021. pixelFormat: (NSOpenGLPixelFormat*) format
  233022. {
  233023. contextLock = new CriticalSection();
  233024. self = [super initWithFrame: frameRect pixelFormat: format];
  233025. if (self != nil)
  233026. [[NSNotificationCenter defaultCenter] addObserver: self
  233027. selector: @selector (_surfaceNeedsUpdate:)
  233028. name: NSViewGlobalFrameDidChangeNotification
  233029. object: self];
  233030. return self;
  233031. }
  233032. - (void) dealloc
  233033. {
  233034. [[NSNotificationCenter defaultCenter] removeObserver: self];
  233035. delete contextLock;
  233036. [super dealloc];
  233037. }
  233038. - (bool) makeActive
  233039. {
  233040. const ScopedLock sl (*contextLock);
  233041. if ([self openGLContext] == 0)
  233042. return false;
  233043. [[self openGLContext] makeCurrentContext];
  233044. if (needsUpdate)
  233045. {
  233046. [super update];
  233047. needsUpdate = false;
  233048. }
  233049. return true;
  233050. }
  233051. - (void) makeInactive
  233052. {
  233053. const ScopedLock sl (*contextLock);
  233054. [NSOpenGLContext clearCurrentContext];
  233055. }
  233056. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  233057. {
  233058. const ScopedLock sl (*contextLock);
  233059. needsUpdate = true;
  233060. }
  233061. - (void) update
  233062. {
  233063. const ScopedLock sl (*contextLock);
  233064. needsUpdate = true;
  233065. }
  233066. - (void) reshape
  233067. {
  233068. const ScopedLock sl (*contextLock);
  233069. needsUpdate = true;
  233070. }
  233071. @end
  233072. BEGIN_JUCE_NAMESPACE
  233073. class WindowedGLContext : public OpenGLContext
  233074. {
  233075. public:
  233076. WindowedGLContext (Component* const component,
  233077. const OpenGLPixelFormat& pixelFormat_,
  233078. NSOpenGLContext* sharedContext)
  233079. : renderContext (0),
  233080. pixelFormat (pixelFormat_)
  233081. {
  233082. jassert (component != 0);
  233083. NSOpenGLPixelFormatAttribute attribs [64];
  233084. int n = 0;
  233085. attribs[n++] = NSOpenGLPFADoubleBuffer;
  233086. attribs[n++] = NSOpenGLPFAAccelerated;
  233087. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  233088. attribs[n++] = NSOpenGLPFAColorSize;
  233089. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  233090. pixelFormat.greenBits,
  233091. pixelFormat.blueBits);
  233092. attribs[n++] = NSOpenGLPFAAlphaSize;
  233093. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  233094. attribs[n++] = NSOpenGLPFADepthSize;
  233095. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  233096. attribs[n++] = NSOpenGLPFAStencilSize;
  233097. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  233098. attribs[n++] = NSOpenGLPFAAccumSize;
  233099. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  233100. pixelFormat.accumulationBufferGreenBits,
  233101. pixelFormat.accumulationBufferBlueBits,
  233102. pixelFormat.accumulationBufferAlphaBits);
  233103. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  233104. attribs[n++] = NSOpenGLPFASampleBuffers;
  233105. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  233106. attribs[n++] = NSOpenGLPFAClosestPolicy;
  233107. attribs[n++] = NSOpenGLPFANoRecovery;
  233108. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  233109. NSOpenGLPixelFormat* format
  233110. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  233111. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233112. pixelFormat: format];
  233113. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  233114. shareContext: sharedContext] autorelease];
  233115. const GLint swapInterval = 1;
  233116. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  233117. [view setOpenGLContext: renderContext];
  233118. [format release];
  233119. viewHolder = new NSViewComponentInternal (view, component);
  233120. }
  233121. ~WindowedGLContext()
  233122. {
  233123. deleteContext();
  233124. viewHolder = 0;
  233125. }
  233126. void deleteContext()
  233127. {
  233128. makeInactive();
  233129. [renderContext clearDrawable];
  233130. [renderContext setView: nil];
  233131. [view setOpenGLContext: nil];
  233132. renderContext = nil;
  233133. }
  233134. bool makeActive() const throw()
  233135. {
  233136. jassert (renderContext != 0);
  233137. if ([renderContext view] != view)
  233138. [renderContext setView: view];
  233139. [view makeActive];
  233140. return isActive();
  233141. }
  233142. bool makeInactive() const throw()
  233143. {
  233144. [view makeInactive];
  233145. return true;
  233146. }
  233147. bool isActive() const throw()
  233148. {
  233149. return [NSOpenGLContext currentContext] == renderContext;
  233150. }
  233151. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233152. void* getRawContext() const throw() { return renderContext; }
  233153. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233154. {
  233155. }
  233156. void swapBuffers()
  233157. {
  233158. [renderContext flushBuffer];
  233159. }
  233160. bool setSwapInterval (const int numFramesPerSwap)
  233161. {
  233162. [renderContext setValues: (const GLint*) &numFramesPerSwap
  233163. forParameter: NSOpenGLCPSwapInterval];
  233164. return true;
  233165. }
  233166. int getSwapInterval() const
  233167. {
  233168. GLint numFrames = 0;
  233169. [renderContext getValues: &numFrames
  233170. forParameter: NSOpenGLCPSwapInterval];
  233171. return numFrames;
  233172. }
  233173. void repaint()
  233174. {
  233175. // we need to invalidate the juce view that holds this gl view, to make it
  233176. // cause a repaint callback
  233177. NSView* v = (NSView*) viewHolder->view;
  233178. NSRect r = [v frame];
  233179. // bit of a bodge here.. if we only invalidate the area of the gl component,
  233180. // it's completely covered by the NSOpenGLView, so the OS throws away the
  233181. // repaint message, thus never causing our paint() callback, and never repainting
  233182. // the comp. So invalidating just a little bit around the edge helps..
  233183. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  233184. }
  233185. void* getNativeWindowHandle() const { return viewHolder->view; }
  233186. juce_UseDebuggingNewOperator
  233187. NSOpenGLContext* renderContext;
  233188. ThreadSafeNSOpenGLView* view;
  233189. private:
  233190. OpenGLPixelFormat pixelFormat;
  233191. ScopedPointer <NSViewComponentInternal> viewHolder;
  233192. WindowedGLContext (const WindowedGLContext&);
  233193. WindowedGLContext& operator= (const WindowedGLContext&);
  233194. };
  233195. OpenGLContext* OpenGLComponent::createContext()
  233196. {
  233197. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  233198. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  233199. return (c->renderContext != 0) ? c.release() : 0;
  233200. }
  233201. void* OpenGLComponent::getNativeWindowHandle() const
  233202. {
  233203. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  233204. : 0;
  233205. }
  233206. void juce_glViewport (const int w, const int h)
  233207. {
  233208. glViewport (0, 0, w, h);
  233209. }
  233210. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233211. OwnedArray <OpenGLPixelFormat>& results)
  233212. {
  233213. /* GLint attribs [64];
  233214. int n = 0;
  233215. attribs[n++] = AGL_RGBA;
  233216. attribs[n++] = AGL_DOUBLEBUFFER;
  233217. attribs[n++] = AGL_ACCELERATED;
  233218. attribs[n++] = AGL_NO_RECOVERY;
  233219. attribs[n++] = AGL_NONE;
  233220. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  233221. while (p != 0)
  233222. {
  233223. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  233224. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  233225. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  233226. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  233227. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  233228. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  233229. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  233230. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  233231. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  233232. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  233233. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  233234. results.add (pf);
  233235. p = aglNextPixelFormat (p);
  233236. }*/
  233237. //jassertfalse // can't see how you do this in cocoa!
  233238. }
  233239. #else
  233240. END_JUCE_NAMESPACE
  233241. @interface JuceGLView : UIView
  233242. {
  233243. }
  233244. + (Class) layerClass;
  233245. @end
  233246. @implementation JuceGLView
  233247. + (Class) layerClass
  233248. {
  233249. return [CAEAGLLayer class];
  233250. }
  233251. @end
  233252. BEGIN_JUCE_NAMESPACE
  233253. class GLESContext : public OpenGLContext
  233254. {
  233255. public:
  233256. GLESContext (UIViewComponentPeer* peer,
  233257. Component* const component_,
  233258. const OpenGLPixelFormat& pixelFormat_,
  233259. const GLESContext* const sharedContext,
  233260. NSUInteger apiType)
  233261. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  233262. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  233263. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  233264. {
  233265. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233266. view.opaque = YES;
  233267. view.hidden = NO;
  233268. view.backgroundColor = [UIColor blackColor];
  233269. view.userInteractionEnabled = NO;
  233270. glLayer = (CAEAGLLayer*) [view layer];
  233271. [peer->view addSubview: view];
  233272. if (sharedContext != 0)
  233273. context = [[EAGLContext alloc] initWithAPI: apiType
  233274. sharegroup: [sharedContext->context sharegroup]];
  233275. else
  233276. context = [[EAGLContext alloc] initWithAPI: apiType];
  233277. createGLBuffers();
  233278. }
  233279. ~GLESContext()
  233280. {
  233281. deleteContext();
  233282. [view removeFromSuperview];
  233283. [view release];
  233284. freeGLBuffers();
  233285. }
  233286. void deleteContext()
  233287. {
  233288. makeInactive();
  233289. [context release];
  233290. context = nil;
  233291. }
  233292. bool makeActive() const throw()
  233293. {
  233294. jassert (context != 0);
  233295. [EAGLContext setCurrentContext: context];
  233296. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233297. return true;
  233298. }
  233299. void swapBuffers()
  233300. {
  233301. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233302. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233303. }
  233304. bool makeInactive() const throw()
  233305. {
  233306. return [EAGLContext setCurrentContext: nil];
  233307. }
  233308. bool isActive() const throw()
  233309. {
  233310. return [EAGLContext currentContext] == context;
  233311. }
  233312. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233313. void* getRawContext() const throw() { return glLayer; }
  233314. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233315. {
  233316. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233317. if (lastWidth != w || lastHeight != h)
  233318. {
  233319. lastWidth = w;
  233320. lastHeight = h;
  233321. freeGLBuffers();
  233322. createGLBuffers();
  233323. }
  233324. }
  233325. bool setSwapInterval (const int numFramesPerSwap)
  233326. {
  233327. numFrames = numFramesPerSwap;
  233328. return true;
  233329. }
  233330. int getSwapInterval() const
  233331. {
  233332. return numFrames;
  233333. }
  233334. void repaint()
  233335. {
  233336. }
  233337. void createGLBuffers()
  233338. {
  233339. makeActive();
  233340. glGenFramebuffersOES (1, &frameBufferHandle);
  233341. glGenRenderbuffersOES (1, &colorBufferHandle);
  233342. glGenRenderbuffersOES (1, &depthBufferHandle);
  233343. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233344. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233345. GLint width, height;
  233346. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233347. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233348. if (useDepthBuffer)
  233349. {
  233350. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233351. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233352. }
  233353. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233354. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233355. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233356. if (useDepthBuffer)
  233357. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233358. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233359. }
  233360. void freeGLBuffers()
  233361. {
  233362. if (frameBufferHandle != 0)
  233363. {
  233364. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233365. frameBufferHandle = 0;
  233366. }
  233367. if (colorBufferHandle != 0)
  233368. {
  233369. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233370. colorBufferHandle = 0;
  233371. }
  233372. if (depthBufferHandle != 0)
  233373. {
  233374. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233375. depthBufferHandle = 0;
  233376. }
  233377. }
  233378. juce_UseDebuggingNewOperator
  233379. private:
  233380. Component::SafePointer<Component> component;
  233381. OpenGLPixelFormat pixelFormat;
  233382. JuceGLView* view;
  233383. CAEAGLLayer* glLayer;
  233384. EAGLContext* context;
  233385. bool useDepthBuffer;
  233386. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233387. int numFrames;
  233388. int lastWidth, lastHeight;
  233389. GLESContext (const GLESContext&);
  233390. GLESContext& operator= (const GLESContext&);
  233391. };
  233392. OpenGLContext* OpenGLComponent::createContext()
  233393. {
  233394. ScopedAutoReleasePool pool;
  233395. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233396. if (peer != 0)
  233397. return new GLESContext (peer, this, preferredPixelFormat,
  233398. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233399. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233400. return 0;
  233401. }
  233402. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233403. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233404. {
  233405. }
  233406. void juce_glViewport (const int w, const int h)
  233407. {
  233408. glViewport (0, 0, w, h);
  233409. }
  233410. #endif
  233411. #endif
  233412. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233413. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233414. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233415. // compiled on its own).
  233416. #if JUCE_INCLUDED_FILE
  233417. class JuceMainMenuHandler;
  233418. END_JUCE_NAMESPACE
  233419. using namespace JUCE_NAMESPACE;
  233420. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233421. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233422. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233423. #else
  233424. @interface JuceMenuCallback : NSObject
  233425. #endif
  233426. {
  233427. JuceMainMenuHandler* owner;
  233428. }
  233429. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233430. - (void) dealloc;
  233431. - (void) menuItemInvoked: (id) menu;
  233432. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233433. @end
  233434. BEGIN_JUCE_NAMESPACE
  233435. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233436. private DeletedAtShutdown
  233437. {
  233438. public:
  233439. static JuceMainMenuHandler* instance;
  233440. JuceMainMenuHandler()
  233441. : currentModel (0),
  233442. lastUpdateTime (0)
  233443. {
  233444. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233445. }
  233446. ~JuceMainMenuHandler()
  233447. {
  233448. setMenu (0);
  233449. jassert (instance == this);
  233450. instance = 0;
  233451. [callback release];
  233452. }
  233453. void setMenu (MenuBarModel* const newMenuBarModel)
  233454. {
  233455. if (currentModel != newMenuBarModel)
  233456. {
  233457. if (currentModel != 0)
  233458. currentModel->removeListener (this);
  233459. currentModel = newMenuBarModel;
  233460. if (currentModel != 0)
  233461. currentModel->addListener (this);
  233462. menuBarItemsChanged (0);
  233463. }
  233464. }
  233465. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233466. const String& name, const int menuId, const int tag)
  233467. {
  233468. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233469. action: nil
  233470. keyEquivalent: @""];
  233471. [item setTag: tag];
  233472. NSMenu* sub = createMenu (child, name, menuId, tag);
  233473. [parent setSubmenu: sub forItem: item];
  233474. [sub setAutoenablesItems: false];
  233475. [sub release];
  233476. }
  233477. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233478. const String& name, const int menuId, const int tag)
  233479. {
  233480. [parentItem setTag: tag];
  233481. NSMenu* menu = [parentItem submenu];
  233482. [menu setTitle: juceStringToNS (name)];
  233483. while ([menu numberOfItems] > 0)
  233484. [menu removeItemAtIndex: 0];
  233485. PopupMenu::MenuItemIterator iter (menuToCopy);
  233486. while (iter.next())
  233487. addMenuItem (iter, menu, menuId, tag);
  233488. [menu setAutoenablesItems: false];
  233489. [menu update];
  233490. }
  233491. void menuBarItemsChanged (MenuBarModel*)
  233492. {
  233493. lastUpdateTime = Time::getMillisecondCounter();
  233494. StringArray menuNames;
  233495. if (currentModel != 0)
  233496. menuNames = currentModel->getMenuBarNames();
  233497. NSMenu* menuBar = [NSApp mainMenu];
  233498. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233499. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233500. int menuId = 1;
  233501. for (int i = 0; i < menuNames.size(); ++i)
  233502. {
  233503. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233504. if (i >= [menuBar numberOfItems] - 1)
  233505. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233506. else
  233507. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233508. }
  233509. }
  233510. static void flashMenuBar (NSMenu* menu)
  233511. {
  233512. if ([[menu title] isEqualToString: @"Apple"])
  233513. return;
  233514. [menu retain];
  233515. const unichar f35Key = NSF35FunctionKey;
  233516. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233517. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233518. action: nil
  233519. keyEquivalent: f35String];
  233520. [item setTarget: nil];
  233521. [menu insertItem: item atIndex: [menu numberOfItems]];
  233522. [item release];
  233523. if ([menu indexOfItem: item] >= 0)
  233524. {
  233525. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233526. location: NSZeroPoint
  233527. modifierFlags: NSCommandKeyMask
  233528. timestamp: 0
  233529. windowNumber: 0
  233530. context: [NSGraphicsContext currentContext]
  233531. characters: f35String
  233532. charactersIgnoringModifiers: f35String
  233533. isARepeat: NO
  233534. keyCode: 0];
  233535. [menu performKeyEquivalent: f35Event];
  233536. if ([menu indexOfItem: item] >= 0)
  233537. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233538. }
  233539. [menu release];
  233540. }
  233541. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233542. {
  233543. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233544. {
  233545. NSMenuItem* m = [menu itemAtIndex: i];
  233546. if ([m tag] == info.commandID)
  233547. return m;
  233548. if ([m submenu] != 0)
  233549. {
  233550. NSMenuItem* found = findMenuItem ([m submenu], info);
  233551. if (found != 0)
  233552. return found;
  233553. }
  233554. }
  233555. return 0;
  233556. }
  233557. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233558. {
  233559. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233560. if (item != 0)
  233561. flashMenuBar ([item menu]);
  233562. }
  233563. void updateMenus()
  233564. {
  233565. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233566. menuBarItemsChanged (0);
  233567. }
  233568. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233569. {
  233570. if (currentModel != 0)
  233571. {
  233572. if (commandManager != 0)
  233573. {
  233574. ApplicationCommandTarget::InvocationInfo info (commandId);
  233575. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233576. commandManager->invoke (info, true);
  233577. }
  233578. currentModel->menuItemSelected (commandId, topLevelIndex);
  233579. }
  233580. }
  233581. MenuBarModel* currentModel;
  233582. uint32 lastUpdateTime;
  233583. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233584. const int topLevelMenuId, const int topLevelIndex)
  233585. {
  233586. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233587. if (text == 0)
  233588. text = @"";
  233589. if (iter.isSeparator)
  233590. {
  233591. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233592. }
  233593. else if (iter.isSectionHeader)
  233594. {
  233595. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233596. action: nil
  233597. keyEquivalent: @""];
  233598. [item setEnabled: false];
  233599. }
  233600. else if (iter.subMenu != 0)
  233601. {
  233602. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233603. action: nil
  233604. keyEquivalent: @""];
  233605. [item setTag: iter.itemId];
  233606. [item setEnabled: iter.isEnabled];
  233607. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233608. [sub setDelegate: nil];
  233609. [menuToAddTo setSubmenu: sub forItem: item];
  233610. [sub release];
  233611. }
  233612. else
  233613. {
  233614. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233615. action: @selector (menuItemInvoked:)
  233616. keyEquivalent: @""];
  233617. [item setTag: iter.itemId];
  233618. [item setEnabled: iter.isEnabled];
  233619. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233620. [item setTarget: (id) callback];
  233621. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233622. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233623. [item setRepresentedObject: info];
  233624. if (iter.commandManager != 0)
  233625. {
  233626. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233627. ->getKeyPressesAssignedToCommand (iter.itemId));
  233628. if (keyPresses.size() > 0)
  233629. {
  233630. const KeyPress& kp = keyPresses.getReference(0);
  233631. if (kp.getKeyCode() != KeyPress::backspaceKey
  233632. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233633. // every time you press the key while editing text)
  233634. {
  233635. juce_wchar key = kp.getTextCharacter();
  233636. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233637. key = NSBackspaceCharacter;
  233638. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233639. key = NSDeleteCharacter;
  233640. else if (key == 0)
  233641. key = (juce_wchar) kp.getKeyCode();
  233642. unsigned int mods = 0;
  233643. if (kp.getModifiers().isShiftDown())
  233644. mods |= NSShiftKeyMask;
  233645. if (kp.getModifiers().isCtrlDown())
  233646. mods |= NSControlKeyMask;
  233647. if (kp.getModifiers().isAltDown())
  233648. mods |= NSAlternateKeyMask;
  233649. if (kp.getModifiers().isCommandDown())
  233650. mods |= NSCommandKeyMask;
  233651. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233652. [item setKeyEquivalentModifierMask: mods];
  233653. }
  233654. }
  233655. }
  233656. }
  233657. }
  233658. JuceMenuCallback* callback;
  233659. private:
  233660. NSMenu* createMenu (const PopupMenu menu,
  233661. const String& menuName,
  233662. const int topLevelMenuId,
  233663. const int topLevelIndex)
  233664. {
  233665. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233666. [m setAutoenablesItems: false];
  233667. [m setDelegate: callback];
  233668. PopupMenu::MenuItemIterator iter (menu);
  233669. while (iter.next())
  233670. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233671. [m update];
  233672. return m;
  233673. }
  233674. };
  233675. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233676. END_JUCE_NAMESPACE
  233677. @implementation JuceMenuCallback
  233678. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233679. {
  233680. [super init];
  233681. owner = owner_;
  233682. return self;
  233683. }
  233684. - (void) dealloc
  233685. {
  233686. [super dealloc];
  233687. }
  233688. - (void) menuItemInvoked: (id) menu
  233689. {
  233690. NSMenuItem* item = (NSMenuItem*) menu;
  233691. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233692. {
  233693. // 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
  233694. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233695. // into the focused component and let it trigger the menu item indirectly.
  233696. NSEvent* e = [NSApp currentEvent];
  233697. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233698. {
  233699. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233700. {
  233701. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233702. if (peer != 0)
  233703. {
  233704. if ([e type] == NSKeyDown)
  233705. peer->redirectKeyDown (e);
  233706. else
  233707. peer->redirectKeyUp (e);
  233708. return;
  233709. }
  233710. }
  233711. }
  233712. NSArray* info = (NSArray*) [item representedObject];
  233713. owner->invoke ((int) [item tag],
  233714. (ApplicationCommandManager*) (pointer_sized_int)
  233715. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233716. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233717. }
  233718. }
  233719. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233720. {
  233721. (void) menu;
  233722. if (JuceMainMenuHandler::instance != 0)
  233723. JuceMainMenuHandler::instance->updateMenus();
  233724. }
  233725. @end
  233726. BEGIN_JUCE_NAMESPACE
  233727. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  233728. const PopupMenu* extraItems)
  233729. {
  233730. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233731. {
  233732. PopupMenu::MenuItemIterator iter (*extraItems);
  233733. while (iter.next())
  233734. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233735. [menu addItem: [NSMenuItem separatorItem]];
  233736. }
  233737. NSMenuItem* item;
  233738. // Services...
  233739. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233740. action: nil keyEquivalent: @""];
  233741. [menu addItem: item];
  233742. [item release];
  233743. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233744. [menu setSubmenu: servicesMenu forItem: item];
  233745. [NSApp setServicesMenu: servicesMenu];
  233746. [servicesMenu release];
  233747. [menu addItem: [NSMenuItem separatorItem]];
  233748. // Hide + Show stuff...
  233749. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233750. action: @selector (hide:) keyEquivalent: @"h"];
  233751. [item setTarget: NSApp];
  233752. [menu addItem: item];
  233753. [item release];
  233754. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233755. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233756. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233757. [item setTarget: NSApp];
  233758. [menu addItem: item];
  233759. [item release];
  233760. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233761. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233762. [item setTarget: NSApp];
  233763. [menu addItem: item];
  233764. [item release];
  233765. [menu addItem: [NSMenuItem separatorItem]];
  233766. // Quit item....
  233767. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233768. action: @selector (terminate:) keyEquivalent: @"q"];
  233769. [item setTarget: NSApp];
  233770. [menu addItem: item];
  233771. [item release];
  233772. return menu;
  233773. }
  233774. // Since our app has no NIB, this initialises a standard app menu...
  233775. static void rebuildMainMenu (const PopupMenu* extraItems)
  233776. {
  233777. // this can't be used in a plugin!
  233778. jassert (JUCEApplication::isStandaloneApp());
  233779. if (JUCEApplication::getInstance() != 0)
  233780. {
  233781. const ScopedAutoReleasePool pool;
  233782. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233783. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233784. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233785. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233786. [mainMenu setSubmenu: appMenu forItem: item];
  233787. [NSApp setMainMenu: mainMenu];
  233788. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233789. [appMenu release];
  233790. [mainMenu release];
  233791. }
  233792. }
  233793. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233794. const PopupMenu* extraAppleMenuItems)
  233795. {
  233796. if (getMacMainMenu() != newMenuBarModel)
  233797. {
  233798. const ScopedAutoReleasePool pool;
  233799. if (newMenuBarModel == 0)
  233800. {
  233801. delete JuceMainMenuHandler::instance;
  233802. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233803. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233804. extraAppleMenuItems = 0;
  233805. }
  233806. else
  233807. {
  233808. if (JuceMainMenuHandler::instance == 0)
  233809. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233810. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233811. }
  233812. }
  233813. rebuildMainMenu (extraAppleMenuItems);
  233814. if (newMenuBarModel != 0)
  233815. newMenuBarModel->menuItemsChanged();
  233816. }
  233817. MenuBarModel* MenuBarModel::getMacMainMenu()
  233818. {
  233819. return JuceMainMenuHandler::instance != 0
  233820. ? JuceMainMenuHandler::instance->currentModel : 0;
  233821. }
  233822. void juce_initialiseMacMainMenu()
  233823. {
  233824. if (JuceMainMenuHandler::instance == 0)
  233825. rebuildMainMenu (0);
  233826. }
  233827. #endif
  233828. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233829. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233830. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233831. // compiled on its own).
  233832. #if JUCE_INCLUDED_FILE
  233833. #if JUCE_MAC
  233834. END_JUCE_NAMESPACE
  233835. using namespace JUCE_NAMESPACE;
  233836. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233837. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233838. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233839. #else
  233840. @interface JuceFileChooserDelegate : NSObject
  233841. #endif
  233842. {
  233843. StringArray* filters;
  233844. }
  233845. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233846. - (void) dealloc;
  233847. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233848. @end
  233849. @implementation JuceFileChooserDelegate
  233850. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233851. {
  233852. [super init];
  233853. filters = filters_;
  233854. return self;
  233855. }
  233856. - (void) dealloc
  233857. {
  233858. delete filters;
  233859. [super dealloc];
  233860. }
  233861. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233862. {
  233863. (void) sender;
  233864. const File f (nsStringToJuce (filename));
  233865. for (int i = filters->size(); --i >= 0;)
  233866. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233867. return true;
  233868. return f.isDirectory();
  233869. }
  233870. @end
  233871. BEGIN_JUCE_NAMESPACE
  233872. void FileChooser::showPlatformDialog (Array<File>& results,
  233873. const String& title,
  233874. const File& currentFileOrDirectory,
  233875. const String& filter,
  233876. bool selectsDirectory,
  233877. bool selectsFiles,
  233878. bool isSaveDialogue,
  233879. bool warnAboutOverwritingExistingFiles,
  233880. bool selectMultipleFiles,
  233881. FilePreviewComponent* extraInfoComponent)
  233882. {
  233883. const ScopedAutoReleasePool pool;
  233884. StringArray* filters = new StringArray();
  233885. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233886. filters->trim();
  233887. filters->removeEmptyStrings();
  233888. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233889. [delegate autorelease];
  233890. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233891. : [NSOpenPanel openPanel];
  233892. [panel setTitle: juceStringToNS (title)];
  233893. if (! isSaveDialogue)
  233894. {
  233895. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233896. [openPanel setCanChooseDirectories: selectsDirectory];
  233897. [openPanel setCanChooseFiles: selectsFiles];
  233898. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233899. }
  233900. [panel setDelegate: delegate];
  233901. if (isSaveDialogue || selectsDirectory)
  233902. [panel setCanCreateDirectories: YES];
  233903. String directory, filename;
  233904. if (currentFileOrDirectory.isDirectory())
  233905. {
  233906. directory = currentFileOrDirectory.getFullPathName();
  233907. }
  233908. else
  233909. {
  233910. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233911. filename = currentFileOrDirectory.getFileName();
  233912. }
  233913. if ([panel runModalForDirectory: juceStringToNS (directory)
  233914. file: juceStringToNS (filename)]
  233915. == NSOKButton)
  233916. {
  233917. if (isSaveDialogue)
  233918. {
  233919. results.add (File (nsStringToJuce ([panel filename])));
  233920. }
  233921. else
  233922. {
  233923. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233924. NSArray* urls = [openPanel filenames];
  233925. for (unsigned int i = 0; i < [urls count]; ++i)
  233926. {
  233927. NSString* f = [urls objectAtIndex: i];
  233928. results.add (File (nsStringToJuce (f)));
  233929. }
  233930. }
  233931. }
  233932. [panel setDelegate: nil];
  233933. }
  233934. #else
  233935. void FileChooser::showPlatformDialog (Array<File>& results,
  233936. const String& title,
  233937. const File& currentFileOrDirectory,
  233938. const String& filter,
  233939. bool selectsDirectory,
  233940. bool selectsFiles,
  233941. bool isSaveDialogue,
  233942. bool warnAboutOverwritingExistingFiles,
  233943. bool selectMultipleFiles,
  233944. FilePreviewComponent* extraInfoComponent)
  233945. {
  233946. const ScopedAutoReleasePool pool;
  233947. jassertfalse; //xxx to do
  233948. }
  233949. #endif
  233950. #endif
  233951. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233952. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233953. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233954. // compiled on its own).
  233955. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233956. END_JUCE_NAMESPACE
  233957. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233958. @interface NonInterceptingQTMovieView : QTMovieView
  233959. {
  233960. }
  233961. - (id) initWithFrame: (NSRect) frame;
  233962. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233963. - (NSView*) hitTest: (NSPoint) p;
  233964. @end
  233965. @implementation NonInterceptingQTMovieView
  233966. - (id) initWithFrame: (NSRect) frame
  233967. {
  233968. self = [super initWithFrame: frame];
  233969. [self setNextResponder: [self superview]];
  233970. return self;
  233971. }
  233972. - (void) dealloc
  233973. {
  233974. [super dealloc];
  233975. }
  233976. - (NSView*) hitTest: (NSPoint) point
  233977. {
  233978. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233979. }
  233980. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233981. {
  233982. return YES;
  233983. }
  233984. @end
  233985. BEGIN_JUCE_NAMESPACE
  233986. #define theMovie (static_cast <QTMovie*> (movie))
  233987. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233988. : movie (0)
  233989. {
  233990. setOpaque (true);
  233991. setVisible (true);
  233992. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233993. setView (view);
  233994. [view release];
  233995. }
  233996. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233997. {
  233998. closeMovie();
  233999. setView (0);
  234000. }
  234001. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  234002. {
  234003. return true;
  234004. }
  234005. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  234006. {
  234007. // unfortunately, QTMovie objects can only be created on the main thread..
  234008. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234009. QTMovie* movie = 0;
  234010. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  234011. if (fin != 0)
  234012. {
  234013. movieFile = fin->getFile();
  234014. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  234015. error: nil];
  234016. }
  234017. else
  234018. {
  234019. MemoryBlock temp;
  234020. movieStream->readIntoMemoryBlock (temp);
  234021. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  234022. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  234023. {
  234024. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  234025. length: temp.getSize()]
  234026. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  234027. MIMEType: @""]
  234028. error: nil];
  234029. if (movie != 0)
  234030. break;
  234031. }
  234032. }
  234033. return movie;
  234034. }
  234035. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  234036. const bool isControllerVisible_)
  234037. {
  234038. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  234039. }
  234040. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  234041. const bool controllerVisible_)
  234042. {
  234043. closeMovie();
  234044. if (getPeer() == 0)
  234045. {
  234046. // To open a movie, this component must be visible inside a functioning window, so that
  234047. // the QT control can be assigned to the window.
  234048. jassertfalse;
  234049. return false;
  234050. }
  234051. movie = openMovieFromStream (movieStream, movieFile);
  234052. [theMovie retain];
  234053. QTMovieView* view = (QTMovieView*) getView();
  234054. [view setMovie: theMovie];
  234055. [view setControllerVisible: controllerVisible_];
  234056. setLooping (looping);
  234057. return movie != nil;
  234058. }
  234059. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  234060. const bool isControllerVisible_)
  234061. {
  234062. // unfortunately, QTMovie objects can only be created on the main thread..
  234063. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234064. closeMovie();
  234065. if (getPeer() == 0)
  234066. {
  234067. // To open a movie, this component must be visible inside a functioning window, so that
  234068. // the QT control can be assigned to the window.
  234069. jassertfalse;
  234070. return false;
  234071. }
  234072. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  234073. NSError* err;
  234074. if ([QTMovie canInitWithURL: url])
  234075. movie = [QTMovie movieWithURL: url error: &err];
  234076. [theMovie retain];
  234077. QTMovieView* view = (QTMovieView*) getView();
  234078. [view setMovie: theMovie];
  234079. [view setControllerVisible: controllerVisible];
  234080. setLooping (looping);
  234081. return movie != nil;
  234082. }
  234083. void QuickTimeMovieComponent::closeMovie()
  234084. {
  234085. stop();
  234086. QTMovieView* view = (QTMovieView*) getView();
  234087. [view setMovie: nil];
  234088. [theMovie release];
  234089. movie = 0;
  234090. movieFile = File::nonexistent;
  234091. }
  234092. bool QuickTimeMovieComponent::isMovieOpen() const
  234093. {
  234094. return movie != nil;
  234095. }
  234096. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  234097. {
  234098. return movieFile;
  234099. }
  234100. void QuickTimeMovieComponent::play()
  234101. {
  234102. [theMovie play];
  234103. }
  234104. void QuickTimeMovieComponent::stop()
  234105. {
  234106. [theMovie stop];
  234107. }
  234108. bool QuickTimeMovieComponent::isPlaying() const
  234109. {
  234110. return movie != 0 && [theMovie rate] != 0;
  234111. }
  234112. void QuickTimeMovieComponent::setPosition (const double seconds)
  234113. {
  234114. if (movie != 0)
  234115. {
  234116. QTTime t;
  234117. t.timeValue = (uint64) (100000.0 * seconds);
  234118. t.timeScale = 100000;
  234119. t.flags = 0;
  234120. [theMovie setCurrentTime: t];
  234121. }
  234122. }
  234123. double QuickTimeMovieComponent::getPosition() const
  234124. {
  234125. if (movie == 0)
  234126. return 0.0;
  234127. QTTime t = [theMovie currentTime];
  234128. return t.timeValue / (double) t.timeScale;
  234129. }
  234130. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  234131. {
  234132. [theMovie setRate: newSpeed];
  234133. }
  234134. double QuickTimeMovieComponent::getMovieDuration() const
  234135. {
  234136. if (movie == 0)
  234137. return 0.0;
  234138. QTTime t = [theMovie duration];
  234139. return t.timeValue / (double) t.timeScale;
  234140. }
  234141. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  234142. {
  234143. looping = shouldLoop;
  234144. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  234145. forKey: QTMovieLoopsAttribute];
  234146. }
  234147. bool QuickTimeMovieComponent::isLooping() const
  234148. {
  234149. return looping;
  234150. }
  234151. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  234152. {
  234153. [theMovie setVolume: newVolume];
  234154. }
  234155. float QuickTimeMovieComponent::getMovieVolume() const
  234156. {
  234157. return movie != 0 ? [theMovie volume] : 0.0f;
  234158. }
  234159. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  234160. {
  234161. width = 0;
  234162. height = 0;
  234163. if (movie != 0)
  234164. {
  234165. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  234166. width = (int) s.width;
  234167. height = (int) s.height;
  234168. }
  234169. }
  234170. void QuickTimeMovieComponent::paint (Graphics& g)
  234171. {
  234172. if (movie == 0)
  234173. g.fillAll (Colours::black);
  234174. }
  234175. bool QuickTimeMovieComponent::isControllerVisible() const
  234176. {
  234177. return controllerVisible;
  234178. }
  234179. void QuickTimeMovieComponent::goToStart()
  234180. {
  234181. setPosition (0.0);
  234182. }
  234183. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  234184. const RectanglePlacement& placement)
  234185. {
  234186. int normalWidth, normalHeight;
  234187. getMovieNormalSize (normalWidth, normalHeight);
  234188. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  234189. {
  234190. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  234191. placement.applyTo (x, y, w, h,
  234192. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  234193. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  234194. if (w > 0 && h > 0)
  234195. {
  234196. setBounds (roundToInt (x), roundToInt (y),
  234197. roundToInt (w), roundToInt (h));
  234198. }
  234199. }
  234200. else
  234201. {
  234202. setBounds (spaceToFitWithin);
  234203. }
  234204. }
  234205. #if ! (JUCE_MAC && JUCE_64BIT)
  234206. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  234207. {
  234208. if (movieStream == 0)
  234209. return false;
  234210. File file;
  234211. QTMovie* movie = openMovieFromStream (movieStream, file);
  234212. if (movie != nil)
  234213. result = [movie quickTimeMovie];
  234214. return movie != nil;
  234215. }
  234216. #endif
  234217. #endif
  234218. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234219. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  234220. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234221. // compiled on its own).
  234222. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  234223. const int kilobytesPerSecond1x = 176;
  234224. END_JUCE_NAMESPACE
  234225. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  234226. @interface OpenDiskDevice : NSObject
  234227. {
  234228. @public
  234229. DRDevice* device;
  234230. NSMutableArray* tracks;
  234231. bool underrunProtection;
  234232. }
  234233. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  234234. - (void) dealloc;
  234235. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  234236. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234237. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  234238. @end
  234239. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  234240. @interface AudioTrackProducer : NSObject
  234241. {
  234242. JUCE_NAMESPACE::AudioSource* source;
  234243. int readPosition, lengthInFrames;
  234244. }
  234245. - (AudioTrackProducer*) init: (int) lengthInFrames;
  234246. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  234247. - (void) dealloc;
  234248. - (void) setupTrackProperties: (DRTrack*) track;
  234249. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  234250. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  234251. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  234252. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  234253. toMedia:(NSDictionary*)mediaInfo;
  234254. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  234255. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  234256. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234257. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234258. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234259. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234260. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234261. ioFlags:(uint32_t*)flags;
  234262. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  234263. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234264. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234265. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234266. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234267. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234268. ioFlags:(uint32_t*)flags;
  234269. @end
  234270. @implementation OpenDiskDevice
  234271. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234272. {
  234273. [super init];
  234274. device = device_;
  234275. tracks = [[NSMutableArray alloc] init];
  234276. underrunProtection = true;
  234277. return self;
  234278. }
  234279. - (void) dealloc
  234280. {
  234281. [tracks release];
  234282. [super dealloc];
  234283. }
  234284. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234285. {
  234286. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234287. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234288. [p setupTrackProperties: t];
  234289. [tracks addObject: t];
  234290. [t release];
  234291. [p release];
  234292. }
  234293. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234294. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234295. {
  234296. DRBurn* burn = [DRBurn burnForDevice: device];
  234297. if (! [device acquireExclusiveAccess])
  234298. {
  234299. *error = "Couldn't open or write to the CD device";
  234300. return;
  234301. }
  234302. [device acquireMediaReservation];
  234303. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234304. [d autorelease];
  234305. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234306. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234307. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234308. if (burnSpeed > 0)
  234309. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234310. if (! underrunProtection)
  234311. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234312. [burn setProperties: d];
  234313. [burn writeLayout: tracks];
  234314. for (;;)
  234315. {
  234316. JUCE_NAMESPACE::Thread::sleep (300);
  234317. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234318. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234319. {
  234320. [burn abort];
  234321. *error = "User cancelled the write operation";
  234322. break;
  234323. }
  234324. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234325. {
  234326. *error = "Write operation failed";
  234327. break;
  234328. }
  234329. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234330. {
  234331. break;
  234332. }
  234333. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234334. objectForKey: DRErrorStatusErrorStringKey];
  234335. if ([err length] > 0)
  234336. {
  234337. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234338. break;
  234339. }
  234340. }
  234341. [device releaseMediaReservation];
  234342. [device releaseExclusiveAccess];
  234343. }
  234344. @end
  234345. @implementation AudioTrackProducer
  234346. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234347. {
  234348. lengthInFrames = lengthInFrames_;
  234349. readPosition = 0;
  234350. return self;
  234351. }
  234352. - (void) setupTrackProperties: (DRTrack*) track
  234353. {
  234354. NSMutableDictionary* p = [[track properties] mutableCopy];
  234355. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234356. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234357. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234358. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234359. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234360. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234361. [track setProperties: p];
  234362. [p release];
  234363. }
  234364. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234365. {
  234366. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234367. if (s != nil)
  234368. s->source = source_;
  234369. return s;
  234370. }
  234371. - (void) dealloc
  234372. {
  234373. if (source != 0)
  234374. {
  234375. source->releaseResources();
  234376. delete source;
  234377. }
  234378. [super dealloc];
  234379. }
  234380. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234381. {
  234382. }
  234383. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234384. {
  234385. return true;
  234386. }
  234387. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234388. {
  234389. return lengthInFrames;
  234390. }
  234391. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234392. toMedia: (NSDictionary*) mediaInfo
  234393. {
  234394. if (source != 0)
  234395. source->prepareToPlay (44100 / 75, 44100);
  234396. readPosition = 0;
  234397. return true;
  234398. }
  234399. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234400. {
  234401. if (source != 0)
  234402. source->prepareToPlay (44100 / 75, 44100);
  234403. return true;
  234404. }
  234405. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234406. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234407. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234408. {
  234409. if (source != 0)
  234410. {
  234411. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234412. if (numSamples > 0)
  234413. {
  234414. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234415. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234416. info.buffer = &tempBuffer;
  234417. info.startSample = 0;
  234418. info.numSamples = numSamples;
  234419. source->getNextAudioBlock (info);
  234420. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  234421. buffer, numSamples, 4);
  234422. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  234423. buffer + 2, numSamples, 4);
  234424. readPosition += numSamples;
  234425. }
  234426. return numSamples * 4;
  234427. }
  234428. return 0;
  234429. }
  234430. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234431. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234432. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234433. ioFlags: (uint32_t*) flags
  234434. {
  234435. zeromem (buffer, bufferLength);
  234436. return bufferLength;
  234437. }
  234438. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234439. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234440. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234441. {
  234442. return true;
  234443. }
  234444. @end
  234445. BEGIN_JUCE_NAMESPACE
  234446. class AudioCDBurner::Pimpl : public Timer
  234447. {
  234448. public:
  234449. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234450. : device (0), owner (owner_)
  234451. {
  234452. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234453. if (dev != 0)
  234454. {
  234455. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234456. lastState = getDiskState();
  234457. startTimer (1000);
  234458. }
  234459. }
  234460. ~Pimpl()
  234461. {
  234462. stopTimer();
  234463. [device release];
  234464. }
  234465. void timerCallback()
  234466. {
  234467. const DiskState state = getDiskState();
  234468. if (state != lastState)
  234469. {
  234470. lastState = state;
  234471. owner.sendChangeMessage (&owner);
  234472. }
  234473. }
  234474. DiskState getDiskState() const
  234475. {
  234476. if ([device->device isValid])
  234477. {
  234478. NSDictionary* status = [device->device status];
  234479. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234480. if ([state isEqualTo: DRDeviceMediaStateNone])
  234481. {
  234482. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234483. return trayOpen;
  234484. return noDisc;
  234485. }
  234486. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234487. {
  234488. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234489. return writableDiskPresent;
  234490. else
  234491. return readOnlyDiskPresent;
  234492. }
  234493. }
  234494. return unknown;
  234495. }
  234496. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234497. const Array<int> getAvailableWriteSpeeds() const
  234498. {
  234499. Array<int> results;
  234500. if ([device->device isValid])
  234501. {
  234502. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234503. for (unsigned int i = 0; i < [speeds count]; ++i)
  234504. {
  234505. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234506. results.add (kbPerSec / kilobytesPerSecond1x);
  234507. }
  234508. }
  234509. return results;
  234510. }
  234511. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234512. {
  234513. if ([device->device isValid])
  234514. {
  234515. device->underrunProtection = shouldBeEnabled;
  234516. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234517. }
  234518. return false;
  234519. }
  234520. int getNumAvailableAudioBlocks() const
  234521. {
  234522. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234523. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234524. }
  234525. OpenDiskDevice* device;
  234526. private:
  234527. DiskState lastState;
  234528. AudioCDBurner& owner;
  234529. };
  234530. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234531. {
  234532. pimpl = new Pimpl (*this, deviceIndex);
  234533. }
  234534. AudioCDBurner::~AudioCDBurner()
  234535. {
  234536. }
  234537. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234538. {
  234539. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234540. if (b->pimpl->device == 0)
  234541. b = 0;
  234542. return b.release();
  234543. }
  234544. static NSArray* findDiskBurnerDevices()
  234545. {
  234546. NSMutableArray* results = [NSMutableArray array];
  234547. NSArray* devs = [DRDevice devices];
  234548. if (devs != 0)
  234549. {
  234550. int num = [devs count];
  234551. int i;
  234552. for (i = 0; i < num; ++i)
  234553. {
  234554. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234555. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234556. if (name != nil)
  234557. [results addObject: name];
  234558. }
  234559. }
  234560. return results;
  234561. }
  234562. const StringArray AudioCDBurner::findAvailableDevices()
  234563. {
  234564. NSArray* names = findDiskBurnerDevices();
  234565. StringArray s;
  234566. for (unsigned int i = 0; i < [names count]; ++i)
  234567. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234568. return s;
  234569. }
  234570. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234571. {
  234572. return pimpl->getDiskState();
  234573. }
  234574. bool AudioCDBurner::isDiskPresent() const
  234575. {
  234576. return getDiskState() == writableDiskPresent;
  234577. }
  234578. bool AudioCDBurner::openTray()
  234579. {
  234580. return pimpl->openTray();
  234581. }
  234582. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234583. {
  234584. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234585. DiskState oldState = getDiskState();
  234586. DiskState newState = oldState;
  234587. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234588. {
  234589. newState = getDiskState();
  234590. Thread::sleep (100);
  234591. }
  234592. return newState;
  234593. }
  234594. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234595. {
  234596. return pimpl->getAvailableWriteSpeeds();
  234597. }
  234598. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234599. {
  234600. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234601. }
  234602. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234603. {
  234604. return pimpl->getNumAvailableAudioBlocks();
  234605. }
  234606. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234607. {
  234608. if ([pimpl->device->device isValid])
  234609. {
  234610. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234611. return true;
  234612. }
  234613. return false;
  234614. }
  234615. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234616. bool ejectDiscAfterwards,
  234617. bool performFakeBurnForTesting,
  234618. int writeSpeed)
  234619. {
  234620. String error ("Couldn't open or write to the CD device");
  234621. if ([pimpl->device->device isValid])
  234622. {
  234623. error = String::empty;
  234624. [pimpl->device burn: listener
  234625. errorString: &error
  234626. ejectAfterwards: ejectDiscAfterwards
  234627. isFake: performFakeBurnForTesting
  234628. speed: writeSpeed];
  234629. }
  234630. return error;
  234631. }
  234632. #endif
  234633. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234634. void AudioCDReader::ejectDisk()
  234635. {
  234636. const ScopedAutoReleasePool p;
  234637. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234638. }
  234639. #endif
  234640. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234641. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234642. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234643. // compiled on its own).
  234644. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234645. namespace CDReaderHelpers
  234646. {
  234647. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234648. {
  234649. forEachXmlChildElementWithTagName (xml, child, "key")
  234650. if (child->getAllSubText() == key)
  234651. return child->getNextElement();
  234652. return 0;
  234653. }
  234654. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234655. {
  234656. const XmlElement* const block = getElementForKey (xml, key);
  234657. return block != 0 ? block->getAllSubText().getIntValue() : defaultValue;
  234658. }
  234659. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234660. // Returns NULL on success, otherwise a const char* representing an error.
  234661. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234662. {
  234663. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234664. if (xml == 0)
  234665. return "Couldn't parse XML in file";
  234666. const XmlElement* const dict = xml->getChildByName ("dict");
  234667. if (dict == 0)
  234668. return "Couldn't get top level dictionary";
  234669. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234670. if (sessions == 0)
  234671. return "Couldn't find sessions key";
  234672. const XmlElement* const session = sessions->getFirstChildElement();
  234673. if (session == 0)
  234674. return "Couldn't find first session";
  234675. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234676. if (leadOut < 0)
  234677. return "Couldn't find Leadout Block";
  234678. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234679. if (trackArray == 0)
  234680. return "Couldn't find Track Array";
  234681. forEachXmlChildElement (*trackArray, track)
  234682. {
  234683. const int trackValue = getIntValueForKey (*track, "Start Block");
  234684. if (trackValue < 0)
  234685. return "Couldn't find Start Block in the track";
  234686. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234687. }
  234688. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234689. return 0;
  234690. }
  234691. static void findDevices (Array<File>& cds)
  234692. {
  234693. File volumes ("/Volumes");
  234694. volumes.findChildFiles (cds, File::findDirectories, false);
  234695. for (int i = cds.size(); --i >= 0;)
  234696. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234697. cds.remove (i);
  234698. }
  234699. struct TrackSorter
  234700. {
  234701. static int getCDTrackNumber (const File& file)
  234702. {
  234703. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234704. }
  234705. static int compareElements (const File& first, const File& second)
  234706. {
  234707. const int firstTrack = getCDTrackNumber (first);
  234708. const int secondTrack = getCDTrackNumber (second);
  234709. jassert (firstTrack > 0 && secondTrack > 0);
  234710. return firstTrack - secondTrack;
  234711. }
  234712. };
  234713. }
  234714. const StringArray AudioCDReader::getAvailableCDNames()
  234715. {
  234716. Array<File> cds;
  234717. CDReaderHelpers::findDevices (cds);
  234718. StringArray names;
  234719. for (int i = 0; i < cds.size(); ++i)
  234720. names.add (cds.getReference(i).getFileName());
  234721. return names;
  234722. }
  234723. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234724. {
  234725. Array<File> cds;
  234726. CDReaderHelpers::findDevices (cds);
  234727. if (cds[index].exists())
  234728. return new AudioCDReader (cds[index]);
  234729. return 0;
  234730. }
  234731. AudioCDReader::AudioCDReader (const File& volume)
  234732. : AudioFormatReader (0, "CD Audio"),
  234733. volumeDir (volume),
  234734. currentReaderTrack (-1),
  234735. reader (0)
  234736. {
  234737. sampleRate = 44100.0;
  234738. bitsPerSample = 16;
  234739. numChannels = 2;
  234740. usesFloatingPointData = false;
  234741. refreshTrackLengths();
  234742. }
  234743. AudioCDReader::~AudioCDReader()
  234744. {
  234745. }
  234746. void AudioCDReader::refreshTrackLengths()
  234747. {
  234748. tracks.clear();
  234749. trackStartSamples.clear();
  234750. lengthInSamples = 0;
  234751. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234752. CDReaderHelpers::TrackSorter sorter;
  234753. tracks.sort (sorter);
  234754. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234755. if (toc.exists())
  234756. {
  234757. XmlDocument doc (toc);
  234758. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234759. (void) error; // could be logged..
  234760. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234761. }
  234762. }
  234763. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234764. int64 startSampleInFile, int numSamples)
  234765. {
  234766. while (numSamples > 0)
  234767. {
  234768. int track = -1;
  234769. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234770. {
  234771. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234772. {
  234773. track = i;
  234774. break;
  234775. }
  234776. }
  234777. if (track < 0)
  234778. return false;
  234779. if (track != currentReaderTrack)
  234780. {
  234781. reader = 0;
  234782. FileInputStream* const in = tracks [track].createInputStream();
  234783. if (in != 0)
  234784. {
  234785. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234786. AiffAudioFormat format;
  234787. reader = format.createReaderFor (bin, true);
  234788. if (reader == 0)
  234789. currentReaderTrack = -1;
  234790. else
  234791. currentReaderTrack = track;
  234792. }
  234793. }
  234794. if (reader == 0)
  234795. return false;
  234796. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234797. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234798. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234799. numSamples -= numAvailable;
  234800. startSampleInFile += numAvailable;
  234801. }
  234802. return true;
  234803. }
  234804. bool AudioCDReader::isCDStillPresent() const
  234805. {
  234806. return volumeDir.exists();
  234807. }
  234808. bool AudioCDReader::isTrackAudio (int trackNum) const
  234809. {
  234810. return tracks [trackNum].hasFileExtension (".aiff");
  234811. }
  234812. void AudioCDReader::enableIndexScanning (bool b)
  234813. {
  234814. // any way to do this on a Mac??
  234815. }
  234816. int AudioCDReader::getLastIndex() const
  234817. {
  234818. return 0;
  234819. }
  234820. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234821. {
  234822. return Array <int>();
  234823. }
  234824. #endif
  234825. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234826. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234827. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234828. // compiled on its own).
  234829. #if JUCE_INCLUDED_FILE
  234830. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234831. for example having more than one juce plugin loaded into a host, then when a
  234832. method is called, the actual code that runs might actually be in a different module
  234833. than the one you expect... So any calls to library functions or statics that are
  234834. made inside obj-c methods will probably end up getting executed in a different DLL's
  234835. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234836. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234837. virtual methods of an object that's known to live inside the right module's space.
  234838. */
  234839. class AppDelegateRedirector
  234840. {
  234841. public:
  234842. AppDelegateRedirector()
  234843. {
  234844. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234845. runLoop = CFRunLoopGetMain();
  234846. #else
  234847. runLoop = CFRunLoopGetCurrent();
  234848. #endif
  234849. CFRunLoopSourceContext sourceContext;
  234850. zerostruct (sourceContext);
  234851. sourceContext.info = this;
  234852. sourceContext.perform = runLoopSourceCallback;
  234853. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234854. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234855. }
  234856. virtual ~AppDelegateRedirector()
  234857. {
  234858. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234859. CFRunLoopSourceInvalidate (runLoopSource);
  234860. CFRelease (runLoopSource);
  234861. }
  234862. virtual NSApplicationTerminateReply shouldTerminate()
  234863. {
  234864. if (JUCEApplication::getInstance() != 0)
  234865. {
  234866. JUCEApplication::getInstance()->systemRequestedQuit();
  234867. if (MessageManager::getInstance()->hasStopMessageBeenSent())
  234868. {
  234869. [NSApp performSelectorOnMainThread: @selector (replyToApplicationShouldTerminate:)
  234870. withObject: [NSNumber numberWithBool: YES]
  234871. waitUntilDone: NO];
  234872. return NSTerminateLater;
  234873. }
  234874. return NSTerminateCancel;
  234875. }
  234876. return NSTerminateNow;
  234877. }
  234878. virtual BOOL openFile (const NSString* filename)
  234879. {
  234880. if (JUCEApplication::getInstance() != 0)
  234881. {
  234882. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234883. return YES;
  234884. }
  234885. return NO;
  234886. }
  234887. virtual void openFiles (NSArray* filenames)
  234888. {
  234889. StringArray files;
  234890. for (unsigned int i = 0; i < [filenames count]; ++i)
  234891. {
  234892. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234893. if (filename.containsChar (' '))
  234894. filename = filename.quoted('"');
  234895. files.add (filename);
  234896. }
  234897. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234898. {
  234899. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234900. }
  234901. }
  234902. virtual void focusChanged()
  234903. {
  234904. juce_HandleProcessFocusChange();
  234905. }
  234906. struct CallbackMessagePayload
  234907. {
  234908. MessageCallbackFunction* function;
  234909. void* parameter;
  234910. void* volatile result;
  234911. bool volatile hasBeenExecuted;
  234912. };
  234913. virtual void performCallback (CallbackMessagePayload* pl)
  234914. {
  234915. pl->result = (*pl->function) (pl->parameter);
  234916. pl->hasBeenExecuted = true;
  234917. }
  234918. virtual void deleteSelf()
  234919. {
  234920. delete this;
  234921. }
  234922. void postMessage (Message* const m)
  234923. {
  234924. messages.add (m);
  234925. CFRunLoopSourceSignal (runLoopSource);
  234926. CFRunLoopWakeUp (runLoop);
  234927. }
  234928. private:
  234929. CFRunLoopRef runLoop;
  234930. CFRunLoopSourceRef runLoopSource;
  234931. OwnedArray <Message, CriticalSection> messages;
  234932. void runLoopCallback()
  234933. {
  234934. int numDispatched = 0;
  234935. do
  234936. {
  234937. Message* const nextMessage = messages.removeAndReturn (0);
  234938. if (nextMessage == 0)
  234939. return;
  234940. const ScopedAutoReleasePool pool;
  234941. MessageManager::getInstance()->deliverMessage (nextMessage);
  234942. } while (++numDispatched <= 4);
  234943. CFRunLoopSourceSignal (runLoopSource);
  234944. CFRunLoopWakeUp (runLoop);
  234945. }
  234946. static void runLoopSourceCallback (void* info)
  234947. {
  234948. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  234949. }
  234950. };
  234951. END_JUCE_NAMESPACE
  234952. using namespace JUCE_NAMESPACE;
  234953. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234954. @interface JuceAppDelegate : NSObject
  234955. {
  234956. @private
  234957. id oldDelegate;
  234958. @public
  234959. AppDelegateRedirector* redirector;
  234960. }
  234961. - (JuceAppDelegate*) init;
  234962. - (void) dealloc;
  234963. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234964. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234965. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234966. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234967. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234968. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234969. - (void) performCallback: (id) info;
  234970. - (void) dummyMethod;
  234971. @end
  234972. @implementation JuceAppDelegate
  234973. - (JuceAppDelegate*) init
  234974. {
  234975. [super init];
  234976. redirector = new AppDelegateRedirector();
  234977. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234978. if (JUCEApplication::isStandaloneApp())
  234979. {
  234980. oldDelegate = [NSApp delegate];
  234981. [NSApp setDelegate: self];
  234982. }
  234983. else
  234984. {
  234985. oldDelegate = 0;
  234986. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234987. name: NSApplicationDidResignActiveNotification object: NSApp];
  234988. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234989. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234990. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234991. name: NSApplicationWillUnhideNotification object: NSApp];
  234992. }
  234993. return self;
  234994. }
  234995. - (void) dealloc
  234996. {
  234997. if (oldDelegate != 0)
  234998. [NSApp setDelegate: oldDelegate];
  234999. redirector->deleteSelf();
  235000. [super dealloc];
  235001. }
  235002. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  235003. {
  235004. (void) app;
  235005. return redirector->shouldTerminate();
  235006. }
  235007. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  235008. {
  235009. (void) app;
  235010. return redirector->openFile (filename);
  235011. }
  235012. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  235013. {
  235014. (void) sender;
  235015. return redirector->openFiles (filenames);
  235016. }
  235017. - (void) applicationDidBecomeActive: (NSNotification*) notification
  235018. {
  235019. (void) notification;
  235020. redirector->focusChanged();
  235021. }
  235022. - (void) applicationDidResignActive: (NSNotification*) notification
  235023. {
  235024. (void) notification;
  235025. redirector->focusChanged();
  235026. }
  235027. - (void) applicationWillUnhide: (NSNotification*) notification
  235028. {
  235029. (void) notification;
  235030. redirector->focusChanged();
  235031. }
  235032. - (void) performCallback: (id) info
  235033. {
  235034. if ([info isKindOfClass: [NSData class]])
  235035. {
  235036. AppDelegateRedirector::CallbackMessagePayload* pl
  235037. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  235038. if (pl != 0)
  235039. redirector->performCallback (pl);
  235040. }
  235041. else
  235042. {
  235043. jassertfalse; // should never get here!
  235044. }
  235045. }
  235046. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  235047. @end
  235048. BEGIN_JUCE_NAMESPACE
  235049. static JuceAppDelegate* juceAppDelegate = 0;
  235050. void MessageManager::runDispatchLoop()
  235051. {
  235052. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  235053. {
  235054. const ScopedAutoReleasePool pool;
  235055. // must only be called by the message thread!
  235056. jassert (isThisTheMessageThread());
  235057. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  235058. @try
  235059. {
  235060. [NSApp run];
  235061. }
  235062. @catch (NSException* e)
  235063. {
  235064. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  235065. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  235066. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  235067. }
  235068. @finally
  235069. {
  235070. }
  235071. #else
  235072. [NSApp run];
  235073. #endif
  235074. }
  235075. }
  235076. void MessageManager::stopDispatchLoop()
  235077. {
  235078. quitMessagePosted = true;
  235079. [NSApp stop: nil];
  235080. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  235081. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  235082. }
  235083. static bool isEventBlockedByModalComps (NSEvent* e)
  235084. {
  235085. if (Component::getNumCurrentlyModalComponents() == 0)
  235086. return false;
  235087. NSWindow* const w = [e window];
  235088. if (w == 0 || [w worksWhenModal])
  235089. return false;
  235090. bool isKey = false, isInputAttempt = false;
  235091. switch ([e type])
  235092. {
  235093. case NSKeyDown:
  235094. case NSKeyUp:
  235095. isKey = isInputAttempt = true;
  235096. break;
  235097. case NSLeftMouseDown:
  235098. case NSRightMouseDown:
  235099. case NSOtherMouseDown:
  235100. isInputAttempt = true;
  235101. break;
  235102. case NSLeftMouseDragged:
  235103. case NSRightMouseDragged:
  235104. case NSLeftMouseUp:
  235105. case NSRightMouseUp:
  235106. case NSOtherMouseUp:
  235107. case NSOtherMouseDragged:
  235108. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  235109. return false;
  235110. break;
  235111. case NSMouseMoved:
  235112. case NSMouseEntered:
  235113. case NSMouseExited:
  235114. case NSCursorUpdate:
  235115. case NSScrollWheel:
  235116. case NSTabletPoint:
  235117. case NSTabletProximity:
  235118. break;
  235119. default:
  235120. return false;
  235121. }
  235122. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  235123. {
  235124. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  235125. NSView* const compView = (NSView*) peer->getNativeHandle();
  235126. if ([compView window] == w)
  235127. {
  235128. if (isKey)
  235129. {
  235130. if (compView == [w firstResponder])
  235131. return false;
  235132. }
  235133. else
  235134. {
  235135. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  235136. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  235137. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  235138. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  235139. return false;
  235140. }
  235141. }
  235142. }
  235143. if (isInputAttempt)
  235144. {
  235145. if (! [NSApp isActive])
  235146. [NSApp activateIgnoringOtherApps: YES];
  235147. Component* const modal = Component::getCurrentlyModalComponent (0);
  235148. if (modal != 0)
  235149. modal->inputAttemptWhenModal();
  235150. }
  235151. return true;
  235152. }
  235153. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  235154. {
  235155. jassert (isThisTheMessageThread()); // must only be called by the message thread
  235156. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  235157. while (! quitMessagePosted)
  235158. {
  235159. const ScopedAutoReleasePool pool;
  235160. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  235161. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  235162. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  235163. inMode: NSDefaultRunLoopMode
  235164. dequeue: YES];
  235165. if (e != 0 && ! isEventBlockedByModalComps (e))
  235166. [NSApp sendEvent: e];
  235167. if (Time::getMillisecondCounter() >= endTime)
  235168. break;
  235169. }
  235170. return ! quitMessagePosted;
  235171. }
  235172. void MessageManager::doPlatformSpecificInitialisation()
  235173. {
  235174. if (juceAppDelegate == 0)
  235175. juceAppDelegate = [[JuceAppDelegate alloc] init];
  235176. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  235177. // correctly (needed prior to 10.5)
  235178. if (! [NSThread isMultiThreaded])
  235179. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  235180. toTarget: juceAppDelegate
  235181. withObject: nil];
  235182. }
  235183. void MessageManager::doPlatformSpecificShutdown()
  235184. {
  235185. if (juceAppDelegate != 0)
  235186. {
  235187. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  235188. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  235189. [juceAppDelegate release];
  235190. juceAppDelegate = 0;
  235191. }
  235192. }
  235193. bool juce_postMessageToSystemQueue (Message* message)
  235194. {
  235195. juceAppDelegate->redirector->postMessage (message);
  235196. return true;
  235197. }
  235198. void MessageManager::broadcastMessage (const String& value)
  235199. {
  235200. }
  235201. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  235202. {
  235203. if (isThisTheMessageThread())
  235204. {
  235205. return (*callback) (data);
  235206. }
  235207. else
  235208. {
  235209. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  235210. // deadlock because the message manager is blocked from running, so can never
  235211. // call your function..
  235212. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  235213. const ScopedAutoReleasePool pool;
  235214. AppDelegateRedirector::CallbackMessagePayload cmp;
  235215. cmp.function = callback;
  235216. cmp.parameter = data;
  235217. cmp.result = 0;
  235218. cmp.hasBeenExecuted = false;
  235219. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  235220. withObject: [NSData dataWithBytesNoCopy: &cmp
  235221. length: sizeof (cmp)
  235222. freeWhenDone: NO]
  235223. waitUntilDone: YES];
  235224. return cmp.result;
  235225. }
  235226. }
  235227. #endif
  235228. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  235229. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235230. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235231. // compiled on its own).
  235232. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  235233. #if JUCE_MAC
  235234. END_JUCE_NAMESPACE
  235235. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  235236. @interface DownloadClickDetector : NSObject
  235237. {
  235238. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  235239. }
  235240. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  235241. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235242. request: (NSURLRequest*) request
  235243. frame: (WebFrame*) frame
  235244. decisionListener: (id<WebPolicyDecisionListener>) listener;
  235245. @end
  235246. @implementation DownloadClickDetector
  235247. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  235248. {
  235249. [super init];
  235250. ownerComponent = ownerComponent_;
  235251. return self;
  235252. }
  235253. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235254. request: (NSURLRequest*) request
  235255. frame: (WebFrame*) frame
  235256. decisionListener: (id <WebPolicyDecisionListener>) listener
  235257. {
  235258. (void) sender;
  235259. (void) request;
  235260. (void) frame;
  235261. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235262. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235263. [listener use];
  235264. else
  235265. [listener ignore];
  235266. }
  235267. @end
  235268. BEGIN_JUCE_NAMESPACE
  235269. class WebBrowserComponentInternal : public NSViewComponent
  235270. {
  235271. public:
  235272. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235273. {
  235274. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235275. frameName: @""
  235276. groupName: @""];
  235277. setView (webView);
  235278. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235279. [webView setPolicyDelegate: clickListener];
  235280. }
  235281. ~WebBrowserComponentInternal()
  235282. {
  235283. [webView setPolicyDelegate: nil];
  235284. [clickListener release];
  235285. setView (0);
  235286. }
  235287. void goToURL (const String& url,
  235288. const StringArray* headers,
  235289. const MemoryBlock* postData)
  235290. {
  235291. NSMutableURLRequest* r
  235292. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235293. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235294. timeoutInterval: 30.0];
  235295. if (postData != 0 && postData->getSize() > 0)
  235296. {
  235297. [r setHTTPMethod: @"POST"];
  235298. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235299. length: postData->getSize()]];
  235300. }
  235301. if (headers != 0)
  235302. {
  235303. for (int i = 0; i < headers->size(); ++i)
  235304. {
  235305. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235306. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235307. [r setValue: juceStringToNS (headerValue)
  235308. forHTTPHeaderField: juceStringToNS (headerName)];
  235309. }
  235310. }
  235311. stop();
  235312. [[webView mainFrame] loadRequest: r];
  235313. }
  235314. void goBack()
  235315. {
  235316. [webView goBack];
  235317. }
  235318. void goForward()
  235319. {
  235320. [webView goForward];
  235321. }
  235322. void stop()
  235323. {
  235324. [webView stopLoading: nil];
  235325. }
  235326. void refresh()
  235327. {
  235328. [webView reload: nil];
  235329. }
  235330. private:
  235331. WebView* webView;
  235332. DownloadClickDetector* clickListener;
  235333. };
  235334. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235335. : browser (0),
  235336. blankPageShown (false),
  235337. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235338. {
  235339. setOpaque (true);
  235340. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235341. }
  235342. WebBrowserComponent::~WebBrowserComponent()
  235343. {
  235344. deleteAndZero (browser);
  235345. }
  235346. void WebBrowserComponent::goToURL (const String& url,
  235347. const StringArray* headers,
  235348. const MemoryBlock* postData)
  235349. {
  235350. lastURL = url;
  235351. lastHeaders.clear();
  235352. if (headers != 0)
  235353. lastHeaders = *headers;
  235354. lastPostData.setSize (0);
  235355. if (postData != 0)
  235356. lastPostData = *postData;
  235357. blankPageShown = false;
  235358. browser->goToURL (url, headers, postData);
  235359. }
  235360. void WebBrowserComponent::stop()
  235361. {
  235362. browser->stop();
  235363. }
  235364. void WebBrowserComponent::goBack()
  235365. {
  235366. lastURL = String::empty;
  235367. blankPageShown = false;
  235368. browser->goBack();
  235369. }
  235370. void WebBrowserComponent::goForward()
  235371. {
  235372. lastURL = String::empty;
  235373. browser->goForward();
  235374. }
  235375. void WebBrowserComponent::refresh()
  235376. {
  235377. browser->refresh();
  235378. }
  235379. void WebBrowserComponent::paint (Graphics&)
  235380. {
  235381. }
  235382. void WebBrowserComponent::checkWindowAssociation()
  235383. {
  235384. if (isShowing())
  235385. {
  235386. if (blankPageShown)
  235387. goBack();
  235388. }
  235389. else
  235390. {
  235391. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235392. {
  235393. // when the component becomes invisible, some stuff like flash
  235394. // carries on playing audio, so we need to force it onto a blank
  235395. // page to avoid this, (and send it back when it's made visible again).
  235396. blankPageShown = true;
  235397. browser->goToURL ("about:blank", 0, 0);
  235398. }
  235399. }
  235400. }
  235401. void WebBrowserComponent::reloadLastURL()
  235402. {
  235403. if (lastURL.isNotEmpty())
  235404. {
  235405. goToURL (lastURL, &lastHeaders, &lastPostData);
  235406. lastURL = String::empty;
  235407. }
  235408. }
  235409. void WebBrowserComponent::parentHierarchyChanged()
  235410. {
  235411. checkWindowAssociation();
  235412. }
  235413. void WebBrowserComponent::resized()
  235414. {
  235415. browser->setSize (getWidth(), getHeight());
  235416. }
  235417. void WebBrowserComponent::visibilityChanged()
  235418. {
  235419. checkWindowAssociation();
  235420. }
  235421. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235422. {
  235423. return true;
  235424. }
  235425. #else
  235426. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235427. {
  235428. }
  235429. WebBrowserComponent::~WebBrowserComponent()
  235430. {
  235431. }
  235432. void WebBrowserComponent::goToURL (const String& url,
  235433. const StringArray* headers,
  235434. const MemoryBlock* postData)
  235435. {
  235436. }
  235437. void WebBrowserComponent::stop()
  235438. {
  235439. }
  235440. void WebBrowserComponent::goBack()
  235441. {
  235442. }
  235443. void WebBrowserComponent::goForward()
  235444. {
  235445. }
  235446. void WebBrowserComponent::refresh()
  235447. {
  235448. }
  235449. void WebBrowserComponent::paint (Graphics& g)
  235450. {
  235451. }
  235452. void WebBrowserComponent::checkWindowAssociation()
  235453. {
  235454. }
  235455. void WebBrowserComponent::reloadLastURL()
  235456. {
  235457. }
  235458. void WebBrowserComponent::parentHierarchyChanged()
  235459. {
  235460. }
  235461. void WebBrowserComponent::resized()
  235462. {
  235463. }
  235464. void WebBrowserComponent::visibilityChanged()
  235465. {
  235466. }
  235467. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235468. {
  235469. return true;
  235470. }
  235471. #endif
  235472. #endif
  235473. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235474. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235475. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235476. // compiled on its own).
  235477. #if JUCE_INCLUDED_FILE
  235478. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235479. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235480. #endif
  235481. #undef log
  235482. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235483. #define log(a) Logger::writeToLog (a)
  235484. #else
  235485. #define log(a)
  235486. #endif
  235487. #undef OK
  235488. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235489. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235490. {
  235491. if (err == noErr)
  235492. return true;
  235493. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235494. jassertfalse;
  235495. return false;
  235496. }
  235497. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235498. #else
  235499. #define OK(a) (a == noErr)
  235500. #endif
  235501. class CoreAudioInternal : public Timer
  235502. {
  235503. public:
  235504. CoreAudioInternal (AudioDeviceID id)
  235505. : inputLatency (0),
  235506. outputLatency (0),
  235507. callback (0),
  235508. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235509. audioProcID (0),
  235510. #endif
  235511. isSlaveDevice (false),
  235512. deviceID (id),
  235513. started (false),
  235514. sampleRate (0),
  235515. bufferSize (512),
  235516. numInputChans (0),
  235517. numOutputChans (0),
  235518. callbacksAllowed (true),
  235519. numInputChannelInfos (0),
  235520. numOutputChannelInfos (0)
  235521. {
  235522. jassert (deviceID != 0);
  235523. updateDetailsFromDevice();
  235524. AudioObjectPropertyAddress pa;
  235525. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235526. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235527. pa.mElement = kAudioObjectPropertyElementWildcard;
  235528. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235529. }
  235530. ~CoreAudioInternal()
  235531. {
  235532. AudioObjectPropertyAddress pa;
  235533. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235534. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235535. pa.mElement = kAudioObjectPropertyElementWildcard;
  235536. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235537. stop (false);
  235538. }
  235539. void allocateTempBuffers()
  235540. {
  235541. const int tempBufSize = bufferSize + 4;
  235542. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235543. tempInputBuffers.calloc (numInputChans + 2);
  235544. tempOutputBuffers.calloc (numOutputChans + 2);
  235545. int i, count = 0;
  235546. for (i = 0; i < numInputChans; ++i)
  235547. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235548. for (i = 0; i < numOutputChans; ++i)
  235549. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235550. }
  235551. // returns the number of actual available channels
  235552. void fillInChannelInfo (const bool input)
  235553. {
  235554. int chanNum = 0;
  235555. UInt32 size;
  235556. AudioObjectPropertyAddress pa;
  235557. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235558. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235559. pa.mElement = kAudioObjectPropertyElementMaster;
  235560. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235561. {
  235562. HeapBlock <AudioBufferList> bufList;
  235563. bufList.calloc (size, 1);
  235564. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235565. {
  235566. const int numStreams = bufList->mNumberBuffers;
  235567. for (int i = 0; i < numStreams; ++i)
  235568. {
  235569. const AudioBuffer& b = bufList->mBuffers[i];
  235570. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235571. {
  235572. String name;
  235573. {
  235574. char channelName [256];
  235575. zerostruct (channelName);
  235576. UInt32 nameSize = sizeof (channelName);
  235577. UInt32 channelNum = chanNum + 1;
  235578. pa.mSelector = kAudioDevicePropertyChannelName;
  235579. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235580. name = String::fromUTF8 (channelName, nameSize);
  235581. }
  235582. if (input)
  235583. {
  235584. if (activeInputChans[chanNum])
  235585. {
  235586. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235587. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235588. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235589. ++numInputChannelInfos;
  235590. }
  235591. if (name.isEmpty())
  235592. name << "Input " << (chanNum + 1);
  235593. inChanNames.add (name);
  235594. }
  235595. else
  235596. {
  235597. if (activeOutputChans[chanNum])
  235598. {
  235599. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235600. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235601. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235602. ++numOutputChannelInfos;
  235603. }
  235604. if (name.isEmpty())
  235605. name << "Output " << (chanNum + 1);
  235606. outChanNames.add (name);
  235607. }
  235608. ++chanNum;
  235609. }
  235610. }
  235611. }
  235612. }
  235613. }
  235614. void updateDetailsFromDevice()
  235615. {
  235616. stopTimer();
  235617. if (deviceID == 0)
  235618. return;
  235619. const ScopedLock sl (callbackLock);
  235620. Float64 sr;
  235621. UInt32 size = sizeof (Float64);
  235622. AudioObjectPropertyAddress pa;
  235623. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235624. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235625. pa.mElement = kAudioObjectPropertyElementMaster;
  235626. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235627. sampleRate = sr;
  235628. UInt32 framesPerBuf;
  235629. size = sizeof (framesPerBuf);
  235630. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235631. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235632. {
  235633. bufferSize = framesPerBuf;
  235634. allocateTempBuffers();
  235635. }
  235636. bufferSizes.clear();
  235637. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235638. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235639. {
  235640. HeapBlock <AudioValueRange> ranges;
  235641. ranges.calloc (size, 1);
  235642. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235643. {
  235644. bufferSizes.add ((int) ranges[0].mMinimum);
  235645. for (int i = 32; i < 2048; i += 32)
  235646. {
  235647. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235648. {
  235649. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235650. {
  235651. bufferSizes.addIfNotAlreadyThere (i);
  235652. break;
  235653. }
  235654. }
  235655. }
  235656. if (bufferSize > 0)
  235657. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235658. }
  235659. }
  235660. if (bufferSizes.size() == 0 && bufferSize > 0)
  235661. bufferSizes.add (bufferSize);
  235662. sampleRates.clear();
  235663. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235664. String rates;
  235665. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235666. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235667. {
  235668. HeapBlock <AudioValueRange> ranges;
  235669. ranges.calloc (size, 1);
  235670. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235671. {
  235672. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235673. {
  235674. bool ok = false;
  235675. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235676. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235677. ok = true;
  235678. if (ok)
  235679. {
  235680. sampleRates.add (possibleRates[i]);
  235681. rates << possibleRates[i] << ' ';
  235682. }
  235683. }
  235684. }
  235685. }
  235686. if (sampleRates.size() == 0 && sampleRate > 0)
  235687. {
  235688. sampleRates.add (sampleRate);
  235689. rates << sampleRate;
  235690. }
  235691. log ("sr: " + rates);
  235692. inputLatency = 0;
  235693. outputLatency = 0;
  235694. UInt32 lat;
  235695. size = sizeof (lat);
  235696. pa.mSelector = kAudioDevicePropertyLatency;
  235697. pa.mScope = kAudioDevicePropertyScopeInput;
  235698. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  235699. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235700. inputLatency = (int) lat;
  235701. pa.mScope = kAudioDevicePropertyScopeOutput;
  235702. size = sizeof (lat);
  235703. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235704. outputLatency = (int) lat;
  235705. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235706. inChanNames.clear();
  235707. outChanNames.clear();
  235708. inputChannelInfo.calloc (numInputChans + 2);
  235709. numInputChannelInfos = 0;
  235710. outputChannelInfo.calloc (numOutputChans + 2);
  235711. numOutputChannelInfos = 0;
  235712. fillInChannelInfo (true);
  235713. fillInChannelInfo (false);
  235714. }
  235715. const StringArray getSources (bool input)
  235716. {
  235717. StringArray s;
  235718. HeapBlock <OSType> types;
  235719. const int num = getAllDataSourcesForDevice (deviceID, types);
  235720. for (int i = 0; i < num; ++i)
  235721. {
  235722. AudioValueTranslation avt;
  235723. char buffer[256];
  235724. avt.mInputData = &(types[i]);
  235725. avt.mInputDataSize = sizeof (UInt32);
  235726. avt.mOutputData = buffer;
  235727. avt.mOutputDataSize = 256;
  235728. UInt32 transSize = sizeof (avt);
  235729. AudioObjectPropertyAddress pa;
  235730. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235731. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235732. pa.mElement = kAudioObjectPropertyElementMaster;
  235733. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235734. {
  235735. DBG (buffer);
  235736. s.add (buffer);
  235737. }
  235738. }
  235739. return s;
  235740. }
  235741. int getCurrentSourceIndex (bool input) const
  235742. {
  235743. OSType currentSourceID = 0;
  235744. UInt32 size = sizeof (currentSourceID);
  235745. int result = -1;
  235746. AudioObjectPropertyAddress pa;
  235747. pa.mSelector = kAudioDevicePropertyDataSource;
  235748. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235749. pa.mElement = kAudioObjectPropertyElementMaster;
  235750. if (deviceID != 0)
  235751. {
  235752. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235753. {
  235754. HeapBlock <OSType> types;
  235755. const int num = getAllDataSourcesForDevice (deviceID, types);
  235756. for (int i = 0; i < num; ++i)
  235757. {
  235758. if (types[num] == currentSourceID)
  235759. {
  235760. result = i;
  235761. break;
  235762. }
  235763. }
  235764. }
  235765. }
  235766. return result;
  235767. }
  235768. void setCurrentSourceIndex (int index, bool input)
  235769. {
  235770. if (deviceID != 0)
  235771. {
  235772. HeapBlock <OSType> types;
  235773. const int num = getAllDataSourcesForDevice (deviceID, types);
  235774. if (((unsigned int) index) < (unsigned int) num)
  235775. {
  235776. AudioObjectPropertyAddress pa;
  235777. pa.mSelector = kAudioDevicePropertyDataSource;
  235778. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235779. pa.mElement = kAudioObjectPropertyElementMaster;
  235780. OSType typeId = types[index];
  235781. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235782. }
  235783. }
  235784. }
  235785. const String reopen (const BigInteger& inputChannels,
  235786. const BigInteger& outputChannels,
  235787. double newSampleRate,
  235788. int bufferSizeSamples)
  235789. {
  235790. String error;
  235791. log ("CoreAudio reopen");
  235792. callbacksAllowed = false;
  235793. stopTimer();
  235794. stop (false);
  235795. activeInputChans = inputChannels;
  235796. activeInputChans.setRange (inChanNames.size(),
  235797. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235798. false);
  235799. activeOutputChans = outputChannels;
  235800. activeOutputChans.setRange (outChanNames.size(),
  235801. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235802. false);
  235803. numInputChans = activeInputChans.countNumberOfSetBits();
  235804. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235805. // set sample rate
  235806. AudioObjectPropertyAddress pa;
  235807. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235808. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235809. pa.mElement = kAudioObjectPropertyElementMaster;
  235810. Float64 sr = newSampleRate;
  235811. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235812. {
  235813. error = "Couldn't change sample rate";
  235814. }
  235815. else
  235816. {
  235817. // change buffer size
  235818. UInt32 framesPerBuf = bufferSizeSamples;
  235819. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235820. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235821. {
  235822. error = "Couldn't change buffer size";
  235823. }
  235824. else
  235825. {
  235826. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235827. // correctly report their new settings until some random time in the future, so
  235828. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235829. // to make sure we're using the correct numbers..
  235830. updateDetailsFromDevice();
  235831. sampleRate = newSampleRate;
  235832. bufferSize = bufferSizeSamples;
  235833. if (sampleRates.size() == 0)
  235834. error = "Device has no available sample-rates";
  235835. else if (bufferSizes.size() == 0)
  235836. error = "Device has no available buffer-sizes";
  235837. else if (inputDevice != 0)
  235838. error = inputDevice->reopen (inputChannels,
  235839. outputChannels,
  235840. newSampleRate,
  235841. bufferSizeSamples);
  235842. }
  235843. }
  235844. callbacksAllowed = true;
  235845. return error;
  235846. }
  235847. bool start (AudioIODeviceCallback* cb)
  235848. {
  235849. if (! started)
  235850. {
  235851. callback = 0;
  235852. if (deviceID != 0)
  235853. {
  235854. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235855. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235856. #else
  235857. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235858. #endif
  235859. {
  235860. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235861. {
  235862. started = true;
  235863. }
  235864. else
  235865. {
  235866. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235867. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235868. #else
  235869. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235870. audioProcID = 0;
  235871. #endif
  235872. }
  235873. }
  235874. }
  235875. }
  235876. if (started)
  235877. {
  235878. const ScopedLock sl (callbackLock);
  235879. callback = cb;
  235880. }
  235881. if (inputDevice != 0)
  235882. return started && inputDevice->start (cb);
  235883. else
  235884. return started;
  235885. }
  235886. void stop (bool leaveInterruptRunning)
  235887. {
  235888. {
  235889. const ScopedLock sl (callbackLock);
  235890. callback = 0;
  235891. }
  235892. if (started
  235893. && (deviceID != 0)
  235894. && ! leaveInterruptRunning)
  235895. {
  235896. OK (AudioDeviceStop (deviceID, audioIOProc));
  235897. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235898. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235899. #else
  235900. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235901. audioProcID = 0;
  235902. #endif
  235903. started = false;
  235904. { const ScopedLock sl (callbackLock); }
  235905. // wait until it's definately stopped calling back..
  235906. for (int i = 40; --i >= 0;)
  235907. {
  235908. Thread::sleep (50);
  235909. UInt32 running = 0;
  235910. UInt32 size = sizeof (running);
  235911. AudioObjectPropertyAddress pa;
  235912. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235913. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235914. pa.mElement = kAudioObjectPropertyElementMaster;
  235915. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235916. if (running == 0)
  235917. break;
  235918. }
  235919. const ScopedLock sl (callbackLock);
  235920. }
  235921. if (inputDevice != 0)
  235922. inputDevice->stop (leaveInterruptRunning);
  235923. }
  235924. double getSampleRate() const
  235925. {
  235926. return sampleRate;
  235927. }
  235928. int getBufferSize() const
  235929. {
  235930. return bufferSize;
  235931. }
  235932. void audioCallback (const AudioBufferList* inInputData,
  235933. AudioBufferList* outOutputData)
  235934. {
  235935. int i;
  235936. const ScopedLock sl (callbackLock);
  235937. if (callback != 0)
  235938. {
  235939. if (inputDevice == 0)
  235940. {
  235941. for (i = numInputChans; --i >= 0;)
  235942. {
  235943. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235944. float* dest = tempInputBuffers [i];
  235945. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235946. + info.dataOffsetSamples;
  235947. const int stride = info.dataStrideSamples;
  235948. if (stride != 0) // if this is zero, info is invalid
  235949. {
  235950. for (int j = bufferSize; --j >= 0;)
  235951. {
  235952. *dest++ = *src;
  235953. src += stride;
  235954. }
  235955. }
  235956. }
  235957. }
  235958. if (! isSlaveDevice)
  235959. {
  235960. if (inputDevice == 0)
  235961. {
  235962. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235963. numInputChans,
  235964. tempOutputBuffers,
  235965. numOutputChans,
  235966. bufferSize);
  235967. }
  235968. else
  235969. {
  235970. jassert (inputDevice->bufferSize == bufferSize);
  235971. // Sometimes the two linked devices seem to get their callbacks in
  235972. // parallel, so we need to lock both devices to stop the input data being
  235973. // changed while inside our callback..
  235974. const ScopedLock sl2 (inputDevice->callbackLock);
  235975. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235976. inputDevice->numInputChans,
  235977. tempOutputBuffers,
  235978. numOutputChans,
  235979. bufferSize);
  235980. }
  235981. for (i = numOutputChans; --i >= 0;)
  235982. {
  235983. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235984. const float* src = tempOutputBuffers [i];
  235985. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235986. + info.dataOffsetSamples;
  235987. const int stride = info.dataStrideSamples;
  235988. if (stride != 0) // if this is zero, info is invalid
  235989. {
  235990. for (int j = bufferSize; --j >= 0;)
  235991. {
  235992. *dest = *src++;
  235993. dest += stride;
  235994. }
  235995. }
  235996. }
  235997. }
  235998. }
  235999. else
  236000. {
  236001. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  236002. {
  236003. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236004. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236005. + info.dataOffsetSamples;
  236006. const int stride = info.dataStrideSamples;
  236007. if (stride != 0) // if this is zero, info is invalid
  236008. {
  236009. for (int j = bufferSize; --j >= 0;)
  236010. {
  236011. *dest = 0.0f;
  236012. dest += stride;
  236013. }
  236014. }
  236015. }
  236016. }
  236017. }
  236018. // called by callbacks
  236019. void deviceDetailsChanged()
  236020. {
  236021. if (callbacksAllowed)
  236022. startTimer (100);
  236023. }
  236024. void timerCallback()
  236025. {
  236026. stopTimer();
  236027. log ("CoreAudio device changed callback");
  236028. const double oldSampleRate = sampleRate;
  236029. const int oldBufferSize = bufferSize;
  236030. updateDetailsFromDevice();
  236031. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  236032. {
  236033. callbacksAllowed = false;
  236034. stop (false);
  236035. updateDetailsFromDevice();
  236036. callbacksAllowed = true;
  236037. }
  236038. }
  236039. CoreAudioInternal* getRelatedDevice() const
  236040. {
  236041. UInt32 size = 0;
  236042. ScopedPointer <CoreAudioInternal> result;
  236043. AudioObjectPropertyAddress pa;
  236044. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  236045. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236046. pa.mElement = kAudioObjectPropertyElementMaster;
  236047. if (deviceID != 0
  236048. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  236049. && size > 0)
  236050. {
  236051. HeapBlock <AudioDeviceID> devs;
  236052. devs.calloc (size, 1);
  236053. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  236054. {
  236055. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  236056. {
  236057. if (devs[i] != deviceID && devs[i] != 0)
  236058. {
  236059. result = new CoreAudioInternal (devs[i]);
  236060. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  236061. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  236062. if (thisIsInput != otherIsInput
  236063. || (inChanNames.size() + outChanNames.size() == 0)
  236064. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  236065. break;
  236066. result = 0;
  236067. }
  236068. }
  236069. }
  236070. }
  236071. return result.release();
  236072. }
  236073. juce_UseDebuggingNewOperator
  236074. int inputLatency, outputLatency;
  236075. BigInteger activeInputChans, activeOutputChans;
  236076. StringArray inChanNames, outChanNames;
  236077. Array <double> sampleRates;
  236078. Array <int> bufferSizes;
  236079. AudioIODeviceCallback* callback;
  236080. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  236081. AudioDeviceIOProcID audioProcID;
  236082. #endif
  236083. ScopedPointer<CoreAudioInternal> inputDevice;
  236084. bool isSlaveDevice;
  236085. private:
  236086. CriticalSection callbackLock;
  236087. AudioDeviceID deviceID;
  236088. bool started;
  236089. double sampleRate;
  236090. int bufferSize;
  236091. HeapBlock <float> audioBuffer;
  236092. int numInputChans, numOutputChans;
  236093. bool callbacksAllowed;
  236094. struct CallbackDetailsForChannel
  236095. {
  236096. int streamNum;
  236097. int dataOffsetSamples;
  236098. int dataStrideSamples;
  236099. };
  236100. int numInputChannelInfos, numOutputChannelInfos;
  236101. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  236102. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  236103. CoreAudioInternal (const CoreAudioInternal&);
  236104. CoreAudioInternal& operator= (const CoreAudioInternal&);
  236105. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  236106. const AudioTimeStamp* /*inNow*/,
  236107. const AudioBufferList* inInputData,
  236108. const AudioTimeStamp* /*inInputTime*/,
  236109. AudioBufferList* outOutputData,
  236110. const AudioTimeStamp* /*inOutputTime*/,
  236111. void* device)
  236112. {
  236113. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  236114. return noErr;
  236115. }
  236116. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236117. {
  236118. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236119. switch (pa->mSelector)
  236120. {
  236121. case kAudioDevicePropertyBufferSize:
  236122. case kAudioDevicePropertyBufferFrameSize:
  236123. case kAudioDevicePropertyNominalSampleRate:
  236124. case kAudioDevicePropertyStreamFormat:
  236125. case kAudioDevicePropertyDeviceIsAlive:
  236126. intern->deviceDetailsChanged();
  236127. break;
  236128. case kAudioDevicePropertyBufferSizeRange:
  236129. case kAudioDevicePropertyVolumeScalar:
  236130. case kAudioDevicePropertyMute:
  236131. case kAudioDevicePropertyPlayThru:
  236132. case kAudioDevicePropertyDataSource:
  236133. case kAudioDevicePropertyDeviceIsRunning:
  236134. break;
  236135. }
  236136. return noErr;
  236137. }
  236138. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  236139. {
  236140. AudioObjectPropertyAddress pa;
  236141. pa.mSelector = kAudioDevicePropertyDataSources;
  236142. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236143. pa.mElement = kAudioObjectPropertyElementMaster;
  236144. UInt32 size = 0;
  236145. if (deviceID != 0
  236146. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236147. {
  236148. types.calloc (size, 1);
  236149. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  236150. return size / (int) sizeof (OSType);
  236151. }
  236152. return 0;
  236153. }
  236154. };
  236155. class CoreAudioIODevice : public AudioIODevice
  236156. {
  236157. public:
  236158. CoreAudioIODevice (const String& deviceName,
  236159. AudioDeviceID inputDeviceId,
  236160. const int inputIndex_,
  236161. AudioDeviceID outputDeviceId,
  236162. const int outputIndex_)
  236163. : AudioIODevice (deviceName, "CoreAudio"),
  236164. inputIndex (inputIndex_),
  236165. outputIndex (outputIndex_),
  236166. isOpen_ (false),
  236167. isStarted (false)
  236168. {
  236169. CoreAudioInternal* device = 0;
  236170. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  236171. {
  236172. jassert (inputDeviceId != 0);
  236173. device = new CoreAudioInternal (inputDeviceId);
  236174. }
  236175. else
  236176. {
  236177. device = new CoreAudioInternal (outputDeviceId);
  236178. if (inputDeviceId != 0)
  236179. {
  236180. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  236181. device->inputDevice = secondDevice;
  236182. secondDevice->isSlaveDevice = true;
  236183. }
  236184. }
  236185. internal = device;
  236186. AudioObjectPropertyAddress pa;
  236187. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236188. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236189. pa.mElement = kAudioObjectPropertyElementWildcard;
  236190. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236191. }
  236192. ~CoreAudioIODevice()
  236193. {
  236194. AudioObjectPropertyAddress pa;
  236195. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236196. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236197. pa.mElement = kAudioObjectPropertyElementWildcard;
  236198. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236199. }
  236200. const StringArray getOutputChannelNames()
  236201. {
  236202. return internal->outChanNames;
  236203. }
  236204. const StringArray getInputChannelNames()
  236205. {
  236206. if (internal->inputDevice != 0)
  236207. return internal->inputDevice->inChanNames;
  236208. else
  236209. return internal->inChanNames;
  236210. }
  236211. int getNumSampleRates()
  236212. {
  236213. return internal->sampleRates.size();
  236214. }
  236215. double getSampleRate (int index)
  236216. {
  236217. return internal->sampleRates [index];
  236218. }
  236219. int getNumBufferSizesAvailable()
  236220. {
  236221. return internal->bufferSizes.size();
  236222. }
  236223. int getBufferSizeSamples (int index)
  236224. {
  236225. return internal->bufferSizes [index];
  236226. }
  236227. int getDefaultBufferSize()
  236228. {
  236229. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  236230. if (getBufferSizeSamples(i) >= 512)
  236231. return getBufferSizeSamples(i);
  236232. return 512;
  236233. }
  236234. const String open (const BigInteger& inputChannels,
  236235. const BigInteger& outputChannels,
  236236. double sampleRate,
  236237. int bufferSizeSamples)
  236238. {
  236239. isOpen_ = true;
  236240. if (bufferSizeSamples <= 0)
  236241. bufferSizeSamples = getDefaultBufferSize();
  236242. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  236243. isOpen_ = lastError.isEmpty();
  236244. return lastError;
  236245. }
  236246. void close()
  236247. {
  236248. isOpen_ = false;
  236249. internal->stop (false);
  236250. }
  236251. bool isOpen()
  236252. {
  236253. return isOpen_;
  236254. }
  236255. int getCurrentBufferSizeSamples()
  236256. {
  236257. return internal != 0 ? internal->getBufferSize() : 512;
  236258. }
  236259. double getCurrentSampleRate()
  236260. {
  236261. return internal != 0 ? internal->getSampleRate() : 0;
  236262. }
  236263. int getCurrentBitDepth()
  236264. {
  236265. return 32; // no way to find out, so just assume it's high..
  236266. }
  236267. const BigInteger getActiveOutputChannels() const
  236268. {
  236269. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236270. }
  236271. const BigInteger getActiveInputChannels() const
  236272. {
  236273. BigInteger chans;
  236274. if (internal != 0)
  236275. {
  236276. chans = internal->activeInputChans;
  236277. if (internal->inputDevice != 0)
  236278. chans |= internal->inputDevice->activeInputChans;
  236279. }
  236280. return chans;
  236281. }
  236282. int getOutputLatencyInSamples()
  236283. {
  236284. if (internal == 0)
  236285. return 0;
  236286. // this seems like a good guess at getting the latency right - comparing
  236287. // this with a round-trip measurement, it gets it to within a few millisecs
  236288. // for the built-in mac soundcard
  236289. return internal->outputLatency + internal->getBufferSize() * 2;
  236290. }
  236291. int getInputLatencyInSamples()
  236292. {
  236293. if (internal == 0)
  236294. return 0;
  236295. return internal->inputLatency + internal->getBufferSize() * 2;
  236296. }
  236297. void start (AudioIODeviceCallback* callback)
  236298. {
  236299. if (internal != 0 && ! isStarted)
  236300. {
  236301. if (callback != 0)
  236302. callback->audioDeviceAboutToStart (this);
  236303. isStarted = true;
  236304. internal->start (callback);
  236305. }
  236306. }
  236307. void stop()
  236308. {
  236309. if (isStarted && internal != 0)
  236310. {
  236311. AudioIODeviceCallback* const lastCallback = internal->callback;
  236312. isStarted = false;
  236313. internal->stop (true);
  236314. if (lastCallback != 0)
  236315. lastCallback->audioDeviceStopped();
  236316. }
  236317. }
  236318. bool isPlaying()
  236319. {
  236320. if (internal->callback == 0)
  236321. isStarted = false;
  236322. return isStarted;
  236323. }
  236324. const String getLastError()
  236325. {
  236326. return lastError;
  236327. }
  236328. int inputIndex, outputIndex;
  236329. juce_UseDebuggingNewOperator
  236330. private:
  236331. ScopedPointer<CoreAudioInternal> internal;
  236332. bool isOpen_, isStarted;
  236333. String lastError;
  236334. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236335. {
  236336. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236337. switch (pa->mSelector)
  236338. {
  236339. case kAudioHardwarePropertyDevices:
  236340. intern->deviceDetailsChanged();
  236341. break;
  236342. case kAudioHardwarePropertyDefaultOutputDevice:
  236343. case kAudioHardwarePropertyDefaultInputDevice:
  236344. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236345. break;
  236346. }
  236347. return noErr;
  236348. }
  236349. CoreAudioIODevice (const CoreAudioIODevice&);
  236350. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236351. };
  236352. class CoreAudioIODeviceType : public AudioIODeviceType
  236353. {
  236354. public:
  236355. CoreAudioIODeviceType()
  236356. : AudioIODeviceType ("CoreAudio"),
  236357. hasScanned (false)
  236358. {
  236359. }
  236360. ~CoreAudioIODeviceType()
  236361. {
  236362. }
  236363. void scanForDevices()
  236364. {
  236365. hasScanned = true;
  236366. inputDeviceNames.clear();
  236367. outputDeviceNames.clear();
  236368. inputIds.clear();
  236369. outputIds.clear();
  236370. UInt32 size;
  236371. AudioObjectPropertyAddress pa;
  236372. pa.mSelector = kAudioHardwarePropertyDevices;
  236373. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236374. pa.mElement = kAudioObjectPropertyElementMaster;
  236375. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236376. {
  236377. HeapBlock <AudioDeviceID> devs;
  236378. devs.calloc (size, 1);
  236379. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236380. {
  236381. const int num = size / (int) sizeof (AudioDeviceID);
  236382. for (int i = 0; i < num; ++i)
  236383. {
  236384. char name [1024];
  236385. size = sizeof (name);
  236386. pa.mSelector = kAudioDevicePropertyDeviceName;
  236387. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236388. {
  236389. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236390. const int numIns = getNumChannels (devs[i], true);
  236391. const int numOuts = getNumChannels (devs[i], false);
  236392. if (numIns > 0)
  236393. {
  236394. inputDeviceNames.add (nameString);
  236395. inputIds.add (devs[i]);
  236396. }
  236397. if (numOuts > 0)
  236398. {
  236399. outputDeviceNames.add (nameString);
  236400. outputIds.add (devs[i]);
  236401. }
  236402. }
  236403. }
  236404. }
  236405. }
  236406. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236407. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236408. }
  236409. const StringArray getDeviceNames (bool wantInputNames) const
  236410. {
  236411. jassert (hasScanned); // need to call scanForDevices() before doing this
  236412. if (wantInputNames)
  236413. return inputDeviceNames;
  236414. else
  236415. return outputDeviceNames;
  236416. }
  236417. int getDefaultDeviceIndex (bool forInput) const
  236418. {
  236419. jassert (hasScanned); // need to call scanForDevices() before doing this
  236420. AudioDeviceID deviceID;
  236421. UInt32 size = sizeof (deviceID);
  236422. // if they're asking for any input channels at all, use the default input, so we
  236423. // get the built-in mic rather than the built-in output with no inputs..
  236424. AudioObjectPropertyAddress pa;
  236425. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236426. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236427. pa.mElement = kAudioObjectPropertyElementMaster;
  236428. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236429. {
  236430. if (forInput)
  236431. {
  236432. for (int i = inputIds.size(); --i >= 0;)
  236433. if (inputIds[i] == deviceID)
  236434. return i;
  236435. }
  236436. else
  236437. {
  236438. for (int i = outputIds.size(); --i >= 0;)
  236439. if (outputIds[i] == deviceID)
  236440. return i;
  236441. }
  236442. }
  236443. return 0;
  236444. }
  236445. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236446. {
  236447. jassert (hasScanned); // need to call scanForDevices() before doing this
  236448. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236449. if (d == 0)
  236450. return -1;
  236451. return asInput ? d->inputIndex
  236452. : d->outputIndex;
  236453. }
  236454. bool hasSeparateInputsAndOutputs() const { return true; }
  236455. AudioIODevice* createDevice (const String& outputDeviceName,
  236456. const String& inputDeviceName)
  236457. {
  236458. jassert (hasScanned); // need to call scanForDevices() before doing this
  236459. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236460. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236461. String deviceName (outputDeviceName);
  236462. if (deviceName.isEmpty())
  236463. deviceName = inputDeviceName;
  236464. if (index >= 0)
  236465. return new CoreAudioIODevice (deviceName,
  236466. inputIds [inputIndex],
  236467. inputIndex,
  236468. outputIds [outputIndex],
  236469. outputIndex);
  236470. return 0;
  236471. }
  236472. juce_UseDebuggingNewOperator
  236473. private:
  236474. StringArray inputDeviceNames, outputDeviceNames;
  236475. Array <AudioDeviceID> inputIds, outputIds;
  236476. bool hasScanned;
  236477. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236478. {
  236479. int total = 0;
  236480. UInt32 size;
  236481. AudioObjectPropertyAddress pa;
  236482. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236483. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236484. pa.mElement = kAudioObjectPropertyElementMaster;
  236485. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236486. {
  236487. HeapBlock <AudioBufferList> bufList;
  236488. bufList.calloc (size, 1);
  236489. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236490. {
  236491. const int numStreams = bufList->mNumberBuffers;
  236492. for (int i = 0; i < numStreams; ++i)
  236493. {
  236494. const AudioBuffer& b = bufList->mBuffers[i];
  236495. total += b.mNumberChannels;
  236496. }
  236497. }
  236498. }
  236499. return total;
  236500. }
  236501. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236502. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236503. };
  236504. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236505. {
  236506. return new CoreAudioIODeviceType();
  236507. }
  236508. #undef log
  236509. #endif
  236510. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236511. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236512. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236513. // compiled on its own).
  236514. #if JUCE_INCLUDED_FILE
  236515. #if JUCE_MAC
  236516. #undef log
  236517. #define log(a) Logger::writeToLog(a)
  236518. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  236519. {
  236520. if (err == noErr)
  236521. return true;
  236522. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236523. jassertfalse;
  236524. return false;
  236525. }
  236526. #undef OK
  236527. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  236528. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236529. {
  236530. String result;
  236531. CFStringRef str = 0;
  236532. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236533. if (str != 0)
  236534. {
  236535. result = PlatformUtilities::cfStringToJuceString (str);
  236536. CFRelease (str);
  236537. str = 0;
  236538. }
  236539. MIDIEntityRef entity = 0;
  236540. MIDIEndpointGetEntity (endpoint, &entity);
  236541. if (entity == 0)
  236542. return result; // probably virtual
  236543. if (result.isEmpty())
  236544. {
  236545. // endpoint name has zero length - try the entity
  236546. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236547. if (str != 0)
  236548. {
  236549. result += PlatformUtilities::cfStringToJuceString (str);
  236550. CFRelease (str);
  236551. str = 0;
  236552. }
  236553. }
  236554. // now consider the device's name
  236555. MIDIDeviceRef device = 0;
  236556. MIDIEntityGetDevice (entity, &device);
  236557. if (device == 0)
  236558. return result;
  236559. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236560. if (str != 0)
  236561. {
  236562. const String s (PlatformUtilities::cfStringToJuceString (str));
  236563. CFRelease (str);
  236564. // if an external device has only one entity, throw away
  236565. // the endpoint name and just use the device name
  236566. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236567. {
  236568. result = s;
  236569. }
  236570. else if (! result.startsWithIgnoreCase (s))
  236571. {
  236572. // prepend the device name to the entity name
  236573. result = (s + " " + result).trimEnd();
  236574. }
  236575. }
  236576. return result;
  236577. }
  236578. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236579. {
  236580. String result;
  236581. // Does the endpoint have connections?
  236582. CFDataRef connections = 0;
  236583. int numConnections = 0;
  236584. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236585. if (connections != 0)
  236586. {
  236587. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236588. if (numConnections > 0)
  236589. {
  236590. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236591. for (int i = 0; i < numConnections; ++i, ++pid)
  236592. {
  236593. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236594. MIDIObjectRef connObject;
  236595. MIDIObjectType connObjectType;
  236596. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236597. if (err == noErr)
  236598. {
  236599. String s;
  236600. if (connObjectType == kMIDIObjectType_ExternalSource
  236601. || connObjectType == kMIDIObjectType_ExternalDestination)
  236602. {
  236603. // Connected to an external device's endpoint (10.3 and later).
  236604. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236605. }
  236606. else
  236607. {
  236608. // Connected to an external device (10.2) (or something else, catch-all)
  236609. CFStringRef str = 0;
  236610. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236611. if (str != 0)
  236612. {
  236613. s = PlatformUtilities::cfStringToJuceString (str);
  236614. CFRelease (str);
  236615. }
  236616. }
  236617. if (s.isNotEmpty())
  236618. {
  236619. if (result.isNotEmpty())
  236620. result += ", ";
  236621. result += s;
  236622. }
  236623. }
  236624. }
  236625. }
  236626. CFRelease (connections);
  236627. }
  236628. if (result.isNotEmpty())
  236629. return result;
  236630. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236631. return getEndpointName (endpoint, false);
  236632. }
  236633. const StringArray MidiOutput::getDevices()
  236634. {
  236635. StringArray s;
  236636. const ItemCount num = MIDIGetNumberOfDestinations();
  236637. for (ItemCount i = 0; i < num; ++i)
  236638. {
  236639. MIDIEndpointRef dest = MIDIGetDestination (i);
  236640. if (dest != 0)
  236641. {
  236642. String name (getConnectedEndpointName (dest));
  236643. if (name.isEmpty())
  236644. name = "<error>";
  236645. s.add (name);
  236646. }
  236647. else
  236648. {
  236649. s.add ("<error>");
  236650. }
  236651. }
  236652. return s;
  236653. }
  236654. int MidiOutput::getDefaultDeviceIndex()
  236655. {
  236656. return 0;
  236657. }
  236658. static MIDIClientRef globalMidiClient;
  236659. static bool hasGlobalClientBeenCreated = false;
  236660. static bool makeSureClientExists()
  236661. {
  236662. if (! hasGlobalClientBeenCreated)
  236663. {
  236664. String name ("JUCE");
  236665. if (JUCEApplication::getInstance() != 0)
  236666. name = JUCEApplication::getInstance()->getApplicationName();
  236667. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236668. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236669. CFRelease (appName);
  236670. }
  236671. return hasGlobalClientBeenCreated;
  236672. }
  236673. class MidiPortAndEndpoint
  236674. {
  236675. public:
  236676. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236677. : port (port_), endPoint (endPoint_)
  236678. {
  236679. }
  236680. ~MidiPortAndEndpoint()
  236681. {
  236682. if (port != 0)
  236683. MIDIPortDispose (port);
  236684. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236685. MIDIEndpointDispose (endPoint);
  236686. }
  236687. MIDIPortRef port;
  236688. MIDIEndpointRef endPoint;
  236689. };
  236690. MidiOutput* MidiOutput::openDevice (int index)
  236691. {
  236692. MidiOutput* mo = 0;
  236693. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236694. {
  236695. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236696. CFStringRef pname;
  236697. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236698. {
  236699. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  236700. if (makeSureClientExists())
  236701. {
  236702. MIDIPortRef port;
  236703. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  236704. {
  236705. mo = new MidiOutput();
  236706. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  236707. }
  236708. }
  236709. CFRelease (pname);
  236710. }
  236711. }
  236712. return mo;
  236713. }
  236714. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236715. {
  236716. MidiOutput* mo = 0;
  236717. if (makeSureClientExists())
  236718. {
  236719. MIDIEndpointRef endPoint;
  236720. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236721. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  236722. {
  236723. mo = new MidiOutput();
  236724. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  236725. }
  236726. CFRelease (name);
  236727. }
  236728. return mo;
  236729. }
  236730. MidiOutput::~MidiOutput()
  236731. {
  236732. delete static_cast<MidiPortAndEndpoint*> (internal);
  236733. }
  236734. void MidiOutput::reset()
  236735. {
  236736. }
  236737. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236738. {
  236739. return false;
  236740. }
  236741. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236742. {
  236743. }
  236744. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236745. {
  236746. MidiPortAndEndpoint* const mpe = static_cast<MidiPortAndEndpoint*> (internal);
  236747. if (message.isSysEx())
  236748. {
  236749. const int maxPacketSize = 256;
  236750. int pos = 0, bytesLeft = message.getRawDataSize();
  236751. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236752. HeapBlock <MIDIPacketList> packets;
  236753. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236754. packets->numPackets = numPackets;
  236755. MIDIPacket* p = packets->packet;
  236756. for (int i = 0; i < numPackets; ++i)
  236757. {
  236758. p->timeStamp = 0;
  236759. p->length = jmin (maxPacketSize, bytesLeft);
  236760. memcpy (p->data, message.getRawData() + pos, p->length);
  236761. pos += p->length;
  236762. bytesLeft -= p->length;
  236763. p = MIDIPacketNext (p);
  236764. }
  236765. if (mpe->port != 0)
  236766. MIDISend (mpe->port, mpe->endPoint, packets);
  236767. else
  236768. MIDIReceived (mpe->endPoint, packets);
  236769. }
  236770. else
  236771. {
  236772. MIDIPacketList packets;
  236773. packets.numPackets = 1;
  236774. packets.packet[0].timeStamp = 0;
  236775. packets.packet[0].length = message.getRawDataSize();
  236776. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236777. if (mpe->port != 0)
  236778. MIDISend (mpe->port, mpe->endPoint, &packets);
  236779. else
  236780. MIDIReceived (mpe->endPoint, &packets);
  236781. }
  236782. }
  236783. const StringArray MidiInput::getDevices()
  236784. {
  236785. StringArray s;
  236786. const ItemCount num = MIDIGetNumberOfSources();
  236787. for (ItemCount i = 0; i < num; ++i)
  236788. {
  236789. MIDIEndpointRef source = MIDIGetSource (i);
  236790. if (source != 0)
  236791. {
  236792. String name (getConnectedEndpointName (source));
  236793. if (name.isEmpty())
  236794. name = "<error>";
  236795. s.add (name);
  236796. }
  236797. else
  236798. {
  236799. s.add ("<error>");
  236800. }
  236801. }
  236802. return s;
  236803. }
  236804. int MidiInput::getDefaultDeviceIndex()
  236805. {
  236806. return 0;
  236807. }
  236808. struct MidiPortAndCallback
  236809. {
  236810. MidiInput* input;
  236811. MidiPortAndEndpoint* portAndEndpoint;
  236812. MidiInputCallback* callback;
  236813. MemoryBlock pendingData;
  236814. int pendingBytes;
  236815. double pendingDataTime;
  236816. bool active;
  236817. void processSysex (const uint8*& d, int& size, const double time)
  236818. {
  236819. if (*d == 0xf0)
  236820. {
  236821. pendingBytes = 0;
  236822. pendingDataTime = time;
  236823. }
  236824. pendingData.ensureSize (pendingBytes + size, false);
  236825. uint8* totalMessage = (uint8*) pendingData.getData();
  236826. uint8* dest = totalMessage + pendingBytes;
  236827. while (size > 0)
  236828. {
  236829. if (pendingBytes > 0 && *d >= 0x80)
  236830. {
  236831. if (*d >= 0xfa || *d == 0xf8)
  236832. {
  236833. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  236834. ++d;
  236835. --size;
  236836. }
  236837. else
  236838. {
  236839. if (*d == 0xf7)
  236840. {
  236841. *dest++ = *d++;
  236842. pendingBytes++;
  236843. --size;
  236844. }
  236845. break;
  236846. }
  236847. }
  236848. else
  236849. {
  236850. *dest++ = *d++;
  236851. pendingBytes++;
  236852. --size;
  236853. }
  236854. }
  236855. if (totalMessage [pendingBytes - 1] == 0xf7)
  236856. {
  236857. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  236858. pendingBytes = 0;
  236859. }
  236860. else
  236861. {
  236862. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  236863. }
  236864. }
  236865. };
  236866. namespace CoreMidiCallbacks
  236867. {
  236868. static CriticalSection callbackLock;
  236869. static Array<void*> activeCallbacks;
  236870. }
  236871. static void midiInputProc (const MIDIPacketList* pktlist,
  236872. void* readProcRefCon,
  236873. void* /*srcConnRefCon*/)
  236874. {
  236875. double time = Time::getMillisecondCounterHiRes() * 0.001;
  236876. const double originalTime = time;
  236877. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  236878. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236879. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  236880. {
  236881. const MIDIPacket* packet = &pktlist->packet[0];
  236882. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236883. {
  236884. const uint8* d = (const uint8*) (packet->data);
  236885. int size = packet->length;
  236886. while (size > 0)
  236887. {
  236888. time = originalTime;
  236889. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  236890. {
  236891. mpc->processSysex (d, size, time);
  236892. }
  236893. else
  236894. {
  236895. int used = 0;
  236896. const MidiMessage m (d, size, used, 0, time);
  236897. if (used <= 0)
  236898. {
  236899. jassertfalse; // malformed midi message
  236900. break;
  236901. }
  236902. else
  236903. {
  236904. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  236905. }
  236906. size -= used;
  236907. d += used;
  236908. }
  236909. }
  236910. packet = MIDIPacketNext (packet);
  236911. }
  236912. }
  236913. }
  236914. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236915. {
  236916. MidiInput* mi = 0;
  236917. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236918. {
  236919. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236920. if (endPoint != 0)
  236921. {
  236922. CFStringRef pname;
  236923. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236924. {
  236925. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  236926. if (makeSureClientExists())
  236927. {
  236928. MIDIPortRef port;
  236929. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  236930. mpc->active = false;
  236931. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  236932. {
  236933. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  236934. {
  236935. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236936. mpc->callback = callback;
  236937. mpc->pendingBytes = 0;
  236938. mpc->pendingData.ensureSize (128);
  236939. mi = new MidiInput (getDevices() [index]);
  236940. mpc->input = mi;
  236941. mi->internal = mpc;
  236942. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236943. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  236944. }
  236945. else
  236946. {
  236947. OK (MIDIPortDispose (port));
  236948. }
  236949. }
  236950. }
  236951. }
  236952. CFRelease (pname);
  236953. }
  236954. }
  236955. return mi;
  236956. }
  236957. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236958. {
  236959. MidiInput* mi = 0;
  236960. if (makeSureClientExists())
  236961. {
  236962. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  236963. mpc->active = false;
  236964. MIDIEndpointRef endPoint;
  236965. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236966. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  236967. {
  236968. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236969. mpc->callback = callback;
  236970. mpc->pendingBytes = 0;
  236971. mpc->pendingData.ensureSize (128);
  236972. mi = new MidiInput (deviceName);
  236973. mpc->input = mi;
  236974. mi->internal = mpc;
  236975. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236976. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  236977. }
  236978. CFRelease (name);
  236979. }
  236980. return mi;
  236981. }
  236982. MidiInput::MidiInput (const String& name_)
  236983. : name (name_)
  236984. {
  236985. }
  236986. MidiInput::~MidiInput()
  236987. {
  236988. MidiPortAndCallback* const mpc = static_cast<MidiPortAndCallback*> (internal);
  236989. mpc->active = false;
  236990. {
  236991. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236992. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  236993. }
  236994. if (mpc->portAndEndpoint->port != 0)
  236995. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  236996. delete mpc->portAndEndpoint;
  236997. delete mpc;
  236998. }
  236999. void MidiInput::start()
  237000. {
  237001. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  237002. static_cast<MidiPortAndCallback*> (internal)->active = true;
  237003. }
  237004. void MidiInput::stop()
  237005. {
  237006. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  237007. static_cast<MidiPortAndCallback*> (internal)->active = false;
  237008. }
  237009. #undef log
  237010. #else
  237011. MidiOutput::~MidiOutput()
  237012. {
  237013. }
  237014. void MidiOutput::reset()
  237015. {
  237016. }
  237017. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  237018. {
  237019. return false;
  237020. }
  237021. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  237022. {
  237023. }
  237024. void MidiOutput::sendMessageNow (const MidiMessage& message)
  237025. {
  237026. }
  237027. const StringArray MidiOutput::getDevices()
  237028. {
  237029. return StringArray();
  237030. }
  237031. MidiOutput* MidiOutput::openDevice (int index)
  237032. {
  237033. return 0;
  237034. }
  237035. const StringArray MidiInput::getDevices()
  237036. {
  237037. return StringArray();
  237038. }
  237039. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  237040. {
  237041. return 0;
  237042. }
  237043. #endif
  237044. #endif
  237045. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  237046. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  237047. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237048. // compiled on its own).
  237049. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  237050. #if ! JUCE_QUICKTIME
  237051. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  237052. #endif
  237053. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  237054. class QTCameraDeviceInteral;
  237055. END_JUCE_NAMESPACE
  237056. @interface QTCaptureCallbackDelegate : NSObject
  237057. {
  237058. @public
  237059. CameraDevice* owner;
  237060. QTCameraDeviceInteral* internal;
  237061. int64 firstPresentationTime;
  237062. int64 averageTimeOffset;
  237063. }
  237064. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  237065. - (void) dealloc;
  237066. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237067. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237068. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237069. fromConnection: (QTCaptureConnection*) connection;
  237070. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237071. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237072. fromConnection: (QTCaptureConnection*) connection;
  237073. @end
  237074. BEGIN_JUCE_NAMESPACE
  237075. class QTCameraDeviceInteral
  237076. {
  237077. public:
  237078. QTCameraDeviceInteral (CameraDevice* owner, int index)
  237079. {
  237080. const ScopedAutoReleasePool pool;
  237081. session = [[QTCaptureSession alloc] init];
  237082. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237083. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  237084. input = 0;
  237085. audioInput = 0;
  237086. audioDevice = 0;
  237087. fileOutput = 0;
  237088. imageOutput = 0;
  237089. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  237090. internalDev: this];
  237091. NSError* err = 0;
  237092. [device retain];
  237093. [device open: &err];
  237094. if (err == 0)
  237095. {
  237096. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237097. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237098. [session addInput: input error: &err];
  237099. if (err == 0)
  237100. {
  237101. resetFile();
  237102. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  237103. [imageOutput setDelegate: callbackDelegate];
  237104. if (err == 0)
  237105. {
  237106. [session startRunning];
  237107. return;
  237108. }
  237109. }
  237110. }
  237111. openingError = nsStringToJuce ([err description]);
  237112. DBG (openingError);
  237113. }
  237114. ~QTCameraDeviceInteral()
  237115. {
  237116. [session stopRunning];
  237117. [session removeOutput: imageOutput];
  237118. [session release];
  237119. [input release];
  237120. [device release];
  237121. [audioDevice release];
  237122. [audioInput release];
  237123. [fileOutput release];
  237124. [imageOutput release];
  237125. [callbackDelegate release];
  237126. }
  237127. void resetFile()
  237128. {
  237129. [fileOutput recordToOutputFileURL: nil];
  237130. [session removeOutput: fileOutput];
  237131. [fileOutput release];
  237132. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  237133. [session removeInput: audioInput];
  237134. [audioInput release];
  237135. audioInput = 0;
  237136. [audioDevice release];
  237137. audioDevice = 0;
  237138. [fileOutput setDelegate: callbackDelegate];
  237139. }
  237140. void addDefaultAudioInput()
  237141. {
  237142. NSError* err = nil;
  237143. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  237144. if ([audioDevice open: &err])
  237145. [audioDevice retain];
  237146. else
  237147. audioDevice = nil;
  237148. if (audioDevice != 0)
  237149. {
  237150. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  237151. [session addInput: audioInput error: &err];
  237152. }
  237153. }
  237154. void addListener (CameraDevice::Listener* listenerToAdd)
  237155. {
  237156. const ScopedLock sl (listenerLock);
  237157. if (listeners.size() == 0)
  237158. [session addOutput: imageOutput error: nil];
  237159. listeners.addIfNotAlreadyThere (listenerToAdd);
  237160. }
  237161. void removeListener (CameraDevice::Listener* listenerToRemove)
  237162. {
  237163. const ScopedLock sl (listenerLock);
  237164. listeners.removeValue (listenerToRemove);
  237165. if (listeners.size() == 0)
  237166. [session removeOutput: imageOutput];
  237167. }
  237168. void callListeners (CIImage* frame, int w, int h)
  237169. {
  237170. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  237171. Image image (cgImage);
  237172. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  237173. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  237174. CGContextFlush (cgImage->context);
  237175. const ScopedLock sl (listenerLock);
  237176. for (int i = listeners.size(); --i >= 0;)
  237177. {
  237178. CameraDevice::Listener* const l = listeners[i];
  237179. if (l != 0)
  237180. l->imageReceived (image);
  237181. }
  237182. }
  237183. QTCaptureDevice* device;
  237184. QTCaptureDeviceInput* input;
  237185. QTCaptureDevice* audioDevice;
  237186. QTCaptureDeviceInput* audioInput;
  237187. QTCaptureSession* session;
  237188. QTCaptureMovieFileOutput* fileOutput;
  237189. QTCaptureDecompressedVideoOutput* imageOutput;
  237190. QTCaptureCallbackDelegate* callbackDelegate;
  237191. String openingError;
  237192. Array<CameraDevice::Listener*> listeners;
  237193. CriticalSection listenerLock;
  237194. };
  237195. END_JUCE_NAMESPACE
  237196. @implementation QTCaptureCallbackDelegate
  237197. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  237198. internalDev: (QTCameraDeviceInteral*) d
  237199. {
  237200. [super init];
  237201. owner = owner_;
  237202. internal = d;
  237203. firstPresentationTime = 0;
  237204. averageTimeOffset = 0;
  237205. return self;
  237206. }
  237207. - (void) dealloc
  237208. {
  237209. [super dealloc];
  237210. }
  237211. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237212. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237213. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237214. fromConnection: (QTCaptureConnection*) connection
  237215. {
  237216. if (internal->listeners.size() > 0)
  237217. {
  237218. const ScopedAutoReleasePool pool;
  237219. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  237220. CVPixelBufferGetWidth (videoFrame),
  237221. CVPixelBufferGetHeight (videoFrame));
  237222. }
  237223. }
  237224. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237225. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237226. fromConnection: (QTCaptureConnection*) connection
  237227. {
  237228. const Time now (Time::getCurrentTime());
  237229. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  237230. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  237231. #else
  237232. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  237233. #endif
  237234. int64 presentationTime = (hosttime != nil)
  237235. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  237236. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  237237. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  237238. if (firstPresentationTime == 0)
  237239. {
  237240. firstPresentationTime = presentationTime;
  237241. averageTimeOffset = timeDiff;
  237242. }
  237243. else
  237244. {
  237245. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  237246. }
  237247. }
  237248. @end
  237249. BEGIN_JUCE_NAMESPACE
  237250. class QTCaptureViewerComp : public NSViewComponent
  237251. {
  237252. public:
  237253. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  237254. {
  237255. const ScopedAutoReleasePool pool;
  237256. captureView = [[QTCaptureView alloc] init];
  237257. [captureView setCaptureSession: internal->session];
  237258. setSize (640, 480); // xxx need to somehow get the movie size - how?
  237259. setView (captureView);
  237260. }
  237261. ~QTCaptureViewerComp()
  237262. {
  237263. setView (0);
  237264. [captureView setCaptureSession: nil];
  237265. [captureView release];
  237266. }
  237267. QTCaptureView* captureView;
  237268. };
  237269. CameraDevice::CameraDevice (const String& name_, int index)
  237270. : name (name_)
  237271. {
  237272. isRecording = false;
  237273. internal = new QTCameraDeviceInteral (this, index);
  237274. }
  237275. CameraDevice::~CameraDevice()
  237276. {
  237277. stopRecording();
  237278. delete static_cast <QTCameraDeviceInteral*> (internal);
  237279. internal = 0;
  237280. }
  237281. Component* CameraDevice::createViewerComponent()
  237282. {
  237283. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  237284. }
  237285. const String CameraDevice::getFileExtension()
  237286. {
  237287. return ".mov";
  237288. }
  237289. void CameraDevice::startRecordingToFile (const File& file, int quality)
  237290. {
  237291. stopRecording();
  237292. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237293. d->callbackDelegate->firstPresentationTime = 0;
  237294. file.deleteFile();
  237295. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  237296. // out wrong, so we'll put some audio in there too..,
  237297. d->addDefaultAudioInput();
  237298. [d->session addOutput: d->fileOutput error: nil];
  237299. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  237300. for (;;)
  237301. {
  237302. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  237303. if (connection == 0)
  237304. break;
  237305. QTCompressionOptions* options = 0;
  237306. NSString* mediaType = [connection mediaType];
  237307. if ([mediaType isEqualToString: QTMediaTypeVideo])
  237308. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  237309. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  237310. : @"QTCompressionOptions240SizeH264Video"];
  237311. else if ([mediaType isEqualToString: QTMediaTypeSound])
  237312. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  237313. [d->fileOutput setCompressionOptions: options forConnection: connection];
  237314. }
  237315. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  237316. isRecording = true;
  237317. }
  237318. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  237319. {
  237320. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237321. if (d->callbackDelegate->firstPresentationTime != 0)
  237322. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  237323. return Time();
  237324. }
  237325. void CameraDevice::stopRecording()
  237326. {
  237327. if (isRecording)
  237328. {
  237329. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  237330. isRecording = false;
  237331. }
  237332. }
  237333. void CameraDevice::addListener (Listener* listenerToAdd)
  237334. {
  237335. if (listenerToAdd != 0)
  237336. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  237337. }
  237338. void CameraDevice::removeListener (Listener* listenerToRemove)
  237339. {
  237340. if (listenerToRemove != 0)
  237341. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  237342. }
  237343. const StringArray CameraDevice::getAvailableDevices()
  237344. {
  237345. const ScopedAutoReleasePool pool;
  237346. StringArray results;
  237347. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237348. for (int i = 0; i < (int) [devs count]; ++i)
  237349. {
  237350. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237351. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237352. }
  237353. return results;
  237354. }
  237355. CameraDevice* CameraDevice::openDevice (int index,
  237356. int minWidth, int minHeight,
  237357. int maxWidth, int maxHeight)
  237358. {
  237359. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237360. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237361. return d.release();
  237362. return 0;
  237363. }
  237364. #endif
  237365. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237366. #endif
  237367. #endif
  237368. END_JUCE_NAMESPACE
  237369. #endif
  237370. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237371. #endif
  237372. #endif